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