ovn-controller: Rename "ovn-patch-port" to "ovn-localnet-port".
[cascardo/ovs.git] / ovn / lib / expr.c
1 /*
2  * Copyright (c) 2015 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "expr.h"
19 #include "dynamic-string.h"
20 #include "json.h"
21 #include "lex.h"
22 #include "match.h"
23 #include "ofp-actions.h"
24 #include "shash.h"
25 #include "simap.h"
26 #include "sset.h"
27 #include "openvswitch/vlog.h"
28
29 VLOG_DEFINE_THIS_MODULE(expr);
30 \f
31 /* Returns the name of measurement level 'level'. */
32 const char *
33 expr_level_to_string(enum expr_level level)
34 {
35     switch (level) {
36     case EXPR_L_NOMINAL: return "nominal";
37     case EXPR_L_BOOLEAN: return "Boolean";
38     case EXPR_L_ORDINAL: return "ordinal";
39     default: OVS_NOT_REACHED();
40     }
41 }
42 \f
43 /* Relational operators. */
44
45 /* Returns a string form of relational operator 'relop'. */
46 const char *
47 expr_relop_to_string(enum expr_relop relop)
48 {
49     switch (relop) {
50     case EXPR_R_EQ: return "==";
51     case EXPR_R_NE: return "!=";
52     case EXPR_R_LT: return "<";
53     case EXPR_R_LE: return "<=";
54     case EXPR_R_GT: return ">";
55     case EXPR_R_GE: return ">=";
56     default: OVS_NOT_REACHED();
57     }
58 }
59
60 bool
61 expr_relop_from_token(enum lex_type type, enum expr_relop *relop)
62 {
63     enum expr_relop r;
64
65     switch ((int) type) {
66     case LEX_T_EQ: r = EXPR_R_EQ; break;
67     case LEX_T_NE: r = EXPR_R_NE; break;
68     case LEX_T_LT: r = EXPR_R_LT; break;
69     case LEX_T_LE: r = EXPR_R_LE; break;
70     case LEX_T_GT: r = EXPR_R_GT; break;
71     case LEX_T_GE: r = EXPR_R_GE; break;
72     default: return false;
73     }
74
75     if (relop) {
76         *relop = r;
77     }
78     return true;
79 }
80
81 /* Returns the relational operator that 'relop' becomes if you turn the
82  * relation's operands around, e.g. EXPR_R_EQ does not change because "a == b"
83  * and "b == a" are equivalent, but EXPR_R_LE becomes EXPR_R_GE because "a <=
84  * b" is equivalent to "b >= a". */
85 static enum expr_relop
86 expr_relop_turn(enum expr_relop relop)
87 {
88     switch (relop) {
89     case EXPR_R_EQ: return EXPR_R_EQ;
90     case EXPR_R_NE: return EXPR_R_NE;
91     case EXPR_R_LT: return EXPR_R_GT;
92     case EXPR_R_LE: return EXPR_R_GE;
93     case EXPR_R_GT: return EXPR_R_LT;
94     case EXPR_R_GE: return EXPR_R_LE;
95     default: OVS_NOT_REACHED();
96     }
97 }
98
99 /* Returns the relational operator that is the opposite of 'relop'. */
100 static enum expr_relop
101 expr_relop_invert(enum expr_relop relop)
102 {
103     switch (relop) {
104     case EXPR_R_EQ: return EXPR_R_NE;
105     case EXPR_R_NE: return EXPR_R_EQ;
106     case EXPR_R_LT: return EXPR_R_GE;
107     case EXPR_R_LE: return EXPR_R_GT;
108     case EXPR_R_GT: return EXPR_R_LE;
109     case EXPR_R_GE: return EXPR_R_LT;
110     default: OVS_NOT_REACHED();
111     }
112 }
113 \f
114 /* Constructing and manipulating expressions. */
115
116 /* Creates and returns a logical AND or OR expression (according to 'type',
117  * which must be EXPR_T_AND or EXPR_T_OR) that initially has no
118  * sub-expressions.  (To satisfy the invariants for expressions, the caller
119  * must add at least two sub-expressions whose types are different from
120  * 'type'.) */
121 struct expr *
122 expr_create_andor(enum expr_type type)
123 {
124     struct expr *e = xmalloc(sizeof *e);
125     e->type = type;
126     list_init(&e->andor);
127     return e;
128 }
129
130 /* Returns a logical AND or OR expression (according to 'type', which must be
131  * EXPR_T_AND or EXPR_T_OR) whose sub-expressions are 'a' and 'b', with some
132  * flexibility:
133  *
134  *     - If 'a' or 'b' is NULL, just returns the other one (which means that if
135  *       that other one is not of the given 'type', then the returned
136  *       expression is not either).
137  *
138  *     - If 'a' or 'b', or both, have type 'type', then they are combined into
139  *       a single node that satisfies the invariants for expressions. */
140 struct expr *
141 expr_combine(enum expr_type type, struct expr *a, struct expr *b)
142 {
143     if (!a) {
144         return b;
145     } else if (!b) {
146         return a;
147     } else if (a->type == type) {
148         if (b->type == type) {
149             list_splice(&a->andor, b->andor.next, &b->andor);
150             free(b);
151         } else {
152             list_push_back(&a->andor, &b->node);
153         }
154         return a;
155     } else if (b->type == type) {
156         list_push_front(&b->andor, &a->node);
157         return b;
158     } else {
159         struct expr *e = expr_create_andor(type);
160         list_push_back(&e->andor, &a->node);
161         list_push_back(&e->andor, &b->node);
162         return e;
163     }
164 }
165
166 static void
167 expr_insert_andor(struct expr *andor, struct expr *before, struct expr *new)
168 {
169     if (new->type == andor->type) {
170         if (andor->type == EXPR_T_AND) {
171             /* Conjunction junction, what's your function? */
172         }
173         list_splice(&before->node, new->andor.next, &new->andor);
174         free(new);
175     } else {
176         list_insert(&before->node, &new->node);
177     }
178 }
179
180 /* Returns an EXPR_T_BOOLEAN expression with value 'b'. */
181 struct expr *
182 expr_create_boolean(bool b)
183 {
184     struct expr *e = xmalloc(sizeof *e);
185     e->type = EXPR_T_BOOLEAN;
186     e->boolean = b;
187     return e;
188 }
189
190 static void
191 expr_not(struct expr *expr)
192 {
193     struct expr *sub;
194
195     switch (expr->type) {
196     case EXPR_T_CMP:
197         expr->cmp.relop = expr_relop_invert(expr->cmp.relop);
198         break;
199
200     case EXPR_T_AND:
201     case EXPR_T_OR:
202         LIST_FOR_EACH (sub, node, &expr->andor) {
203             expr_not(sub);
204         }
205         expr->type = expr->type == EXPR_T_AND ? EXPR_T_OR : EXPR_T_AND;
206         break;
207
208     case EXPR_T_BOOLEAN:
209         expr->boolean = !expr->boolean;
210         break;
211     default:
212         OVS_NOT_REACHED();
213     }
214 }
215
216 static struct expr *
217 expr_fix_andor(struct expr *expr, bool short_circuit)
218 {
219     struct expr *sub, *next;
220
221     LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
222         if (sub->type == EXPR_T_BOOLEAN) {
223             if (sub->boolean == short_circuit) {
224                 expr_destroy(expr);
225                 return expr_create_boolean(short_circuit);
226             } else {
227                 list_remove(&sub->node);
228                 expr_destroy(sub);
229             }
230         }
231     }
232
233     if (list_is_short(&expr->andor)) {
234         if (list_is_empty(&expr->andor)) {
235             free(expr);
236             return expr_create_boolean(!short_circuit);
237         } else {
238             sub = expr_from_node(list_front(&expr->andor));
239             free(expr);
240             return sub;
241         }
242     } else {
243         return expr;
244     }
245 }
246
247 /* Returns 'expr' modified so that top-level oddities are fixed up:
248  *
249  *     - Eliminates any EXPR_T_BOOLEAN operands at the top level.
250  *
251  *     - Replaces one-operand EXPR_T_AND or EXPR_T_OR by its subexpression. */
252 static struct expr *
253 expr_fix(struct expr *expr)
254 {
255     switch (expr->type) {
256     case EXPR_T_CMP:
257         return expr;
258
259     case EXPR_T_AND:
260         return expr_fix_andor(expr, false);
261
262     case EXPR_T_OR:
263         return expr_fix_andor(expr, true);
264
265     case EXPR_T_BOOLEAN:
266         return expr;
267
268     default:
269         OVS_NOT_REACHED();
270     }
271 }
272 \f
273 /* Formatting. */
274
275 static void
276 find_bitwise_range(const union mf_subvalue *sv, int width,
277                    int *startp, int *n_bitsp)
278 {
279     unsigned int start = bitwise_scan(sv, sizeof *sv, true, 0, width);
280     if (start < width) {
281         unsigned int end = bitwise_scan(sv, sizeof *sv, false, start, width);
282         if (end >= width
283             || bitwise_scan(sv, sizeof *sv, true, end, width) >= width) {
284             *startp = start;
285             *n_bitsp = end - start;
286             return;
287         }
288     }
289     *startp = *n_bitsp = 0;
290 }
291
292 static void
293 expr_format_cmp(const struct expr *e, struct ds *s)
294 {
295     /* The common case is numerical comparisons.
296      * Handle string comparisons as a special case. */
297     if (!e->cmp.symbol->width) {
298         ds_put_format(s, "%s %s ", e->cmp.symbol->name,
299                       expr_relop_to_string(e->cmp.relop));
300         json_string_escape(e->cmp.string, s);
301         return;
302     }
303
304     int ofs, n;
305     find_bitwise_range(&e->cmp.mask, e->cmp.symbol->width, &ofs, &n);
306     if (n == 1 && (e->cmp.relop == EXPR_R_EQ || e->cmp.relop == EXPR_R_NE)) {
307         bool positive;
308
309         positive = bitwise_get_bit(&e->cmp.value, sizeof e->cmp.value, ofs);
310         positive ^= e->cmp.relop == EXPR_R_NE;
311         if (!positive) {
312             ds_put_char(s, '!');
313         }
314         ds_put_cstr(s, e->cmp.symbol->name);
315         if (e->cmp.symbol->width > 1) {
316             ds_put_format(s, "[%d]", ofs);
317         }
318         return;
319     }
320
321     ds_put_cstr(s, e->cmp.symbol->name);
322     if (n > 0 && n < e->cmp.symbol->width) {
323         if (n > 1) {
324             ds_put_format(s, "[%d..%d]", ofs, ofs + n - 1);
325         } else {
326             ds_put_format(s, "[%d]", ofs);
327         }
328     }
329
330     ds_put_format(s, " %s ", expr_relop_to_string(e->cmp.relop));
331
332     if (n) {
333         union mf_subvalue value;
334
335         memset(&value, 0, sizeof value);
336         bitwise_copy(&e->cmp.value, sizeof e->cmp.value, ofs,
337                      &value, sizeof value, 0,
338                      n);
339         mf_format_subvalue(&value, s);
340     } else {
341         mf_format_subvalue(&e->cmp.value, s);
342         ds_put_char(s, '/');
343         mf_format_subvalue(&e->cmp.mask, s);
344     }
345 }
346
347 static void
348 expr_format_andor(const struct expr *e, const char *op, struct ds *s)
349 {
350     struct expr *sub;
351     int i = 0;
352
353     LIST_FOR_EACH (sub, node, &e->andor) {
354         if (i++) {
355             ds_put_format(s, " %s ", op);
356         }
357
358         if (sub->type == EXPR_T_AND || sub->type == EXPR_T_OR) {
359             ds_put_char(s, '(');
360             expr_format(sub, s);
361             ds_put_char(s, ')');
362         } else {
363             expr_format(sub, s);
364         }
365     }
366 }
367
368 /* Appends a string form of 'e' to 's'.  The string form is acceptable for
369  * parsing back into an equivalent expression. */
370 void
371 expr_format(const struct expr *e, struct ds *s)
372 {
373     switch (e->type) {
374     case EXPR_T_CMP:
375         expr_format_cmp(e, s);
376         break;
377
378     case EXPR_T_AND:
379         expr_format_andor(e, "&&", s);
380         break;
381
382     case EXPR_T_OR:
383         expr_format_andor(e, "||", s);
384         break;
385
386     case EXPR_T_BOOLEAN:
387         ds_put_char(s, e->boolean ? '1' : '0');
388         break;
389     }
390 }
391
392 /* Prints a string form of 'e' on stdout, followed by a new-line. */
393 void
394 expr_print(const struct expr *e)
395 {
396     struct ds output;
397
398     ds_init(&output);
399     expr_format(e, &output);
400     puts(ds_cstr(&output));
401     ds_destroy(&output);
402 }
403 \f
404 /* Parsing. */
405
406 /* Type of a "union expr_constant" or "struct expr_constant_set". */
407 enum expr_constant_type {
408     EXPR_C_INTEGER,
409     EXPR_C_STRING
410 };
411
412 /* A string or integer constant (one must know which from context). */
413 union expr_constant {
414     /* Integer constant.
415      *
416      * The width of a constant isn't always clear, e.g. if you write "1",
417      * there's no way to tell whether you mean for that to be a 1-bit constant
418      * or a 128-bit constant or somewhere in between. */
419     struct {
420         union mf_subvalue value;
421         union mf_subvalue mask; /* Only initialized if 'masked'. */
422         bool masked;
423
424         enum lex_format format; /* From the constant's lex_token. */
425     };
426
427     /* Null-terminated string constant. */
428     char *string;
429 };
430
431 /* A collection of "union expr_constant"s of the same type. */
432 struct expr_constant_set {
433     union expr_constant *values;  /* Constants. */
434     size_t n_values;              /* Number of constants. */
435     enum expr_constant_type type; /* Type of the constants. */
436     bool in_curlies;              /* Whether the constants were in {}. */
437 };
438
439 /* A reference to a symbol or a subfield of a symbol.
440  *
441  * For string fields, ofs and n_bits are 0. */
442 struct expr_field {
443     const struct expr_symbol *symbol; /* The symbol. */
444     int ofs;                          /* Starting bit offset. */
445     int n_bits;                       /* Number of bits. */
446 };
447
448 /* Context maintained during expr_parse(). */
449 struct expr_context {
450     struct lexer *lexer;        /* Lexer for pulling more tokens. */
451     const struct shash *symtab; /* Symbol table. */
452     char *error;                /* Error, if any, otherwise NULL. */
453     bool not;                   /* True inside odd number of NOT operators. */
454 };
455
456 struct expr *expr_parse__(struct expr_context *);
457 static void expr_not(struct expr *);
458 static void expr_constant_set_destroy(struct expr_constant_set *);
459 static bool parse_field(struct expr_context *, struct expr_field *);
460
461 static bool
462 expr_error_handle_common(struct expr_context *ctx)
463 {
464     if (ctx->error) {
465         /* Already have an error, suppress this one since the cascade seems
466          * unlikely to be useful. */
467         return true;
468     } else if (ctx->lexer->token.type == LEX_T_ERROR) {
469         /* The lexer signaled an error.  Nothing at the expression level
470          * accepts an error token, so we'll inevitably end up here with some
471          * meaningless parse error.  Report the lexical error instead. */
472         ctx->error = xstrdup(ctx->lexer->token.s);
473         return true;
474     } else {
475         return false;
476     }
477 }
478
479 static void OVS_PRINTF_FORMAT(2, 3)
480 expr_error(struct expr_context *ctx, const char *message, ...)
481 {
482     if (expr_error_handle_common(ctx)) {
483         return;
484     }
485
486     va_list args;
487     va_start(args, message);
488     ctx->error = xvasprintf(message, args);
489     va_end(args);
490 }
491
492 static void OVS_PRINTF_FORMAT(2, 3)
493 expr_syntax_error(struct expr_context *ctx, const char *message, ...)
494 {
495     if (expr_error_handle_common(ctx)) {
496         return;
497     }
498
499     struct ds s;
500
501     ds_init(&s);
502     ds_put_cstr(&s, "Syntax error ");
503     if (ctx->lexer->token.type == LEX_T_END) {
504         ds_put_cstr(&s, "at end of input ");
505     } else if (ctx->lexer->start) {
506         ds_put_format(&s, "at `%.*s' ",
507                       (int) (ctx->lexer->input - ctx->lexer->start),
508                       ctx->lexer->start);
509     }
510
511     va_list args;
512     va_start(args, message);
513     ds_put_format_valist(&s, message, args);
514     va_end(args);
515
516     ctx->error = ds_steal_cstr(&s);
517 }
518
519 static struct expr *
520 make_cmp__(const struct expr_field *f, enum expr_relop r,
521              const union expr_constant *c)
522 {
523     struct expr *e = xzalloc(sizeof *e);
524     e->type = EXPR_T_CMP;
525     e->cmp.symbol = f->symbol;
526     e->cmp.relop = r;
527     if (f->symbol->width) {
528         bitwise_copy(&c->value, sizeof c->value, 0,
529                      &e->cmp.value, sizeof e->cmp.value, f->ofs,
530                      f->n_bits);
531         if (c->masked) {
532             bitwise_copy(&c->mask, sizeof c->mask, 0,
533                          &e->cmp.mask, sizeof e->cmp.mask, f->ofs,
534                          f->n_bits);
535         } else {
536             bitwise_one(&e->cmp.mask, sizeof e->cmp.mask, f->ofs,
537                         f->n_bits);
538         }
539     } else {
540         e->cmp.string = xstrdup(c->string);
541     }
542     return e;
543 }
544
545 /* Returns the minimum reasonable width for integer constant 'c'. */
546 static int
547 expr_constant_width(const union expr_constant *c)
548 {
549     if (c->masked) {
550         return mf_subvalue_width(&c->mask);
551     }
552
553     switch (c->format) {
554     case LEX_F_DECIMAL:
555     case LEX_F_HEXADECIMAL:
556         return mf_subvalue_width(&c->value);
557
558     case LEX_F_IPV4:
559         return 32;
560
561     case LEX_F_IPV6:
562         return 128;
563
564     case LEX_F_ETHERNET:
565         return 48;
566
567     default:
568         OVS_NOT_REACHED();
569     }
570 }
571
572 static bool
573 type_check(struct expr_context *ctx, const struct expr_field *f,
574            struct expr_constant_set *cs)
575 {
576     if (cs->type != (f->symbol->width ? EXPR_C_INTEGER : EXPR_C_STRING)) {
577         expr_error(ctx, "%s field %s is not compatible with %s constant.",
578                    f->symbol->width ? "Integer" : "String",
579                    f->symbol->name,
580                    cs->type == EXPR_C_INTEGER ? "integer" : "string");
581         return false;
582     }
583
584     if (f->symbol->width) {
585         for (size_t i = 0; i < cs->n_values; i++) {
586             int w = expr_constant_width(&cs->values[i]);
587             if (w > f->symbol->width) {
588                 expr_error(ctx, "%d-bit constant is not compatible with "
589                            "%d-bit field %s.",
590                            w, f->symbol->width, f->symbol->name);
591                 return false;
592             }
593         }
594     }
595
596     return true;
597 }
598
599 static struct expr *
600 make_cmp(struct expr_context *ctx,
601          const struct expr_field *f, enum expr_relop r,
602          struct expr_constant_set *cs)
603 {
604     struct expr *e = NULL;
605
606     if (!type_check(ctx, f, cs)) {
607         goto exit;
608     }
609
610     if (r != EXPR_R_EQ && r != EXPR_R_NE) {
611         if (cs->in_curlies) {
612             expr_error(ctx, "Only == and != operators may be used "
613                        "with value sets.");
614             goto exit;
615         }
616         if (f->symbol->level == EXPR_L_NOMINAL ||
617             f->symbol->level == EXPR_L_BOOLEAN) {
618             expr_error(ctx, "Only == and != operators may be used "
619                        "with %s field %s.",
620                        expr_level_to_string(f->symbol->level),
621                        f->symbol->name);
622             goto exit;
623         }
624         if (cs->values[0].masked) {
625             expr_error(ctx, "Only == and != operators may be used with "
626                        "masked constants.  Consider using subfields instead "
627                        "(e.g. eth.src[0..15] > 0x1111 in place of "
628                        "eth.src > 00:00:00:00:11:11/00:00:00:00:ff:ff).");
629             goto exit;
630         }
631     }
632
633     if (f->symbol->level == EXPR_L_NOMINAL) {
634         if (f->symbol->expansion) {
635             ovs_assert(f->symbol->width > 0);
636             for (size_t i = 0; i < cs->n_values; i++) {
637                 const union mf_subvalue *value = &cs->values[i].value;
638                 bool positive = (value->integer & htonll(1)) != 0;
639                 positive ^= r == EXPR_R_NE;
640                 positive ^= ctx->not;
641                 if (!positive) {
642                     const char *name = f->symbol->name;
643                     expr_error(ctx, "Nominal predicate %s may only be tested "
644                                "positively, e.g. `%s' or `%s == 1' but not "
645                                "`!%s' or `%s == 0'.",
646                                name, name, name, name, name);
647                     goto exit;
648                 }
649             }
650         } else if (r != (ctx->not ? EXPR_R_NE : EXPR_R_EQ)) {
651             expr_error(ctx, "Nominal field %s may only be tested for "
652                        "equality (taking enclosing `!' operators into "
653                        "account).", f->symbol->name);
654             goto exit;
655         }
656     }
657
658     e = make_cmp__(f, r, &cs->values[0]);
659     for (size_t i = 1; i < cs->n_values; i++) {
660         e = expr_combine(r == EXPR_R_EQ ? EXPR_T_OR : EXPR_T_AND,
661                          e, make_cmp__(f, r, &cs->values[i]));
662     }
663 exit:
664     expr_constant_set_destroy(cs);
665     return e;
666 }
667
668 static bool
669 expr_get_int(struct expr_context *ctx, int *value)
670 {
671     bool ok = lexer_get_int(ctx->lexer, value);
672     if (!ok) {
673         expr_syntax_error(ctx, "expecting small integer.");
674     }
675     return ok;
676 }
677
678 static bool
679 parse_field(struct expr_context *ctx, struct expr_field *f)
680 {
681     const struct expr_symbol *symbol;
682
683     if (ctx->lexer->token.type != LEX_T_ID) {
684         expr_syntax_error(ctx, "expecting field name.");
685         return false;
686     }
687
688     symbol = shash_find_data(ctx->symtab, ctx->lexer->token.s);
689     if (!symbol) {
690         expr_syntax_error(ctx, "expecting field name.");
691         return false;
692     }
693     lexer_get(ctx->lexer);
694
695     f->symbol = symbol;
696     if (lexer_match(ctx->lexer, LEX_T_LSQUARE)) {
697         int low, high;
698
699         if (!symbol->width) {
700             expr_error(ctx, "Cannot select subfield of string field %s.",
701                        symbol->name);
702             return false;
703         }
704
705         if (!expr_get_int(ctx, &low)) {
706             return false;
707         }
708         if (lexer_match(ctx->lexer, LEX_T_ELLIPSIS)) {
709             if (!expr_get_int(ctx, &high)) {
710                 return false;
711             }
712         } else {
713             high = low;
714         }
715
716         if (!lexer_match(ctx->lexer, LEX_T_RSQUARE)) {
717             expr_syntax_error(ctx, "expecting `]'.");
718             return false;
719         }
720
721         if (low > high) {
722             expr_error(ctx, "Invalid bit range %d to %d.", low, high);
723             return false;
724         } else if (high >= symbol->width) {
725             expr_error(ctx, "Cannot select bits %d to %d of %d-bit field %s.",
726                        low, high, symbol->width, symbol->name);
727             return false;
728         } else if (symbol->level == EXPR_L_NOMINAL
729                    && (low != 0 || high != symbol->width - 1)) {
730             expr_error(ctx, "Cannot select subfield of nominal field %s.",
731                        symbol->name);
732             return false;
733         }
734
735         f->ofs = low;
736         f->n_bits = high - low + 1;
737     } else {
738         f->ofs = 0;
739         f->n_bits = symbol->width;
740     }
741
742     return true;
743 }
744
745 static bool
746 parse_relop(struct expr_context *ctx, enum expr_relop *relop)
747 {
748     if (expr_relop_from_token(ctx->lexer->token.type, relop)) {
749         lexer_get(ctx->lexer);
750         return true;
751     } else {
752         expr_syntax_error(ctx, "expecting relational operator.");
753         return false;
754     }
755 }
756
757 static bool
758 assign_constant_set_type(struct expr_context *ctx,
759                          struct expr_constant_set *cs,
760                          enum expr_constant_type type)
761 {
762     if (!cs->n_values || cs->type == type) {
763         cs->type = type;
764         return true;
765     } else {
766         expr_syntax_error(ctx, "expecting %s.",
767                           cs->type == EXPR_C_INTEGER ? "integer" : "string");
768         return false;
769     }
770 }
771
772 static bool
773 parse_constant(struct expr_context *ctx, struct expr_constant_set *cs,
774                size_t *allocated_values)
775 {
776     if (cs->n_values >= *allocated_values) {
777         cs->values = x2nrealloc(cs->values, allocated_values,
778                                 sizeof *cs->values);
779     }
780
781     if (ctx->lexer->token.type == LEX_T_STRING) {
782         if (!assign_constant_set_type(ctx, cs, EXPR_C_STRING)) {
783             return false;
784         }
785         cs->values[cs->n_values++].string = xstrdup(ctx->lexer->token.s);
786         lexer_get(ctx->lexer);
787         return true;
788     } else if (ctx->lexer->token.type == LEX_T_INTEGER ||
789                ctx->lexer->token.type == LEX_T_MASKED_INTEGER) {
790         if (!assign_constant_set_type(ctx, cs, EXPR_C_INTEGER)) {
791             return false;
792         }
793
794         union expr_constant *c = &cs->values[cs->n_values++];
795         c->value = ctx->lexer->token.value;
796         c->format = ctx->lexer->token.format;
797         c->masked = ctx->lexer->token.type == LEX_T_MASKED_INTEGER;
798         if (c->masked) {
799             c->mask = ctx->lexer->token.mask;
800         }
801         lexer_get(ctx->lexer);
802         return true;
803     } else {
804         expr_syntax_error(ctx, "expecting constant.");
805         return false;
806     }
807 }
808
809 /* Parses a single or {}-enclosed set of integer or string constants into 'cs',
810  * which the caller need not have initialized.  Returns true on success, in
811  * which case the caller owns 'cs', false on failure, in which case 'cs' is
812  * indeterminate. */
813 static bool
814 parse_constant_set(struct expr_context *ctx, struct expr_constant_set *cs)
815 {
816     size_t allocated_values = 0;
817     bool ok;
818
819     memset(cs, 0, sizeof *cs);
820     if (lexer_match(ctx->lexer, LEX_T_LCURLY)) {
821         ok = true;
822         cs->in_curlies = true;
823         do {
824             if (!parse_constant(ctx, cs, &allocated_values)) {
825                 ok = false;
826                 break;
827             }
828             lexer_match(ctx->lexer, LEX_T_COMMA);
829         } while (!lexer_match(ctx->lexer, LEX_T_RCURLY));
830     } else {
831         ok = parse_constant(ctx, cs, &allocated_values);
832     }
833     if (!ok) {
834         expr_constant_set_destroy(cs);
835     }
836     return ok;
837 }
838
839 static void
840 expr_constant_set_destroy(struct expr_constant_set *cs)
841 {
842     if (cs) {
843         if (cs->type == EXPR_C_STRING) {
844             for (size_t i = 0; i < cs->n_values; i++) {
845                 free(cs->values[i].string);
846             }
847         }
848         free(cs->values);
849     }
850 }
851
852 static struct expr *
853 expr_parse_primary(struct expr_context *ctx, bool *atomic)
854 {
855     *atomic = false;
856     if (lexer_match(ctx->lexer, LEX_T_LPAREN)) {
857         struct expr *e = expr_parse__(ctx);
858         if (!lexer_match(ctx->lexer, LEX_T_RPAREN)) {
859             expr_destroy(e);
860             expr_syntax_error(ctx, "expecting `)'.");
861             return NULL;
862         }
863         *atomic = true;
864         return e;
865     }
866
867     if (ctx->lexer->token.type == LEX_T_ID) {
868         struct expr_field f;
869         enum expr_relop r;
870         struct expr_constant_set c;
871
872         if (!parse_field(ctx, &f)) {
873             return NULL;
874         }
875
876         if (!expr_relop_from_token(ctx->lexer->token.type, &r)) {
877             if (f.n_bits > 1 && !ctx->not) {
878                 expr_error(ctx, "Explicit `!= 0' is required for inequality "
879                            "test of multibit field against 0.");
880                 return NULL;
881             }
882
883             *atomic = true;
884
885             union expr_constant *cst = xzalloc(sizeof *cst);
886             cst->format = LEX_F_HEXADECIMAL;
887             cst->masked = false;
888
889             c.type = EXPR_C_INTEGER;
890             c.values = cst;
891             c.n_values = 1;
892             c.in_curlies = false;
893             return make_cmp(ctx, &f, EXPR_R_NE, &c);
894         } else if (parse_relop(ctx, &r) && parse_constant_set(ctx, &c)) {
895             return make_cmp(ctx, &f, r, &c);
896         } else {
897             return NULL;
898         }
899     } else {
900         struct expr_constant_set c1;
901         if (!parse_constant_set(ctx, &c1)) {
902             return NULL;
903         }
904
905         if (!expr_relop_from_token(ctx->lexer->token.type, NULL)
906             && c1.n_values == 1
907             && c1.type == EXPR_C_INTEGER
908             && c1.values[0].format == LEX_F_DECIMAL
909             && !c1.values[0].masked
910             && !c1.in_curlies) {
911             uint64_t x = ntohll(c1.values[0].value.integer);
912             if (x <= 1) {
913                 *atomic = true;
914                 expr_constant_set_destroy(&c1);
915                 return expr_create_boolean(x);
916             }
917         }
918
919         enum expr_relop r1;
920         struct expr_field f;
921         if (!parse_relop(ctx, &r1) || !parse_field(ctx, &f)) {
922             expr_constant_set_destroy(&c1);
923             return NULL;
924         }
925
926         if (!expr_relop_from_token(ctx->lexer->token.type, NULL)) {
927             return make_cmp(ctx, &f, expr_relop_turn(r1), &c1);
928         }
929
930         enum expr_relop r2;
931         struct expr_constant_set c2;
932         if (!parse_relop(ctx, &r2) || !parse_constant_set(ctx, &c2)) {
933             expr_constant_set_destroy(&c1);
934             return NULL;
935         } else {
936             /* Reject "1 == field == 2", "1 < field > 2", and so on. */
937             if (!(((r1 == EXPR_R_LT || r1 == EXPR_R_LE) &&
938                    (r2 == EXPR_R_LT || r2 == EXPR_R_LE)) ||
939                   ((r1 == EXPR_R_GT || r1 == EXPR_R_GE) &&
940                    (r2 == EXPR_R_GT || r2 == EXPR_R_GE)))) {
941                 expr_error(ctx, "Range expressions must have the form "
942                            "`x < field < y' or `x > field > y', with each "
943                            "`<' optionally replaced by `<=' or `>' by `>=').");
944                 expr_constant_set_destroy(&c1);
945                 expr_constant_set_destroy(&c2);
946                 return NULL;
947             }
948
949             struct expr *e1 = make_cmp(ctx, &f, expr_relop_turn(r1), &c1);
950             struct expr *e2 = make_cmp(ctx, &f, r2, &c2);
951             if (ctx->error) {
952                 expr_destroy(e1);
953                 expr_destroy(e2);
954                 return NULL;
955             }
956             return expr_combine(EXPR_T_AND, e1, e2);
957         }
958     }
959 }
960
961 static struct expr *
962 expr_parse_not(struct expr_context *ctx)
963 {
964     bool atomic;
965
966     if (lexer_match(ctx->lexer, LEX_T_LOG_NOT)) {
967         ctx->not = !ctx->not;
968         struct expr *expr = expr_parse_primary(ctx, &atomic);
969         ctx->not = !ctx->not;
970
971         if (expr) {
972             if (!atomic) {
973                 expr_error(ctx, "Missing parentheses around operand of !.");
974                 expr_destroy(expr);
975                 return NULL;
976             }
977             expr_not(expr);
978         }
979         return expr;
980     } else {
981         return expr_parse_primary(ctx, &atomic);
982     }
983 }
984
985 struct expr *
986 expr_parse__(struct expr_context *ctx)
987 {
988     struct expr *e = expr_parse_not(ctx);
989     if (!e) {
990         return NULL;
991     }
992
993     enum lex_type lex_type = ctx->lexer->token.type;
994     if (lex_type == LEX_T_LOG_AND || lex_type == LEX_T_LOG_OR) {
995         enum expr_type expr_type
996             = lex_type == LEX_T_LOG_AND ? EXPR_T_AND : EXPR_T_OR;
997
998         lexer_get(ctx->lexer);
999         do {
1000             struct expr *e2 = expr_parse_not(ctx);
1001             if (!e2) {
1002                 expr_destroy(e);
1003                 return NULL;
1004             }
1005             e = expr_combine(expr_type, e, e2);
1006         } while (lexer_match(ctx->lexer, lex_type));
1007         if (ctx->lexer->token.type == LEX_T_LOG_AND
1008             || ctx->lexer->token.type == LEX_T_LOG_OR) {
1009             expr_destroy(e);
1010             expr_error(ctx,
1011                        "&& and || must be parenthesized when used together.");
1012             return NULL;
1013         }
1014     }
1015     return e;
1016 }
1017
1018 /* Parses an expression using the symbols in 'symtab' from 'lexer'.  If
1019  * successful, returns the new expression and sets '*errorp' to NULL.  On
1020  * failure, returns NULL and sets '*errorp' to an explanatory error message.
1021  * The caller must eventually free the returned expression (with
1022  * expr_destroy()) or error (with free()). */
1023 struct expr *
1024 expr_parse(struct lexer *lexer, const struct shash *symtab, char **errorp)
1025 {
1026     struct expr_context ctx;
1027
1028     ctx.lexer = lexer;
1029     ctx.symtab = symtab;
1030     ctx.error = NULL;
1031     ctx.not = false;
1032
1033     struct expr *e = expr_parse__(&ctx);
1034     *errorp = ctx.error;
1035     ovs_assert((ctx.error != NULL) != (e != NULL));
1036     return e;
1037 }
1038
1039 /* Like expr_parse(), but the expression is taken from 's'. */
1040 struct expr *
1041 expr_parse_string(const char *s, const struct shash *symtab, char **errorp)
1042 {
1043     struct lexer lexer;
1044     struct expr *expr;
1045
1046     lexer_init(&lexer, s);
1047     lexer_get(&lexer);
1048     expr = expr_parse(&lexer, symtab, errorp);
1049     if (!*errorp && lexer.token.type != LEX_T_END) {
1050         *errorp = xstrdup("Extra tokens at end of input.");
1051         expr_destroy(expr);
1052         expr = NULL;
1053     }
1054     lexer_destroy(&lexer);
1055
1056     return expr;
1057 }
1058 \f
1059 static struct expr_symbol *
1060 add_symbol(struct shash *symtab, const char *name, int width,
1061            const char *prereqs, enum expr_level level,
1062            bool must_crossproduct)
1063 {
1064     struct expr_symbol *symbol = xzalloc(sizeof *symbol);
1065     symbol->name = xstrdup(name);
1066     symbol->prereqs = prereqs && prereqs[0] ? xstrdup(prereqs) : NULL;
1067     symbol->width = width;
1068     symbol->level = level;
1069     symbol->must_crossproduct = must_crossproduct;
1070     shash_add_assert(symtab, symbol->name, symbol);
1071     return symbol;
1072 }
1073
1074 /* Adds field 'id' to symbol table 'symtab' under the given 'name'.  Whenever
1075  * 'name' is referenced, expression annotation (see expr_annotate()) will
1076  * ensure that 'prereqs' are also true.  If 'must_crossproduct' is true, then
1077  * conversion to flows will never attempt to use the field as a conjunctive
1078  * match dimension (see "Crossproducting" in the large comment on struct
1079  * expr_symbol in expr.h for an example).
1080  *
1081  * A given field 'id' must only be used for a single symbol in a symbol table.
1082  * Use subfields to duplicate or subset a field (you can even make a subfield
1083  * include all the bits of the "parent" field if you like). */
1084 struct expr_symbol *
1085 expr_symtab_add_field(struct shash *symtab, const char *name,
1086                       enum mf_field_id id, const char *prereqs,
1087                       bool must_crossproduct)
1088 {
1089     const struct mf_field *field = mf_from_id(id);
1090     struct expr_symbol *symbol;
1091
1092     symbol = add_symbol(symtab, name, field->n_bits, prereqs,
1093                         (field->maskable == MFM_FULLY
1094                          ? EXPR_L_ORDINAL
1095                          : EXPR_L_NOMINAL),
1096                         must_crossproduct);
1097     symbol->field = field;
1098     return symbol;
1099 }
1100
1101 static bool
1102 parse_field_from_string(const char *s, const struct shash *symtab,
1103                         struct expr_field *field, char **errorp)
1104 {
1105     struct lexer lexer;
1106     lexer_init(&lexer, s);
1107     lexer_get(&lexer);
1108
1109     struct expr_context ctx;
1110     ctx.lexer = &lexer;
1111     ctx.symtab = symtab;
1112     ctx.error = NULL;
1113     ctx.not = false;
1114
1115     bool ok = parse_field(&ctx, field);
1116     if (!ok) {
1117         *errorp = ctx.error;
1118     } else if (lexer.token.type != LEX_T_END) {
1119         *errorp = xstrdup("Extra tokens at end of input.");
1120         ok = false;
1121     }
1122
1123     lexer_destroy(&lexer);
1124
1125     return ok;
1126 }
1127
1128 /* Adds 'name' as a subfield of a larger field in 'symtab'.  Whenever
1129  * 'name' is referenced, expression annotation (see expr_annotate()) will
1130  * ensure that 'prereqs' are also true.
1131  *
1132  * 'subfield' must describe the subfield as a string, e.g. "vlan.tci[0..11]"
1133  * for the low 12 bits of a larger field named "vlan.tci". */
1134 struct expr_symbol *
1135 expr_symtab_add_subfield(struct shash *symtab, const char *name,
1136                          const char *prereqs, const char *subfield)
1137 {
1138     struct expr_symbol *symbol;
1139     struct expr_field f;
1140     char *error;
1141
1142     if (!parse_field_from_string(subfield, symtab, &f, &error)) {
1143         VLOG_WARN("%s: error parsing %s subfield (%s)", subfield, name, error);
1144         free(error);
1145         return NULL;
1146     }
1147
1148     enum expr_level level = f.symbol->level;
1149     if (level != EXPR_L_ORDINAL) {
1150         VLOG_WARN("can't define %s as subfield of %s field %s",
1151                   name, expr_level_to_string(level), f.symbol->name);
1152     }
1153
1154     symbol = add_symbol(symtab, name, f.n_bits, prereqs, level, false);
1155     symbol->expansion = xstrdup(subfield);
1156     return symbol;
1157 }
1158
1159 /* Adds a string-valued symbol named 'name' to 'symtab' with the specified
1160  * 'prereqs'. */
1161 struct expr_symbol *
1162 expr_symtab_add_string(struct shash *symtab, const char *name,
1163                        enum mf_field_id id, const char *prereqs)
1164 {
1165     const struct mf_field *field = mf_from_id(id);
1166     struct expr_symbol *symbol;
1167
1168     symbol = add_symbol(symtab, name, 0, prereqs, EXPR_L_NOMINAL, false);
1169     symbol->field = field;
1170     return symbol;
1171 }
1172
1173 static enum expr_level
1174 expr_get_level(const struct expr *expr)
1175 {
1176     const struct expr *sub;
1177     enum expr_level level = EXPR_L_ORDINAL;
1178
1179     switch (expr->type) {
1180     case EXPR_T_CMP:
1181         return (expr->cmp.symbol->level == EXPR_L_NOMINAL
1182                 ? EXPR_L_NOMINAL
1183                 : EXPR_L_BOOLEAN);
1184
1185     case EXPR_T_AND:
1186     case EXPR_T_OR:
1187         LIST_FOR_EACH (sub, node, &expr->andor) {
1188             enum expr_level sub_level = expr_get_level(sub);
1189             level = MIN(level, sub_level);
1190         }
1191         return level;
1192
1193     case EXPR_T_BOOLEAN:
1194         return EXPR_L_BOOLEAN;
1195
1196     default:
1197         OVS_NOT_REACHED();
1198     }
1199 }
1200
1201 static enum expr_level
1202 expr_parse_level(const char *s, const struct shash *symtab, char **errorp)
1203 {
1204     struct expr *expr = expr_parse_string(s, symtab, errorp);
1205     enum expr_level level = expr ? expr_get_level(expr) : EXPR_L_NOMINAL;
1206     expr_destroy(expr);
1207     return level;
1208 }
1209
1210 /* Adds a predicate symbol, whose value is the given Boolean 'expression',
1211  * named 'name' to 'symtab'.  For example, "ip4 && ip4.proto == 6" might be an
1212  * appropriate predicate named "tcp4". */
1213 struct expr_symbol *
1214 expr_symtab_add_predicate(struct shash *symtab, const char *name,
1215                           const char *expansion)
1216 {
1217     struct expr_symbol *symbol;
1218     enum expr_level level;
1219     char *error;
1220
1221     level = expr_parse_level(expansion, symtab, &error);
1222     if (error) {
1223         VLOG_WARN("%s: error parsing %s expansion (%s)",
1224                   expansion, name, error);
1225         free(error);
1226         return NULL;
1227     }
1228
1229     symbol = add_symbol(symtab, name, 1, NULL, level, false);
1230     symbol->expansion = xstrdup(expansion);
1231     return symbol;
1232 }
1233
1234 /* Destroys 'symtab' and all of its symbols. */
1235 void
1236 expr_symtab_destroy(struct shash *symtab)
1237 {
1238     struct shash_node *node, *next;
1239
1240     SHASH_FOR_EACH_SAFE (node, next, symtab) {
1241         struct expr_symbol *symbol = node->data;
1242
1243         shash_delete(symtab, node);
1244         free(symbol->name);
1245         free(symbol->prereqs);
1246         free(symbol->expansion);
1247         free(symbol);
1248     }
1249 }
1250 \f
1251 /* Cloning. */
1252
1253 static struct expr *
1254 expr_clone_cmp(struct expr *expr)
1255 {
1256     struct expr *new = xmemdup(expr, sizeof *expr);
1257     if (!new->cmp.symbol->width) {
1258         new->cmp.string = xstrdup(new->cmp.string);
1259     }
1260     return new;
1261 }
1262
1263 static struct expr *
1264 expr_clone_andor(struct expr *expr)
1265 {
1266     struct expr *new = expr_create_andor(expr->type);
1267     struct expr *sub;
1268
1269     LIST_FOR_EACH (sub, node, &expr->andor) {
1270         struct expr *new_sub = expr_clone(sub);
1271         list_push_back(&new->andor, &new_sub->node);
1272     }
1273     return new;
1274 }
1275
1276 /* Returns a clone of 'expr'.  This is a "deep copy": neither the returned
1277  * expression nor any of its substructure will be shared with 'expr'. */
1278 struct expr *
1279 expr_clone(struct expr *expr)
1280 {
1281     switch (expr->type) {
1282     case EXPR_T_CMP:
1283         return expr_clone_cmp(expr);
1284
1285     case EXPR_T_AND:
1286     case EXPR_T_OR:
1287         return expr_clone_andor(expr);
1288
1289     case EXPR_T_BOOLEAN:
1290         return expr_create_boolean(expr->boolean);
1291     }
1292     OVS_NOT_REACHED();
1293 }
1294 \f
1295 /* Destroys 'expr' and all of the sub-expressions it references. */
1296 void
1297 expr_destroy(struct expr *expr)
1298 {
1299     if (!expr) {
1300         return;
1301     }
1302
1303     struct expr *sub, *next;
1304
1305     switch (expr->type) {
1306     case EXPR_T_CMP:
1307         if (!expr->cmp.symbol->width) {
1308             free(expr->cmp.string);
1309         }
1310         break;
1311
1312     case EXPR_T_AND:
1313     case EXPR_T_OR:
1314         LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1315             list_remove(&sub->node);
1316             expr_destroy(sub);
1317         }
1318         break;
1319
1320     case EXPR_T_BOOLEAN:
1321         break;
1322     }
1323     free(expr);
1324 }
1325 \f
1326 /* Annotation. */
1327
1328 /* An element in a linked list of symbols.
1329  *
1330  * Used to detect when a symbol is being expanded recursively, to allow
1331  * flagging an error. */
1332 struct annotation_nesting {
1333     struct ovs_list node;
1334     const struct expr_symbol *symbol;
1335 };
1336
1337 struct expr *expr_annotate__(struct expr *, const struct shash *symtab,
1338                              struct ovs_list *nesting, char **errorp);
1339
1340 static struct expr *
1341 parse_and_annotate(const char *s, const struct shash *symtab,
1342                    struct ovs_list *nesting, char **errorp)
1343 {
1344     char *error;
1345     struct expr *expr;
1346
1347     expr = expr_parse_string(s, symtab, &error);
1348     if (expr) {
1349         expr = expr_annotate__(expr, symtab, nesting, &error);
1350     }
1351     if (expr) {
1352         *errorp = NULL;
1353     } else {
1354         *errorp = xasprintf("Error parsing expression `%s' encountered as "
1355                             "prerequisite or predicate of initial expression: "
1356                             "%s", s, error);
1357         free(error);
1358     }
1359     return expr;
1360 }
1361
1362 static struct expr *
1363 expr_annotate_cmp(struct expr *expr, const struct shash *symtab,
1364                   struct ovs_list *nesting, char **errorp)
1365 {
1366     const struct expr_symbol *symbol = expr->cmp.symbol;
1367     const struct annotation_nesting *iter;
1368     LIST_FOR_EACH (iter, node, nesting) {
1369         if (iter->symbol == symbol) {
1370             *errorp = xasprintf("Recursive expansion of symbol `%s'.",
1371                                 symbol->name);
1372             expr_destroy(expr);
1373             return NULL;
1374         }
1375     }
1376
1377     struct annotation_nesting an;
1378     an.symbol = symbol;
1379     list_push_back(nesting, &an.node);
1380
1381     struct expr *prereqs = NULL;
1382     if (symbol->prereqs) {
1383         prereqs = parse_and_annotate(symbol->prereqs, symtab, nesting, errorp);
1384         if (!prereqs) {
1385             goto error;
1386         }
1387     }
1388
1389     if (symbol->expansion) {
1390         if (symbol->level == EXPR_L_ORDINAL) {
1391             struct expr_field field;
1392
1393             if (!parse_field_from_string(symbol->expansion, symtab,
1394                                          &field, errorp)) {
1395                 goto error;
1396             }
1397
1398             expr->cmp.symbol = field.symbol;
1399             mf_subvalue_shift(&expr->cmp.value, field.ofs);
1400             mf_subvalue_shift(&expr->cmp.mask, field.ofs);
1401         } else {
1402             struct expr *expansion;
1403
1404             expansion = parse_and_annotate(symbol->expansion, symtab,
1405                                            nesting, errorp);
1406             if (!expansion) {
1407                 goto error;
1408             }
1409
1410             bool positive = (expr->cmp.value.integer & htonll(1)) != 0;
1411             positive ^= expr->cmp.relop == EXPR_R_NE;
1412             if (!positive) {
1413                 expr_not(expansion);
1414             }
1415
1416             expr_destroy(expr);
1417             expr = expansion;
1418         }
1419     }
1420
1421     list_remove(&an.node);
1422     return prereqs ? expr_combine(EXPR_T_AND, expr, prereqs) : expr;
1423
1424 error:
1425     expr_destroy(expr);
1426     expr_destroy(prereqs);
1427     list_remove(&an.node);
1428     return NULL;
1429 }
1430
1431 struct expr *
1432 expr_annotate__(struct expr *expr, const struct shash *symtab,
1433                 struct ovs_list *nesting, char **errorp)
1434 {
1435     switch (expr->type) {
1436     case EXPR_T_CMP:
1437         return expr_annotate_cmp(expr, symtab, nesting, errorp);
1438
1439     case EXPR_T_AND:
1440     case EXPR_T_OR: {
1441         struct expr *sub, *next;
1442
1443         LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1444             list_remove(&sub->node);
1445             struct expr *new_sub = expr_annotate__(sub, symtab,
1446                                                    nesting, errorp);
1447             if (!new_sub) {
1448                 expr_destroy(expr);
1449                 return NULL;
1450             }
1451             expr_insert_andor(expr, next, new_sub);
1452         }
1453         *errorp = NULL;
1454         return expr;
1455     }
1456
1457     case EXPR_T_BOOLEAN:
1458         *errorp = NULL;
1459         return expr;
1460
1461     default:
1462         OVS_NOT_REACHED();
1463     }
1464 }
1465
1466 /* "Annotates" 'expr', which does the following:
1467  *
1468  *     - Applies prerequisites, by locating each comparison operator whose
1469  *       field has a prerequisite and adding a logical AND against those
1470  *       prerequisites.
1471  *
1472  *     - Expands references to subfield symbols, by replacing them by
1473  *       references to their underlying field symbols (suitably shifted).
1474  *
1475  *     - Expands references to predicate symbols, by replacing them by the
1476  *       expressions that they expand to.
1477  *
1478  * In each case, annotation occurs recursively as necessary.
1479  *
1480  * On failure, returns NULL and sets '*errorp' to an explanatory error
1481  * message, which the caller must free. */
1482 struct expr *
1483 expr_annotate(struct expr *expr, const struct shash *symtab, char **errorp)
1484 {
1485     struct ovs_list nesting = OVS_LIST_INITIALIZER(&nesting);
1486     return expr_annotate__(expr, symtab, &nesting, errorp);
1487 }
1488 \f
1489 static struct expr *
1490 expr_simplify_ne(struct expr *expr)
1491 {
1492     struct expr *new = NULL;
1493     const union mf_subvalue *value = &expr->cmp.value;
1494     const union mf_subvalue *mask = &expr->cmp.mask;
1495     int w = expr->cmp.symbol->width;
1496     int i;
1497
1498     for (i = 0; (i = bitwise_scan(mask, sizeof *mask, true, i, w)) < w; i++) {
1499         struct expr *e;
1500
1501         e = xzalloc(sizeof *e);
1502         e->type = EXPR_T_CMP;
1503         e->cmp.symbol = expr->cmp.symbol;
1504         e->cmp.relop = EXPR_R_EQ;
1505         bitwise_put_bit(&e->cmp.value, sizeof e->cmp.value, i,
1506                         !bitwise_get_bit(value, sizeof *value, i));
1507         bitwise_put1(&e->cmp.mask, sizeof e->cmp.mask, i);
1508
1509         new = expr_combine(EXPR_T_OR, new, e);
1510     }
1511     ovs_assert(new);
1512
1513     expr_destroy(expr);
1514
1515     return new;
1516 }
1517
1518 static struct expr *
1519 expr_simplify_relational(struct expr *expr)
1520 {
1521     const union mf_subvalue *value = &expr->cmp.value;
1522     int start, n_bits, end;
1523
1524     find_bitwise_range(&expr->cmp.mask, expr->cmp.symbol->width,
1525                        &start, &n_bits);
1526     ovs_assert(n_bits > 0);
1527     end = start + n_bits;
1528
1529     struct expr *new;
1530     if (expr->cmp.relop == EXPR_R_LE || expr->cmp.relop == EXPR_R_GE) {
1531         new = xmemdup(expr, sizeof *expr);
1532         new->cmp.relop = EXPR_R_EQ;
1533     } else {
1534         new = NULL;
1535     }
1536
1537     bool b = expr->cmp.relop == EXPR_R_LT || expr->cmp.relop == EXPR_R_LE;
1538     for (int z = bitwise_scan(value, sizeof *value, b, start, end);
1539          z < end;
1540          z = bitwise_scan(value, sizeof *value, b, z + 1, end)) {
1541         struct expr *e;
1542
1543         e = xmemdup(expr, sizeof *expr);
1544         e->cmp.relop = EXPR_R_EQ;
1545         bitwise_toggle_bit(&e->cmp.value, sizeof e->cmp.value, z);
1546         bitwise_zero(&e->cmp.value, sizeof e->cmp.value, start, z - start);
1547         bitwise_zero(&e->cmp.mask, sizeof e->cmp.mask, start, z - start);
1548         new = expr_combine(EXPR_T_OR, new, e);
1549     }
1550     expr_destroy(expr);
1551     return new ? new : expr_create_boolean(false);
1552 }
1553
1554 /* Takes ownership of 'expr' and returns an equivalent expression whose
1555  * EXPR_T_CMP nodes use only tests for equality (EXPR_R_EQ). */
1556 struct expr *
1557 expr_simplify(struct expr *expr)
1558 {
1559     struct expr *sub, *next;
1560
1561     switch (expr->type) {
1562     case EXPR_T_CMP:
1563         return (expr->cmp.relop == EXPR_R_EQ || !expr->cmp.symbol->width ? expr
1564                 : expr->cmp.relop == EXPR_R_NE ? expr_simplify_ne(expr)
1565                 : expr_simplify_relational(expr));
1566
1567     case EXPR_T_AND:
1568     case EXPR_T_OR:
1569         LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1570             list_remove(&sub->node);
1571             expr_insert_andor(expr, next, expr_simplify(sub));
1572         }
1573         return expr_fix(expr);
1574
1575     case EXPR_T_BOOLEAN:
1576         return expr;
1577     }
1578     OVS_NOT_REACHED();
1579 }
1580 \f
1581 static const struct expr_symbol *
1582 expr_is_cmp(const struct expr *expr)
1583 {
1584     switch (expr->type) {
1585     case EXPR_T_CMP:
1586         return expr->cmp.symbol;
1587
1588     case EXPR_T_AND:
1589     case EXPR_T_OR: {
1590         const struct expr_symbol *prev = NULL;
1591         struct expr *sub;
1592
1593         LIST_FOR_EACH (sub, node, &expr->andor) {
1594             const struct expr_symbol *symbol = expr_is_cmp(sub);
1595             if (!symbol || (prev && symbol != prev)) {
1596                 return NULL;
1597             }
1598             prev = symbol;
1599         }
1600         return prev;
1601     }
1602
1603     case EXPR_T_BOOLEAN:
1604         return NULL;
1605
1606     default:
1607         OVS_NOT_REACHED();
1608     }
1609 }
1610
1611 struct expr_sort {
1612     struct expr *expr;
1613     const struct expr_symbol *relop;
1614     enum expr_type type;
1615 };
1616
1617 static int
1618 compare_expr_sort(const void *a_, const void *b_)
1619 {
1620     const struct expr_sort *a = a_;
1621     const struct expr_sort *b = b_;
1622
1623     if (a->type != b->type) {
1624         return a->type < b->type ? -1 : 1;
1625     } else if (a->relop) {
1626         int cmp = strcmp(a->relop->name, b->relop->name);
1627         if (cmp) {
1628             return cmp;
1629         }
1630
1631         enum expr_type a_type = a->expr->type;
1632         enum expr_type b_type = a->expr->type;
1633         return a_type < b_type ? -1 : a_type > b_type;
1634     } else if (a->type == EXPR_T_AND || a->type == EXPR_T_OR) {
1635         size_t a_len = list_size(&a->expr->andor);
1636         size_t b_len = list_size(&b->expr->andor);
1637         return a_len < b_len ? -1 : a_len > b_len;
1638     } else {
1639         return 0;
1640     }
1641 }
1642
1643 static struct expr *crush_cmps(struct expr *, const struct expr_symbol *);
1644
1645 static bool
1646 disjunction_matches_string(const struct expr *or, const char *s)
1647 {
1648     const struct expr *sub;
1649
1650     LIST_FOR_EACH (sub, node, &or->andor) {
1651         if (!strcmp(sub->cmp.string, s)) {
1652             return true;
1653         }
1654     }
1655
1656     return false;
1657 }
1658
1659 /* Implementation of crush_cmps() for expr->type == EXPR_T_AND and a
1660  * string-typed 'symbol'. */
1661 static struct expr *
1662 crush_and_string(struct expr *expr, const struct expr_symbol *symbol)
1663 {
1664     ovs_assert(!list_is_short(&expr->andor));
1665
1666     struct expr *singleton = NULL;
1667
1668     /* First crush each subexpression into either a single EXPR_T_CMP or an
1669      * EXPR_T_OR with EXPR_T_CMP subexpressions. */
1670     struct expr *sub, *next = NULL;
1671     LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1672         list_remove(&sub->node);
1673         struct expr *new = crush_cmps(sub, symbol);
1674         switch (new->type) {
1675         case EXPR_T_CMP:
1676             if (!singleton) {
1677                 list_insert(&next->node, &new->node);
1678                 singleton = new;
1679             } else {
1680                 bool match = !strcmp(new->cmp.string, singleton->cmp.string);
1681                 expr_destroy(new);
1682                 if (!match) {
1683                     expr_destroy(expr);
1684                     return expr_create_boolean(false);
1685                 }
1686             }
1687             break;
1688         case EXPR_T_AND:
1689             OVS_NOT_REACHED();
1690         case EXPR_T_OR:
1691             list_insert(&next->node, &new->node);
1692             break;
1693         case EXPR_T_BOOLEAN:
1694             if (!new->boolean) {
1695                 expr_destroy(expr);
1696                 return new;
1697             }
1698             free(new);
1699             break;
1700         }
1701     }
1702
1703     /* If we have a singleton, then the result is either the singleton itself
1704      * (if the ORs allow the singleton) or false. */
1705     if (singleton) {
1706         LIST_FOR_EACH (sub, node, &expr->andor) {
1707             if (sub->type == EXPR_T_OR
1708                 && !disjunction_matches_string(sub, singleton->cmp.string)) {
1709                 expr_destroy(expr);
1710                 return expr_create_boolean(false);
1711             }
1712         }
1713         list_remove(&singleton->node);
1714         expr_destroy(expr);
1715         return singleton;
1716     }
1717
1718     /* Otherwise the result is the intersection of all of the ORs. */
1719     struct sset result = SSET_INITIALIZER(&result);
1720     LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1721         struct sset strings = SSET_INITIALIZER(&strings);
1722         const struct expr *s;
1723         LIST_FOR_EACH (s, node, &sub->andor) {
1724             sset_add(&strings, s->cmp.string);
1725         }
1726         if (sset_is_empty(&result)) {
1727             sset_swap(&result, &strings);
1728         } else {
1729             sset_intersect(&result, &strings);
1730         }
1731         sset_destroy(&strings);
1732
1733         if (sset_is_empty(&result)) {
1734             expr_destroy(expr);
1735             sset_destroy(&result);
1736             return expr_create_boolean(false);
1737         }
1738     }
1739
1740     expr_destroy(expr);
1741     expr = expr_create_andor(EXPR_T_OR);
1742
1743     const char *string;
1744     SSET_FOR_EACH (string, &result) {
1745         sub = xmalloc(sizeof *sub);
1746         sub->type = EXPR_T_CMP;
1747         sub->cmp.symbol = symbol;
1748         sub->cmp.string = xstrdup(string);
1749         list_push_back(&expr->andor, &sub->node);
1750     }
1751     return expr_fix(expr);
1752 }
1753
1754 /* Implementation of crush_cmps() for expr->type == EXPR_T_AND and a
1755  * numeric-typed 'symbol'. */
1756 static struct expr *
1757 crush_and_numeric(struct expr *expr, const struct expr_symbol *symbol)
1758 {
1759     ovs_assert(!list_is_short(&expr->andor));
1760
1761     union mf_subvalue value, mask;
1762     memset(&value, 0, sizeof value);
1763     memset(&mask, 0, sizeof mask);
1764
1765     struct expr *sub, *next = NULL;
1766     LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1767         list_remove(&sub->node);
1768         struct expr *new = crush_cmps(sub, symbol);
1769         switch (new->type) {
1770         case EXPR_T_CMP:
1771             if (!mf_subvalue_intersect(&value, &mask,
1772                                        &new->cmp.value, &new->cmp.mask,
1773                                        &value, &mask)) {
1774                 expr_destroy(new);
1775                 expr_destroy(expr);
1776                 return expr_create_boolean(false);
1777             }
1778             expr_destroy(new);
1779             break;
1780         case EXPR_T_AND:
1781             OVS_NOT_REACHED();
1782         case EXPR_T_OR:
1783             list_insert(&next->node, &new->node);
1784             break;
1785         case EXPR_T_BOOLEAN:
1786             if (!new->boolean) {
1787                 expr_destroy(expr);
1788                 return new;
1789             }
1790             free(new);
1791             break;
1792         }
1793     }
1794     if (list_is_empty(&expr->andor)) {
1795         if (is_all_zeros(&mask, sizeof mask)) {
1796             expr_destroy(expr);
1797             return expr_create_boolean(true);
1798         } else {
1799             struct expr *cmp;
1800             cmp = xmalloc(sizeof *cmp);
1801             cmp->type = EXPR_T_CMP;
1802             cmp->cmp.symbol = symbol;
1803             cmp->cmp.relop = EXPR_R_EQ;
1804             cmp->cmp.value = value;
1805             cmp->cmp.mask = mask;
1806             expr_destroy(expr);
1807             return cmp;
1808         }
1809     } else if (list_is_short(&expr->andor)) {
1810         /* Transform "a && (b || c || d)" into "ab || ac || ad" where "ab" is
1811          * computed as "a && b", etc. */
1812         struct expr *disjuncts = expr_from_node(list_pop_front(&expr->andor));
1813         struct expr *or;
1814
1815         or = xmalloc(sizeof *or);
1816         or->type = EXPR_T_OR;
1817         list_init(&or->andor);
1818
1819         ovs_assert(disjuncts->type == EXPR_T_OR);
1820         LIST_FOR_EACH_SAFE (sub, next, node, &disjuncts->andor) {
1821             ovs_assert(sub->type == EXPR_T_CMP);
1822             list_remove(&sub->node);
1823             if (mf_subvalue_intersect(&value, &mask,
1824                                       &sub->cmp.value, &sub->cmp.mask,
1825                                       &sub->cmp.value, &sub->cmp.mask)) {
1826                 list_push_back(&or->andor, &sub->node);
1827             } else {
1828                 free(sub);
1829             }
1830         }
1831         free(disjuncts);
1832         free(expr);
1833         if (list_is_empty(&or->andor)) {
1834             free(or);
1835             return expr_create_boolean(false);
1836         } else if (list_is_short(&or->andor)) {
1837             struct expr *cmp = expr_from_node(list_pop_front(&or->andor));
1838             free(or);
1839             return cmp;
1840         } else {
1841             return or;
1842         }
1843     } else {
1844         /* Transform "x && (a0 || a1) && (b0 || b1) && ..." into
1845          *           "(xa0b0 || xa0b1 || xa1b0 || xa1b1) && ...". */
1846         struct expr *as = expr_from_node(list_pop_front(&expr->andor));
1847         struct expr *bs = expr_from_node(list_pop_front(&expr->andor));
1848         struct expr *new = NULL;
1849         struct expr *or;
1850
1851         or = xmalloc(sizeof *or);
1852         or->type = EXPR_T_OR;
1853         list_init(&or->andor);
1854
1855         struct expr *a;
1856         LIST_FOR_EACH (a, node, &as->andor) {
1857             union mf_subvalue a_value, a_mask;
1858
1859             ovs_assert(a->type == EXPR_T_CMP);
1860             if (!mf_subvalue_intersect(&value, &mask,
1861                                        &a->cmp.value, &a->cmp.mask,
1862                                        &a_value, &a_mask)) {
1863                 continue;
1864             }
1865
1866             struct expr *b;
1867             LIST_FOR_EACH (b, node, &bs->andor) {
1868                 ovs_assert(b->type == EXPR_T_CMP);
1869                 if (!new) {
1870                     new = xmalloc(sizeof *new);
1871                     new->type = EXPR_T_CMP;
1872                     new->cmp.symbol = symbol;
1873                     new->cmp.relop = EXPR_R_EQ;
1874                 }
1875                 if (mf_subvalue_intersect(&a_value, &a_mask,
1876                                           &b->cmp.value, &b->cmp.mask,
1877                                           &new->cmp.value, &new->cmp.mask)) {
1878                     list_push_back(&or->andor, &new->node);
1879                     new = NULL;
1880                 }
1881             }
1882         }
1883         expr_destroy(as);
1884         expr_destroy(bs);
1885         free(new);
1886
1887         if (list_is_empty(&or->andor)) {
1888             expr_destroy(expr);
1889             free(or);
1890             return expr_create_boolean(false);
1891         } else if (list_is_short(&or->andor)) {
1892             struct expr *cmp = expr_from_node(list_pop_front(&or->andor));
1893             free(or);
1894             if (list_is_empty(&expr->andor)) {
1895                 expr_destroy(expr);
1896                 return crush_cmps(cmp, symbol);
1897             } else {
1898                 return crush_cmps(expr_combine(EXPR_T_AND, cmp, expr), symbol);
1899             }
1900         } else if (!list_is_empty(&expr->andor)) {
1901             struct expr *e = expr_combine(EXPR_T_AND, or, expr);
1902             ovs_assert(!list_is_short(&e->andor));
1903             return crush_cmps(e, symbol);
1904         } else {
1905             expr_destroy(expr);
1906             return crush_cmps(or, symbol);
1907         }
1908     }
1909 }
1910
1911 static int
1912 compare_cmps_3way(const struct expr *a, const struct expr *b)
1913 {
1914     ovs_assert(a->cmp.symbol == b->cmp.symbol);
1915     if (!a->cmp.symbol->width) {
1916         return strcmp(a->cmp.string, b->cmp.string);
1917     } else {
1918         int d = memcmp(&a->cmp.value, &b->cmp.value, sizeof a->cmp.value);
1919         if (!d) {
1920             d = memcmp(&a->cmp.mask, &b->cmp.mask, sizeof a->cmp.mask);
1921         }
1922         return d;
1923     }
1924 }
1925
1926 static int
1927 compare_cmps_cb(const void *a_, const void *b_)
1928 {
1929     const struct expr *const *ap = a_;
1930     const struct expr *const *bp = b_;
1931     const struct expr *a = *ap;
1932     const struct expr *b = *bp;
1933     return compare_cmps_3way(a, b);
1934 }
1935
1936 /* Implementation of crush_cmps() for expr->type == EXPR_T_OR. */
1937 static struct expr *
1938 crush_or(struct expr *expr, const struct expr_symbol *symbol)
1939 {
1940     struct expr *sub, *next = NULL;
1941
1942     /* First, crush all the subexpressions.  That might eliminate the
1943      * OR-expression entirely; if so, return the result.  Otherwise, 'expr'
1944      * is now a disjunction of cmps over the same symbol. */
1945     LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1946         list_remove(&sub->node);
1947         expr_insert_andor(expr, next, crush_cmps(sub, symbol));
1948     }
1949     expr = expr_fix(expr);
1950     if (expr->type != EXPR_T_OR) {
1951         return expr;
1952     }
1953
1954     /* Sort subexpressions by value and mask, to bring together duplicates. */
1955     size_t n = list_size(&expr->andor);
1956     struct expr **subs = xmalloc(n * sizeof *subs);
1957
1958     size_t i = 0;
1959     LIST_FOR_EACH (sub, node, &expr->andor) {
1960         subs[i++] = sub;
1961     }
1962     ovs_assert(i == n);
1963
1964     qsort(subs, n, sizeof *subs, compare_cmps_cb);
1965
1966     /* Eliminate duplicates. */
1967     list_init(&expr->andor);
1968     list_push_back(&expr->andor, &subs[0]->node);
1969     for (i = 1; i < n; i++) {
1970         struct expr *a = expr_from_node(list_back(&expr->andor));
1971         struct expr *b = subs[i];
1972         if (compare_cmps_3way(a, b)) {
1973             list_push_back(&expr->andor, &b->node);
1974         } else {
1975             free(b);
1976         }
1977     }
1978     free(subs);
1979     return expr_fix(expr);
1980 }
1981
1982 /* Takes ownership of 'expr', which must be a cmp in the sense determined by
1983  * 'expr_is_cmp(expr)', where 'symbol' is the symbol returned by that function.
1984  * Returns an equivalent expression owned by the caller that is a single
1985  * EXPR_T_CMP or a disjunction of them or a EXPR_T_BOOLEAN. */
1986 static struct expr *
1987 crush_cmps(struct expr *expr, const struct expr_symbol *symbol)
1988 {
1989     switch (expr->type) {
1990     case EXPR_T_OR:
1991         return crush_or(expr, symbol);
1992
1993     case EXPR_T_AND:
1994         return (symbol->width
1995                 ? crush_and_numeric(expr, symbol)
1996                 : crush_and_string(expr, symbol));
1997
1998     case EXPR_T_CMP:
1999         return expr;
2000
2001     case EXPR_T_BOOLEAN:
2002         return expr;
2003
2004     default:
2005         OVS_NOT_REACHED();
2006     }
2007 }
2008
2009 static struct expr *
2010 expr_sort(struct expr *expr)
2011 {
2012     size_t n = list_size(&expr->andor);
2013     struct expr_sort *subs = xmalloc(n * sizeof *subs);
2014     struct expr *sub;
2015     size_t i;
2016
2017     i = 0;
2018     LIST_FOR_EACH (sub, node, &expr->andor) {
2019         subs[i].expr = sub;
2020         subs[i].relop = expr_is_cmp(sub);
2021         subs[i].type = subs[i].relop ? EXPR_T_CMP : sub->type;
2022         i++;
2023     }
2024     ovs_assert(i == n);
2025
2026     qsort(subs, n, sizeof *subs, compare_expr_sort);
2027
2028     list_init(&expr->andor);
2029     for (int i = 0; i < n; ) {
2030         if (subs[i].relop) {
2031             int j;
2032             for (j = i + 1; j < n; j++) {
2033                 if (subs[i].relop != subs[j].relop) {
2034                     break;
2035                 }
2036             }
2037
2038             struct expr *crushed;
2039             if (j == i + 1) {
2040                 crushed = crush_cmps(subs[i].expr, subs[i].relop);
2041             } else {
2042                 struct expr *combined = subs[i].expr;
2043                 for (int k = i + 1; k < j; k++) {
2044                     combined = expr_combine(EXPR_T_AND, combined,
2045                                             subs[k].expr);
2046                 }
2047                 ovs_assert(!list_is_short(&combined->andor));
2048                 crushed = crush_cmps(combined, subs[i].relop);
2049             }
2050             if (crushed->type == EXPR_T_BOOLEAN) {
2051                 if (!crushed->boolean) {
2052                     for (int k = j; k < n; k++) {
2053                         expr_destroy(subs[k].expr);
2054                     }
2055                     expr_destroy(expr);
2056                     expr = crushed;
2057                     break;
2058                 } else {
2059                     free(crushed);
2060                 }
2061             } else {
2062                 expr = expr_combine(EXPR_T_AND, expr, crushed);
2063             }
2064             i = j;
2065         } else {
2066             expr = expr_combine(EXPR_T_AND, expr, subs[i++].expr);
2067         }
2068     }
2069     free(subs);
2070
2071     return expr;
2072 }
2073
2074 static struct expr *expr_normalize_or(struct expr *expr);
2075
2076 /* Returns 'expr', which is an AND, reduced to OR(AND(clause)) where
2077  * a clause is a cmp or a disjunction of cmps on a single field. */
2078 static struct expr *
2079 expr_normalize_and(struct expr *expr)
2080 {
2081     ovs_assert(expr->type == EXPR_T_AND);
2082
2083     expr = expr_sort(expr);
2084     if (expr->type != EXPR_T_AND) {
2085         ovs_assert(expr->type == EXPR_T_BOOLEAN);
2086         return expr;
2087     }
2088
2089     struct expr *a, *b;
2090     LIST_FOR_EACH_SAFE (a, b, node, &expr->andor) {
2091         if (&b->node == &expr->andor
2092             || a->type != EXPR_T_CMP || b->type != EXPR_T_CMP
2093             || a->cmp.symbol != b->cmp.symbol) {
2094             continue;
2095         } else if (a->cmp.symbol->width
2096                    ? mf_subvalue_intersect(&a->cmp.value, &a->cmp.mask,
2097                                            &b->cmp.value, &b->cmp.mask,
2098                                            &b->cmp.value, &b->cmp.mask)
2099                    : !strcmp(a->cmp.string, b->cmp.string)) {
2100             list_remove(&a->node);
2101             expr_destroy(a);
2102         } else {
2103             expr_destroy(expr);
2104             return expr_create_boolean(false);
2105         }
2106     }
2107     if (list_is_short(&expr->andor)) {
2108         struct expr *sub = expr_from_node(list_front(&expr->andor));
2109         free(expr);
2110         return sub;
2111     }
2112
2113     struct expr *sub;
2114     LIST_FOR_EACH (sub, node, &expr->andor) {
2115         if (sub->type == EXPR_T_CMP) {
2116             continue;
2117         }
2118
2119         ovs_assert(sub->type == EXPR_T_OR);
2120         const struct expr_symbol *symbol = expr_is_cmp(sub);
2121         if (!symbol || symbol->must_crossproduct) {
2122             struct expr *or = expr_create_andor(EXPR_T_OR);
2123             struct expr *k;
2124
2125             LIST_FOR_EACH (k, node, &sub->andor) {
2126                 struct expr *and = expr_create_andor(EXPR_T_AND);
2127                 struct expr *m;
2128
2129                 LIST_FOR_EACH (m, node, &expr->andor) {
2130                     struct expr *term = m == sub ? k : m;
2131                     if (term->type == EXPR_T_AND) {
2132                         struct expr *p;
2133
2134                         LIST_FOR_EACH (p, node, &term->andor) {
2135                             struct expr *new = expr_clone(p);
2136                             list_push_back(&and->andor, &new->node);
2137                         }
2138                     } else {
2139                         struct expr *new = expr_clone(term);
2140                         list_push_back(&and->andor, &new->node);
2141                     }
2142                 }
2143                 list_push_back(&or->andor, &and->node);
2144             }
2145             expr_destroy(expr);
2146             return expr_normalize_or(or);
2147         }
2148     }
2149     return expr;
2150 }
2151
2152 static struct expr *
2153 expr_normalize_or(struct expr *expr)
2154 {
2155     struct expr *sub, *next;
2156
2157     LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
2158         if (sub->type == EXPR_T_AND) {
2159             list_remove(&sub->node);
2160
2161             struct expr *new = expr_normalize_and(sub);
2162             if (new->type == EXPR_T_BOOLEAN) {
2163                 if (new->boolean) {
2164                     expr_destroy(expr);
2165                     return new;
2166                 }
2167                 free(new);
2168             } else {
2169                 expr_insert_andor(expr, next, new);
2170             }
2171         } else {
2172             ovs_assert(sub->type == EXPR_T_CMP);
2173         }
2174     }
2175     if (list_is_empty(&expr->andor)) {
2176         free(expr);
2177         return expr_create_boolean(false);
2178     }
2179     if (list_is_short(&expr->andor)) {
2180         struct expr *sub = expr_from_node(list_pop_front(&expr->andor));
2181         free(expr);
2182         return sub;
2183     }
2184
2185     return expr;
2186 }
2187
2188 /* Takes ownership of 'expr', which is either a constant "true" or "false" or
2189  * an expression in terms of only relationals, AND, and OR.  Returns either a
2190  * constant "true" or "false" or 'expr' reduced to OR(AND(clause)) where a
2191  * clause is a cmp or a disjunction of cmps on a single field.  This form is
2192  * significant because it is a form that can be directly converted to OpenFlow
2193  * flows with the Open vSwitch "conjunctive match" extension.
2194  *
2195  * 'expr' must already have been simplified, with expr_simplify(). */
2196 struct expr *
2197 expr_normalize(struct expr *expr)
2198 {
2199     switch (expr->type) {
2200     case EXPR_T_CMP:
2201         return expr;
2202
2203     case EXPR_T_AND:
2204         return expr_normalize_and(expr);
2205
2206     case EXPR_T_OR:
2207         return expr_normalize_or(expr);
2208
2209     case EXPR_T_BOOLEAN:
2210         return expr;
2211     }
2212     OVS_NOT_REACHED();
2213 }
2214 \f
2215 /* Creates, initializes, and returns a new 'struct expr_match'.  If 'm' is
2216  * nonnull then it is copied into the new expr_match, otherwise the new
2217  * expr_match's 'match' member is initialized to a catch-all match for the
2218  * caller to refine in-place.
2219  *
2220  * If 'conj_id' is nonzero, adds one conjunction based on 'conj_id', 'clause',
2221  * and 'n_clauses' to the returned 'struct expr_match', otherwise the
2222  * expr_match will not have any conjunctions.
2223  *
2224  * The caller should use expr_match_add() to add the expr_match to a hash table
2225  * after it is finalized. */
2226 static struct expr_match *
2227 expr_match_new(const struct match *m, uint8_t clause, uint8_t n_clauses,
2228                uint32_t conj_id)
2229 {
2230     struct expr_match *match = xmalloc(sizeof *match);
2231     if (m) {
2232         match->match = *m;
2233     } else {
2234         match_init_catchall(&match->match);
2235     }
2236     if (conj_id) {
2237         match->conjunctions = xmalloc(sizeof *match->conjunctions);
2238         match->conjunctions[0].id = conj_id;
2239         match->conjunctions[0].clause = clause;
2240         match->conjunctions[0].n_clauses = n_clauses;
2241         match->n = 1;
2242         match->allocated = 1;
2243     } else {
2244         match->conjunctions = NULL;
2245         match->n = 0;
2246         match->allocated = 0;
2247     }
2248     return match;
2249 }
2250
2251 /* Adds 'match' to hash table 'matches', which becomes the new owner of
2252  * 'match'.
2253  *
2254  * This might actually destroy 'match' because it gets merged together with
2255  * some existing conjunction.*/
2256 static void
2257 expr_match_add(struct hmap *matches, struct expr_match *match)
2258 {
2259     uint32_t hash = match_hash(&match->match, 0);
2260     struct expr_match *m;
2261
2262     HMAP_FOR_EACH_WITH_HASH (m, hmap_node, hash, matches) {
2263         if (match_equal(&m->match, &match->match)) {
2264             if (!m->n || !match->n) {
2265                 free(m->conjunctions);
2266                 m->conjunctions = NULL;
2267                 m->n = 0;
2268                 m->allocated = 0;
2269             } else {
2270                 ovs_assert(match->n == 1);
2271                 if (m->n >= m->allocated) {
2272                     m->conjunctions = x2nrealloc(m->conjunctions,
2273                                                  &m->allocated,
2274                                                  sizeof *m->conjunctions);
2275                 }
2276                 m->conjunctions[m->n++] = match->conjunctions[0];
2277             }
2278             free(match->conjunctions);
2279             free(match);
2280             return;
2281         }
2282     }
2283
2284     hmap_insert(matches, &match->hmap_node, hash);
2285 }
2286
2287 static bool
2288 constrain_match(const struct expr *expr, const struct simap *ports,
2289                 struct match *m)
2290 {
2291     ovs_assert(expr->type == EXPR_T_CMP);
2292     if (expr->cmp.symbol->width) {
2293         mf_mask_subfield(expr->cmp.symbol->field, &expr->cmp.value,
2294                          &expr->cmp.mask, m);
2295     } else {
2296         const struct simap_node *node;
2297         node = ports ? simap_find(ports, expr->cmp.string) : NULL;
2298         if (!node) {
2299             return false;
2300         }
2301
2302         struct mf_subfield sf;
2303         sf.field = expr->cmp.symbol->field;
2304         sf.ofs = 0;
2305         sf.n_bits = expr->cmp.symbol->field->n_bits;
2306
2307         union mf_subvalue x;
2308         memset(&x, 0, sizeof x);
2309         x.integer = htonll(node->data);
2310
2311         mf_write_subfield(&sf, &x, m);
2312     }
2313     return true;
2314 }
2315
2316 static bool
2317 add_disjunction(const struct expr *or, const struct simap *ports,
2318                 struct match *m, uint8_t clause, uint8_t n_clauses,
2319                 uint32_t conj_id, struct hmap *matches)
2320 {
2321     struct expr *sub;
2322     int n = 0;
2323
2324     ovs_assert(or->type == EXPR_T_OR);
2325     LIST_FOR_EACH (sub, node, &or->andor) {
2326         struct expr_match *match = expr_match_new(m, clause, n_clauses,
2327                                                   conj_id);
2328         if (constrain_match(sub, ports, &match->match)) {
2329             expr_match_add(matches, match);
2330             n++;
2331         } else {
2332             free(match->conjunctions);
2333             free(match);
2334         }
2335     }
2336
2337     /* If n == 1, then this didn't really need to be a disjunction.  Oh well,
2338      * that shouldn't happen much. */
2339     return n > 0;
2340 }
2341
2342 static void
2343 add_conjunction(const struct expr *and, const struct simap *ports,
2344                 uint32_t *n_conjsp, struct hmap *matches)
2345 {
2346     struct match match;
2347     int n_clauses = 0;
2348     struct expr *sub;
2349
2350     match_init_catchall(&match);
2351
2352     ovs_assert(and->type == EXPR_T_AND);
2353     LIST_FOR_EACH (sub, node, &and->andor) {
2354         switch (sub->type) {
2355         case EXPR_T_CMP:
2356             if (!constrain_match(sub, ports, &match)) {
2357                 return;
2358             }
2359             break;
2360         case EXPR_T_OR:
2361             n_clauses++;
2362             break;
2363         case EXPR_T_AND:
2364         case EXPR_T_BOOLEAN:
2365             OVS_NOT_REACHED();
2366         }
2367     }
2368
2369     if (!n_clauses) {
2370         expr_match_add(matches, expr_match_new(&match, 0, 0, 0));
2371     } else if (n_clauses == 1) {
2372         LIST_FOR_EACH (sub, node, &and->andor) {
2373             if (sub->type == EXPR_T_OR) {
2374                 add_disjunction(sub, ports, &match, 0, 0, 0, matches);
2375             }
2376         }
2377     } else {
2378         int clause = 0;
2379         (*n_conjsp)++;
2380         LIST_FOR_EACH (sub, node, &and->andor) {
2381             if (sub->type == EXPR_T_OR) {
2382                 if (!add_disjunction(sub, ports, &match, clause++,
2383                                      n_clauses, *n_conjsp, matches)) {
2384                     /* This clause can't ever match, so we might as well skip
2385                      * adding the other clauses--the overall disjunctive flow
2386                      * can't ever match.  Ideally we would also back out all of
2387                      * the clauses we already added, but that seems like a lot
2388                      * of trouble for a case that might never occur in
2389                      * practice. */
2390                     return;
2391                 }
2392             }
2393         }
2394
2395         /* Add the flow that matches on conj_id. */
2396         match_set_conj_id(&match, *n_conjsp);
2397         expr_match_add(matches, expr_match_new(&match, 0, 0, 0));
2398     }
2399 }
2400
2401 static void
2402 add_cmp_flow(const struct expr *cmp, const struct simap *ports,
2403              struct hmap *matches)
2404 {
2405     struct expr_match *m = expr_match_new(NULL, 0, 0, 0);
2406     if (constrain_match(cmp, ports, &m->match)) {
2407         expr_match_add(matches, m);
2408     } else {
2409         free(m);
2410     }
2411 }
2412
2413 /* Converts 'expr', which must be in the form returned by expr_normalize(), to
2414  * a collection of Open vSwitch flows in 'matches', which this function
2415  * initializes to an hmap of "struct expr_match" structures.  Returns the
2416  * number of conjunctive match IDs consumed by 'matches', which uses
2417  * conjunctive match IDs beginning with 0; the caller must offset or remap them
2418  * into the desired range as necessary.
2419  *
2420  * The matches inserted into 'matches' will be of three distinct kinds:
2421  *
2422  *     - Ordinary flows.  The caller should add these OpenFlow flows with
2423  *       its desired actions.
2424  *
2425  *     - Conjunctive flows, distinguished by 'n > 0' in the expr_match
2426  *       structure.  The caller should add these OpenFlow flows with the
2427  *       conjunction(id, k/n) actions as specified in the 'conjunctions' array,
2428  *       remapping the ids.
2429  *
2430  *     - conj_id flows, distinguished by matching on the "conj_id" field.  The
2431  *       caller should remap the conj_id and add the OpenFlow flow with its
2432  *       desired actions.
2433  *
2434  * 'ports' must be a map from strings (presumably names of ports) to integers.
2435  * Any comparisons against string fields in 'expr' are translated into integers
2436  * through this map.  A comparison against a string that is not in 'ports' acts
2437  * like a Boolean "false"; that is, it will always fail to match.  For a simple
2438  * expression, this means that the overall expression always fails to match,
2439  * but an expression with a disjunction on the string field might still match
2440  * on other port names.
2441  *
2442  * (This treatment of string fields might be too simplistic in general, but it
2443  * seems reasonable for now when string fields are used only for ports.) */
2444 uint32_t
2445 expr_to_matches(const struct expr *expr, const struct simap *ports,
2446                 struct hmap *matches)
2447 {
2448     uint32_t n_conjs = 0;
2449
2450     hmap_init(matches);
2451     switch (expr->type) {
2452     case EXPR_T_CMP:
2453         add_cmp_flow(expr, ports, matches);
2454         break;
2455
2456     case EXPR_T_AND:
2457         add_conjunction(expr, ports, &n_conjs, matches);
2458         break;
2459
2460     case EXPR_T_OR:
2461         if (expr_is_cmp(expr)) {
2462             struct expr *sub;
2463
2464             LIST_FOR_EACH (sub, node, &expr->andor) {
2465                 add_cmp_flow(sub, ports, matches);
2466             }
2467         } else {
2468             struct expr *sub;
2469
2470             LIST_FOR_EACH (sub, node, &expr->andor) {
2471                 if (sub->type == EXPR_T_AND) {
2472                     add_conjunction(sub, ports, &n_conjs, matches);
2473                 } else {
2474                     add_cmp_flow(sub, ports, matches);
2475                 }
2476             }
2477         }
2478         break;
2479
2480     case EXPR_T_BOOLEAN:
2481         if (expr->boolean) {
2482             struct expr_match *m = expr_match_new(NULL, 0, 0, 0);
2483             expr_match_add(matches, m);
2484         } else {
2485             /* No match. */
2486         }
2487         break;
2488     }
2489     return n_conjs;
2490 }
2491
2492 /* Destroys all of the 'struct expr_match'es in 'matches', as well as the
2493  * 'matches' hmap itself. */
2494 void
2495 expr_matches_destroy(struct hmap *matches)
2496 {
2497     struct expr_match *m, *n;
2498
2499     HMAP_FOR_EACH_SAFE (m, n, hmap_node, matches) {
2500         hmap_remove(matches, &m->hmap_node);
2501         free(m->conjunctions);
2502         free(m);
2503     }
2504     hmap_destroy(matches);
2505 }
2506
2507 /* Prints a representation of the 'struct expr_match'es in 'matches' to
2508  * 'stream'. */
2509 void
2510 expr_matches_print(const struct hmap *matches, FILE *stream)
2511 {
2512     if (hmap_is_empty(matches)) {
2513         fputs("(no flows)\n", stream);
2514         return;
2515     }
2516
2517     const struct expr_match *m;
2518     HMAP_FOR_EACH (m, hmap_node, matches) {
2519         char *s = match_to_string(&m->match, OFP_DEFAULT_PRIORITY);
2520         fputs(s, stream);
2521         free(s);
2522
2523         if (m->n) {
2524             for (int i = 0; i < m->n; i++) {
2525                 const struct cls_conjunction *c = &m->conjunctions[i];
2526                 fprintf(stream, "%c conjunction(%"PRIu32", %d/%d)",
2527                         i == 0 ? ':' : ',', c->id, c->clause, c->n_clauses);
2528             }
2529         }
2530         putc('\n', stream);
2531     }
2532 }
2533 \f
2534 /* Returns true if 'expr' honors the invariants for expressions (see the large
2535  * comment above "struct expr" in expr.h), false otherwise. */
2536 bool
2537 expr_honors_invariants(const struct expr *expr)
2538 {
2539     const struct expr *sub;
2540
2541     switch (expr->type) {
2542     case EXPR_T_CMP:
2543         if (expr->cmp.symbol->width) {
2544             for (int i = 0; i < ARRAY_SIZE(expr->cmp.value.be64); i++) {
2545                 if (expr->cmp.value.be64[i] & ~expr->cmp.mask.be64[i]) {
2546                     return false;
2547                 }
2548             }
2549         }
2550         return true;
2551
2552     case EXPR_T_AND:
2553     case EXPR_T_OR:
2554         if (list_is_short(&expr->andor)) {
2555             return false;
2556         }
2557         LIST_FOR_EACH (sub, node, &expr->andor) {
2558             if (sub->type == expr->type || !expr_honors_invariants(sub)) {
2559                 return false;
2560             }
2561         }
2562         return true;
2563
2564     case EXPR_T_BOOLEAN:
2565         return true;
2566
2567     default:
2568         OVS_NOT_REACHED();
2569     }
2570 }
2571
2572 static bool
2573 expr_is_normalized_and(const struct expr *expr)
2574 {
2575     /* XXX should also check that no symbol is repeated. */
2576     const struct expr *sub;
2577
2578     LIST_FOR_EACH (sub, node, &expr->andor) {
2579         if (!expr_is_cmp(sub)) {
2580             return false;
2581         }
2582     }
2583     return true;
2584 }
2585
2586 /* Returns true if 'expr' is in the form returned by expr_normalize(), false
2587  * otherwise. */
2588 bool
2589 expr_is_normalized(const struct expr *expr)
2590 {
2591     switch (expr->type) {
2592     case EXPR_T_CMP:
2593         return true;
2594
2595     case EXPR_T_AND:
2596         return expr_is_normalized_and(expr);
2597
2598     case EXPR_T_OR:
2599         if (!expr_is_cmp(expr)) {
2600             const struct expr *sub;
2601
2602             LIST_FOR_EACH (sub, node, &expr->andor) {
2603                 if (!expr_is_cmp(sub) && !expr_is_normalized_and(sub)) {
2604                     return false;
2605                 }
2606             }
2607         }
2608         return true;
2609
2610     case EXPR_T_BOOLEAN:
2611         return true;
2612
2613     default:
2614         OVS_NOT_REACHED();
2615     }
2616 }
2617 \f
2618 /* Action parsing helper. */
2619
2620 /* Expands 'f' repeatedly as long as it has an expansion, that is, as long as
2621  * it is a subfield or a predicate.  Adds any prerequisites for 'f' to
2622  * '*prereqs'.
2623  *
2624  * If 'rw', verifies that 'f' is a read/write field.
2625  *
2626  * 'exchange' should be true if an exchange action is being parsed.  This is
2627  * only used to improve error message phrasing.
2628  *
2629  * Returns true if successful, false if an error was encountered (in which case
2630  * 'ctx->error' reports the particular error). */
2631 static bool
2632 expand_symbol(struct expr_context *ctx, bool rw, bool exchange,
2633               struct expr_field *f, struct expr **prereqsp)
2634 {
2635     const struct expr_symbol *orig_symbol = f->symbol;
2636
2637     if (f->symbol->expansion && f->symbol->level != EXPR_L_ORDINAL) {
2638         expr_error(ctx, "Predicate symbol %s cannot be used in %s.",
2639                    f->symbol->name, exchange ? "exchange" : "assignment");
2640         return false;
2641     }
2642
2643     for (;;) {
2644         /* Accumulate prerequisites. */
2645         if (f->symbol->prereqs) {
2646             struct ovs_list nesting = OVS_LIST_INITIALIZER(&nesting);
2647             char *error;
2648             struct expr *e;
2649             e = parse_and_annotate(f->symbol->prereqs, ctx->symtab, &nesting,
2650                                    &error);
2651             if (error) {
2652                 expr_error(ctx, "%s", error);
2653                 free(error);
2654                 return false;
2655             }
2656             *prereqsp = expr_combine(EXPR_T_AND, *prereqsp, e);
2657         }
2658
2659         /* If there's no expansion, we're done. */
2660         if (!f->symbol->expansion) {
2661             break;
2662         }
2663
2664         /* Expand. */
2665         struct expr_field expansion;
2666         char *error;
2667         if (!parse_field_from_string(f->symbol->expansion, ctx->symtab,
2668                                      &expansion, &error)) {
2669             expr_error(ctx, "%s", error);
2670             free(error);
2671             return false;
2672         }
2673         f->symbol = expansion.symbol;
2674         f->ofs += expansion.ofs;
2675     }
2676
2677     if (rw && !f->symbol->field->writable) {
2678         expr_error(ctx, "Field %s is not modifiable.", orig_symbol->name);
2679         return false;
2680     }
2681
2682     return true;
2683 }
2684
2685 static void
2686 mf_subfield_from_expr_field(const struct expr_field *f, struct mf_subfield *sf)
2687 {
2688     sf->field = f->symbol->field;
2689     sf->ofs = f->ofs;
2690     sf->n_bits = f->n_bits ? f->n_bits : f->symbol->field->n_bits;
2691 }
2692
2693 static void
2694 init_stack_action(const struct expr_field *f, struct ofpact_stack *stack)
2695 {
2696     mf_subfield_from_expr_field(f, &stack->subfield);
2697 }
2698
2699 static struct expr *
2700 parse_assignment(struct expr_context *ctx, const struct simap *ports,
2701                  struct ofpbuf *ofpacts)
2702 {
2703     struct expr *prereqs = NULL;
2704
2705     /* Parse destination and do basic checking. */
2706     struct expr_field dst;
2707     if (!parse_field(ctx, &dst)) {
2708         goto exit;
2709     }
2710     bool exchange = lexer_match(ctx->lexer, LEX_T_EXCHANGE);
2711     if (!exchange && !lexer_match(ctx->lexer, LEX_T_EQUALS)) {
2712         expr_syntax_error(ctx, "expecting `='.");
2713         goto exit;
2714     }
2715     const struct expr_symbol *orig_dst = dst.symbol;
2716     if (!expand_symbol(ctx, true, exchange, &dst, &prereqs)) {
2717         goto exit;
2718     }
2719
2720     if (exchange || ctx->lexer->token.type == LEX_T_ID) {
2721         struct expr_field src;
2722         if (!parse_field(ctx, &src)) {
2723             goto exit;
2724         }
2725         const struct expr_symbol *orig_src = src.symbol;
2726         if (!expand_symbol(ctx, exchange, exchange, &src, &prereqs)) {
2727             goto exit;
2728         }
2729
2730         if ((dst.symbol->width != 0) != (src.symbol->width != 0)) {
2731             if (exchange) {
2732                 expr_error(ctx,
2733                            "Can't exchange %s field (%s) with %s field (%s).",
2734                            orig_dst->width ? "integer" : "string",
2735                            orig_dst->name,
2736                            orig_src->width ? "integer" : "string",
2737                            orig_src->name);
2738             } else {
2739                 expr_error(ctx, "Can't assign %s field (%s) to %s field (%s).",
2740                            orig_src->width ? "integer" : "string",
2741                            orig_src->name,
2742                            orig_dst->width ? "integer" : "string",
2743                            orig_dst->name);
2744             }
2745             goto exit;
2746         }
2747
2748         if (dst.n_bits != src.n_bits) {
2749             if (exchange) {
2750                 expr_error(ctx,
2751                            "Can't exchange %d-bit field with %d-bit field.",
2752                            dst.n_bits, src.n_bits);
2753             } else {
2754                 expr_error(ctx,
2755                            "Can't assign %d-bit value to %d-bit destination.",
2756                            src.n_bits, dst.n_bits);
2757             }
2758             goto exit;
2759         } else if (!dst.n_bits
2760                    && dst.symbol->field->n_bits != src.symbol->field->n_bits) {
2761             expr_error(ctx, "String fields %s and %s are incompatible for "
2762                        "%s.", orig_dst->name, orig_src->name,
2763                        exchange ? "exchange" : "assignment");
2764             goto exit;
2765         }
2766
2767         if (exchange) {
2768             init_stack_action(&src, ofpact_put_STACK_PUSH(ofpacts));
2769             init_stack_action(&dst, ofpact_put_STACK_PUSH(ofpacts));
2770             init_stack_action(&src, ofpact_put_STACK_POP(ofpacts));
2771             init_stack_action(&dst, ofpact_put_STACK_POP(ofpacts));
2772         } else {
2773             struct ofpact_reg_move *move = ofpact_put_REG_MOVE(ofpacts);
2774             mf_subfield_from_expr_field(&src, &move->src);
2775             mf_subfield_from_expr_field(&dst, &move->dst);
2776         }
2777     } else {
2778         struct expr_constant_set cs;
2779         if (!parse_constant_set(ctx, &cs)) {
2780             goto exit;
2781         }
2782
2783         if (!type_check(ctx, &dst, &cs)) {
2784             goto exit_destroy_cs;
2785         }
2786         if (cs.in_curlies) {
2787             expr_error(ctx, "Assignments require a single value.");
2788             goto exit_destroy_cs;
2789         }
2790
2791         union expr_constant *c = cs.values;
2792         struct ofpact_set_field *sf = ofpact_put_SET_FIELD(ofpacts);
2793         sf->field = dst.symbol->field;
2794         if (dst.symbol->width) {
2795             mf_subvalue_shift(&c->value, dst.ofs);
2796             if (!c->masked) {
2797                 memset(&c->mask, 0, sizeof c->mask);
2798                 bitwise_one(&c->mask, sizeof c->mask, dst.ofs, dst.n_bits);
2799             } else {
2800                 mf_subvalue_shift(&c->mask, dst.ofs);
2801             }
2802
2803             memcpy(&sf->value,
2804                    &c->value.u8[sizeof c->value - sf->field->n_bytes],
2805                    sf->field->n_bytes);
2806             memcpy(&sf->mask,
2807                    &c->mask.u8[sizeof c->mask - sf->field->n_bytes],
2808                    sf->field->n_bytes);
2809         } else {
2810             uint32_t port = simap_get(ports, c->string);
2811             bitwise_put(port, &sf->value,
2812                         sf->field->n_bytes, 0, sf->field->n_bits);
2813             bitwise_put(UINT64_MAX, &sf->mask,
2814                         sf->field->n_bytes, 0, sf->field->n_bits);
2815         }
2816
2817     exit_destroy_cs:
2818         expr_constant_set_destroy(&cs);
2819     }
2820
2821 exit:
2822     return prereqs;
2823 }
2824
2825 /* A helper for actions_parse(), to parse an OVN assignment action in the form
2826  * "field = value" or "field1 = field2", or a "exchange" action in the form
2827  * "field1 <-> field2", into 'ofpacts'.  The parameters and return value match
2828  * those for actions_parse(). */
2829 char *
2830 expr_parse_assignment(struct lexer *lexer, const struct shash *symtab,
2831                       const struct simap *ports,
2832                       struct ofpbuf *ofpacts, struct expr **prereqsp)
2833 {
2834     struct expr_context ctx;
2835     ctx.lexer = lexer;
2836     ctx.symtab = symtab;
2837     ctx.error = NULL;
2838     ctx.not = false;
2839
2840     struct expr *prereqs = parse_assignment(&ctx, ports, ofpacts);
2841     if (ctx.error) {
2842         expr_destroy(prereqs);
2843         prereqs = NULL;
2844     }
2845     *prereqsp = prereqs;
2846     return ctx.error;
2847 }