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