2 * Copyright (c) 2015 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "dynamic-string.h"
25 #include "openvswitch/vlog.h"
27 VLOG_DEFINE_THIS_MODULE(expr);
29 /* Returns the name of measurement level 'level'. */
31 expr_level_to_string(enum expr_level level)
34 case EXPR_L_NOMINAL: return "nominal";
35 case EXPR_L_BOOLEAN: return "Boolean";
36 case EXPR_L_ORDINAL: return "ordinal";
37 default: OVS_NOT_REACHED();
41 /* Relational operators. */
43 /* Returns a string form of relational operator 'relop'. */
45 expr_relop_to_string(enum expr_relop relop)
48 case EXPR_R_EQ: return "==";
49 case EXPR_R_NE: return "!=";
50 case EXPR_R_LT: return "<";
51 case EXPR_R_LE: return "<=";
52 case EXPR_R_GT: return ">";
53 case EXPR_R_GE: return ">=";
54 default: OVS_NOT_REACHED();
59 expr_relop_from_token(enum lex_type type, enum expr_relop *relop)
64 case LEX_T_EQ: r = EXPR_R_EQ; break;
65 case LEX_T_NE: r = EXPR_R_NE; break;
66 case LEX_T_LT: r = EXPR_R_LT; break;
67 case LEX_T_LE: r = EXPR_R_LE; break;
68 case LEX_T_GT: r = EXPR_R_GT; break;
69 case LEX_T_GE: r = EXPR_R_GE; break;
70 default: return false;
79 /* Returns the relational operator that 'relop' becomes if you turn the
80 * relation's operands around, e.g. EXPR_R_EQ does not change because "a == b"
81 * and "b == a" are equivalent, but EXPR_R_LE becomes EXPR_R_GE because "a <=
82 * b" is equivalent to "b >= a". */
83 static enum expr_relop
84 expr_relop_turn(enum expr_relop relop)
87 case EXPR_R_EQ: return EXPR_R_EQ;
88 case EXPR_R_NE: return EXPR_R_NE;
89 case EXPR_R_LT: return EXPR_R_GT;
90 case EXPR_R_LE: return EXPR_R_GE;
91 case EXPR_R_GT: return EXPR_R_LT;
92 case EXPR_R_GE: return EXPR_R_LE;
93 default: OVS_NOT_REACHED();
97 /* Returns the relational operator that is the opposite of 'relop'. */
98 static enum expr_relop
99 expr_relop_invert(enum expr_relop relop)
102 case EXPR_R_EQ: return EXPR_R_NE;
103 case EXPR_R_NE: return EXPR_R_EQ;
104 case EXPR_R_LT: return EXPR_R_GE;
105 case EXPR_R_LE: return EXPR_R_GT;
106 case EXPR_R_GT: return EXPR_R_LE;
107 case EXPR_R_GE: return EXPR_R_LT;
108 default: OVS_NOT_REACHED();
112 /* Constructing and manipulating expressions. */
114 /* Creates and returns a logical AND or OR expression (according to 'type',
115 * which must be EXPR_T_AND or EXPR_T_OR) that initially has no
116 * sub-expressions. (To satisfy the invariants for expressions, the caller
117 * must add at least two sub-expressions whose types are different from
120 expr_create_andor(enum expr_type type)
122 struct expr *e = xmalloc(sizeof *e);
124 list_init(&e->andor);
128 /* Returns a logical AND or OR expression (according to 'type', which must be
129 * EXPR_T_AND or EXPR_T_OR) whose sub-expressions are 'a' and 'b', with some
132 * - If 'a' or 'b' is NULL, just returns the other one (which means that if
133 * that other one is not of the given 'type', then the returned
134 * expression is not either).
136 * - If 'a' or 'b', or both, have type 'type', then they are combined into
137 * a single node that satisfies the invariants for expressions. */
139 expr_combine(enum expr_type type, struct expr *a, struct expr *b)
145 } else if (a->type == type) {
146 if (b->type == type) {
147 list_splice(&a->andor, b->andor.next, &b->andor);
150 list_push_back(&a->andor, &b->node);
153 } else if (b->type == type) {
154 list_push_front(&b->andor, &a->node);
157 struct expr *e = expr_create_andor(type);
158 list_push_back(&e->andor, &a->node);
159 list_push_back(&e->andor, &b->node);
165 expr_insert_andor(struct expr *andor, struct expr *before, struct expr *new)
167 if (new->type == andor->type) {
168 if (andor->type == EXPR_T_AND) {
169 /* Conjunction junction, what's your function? */
171 list_splice(&before->node, new->andor.next, &new->andor);
174 list_insert(&before->node, &new->node);
178 /* Returns an EXPR_T_BOOLEAN expression with value 'b'. */
180 expr_create_boolean(bool b)
182 struct expr *e = xmalloc(sizeof *e);
183 e->type = EXPR_T_BOOLEAN;
189 expr_not(struct expr *expr)
193 switch (expr->type) {
195 expr->cmp.relop = expr_relop_invert(expr->cmp.relop);
200 LIST_FOR_EACH (sub, node, &expr->andor) {
203 expr->type = expr->type == EXPR_T_AND ? EXPR_T_OR : EXPR_T_AND;
207 expr->boolean = !expr->boolean;
215 expr_fix_andor(struct expr *expr, bool short_circuit)
217 struct expr *sub, *next;
219 LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
220 if (sub->type == EXPR_T_BOOLEAN) {
221 if (sub->boolean == short_circuit) {
223 return expr_create_boolean(short_circuit);
225 list_remove(&sub->node);
231 if (list_is_short(&expr->andor)) {
232 if (list_is_empty(&expr->andor)) {
234 return expr_create_boolean(!short_circuit);
236 sub = expr_from_node(list_front(&expr->andor));
246 expr_fix(struct expr *expr)
248 switch (expr->type) {
253 return expr_fix_andor(expr, false);
256 return expr_fix_andor(expr, true);
269 find_bitwise_range(const union mf_subvalue *sv, int width,
270 int *startp, int *n_bitsp)
272 unsigned int start = bitwise_scan(sv, sizeof *sv, true, 0, width);
274 unsigned int end = bitwise_scan(sv, sizeof *sv, false, start, width);
276 || bitwise_scan(sv, sizeof *sv, true, end, width) >= width) {
278 *n_bitsp = end - start;
282 *startp = *n_bitsp = 0;
286 expr_format_string(const char *s, struct ds *ds)
290 .u.string = CONST_CAST(char *, s),
292 json_to_ds(&json, 0, ds);
296 expr_format_cmp(const struct expr *e, struct ds *s)
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));
303 expr_format_string(e->cmp.string, s);
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)) {
312 positive = bitwise_get_bit(&e->cmp.value, sizeof e->cmp.value, ofs);
313 positive ^= e->cmp.relop == EXPR_R_NE;
317 ds_put_cstr(s, e->cmp.symbol->name);
318 if (e->cmp.symbol->width > 1) {
319 ds_put_format(s, "[%d]", ofs);
324 ds_put_cstr(s, e->cmp.symbol->name);
325 if (n > 0 && n < e->cmp.symbol->width) {
327 ds_put_format(s, "[%d..%d]", ofs, ofs + n - 1);
329 ds_put_format(s, "[%d]", ofs);
333 ds_put_format(s, " %s ", expr_relop_to_string(e->cmp.relop));
336 union mf_subvalue value;
338 memset(&value, 0, sizeof value);
339 bitwise_copy(&e->cmp.value, sizeof e->cmp.value, ofs,
340 &value, sizeof value, 0,
342 mf_format_subvalue(&value, s);
344 mf_format_subvalue(&e->cmp.value, s);
346 mf_format_subvalue(&e->cmp.mask, s);
351 expr_format_andor(const struct expr *e, const char *op, struct ds *s)
356 LIST_FOR_EACH (sub, node, &e->andor) {
358 ds_put_format(s, " %s ", op);
361 if (sub->type == EXPR_T_AND || sub->type == EXPR_T_OR) {
371 /* Appends a string form of 'e' to 's'. The string form is acceptable for
372 * parsing back into an equivalent expression. */
374 expr_format(const struct expr *e, struct ds *s)
378 expr_format_cmp(e, s);
382 expr_format_andor(e, "&&", s);
386 expr_format_andor(e, "||", s);
390 ds_put_char(s, e->boolean ? '1' : '0');
395 /* Prints a string form of 'e' on stdout, followed by a new-line. */
397 expr_print(const struct expr *e)
402 expr_format(e, &output);
403 puts(ds_cstr(&output));
409 /* Type of a "union expr_constant" or "struct expr_constant_set". */
410 enum expr_constant_type {
415 /* A string or integer constant (one must know which from context). */
416 union expr_constant {
419 * The width of a constant isn't always clear, e.g. if you write "1",
420 * there's no way to tell whether you mean for that to be a 1-bit constant
421 * or a 128-bit constant or somewhere in between. */
423 union mf_subvalue value;
424 union mf_subvalue mask; /* Only initialized if 'masked'. */
427 enum lex_format format; /* From the constant's lex_token. */
430 /* Null-terminated string constant. */
434 /* A collection of "union expr_constant"s of the same type. */
435 struct expr_constant_set {
436 union expr_constant *values; /* Constants. */
437 size_t n_values; /* Number of constants. */
438 enum expr_constant_type type; /* Type of the constants. */
439 bool in_curlies; /* Whether the constants were in {}. */
442 /* A reference to a symbol or a subfield of a symbol.
444 * For string fields, ofs and n_bits are 0. */
446 const struct expr_symbol *symbol; /* The symbol. */
447 int ofs; /* Starting bit offset. */
448 int n_bits; /* Number of bits. */
451 /* Context maintained during expr_parse(). */
452 struct expr_context {
453 struct lexer *lexer; /* Lexer for pulling more tokens. */
454 const struct shash *symtab; /* Symbol table. */
455 char *error; /* Error, if any, otherwise NULL. */
456 bool not; /* True inside odd number of NOT operators. */
459 struct expr *expr_parse__(struct expr_context *);
460 static void expr_not(struct expr *);
461 static void expr_constant_set_destroy(struct expr_constant_set *);
462 static bool parse_field(struct expr_context *, struct expr_field *);
465 expr_error_handle_common(struct expr_context *ctx)
468 /* Already have an error, suppress this one since the cascade seems
469 * unlikely to be useful. */
471 } else if (ctx->lexer->token.type == LEX_T_ERROR) {
472 /* The lexer signaled an error. Nothing at the expression level
473 * accepts an error token, so we'll inevitably end up here with some
474 * meaningless parse error. Report the lexical error instead. */
475 ctx->error = xstrdup(ctx->lexer->token.s);
482 static void OVS_PRINTF_FORMAT(2, 3)
483 expr_error(struct expr_context *ctx, const char *message, ...)
485 if (expr_error_handle_common(ctx)) {
490 va_start(args, message);
491 ctx->error = xvasprintf(message, args);
495 static void OVS_PRINTF_FORMAT(2, 3)
496 expr_syntax_error(struct expr_context *ctx, const char *message, ...)
498 if (expr_error_handle_common(ctx)) {
505 ds_put_cstr(&s, "Syntax error ");
506 if (ctx->lexer->token.type == LEX_T_END) {
507 ds_put_cstr(&s, "at end of input ");
508 } else if (ctx->lexer->start) {
509 ds_put_format(&s, "at `%.*s' ",
510 (int) (ctx->lexer->input - ctx->lexer->start),
515 va_start(args, message);
516 ds_put_format_valist(&s, message, args);
519 ctx->error = ds_steal_cstr(&s);
523 make_cmp__(const struct expr_field *f, enum expr_relop r,
524 const union expr_constant *c)
526 struct expr *e = xzalloc(sizeof *e);
527 e->type = EXPR_T_CMP;
528 e->cmp.symbol = f->symbol;
530 if (f->symbol->width) {
531 bitwise_copy(&c->value, sizeof c->value, 0,
532 &e->cmp.value, sizeof e->cmp.value, f->ofs,
535 bitwise_copy(&c->mask, sizeof c->mask, 0,
536 &e->cmp.mask, sizeof e->cmp.mask, f->ofs,
539 bitwise_one(&e->cmp.mask, sizeof e->cmp.mask, f->ofs,
543 e->cmp.string = xstrdup(c->string);
548 /* Returns the minimum reasonable width for integer constant 'c'. */
550 expr_constant_width(const union expr_constant *c)
553 return mf_subvalue_width(&c->mask);
558 case LEX_F_HEXADECIMAL:
559 return mf_subvalue_width(&c->value);
576 make_cmp(struct expr_context *ctx,
577 const struct expr_field *f, enum expr_relop r,
578 struct expr_constant_set *cs)
580 struct expr *e = NULL;
582 if (cs->type != (f->symbol->width ? EXPR_C_INTEGER : EXPR_C_STRING)) {
583 expr_error(ctx, "Can't compare %s field %s to %s constant.",
584 f->symbol->width ? "integer" : "string",
586 cs->type == EXPR_C_INTEGER ? "integer" : "string");
590 if (r != EXPR_R_EQ && r != EXPR_R_NE) {
591 if (cs->in_curlies) {
592 expr_error(ctx, "Only == and != operators may be used "
596 if (f->symbol->level == EXPR_L_NOMINAL ||
597 f->symbol->level == EXPR_L_BOOLEAN) {
598 expr_error(ctx, "Only == and != operators may be used "
600 expr_level_to_string(f->symbol->level),
604 if (cs->values[0].masked) {
605 expr_error(ctx, "Only == and != operators may be used with "
606 "masked constants. Consider using subfields instead "
607 "(e.g. eth.src[0..15] > 0x1111 in place of "
608 "eth.src > 00:00:00:00:11:11/00:00:00:00:ff:ff).");
613 if (f->symbol->level == EXPR_L_NOMINAL) {
614 if (f->symbol->expansion) {
615 for (size_t i = 0; i < cs->n_values; i++) {
616 const union mf_subvalue *value = &cs->values[i].value;
617 bool positive = (value->integer & htonll(1)) != 0;
618 positive ^= r == EXPR_R_NE;
619 positive ^= ctx->not;
621 const char *name = f->symbol->name;
622 expr_error(ctx, "Nominal predicate %s may only be tested "
623 "positively, e.g. `%s' or `%s == 1' but not "
624 "`!%s' or `%s == 0'.",
625 name, name, name, name, name);
629 } else if (r != (ctx->not ? EXPR_R_NE : EXPR_R_EQ)) {
630 expr_error(ctx, "Nominal field %s may only be tested for "
631 "equality (taking enclosing `!' operators into "
632 "account).", f->symbol->name);
637 if (f->symbol->width) {
638 for (size_t i = 0; i < cs->n_values; i++) {
639 int w = expr_constant_width(&cs->values[i]);
640 if (w > f->symbol->width) {
641 expr_error(ctx, "Cannot compare %d-bit constant against "
643 w, f->symbol->width, f->symbol->name);
649 e = make_cmp__(f, r, &cs->values[0]);
650 for (size_t i = 1; i < cs->n_values; i++) {
651 e = expr_combine(r == EXPR_R_EQ ? EXPR_T_OR : EXPR_T_AND,
652 e, make_cmp__(f, r, &cs->values[i]));
655 expr_constant_set_destroy(cs);
660 expr_get_int(struct expr_context *ctx, int *value)
662 if (ctx->lexer->token.type == LEX_T_INTEGER
663 && ctx->lexer->token.format == LEX_F_DECIMAL
664 && ntohll(ctx->lexer->token.value.integer) <= INT_MAX) {
665 *value = ntohll(ctx->lexer->token.value.integer);
666 lexer_get(ctx->lexer);
669 expr_syntax_error(ctx, "expecting small integer.");
675 parse_field(struct expr_context *ctx, struct expr_field *f)
677 const struct expr_symbol *symbol;
679 if (ctx->lexer->token.type != LEX_T_ID) {
680 expr_syntax_error(ctx, "expecting field name.");
684 symbol = shash_find_data(ctx->symtab, ctx->lexer->token.s);
686 expr_syntax_error(ctx, "expecting field name.");
689 lexer_get(ctx->lexer);
692 if (lexer_match(ctx->lexer, LEX_T_LSQUARE)) {
695 if (!symbol->width) {
696 expr_error(ctx, "Cannot select subfield of string field %s.",
701 if (!expr_get_int(ctx, &low)) {
704 if (lexer_match(ctx->lexer, LEX_T_ELLIPSIS)) {
705 if (!expr_get_int(ctx, &high)) {
712 if (!lexer_match(ctx->lexer, LEX_T_RSQUARE)) {
713 expr_syntax_error(ctx, "expecting `]'.");
718 expr_error(ctx, "Invalid bit range %d to %d.", low, high);
720 } else if (high >= symbol->width) {
721 expr_error(ctx, "Cannot select bits %d to %d of %d-bit field %s.",
722 low, high, symbol->width, symbol->name);
724 } else if (symbol->level == EXPR_L_NOMINAL
725 && (low != 0 || high != symbol->width - 1)) {
726 expr_error(ctx, "Cannot select subfield of nominal field %s.",
732 f->n_bits = high - low + 1;
735 f->n_bits = symbol->width;
742 parse_relop(struct expr_context *ctx, enum expr_relop *relop)
744 if (expr_relop_from_token(ctx->lexer->token.type, relop)) {
745 lexer_get(ctx->lexer);
748 expr_syntax_error(ctx, "expecting relational operator.");
754 assign_constant_set_type(struct expr_context *ctx,
755 struct expr_constant_set *cs,
756 enum expr_constant_type type)
758 if (!cs->n_values || cs->type == type) {
762 expr_syntax_error(ctx, "expecting %s.",
763 cs->type == EXPR_C_INTEGER ? "integer" : "string");
769 parse_constant(struct expr_context *ctx, struct expr_constant_set *cs,
770 size_t *allocated_values)
772 if (cs->n_values >= *allocated_values) {
773 cs->values = x2nrealloc(cs->values, allocated_values,
777 if (ctx->lexer->token.type == LEX_T_STRING) {
778 if (!assign_constant_set_type(ctx, cs, EXPR_C_STRING)) {
781 cs->values[cs->n_values++].string = xstrdup(ctx->lexer->token.s);
782 lexer_get(ctx->lexer);
784 } else if (ctx->lexer->token.type == LEX_T_INTEGER ||
785 ctx->lexer->token.type == LEX_T_MASKED_INTEGER) {
786 if (!assign_constant_set_type(ctx, cs, EXPR_C_INTEGER)) {
790 union expr_constant *c = &cs->values[cs->n_values++];
791 c->value = ctx->lexer->token.value;
792 c->format = ctx->lexer->token.format;
793 c->masked = ctx->lexer->token.type == LEX_T_MASKED_INTEGER;
795 c->mask = ctx->lexer->token.mask;
797 lexer_get(ctx->lexer);
800 expr_syntax_error(ctx, "expecting constant.");
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
810 parse_constant_set(struct expr_context *ctx, struct expr_constant_set *cs)
812 size_t allocated_values = 0;
815 memset(cs, 0, sizeof *cs);
816 if (lexer_match(ctx->lexer, LEX_T_LCURLY)) {
818 cs->in_curlies = true;
820 if (!parse_constant(ctx, cs, &allocated_values)) {
824 lexer_match(ctx->lexer, LEX_T_COMMA);
825 } while (!lexer_match(ctx->lexer, LEX_T_RCURLY));
827 ok = parse_constant(ctx, cs, &allocated_values);
830 expr_constant_set_destroy(cs);
836 expr_constant_set_destroy(struct expr_constant_set *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);
849 expr_parse_primary(struct expr_context *ctx, bool *atomic)
852 if (lexer_match(ctx->lexer, LEX_T_LPAREN)) {
853 struct expr *e = expr_parse__(ctx);
854 if (!lexer_match(ctx->lexer, LEX_T_RPAREN)) {
856 expr_syntax_error(ctx, "expecting `)'.");
863 if (ctx->lexer->token.type == LEX_T_ID) {
866 struct expr_constant_set c;
868 if (!parse_field(ctx, &f)) {
872 if (!expr_relop_from_token(ctx->lexer->token.type, &r)) {
873 if (f.n_bits > 1 && !ctx->not) {
874 expr_error(ctx, "Explicit `!= 0' is required for inequality "
875 "test of multibit field against 0.");
881 union expr_constant *cst = xzalloc(sizeof *cst);
882 cst->format = LEX_F_HEXADECIMAL;
885 c.type = EXPR_C_INTEGER;
888 c.in_curlies = false;
889 return make_cmp(ctx, &f, EXPR_R_NE, &c);
890 } else if (parse_relop(ctx, &r) && parse_constant_set(ctx, &c)) {
891 return make_cmp(ctx, &f, r, &c);
896 struct expr_constant_set c1;
897 if (!parse_constant_set(ctx, &c1)) {
901 if (!expr_relop_from_token(ctx->lexer->token.type, NULL)
903 && c1.type == EXPR_C_INTEGER
904 && c1.values[0].format == LEX_F_DECIMAL
905 && !c1.values[0].masked
907 uint64_t x = ntohll(c1.values[0].value.integer);
910 expr_constant_set_destroy(&c1);
911 return expr_create_boolean(x);
917 if (!parse_relop(ctx, &r1) || !parse_field(ctx, &f)) {
918 expr_constant_set_destroy(&c1);
922 if (!expr_relop_from_token(ctx->lexer->token.type, NULL)) {
923 return make_cmp(ctx, &f, expr_relop_turn(r1), &c1);
927 struct expr_constant_set c2;
928 if (!parse_relop(ctx, &r2) || !parse_constant_set(ctx, &c2)) {
929 expr_constant_set_destroy(&c1);
932 /* Reject "1 == field == 2", "1 < field > 2", and so on. */
933 if (!(((r1 == EXPR_R_LT || r1 == EXPR_R_LE) &&
934 (r2 == EXPR_R_LT || r2 == EXPR_R_LE)) ||
935 ((r1 == EXPR_R_GT || r1 == EXPR_R_GE) &&
936 (r2 == EXPR_R_GT || r2 == EXPR_R_GE)))) {
937 expr_error(ctx, "Range expressions must have the form "
938 "`x < field < y' or `x > field > y', with each "
939 "`<' optionally replaced by `<=' or `>' by `>=').");
940 expr_constant_set_destroy(&c1);
941 expr_constant_set_destroy(&c2);
945 struct expr *e1 = make_cmp(ctx, &f, expr_relop_turn(r1), &c1);
946 struct expr *e2 = make_cmp(ctx, &f, r2, &c2);
952 return expr_combine(EXPR_T_AND, e1, e2);
958 expr_parse_not(struct expr_context *ctx)
962 if (lexer_match(ctx->lexer, LEX_T_LOG_NOT)) {
963 ctx->not = !ctx->not;
964 struct expr *expr = expr_parse_primary(ctx, &atomic);
965 ctx->not = !ctx->not;
969 expr_error(ctx, "Missing parentheses around operand of !.");
977 return expr_parse_primary(ctx, &atomic);
982 expr_parse__(struct expr_context *ctx)
984 struct expr *e = expr_parse_not(ctx);
989 enum lex_type lex_type = ctx->lexer->token.type;
990 if (lex_type == LEX_T_LOG_AND || lex_type == LEX_T_LOG_OR) {
991 enum expr_type expr_type
992 = lex_type == LEX_T_LOG_AND ? EXPR_T_AND : EXPR_T_OR;
994 lexer_get(ctx->lexer);
996 struct expr *e2 = expr_parse_not(ctx);
1001 e = expr_combine(expr_type, e, e2);
1002 } while (lexer_match(ctx->lexer, lex_type));
1003 if (ctx->lexer->token.type == LEX_T_LOG_AND
1004 || ctx->lexer->token.type == LEX_T_LOG_OR) {
1007 "&& and || must be parenthesized when used together.");
1014 /* Parses an expression using the symbols in 'symtab' from 'lexer'. If
1015 * successful, returns the new expression and sets '*errorp' to NULL. On
1016 * failure, returns NULL and sets '*errorp' to an explanatory error message.
1017 * The caller must eventually free the returned expression (with
1018 * expr_destroy()) or error (with free()). */
1020 expr_parse(struct lexer *lexer, const struct shash *symtab, char **errorp)
1022 struct expr_context ctx;
1025 ctx.symtab = symtab;
1029 struct expr *e = expr_parse__(&ctx);
1030 *errorp = ctx.error;
1031 ovs_assert((ctx.error != NULL) != (e != NULL));
1035 /* Like expr_parse(), but the expression is taken from 's'. */
1037 expr_parse_string(const char *s, const struct shash *symtab, char **errorp)
1042 lexer_init(&lexer, s);
1044 expr = expr_parse(&lexer, symtab, errorp);
1045 if (!errorp && lexer.token.type != LEX_T_END) {
1046 *errorp = xstrdup("Extra tokens at end of input.");
1050 lexer_destroy(&lexer);
1055 static struct expr_symbol *
1056 add_symbol(struct shash *symtab, const char *name, int width,
1057 const char *prereqs, enum expr_level level,
1058 bool must_crossproduct)
1060 struct expr_symbol *symbol = xzalloc(sizeof *symbol);
1061 symbol->name = xstrdup(name);
1062 symbol->prereqs = prereqs && prereqs[0] ? xstrdup(prereqs) : NULL;
1063 symbol->width = width;
1064 symbol->level = level;
1065 symbol->must_crossproduct = must_crossproduct;
1066 shash_add_assert(symtab, symbol->name, symbol);
1070 /* Adds field 'id' to symbol table 'symtab' under the given 'name'. Whenever
1071 * 'name' is referenced, expression annotation (see expr_annotate()) will
1072 * ensure that 'prereqs' are also true. If 'must_crossproduct' is true, then
1073 * conversion to flows will never attempt to use the field as a conjunctive
1074 * match dimension (see "Crossproducting" in the large comment on struct
1075 * expr_symbol in expr.h for an example).
1077 * A given field 'id' must only be used for a single symbol in a symbol table.
1078 * Use subfields to duplicate or subset a field (you can even make a subfield
1079 * include all the bits of the "parent" field if you like). */
1080 struct expr_symbol *
1081 expr_symtab_add_field(struct shash *symtab, const char *name,
1082 enum mf_field_id id, const char *prereqs,
1083 bool must_crossproduct)
1085 const struct mf_field *field = mf_from_id(id);
1086 struct expr_symbol *symbol;
1088 symbol = add_symbol(symtab, name, field->n_bits, prereqs,
1089 (field->maskable == MFM_FULLY
1093 symbol->field = field;
1098 parse_field_from_string(const char *s, const struct shash *symtab,
1099 struct expr_field *field, char **errorp)
1102 lexer_init(&lexer, s);
1105 struct expr_context ctx;
1107 ctx.symtab = symtab;
1111 bool ok = parse_field(&ctx, field);
1113 *errorp = ctx.error;
1114 } else if (lexer.token.type != LEX_T_END) {
1115 *errorp = xstrdup("Extra tokens at end of input.");
1119 lexer_destroy(&lexer);
1124 /* Adds 'name' as a subfield of a larger field in 'symtab'. Whenever
1125 * 'name' is referenced, expression annotation (see expr_annotate()) will
1126 * ensure that 'prereqs' are also true.
1128 * 'subfield' must describe the subfield as a string, e.g. "vlan.tci[0..11]"
1129 * for the low 12 bits of a larger field named "vlan.tci". */
1130 struct expr_symbol *
1131 expr_symtab_add_subfield(struct shash *symtab, const char *name,
1132 const char *prereqs, const char *subfield)
1134 struct expr_symbol *symbol;
1135 struct expr_field f;
1138 if (!parse_field_from_string(subfield, symtab, &f, &error)) {
1139 VLOG_WARN("%s: error parsing %s subfield (%s)", subfield, name, error);
1144 enum expr_level level = f.symbol->level;
1145 if (level != EXPR_L_ORDINAL) {
1146 VLOG_WARN("can't define %s as subfield of %s field %s",
1147 name, expr_level_to_string(level), f.symbol->name);
1150 symbol = add_symbol(symtab, name, f.n_bits, prereqs, level, false);
1151 symbol->expansion = xstrdup(subfield);
1155 /* Adds a string-valued symbol named 'name' to 'symtab' with the specified
1157 struct expr_symbol *
1158 expr_symtab_add_string(struct shash *symtab, const char *name,
1159 enum mf_field_id id, const char *prereqs)
1161 const struct mf_field *field = mf_from_id(id);
1162 struct expr_symbol *symbol;
1164 symbol = add_symbol(symtab, name, 0, prereqs, EXPR_L_NOMINAL, false);
1165 symbol->field = field;
1169 static enum expr_level
1170 expr_get_level(const struct expr *expr)
1172 const struct expr *sub;
1173 enum expr_level level = EXPR_L_ORDINAL;
1175 switch (expr->type) {
1177 return (expr->cmp.symbol->level == EXPR_L_NOMINAL
1183 LIST_FOR_EACH (sub, node, &expr->andor) {
1184 enum expr_level sub_level = expr_get_level(sub);
1185 level = MIN(level, sub_level);
1189 case EXPR_T_BOOLEAN:
1190 return EXPR_L_BOOLEAN;
1197 static enum expr_level
1198 expr_parse_level(const char *s, const struct shash *symtab, char **errorp)
1200 struct expr *expr = expr_parse_string(s, symtab, errorp);
1201 enum expr_level level = expr ? expr_get_level(expr) : EXPR_L_NOMINAL;
1206 /* Adds a predicate symbol, whose value is the given Boolean 'expression',
1207 * named 'name' to 'symtab'. For example, "ip4 && ip4.proto == 1" might be an
1208 * appropriate predicate named "tcp4". */
1209 struct expr_symbol *
1210 expr_symtab_add_predicate(struct shash *symtab, const char *name,
1211 const char *expansion)
1213 struct expr_symbol *symbol;
1214 enum expr_level level;
1217 level = expr_parse_level(expansion, symtab, &error);
1219 VLOG_WARN("%s: error parsing %s expansion (%s)",
1220 expansion, name, error);
1225 symbol = add_symbol(symtab, name, 1, NULL, level, false);
1226 symbol->expansion = xstrdup(expansion);
1230 /* Destroys 'symtab' and all of its symbols. */
1232 expr_symtab_destroy(struct shash *symtab)
1234 struct shash_node *node, *next;
1236 SHASH_FOR_EACH_SAFE (node, next, symtab) {
1237 struct expr_symbol *symbol = node->data;
1239 shash_delete(symtab, node);
1241 free(symbol->prereqs);
1242 free(symbol->expansion);
1249 static struct expr *
1250 expr_clone_cmp(struct expr *expr)
1252 struct expr *new = xmemdup(expr, sizeof *expr);
1253 if (!new->cmp.symbol->width) {
1254 new->cmp.string = xstrdup(new->cmp.string);
1259 static struct expr *
1260 expr_clone_andor(struct expr *expr)
1262 struct expr *new = expr_create_andor(expr->type);
1265 LIST_FOR_EACH (sub, node, &expr->andor) {
1266 struct expr *new_sub = expr_clone(sub);
1267 list_push_back(&new->andor, &new_sub->node);
1272 /* Returns a clone of 'expr'. This is a "deep copy": neither the returned
1273 * expression nor any of its substructure will be shared with 'expr'. */
1275 expr_clone(struct expr *expr)
1277 switch (expr->type) {
1279 return expr_clone_cmp(expr);
1283 return expr_clone_andor(expr);
1285 case EXPR_T_BOOLEAN:
1286 return expr_create_boolean(expr->boolean);
1291 /* Destroys 'expr' and all of the sub-expressions it references. */
1293 expr_destroy(struct expr *expr)
1299 struct expr *sub, *next;
1301 switch (expr->type) {
1303 if (!expr->cmp.symbol->width) {
1304 free(expr->cmp.string);
1310 LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1311 list_remove(&sub->node);
1316 case EXPR_T_BOOLEAN:
1324 /* An element in a linked list of symbols.
1326 * Used to detect when a symbol is being expanded recursively, to allow
1327 * flagging an error. */
1328 struct annotation_nesting {
1329 struct ovs_list node;
1330 const struct expr_symbol *symbol;
1333 struct expr *expr_annotate__(struct expr *, const struct shash *symtab,
1334 struct ovs_list *nesting, char **errorp);
1336 static struct expr *
1337 parse_and_annotate(const char *s, const struct shash *symtab,
1338 struct ovs_list *nesting, char **errorp)
1343 expr = expr_parse_string(s, symtab, &error);
1345 expr = expr_annotate__(expr, symtab, nesting, &error);
1348 *errorp = xasprintf("Error parsing expression `%s' encountered as "
1349 "prerequisite or predicate of initial expression: "
1356 static struct expr *
1357 expr_annotate_cmp(struct expr *expr, const struct shash *symtab,
1358 struct ovs_list *nesting, char **errorp)
1360 const struct expr_symbol *symbol = expr->cmp.symbol;
1361 const struct annotation_nesting *iter;
1362 LIST_FOR_EACH (iter, node, nesting) {
1363 if (iter->symbol == symbol) {
1364 *errorp = xasprintf("Recursive expansion of symbol `%s'.",
1371 struct annotation_nesting an;
1373 list_push_back(nesting, &an.node);
1375 struct expr *prereqs = NULL;
1376 if (symbol->prereqs) {
1377 prereqs = parse_and_annotate(symbol->prereqs, symtab, nesting, errorp);
1383 if (symbol->expansion) {
1384 if (symbol->level == EXPR_L_ORDINAL) {
1385 struct expr_field field;
1387 if (!parse_field_from_string(symbol->expansion, symtab,
1392 expr->cmp.symbol = field.symbol;
1393 mf_subvalue_shift(&expr->cmp.value, field.ofs);
1394 mf_subvalue_shift(&expr->cmp.mask, field.ofs);
1396 struct expr *expansion;
1398 expansion = parse_and_annotate(symbol->expansion, symtab,
1404 bool positive = (expr->cmp.value.integer & htonll(1)) != 0;
1405 positive ^= expr->cmp.relop == EXPR_R_NE;
1407 expr_not(expansion);
1415 list_remove(&an.node);
1416 return prereqs ? expr_combine(EXPR_T_AND, expr, prereqs) : expr;
1420 expr_destroy(prereqs);
1421 list_remove(&an.node);
1426 expr_annotate__(struct expr *expr, const struct shash *symtab,
1427 struct ovs_list *nesting, char **errorp)
1429 switch (expr->type) {
1431 return expr_annotate_cmp(expr, symtab, nesting, errorp);
1435 struct expr *sub, *next;
1437 LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1438 list_remove(&sub->node);
1439 struct expr *new_sub = expr_annotate__(sub, symtab,
1445 expr_insert_andor(expr, next, new_sub);
1451 case EXPR_T_BOOLEAN:
1460 /* "Annotates" 'expr', which does the following:
1462 * - Applies prerequisites, by locating each comparison operator whose
1463 * field has a prerequisite and adding a logical AND against those
1466 * - Expands references to subfield symbols, by replacing them by
1467 * references to their underlying field symbols (suitably shifted).
1469 * - Expands references to predicate symbols, by replacing them by the
1470 * expressions that they expand to.
1472 * In each case, annotation occurs recursively as necessary. */
1474 expr_annotate(struct expr *expr, const struct shash *symtab, char **errorp)
1476 struct ovs_list nesting = OVS_LIST_INITIALIZER(&nesting);
1477 return expr_annotate__(expr, symtab, &nesting, errorp);
1480 static struct expr *
1481 expr_simplify_ne(struct expr *expr)
1483 struct expr *new = NULL;
1484 const union mf_subvalue *value = &expr->cmp.value;
1485 const union mf_subvalue *mask = &expr->cmp.mask;
1486 int w = expr->cmp.symbol->width;
1489 for (i = 0; (i = bitwise_scan(mask, sizeof *mask, true, i, w)) < w; i++) {
1492 e = xzalloc(sizeof *e);
1493 e->type = EXPR_T_CMP;
1494 e->cmp.symbol = expr->cmp.symbol;
1495 e->cmp.relop = EXPR_R_EQ;
1496 bitwise_put_bit(&e->cmp.value, sizeof e->cmp.value, i,
1497 !bitwise_get_bit(value, sizeof *value, i));
1498 bitwise_put1(&e->cmp.mask, sizeof e->cmp.mask, i);
1500 new = expr_combine(EXPR_T_OR, new, e);
1509 static struct expr *
1510 expr_simplify_relational(struct expr *expr)
1512 const union mf_subvalue *value = &expr->cmp.value;
1513 int start, n_bits, end;
1515 find_bitwise_range(&expr->cmp.mask, expr->cmp.symbol->width,
1517 ovs_assert(n_bits > 0);
1518 end = start + n_bits;
1521 if (expr->cmp.relop == EXPR_R_LE || expr->cmp.relop == EXPR_R_GE) {
1522 new = xmemdup(expr, sizeof *expr);
1523 new->cmp.relop = EXPR_R_EQ;
1528 bool b = expr->cmp.relop == EXPR_R_LT || expr->cmp.relop == EXPR_R_LE;
1529 for (int z = bitwise_scan(value, sizeof *value, b, start, end);
1531 z = bitwise_scan(value, sizeof *value, b, z + 1, end)) {
1534 e = xmemdup(expr, sizeof *expr);
1535 e->cmp.relop = EXPR_R_EQ;
1536 bitwise_toggle_bit(&e->cmp.value, sizeof e->cmp.value, z);
1537 bitwise_zero(&e->cmp.value, sizeof e->cmp.value, start, z - start);
1538 bitwise_zero(&e->cmp.mask, sizeof e->cmp.mask, start, z - start);
1539 new = expr_combine(EXPR_T_OR, new, e);
1542 return new ? new : expr_create_boolean(false);
1545 /* Takes ownership of 'expr' and returns an equivalent expression whose
1546 * EXPR_T_CMP nodes use only tests for equality (EXPR_R_EQ). */
1548 expr_simplify(struct expr *expr)
1550 struct expr *sub, *next;
1552 switch (expr->type) {
1554 return (expr->cmp.relop == EXPR_R_EQ || !expr->cmp.symbol->width ? expr
1555 : expr->cmp.relop == EXPR_R_NE ? expr_simplify_ne(expr)
1556 : expr_simplify_relational(expr));
1560 LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1561 list_remove(&sub->node);
1562 expr_insert_andor(expr, next, expr_simplify(sub));
1564 return expr_fix(expr);
1566 case EXPR_T_BOOLEAN:
1572 static const struct expr_symbol *
1573 expr_is_cmp(const struct expr *expr)
1575 switch (expr->type) {
1577 return expr->cmp.symbol;
1581 const struct expr_symbol *prev = NULL;
1584 LIST_FOR_EACH (sub, node, &expr->andor) {
1585 const struct expr_symbol *symbol = expr_is_cmp(sub);
1586 if (!symbol || (prev && symbol != prev)) {
1594 case EXPR_T_BOOLEAN:
1604 const struct expr_symbol *relop;
1605 enum expr_type type;
1609 compare_expr_sort(const void *a_, const void *b_)
1611 const struct expr_sort *a = a_;
1612 const struct expr_sort *b = b_;
1614 if (a->type != b->type) {
1615 return a->type < b->type ? -1 : 1;
1616 } else if (a->relop) {
1617 int cmp = strcmp(a->relop->name, b->relop->name);
1622 enum expr_type a_type = a->expr->type;
1623 enum expr_type b_type = a->expr->type;
1624 return a_type < b_type ? -1 : a_type > b_type;
1625 } else if (a->type == EXPR_T_AND || a->type == EXPR_T_OR) {
1626 size_t a_len = list_size(&a->expr->andor);
1627 size_t b_len = list_size(&b->expr->andor);
1628 return a_len < b_len ? -1 : a_len > b_len;
1634 static struct expr *crush_cmps(struct expr *, const struct expr_symbol *);
1636 static struct expr *
1637 crush_and(struct expr *expr, const struct expr_symbol *symbol)
1639 ovs_assert(!list_is_short(&expr->andor));
1641 union mf_subvalue value, mask;
1642 memset(&value, 0, sizeof value);
1643 memset(&mask, 0, sizeof mask);
1645 struct expr *sub, *next = NULL;
1646 LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1647 list_remove(&sub->node);
1648 struct expr *new = crush_cmps(sub, symbol);
1649 switch (new->type) {
1651 if (!mf_subvalue_intersect(&value, &mask,
1652 &new->cmp.value, &new->cmp.mask,
1656 return expr_create_boolean(false);
1663 list_insert(&next->node, &new->node);
1665 case EXPR_T_BOOLEAN:
1666 if (!new->boolean) {
1674 if (list_is_empty(&expr->andor)) {
1675 if (is_all_zeros(&mask, sizeof mask)) {
1677 return expr_create_boolean(true);
1680 cmp = xmalloc(sizeof *cmp);
1681 cmp->type = EXPR_T_CMP;
1682 cmp->cmp.symbol = symbol;
1683 cmp->cmp.relop = EXPR_R_EQ;
1684 cmp->cmp.value = value;
1685 cmp->cmp.mask = mask;
1689 } else if (list_is_short(&expr->andor)) {
1690 /* Transform "a && (b || c || d)" into "ab || ac || ad" where "ab" is
1691 * computed as "a && b", etc. */
1692 struct expr *disjuncts = expr_from_node(list_pop_front(&expr->andor));
1695 or = xmalloc(sizeof *or);
1696 or->type = EXPR_T_OR;
1697 list_init(&or->andor);
1699 ovs_assert(disjuncts->type == EXPR_T_OR);
1700 LIST_FOR_EACH_SAFE (sub, next, node, &disjuncts->andor) {
1701 ovs_assert(sub->type == EXPR_T_CMP);
1702 list_remove(&sub->node);
1703 if (mf_subvalue_intersect(&value, &mask,
1704 &sub->cmp.value, &sub->cmp.mask,
1705 &sub->cmp.value, &sub->cmp.mask)) {
1706 list_push_back(&or->andor, &sub->node);
1713 if (list_is_empty(&or->andor)) {
1715 return expr_create_boolean(false);
1716 } else if (list_is_short(&or->andor)) {
1717 struct expr *cmp = expr_from_node(list_pop_front(&or->andor));
1724 /* Transform "x && (a0 || a1) && (b0 || b1) && ..." into
1725 * "(xa0b0 || xa0b1 || xa1b0 || xa1b1) && ...". */
1726 struct expr *as = expr_from_node(list_pop_front(&expr->andor));
1727 struct expr *bs = expr_from_node(list_pop_front(&expr->andor));
1728 struct expr *new = NULL;
1731 or = xmalloc(sizeof *or);
1732 or->type = EXPR_T_OR;
1733 list_init(&or->andor);
1736 LIST_FOR_EACH (a, node, &as->andor) {
1737 union mf_subvalue a_value, a_mask;
1739 ovs_assert(a->type == EXPR_T_CMP);
1740 if (!mf_subvalue_intersect(&value, &mask,
1741 &a->cmp.value, &a->cmp.mask,
1742 &a_value, &a_mask)) {
1747 LIST_FOR_EACH (b, node, &bs->andor) {
1748 ovs_assert(b->type == EXPR_T_CMP);
1750 new = xmalloc(sizeof *new);
1751 new->type = EXPR_T_CMP;
1752 new->cmp.symbol = symbol;
1753 new->cmp.relop = EXPR_R_EQ;
1755 if (mf_subvalue_intersect(&a_value, &a_mask,
1756 &b->cmp.value, &b->cmp.mask,
1757 &new->cmp.value, &new->cmp.mask)) {
1758 list_push_back(&or->andor, &new->node);
1767 if (list_is_empty(&or->andor)) {
1770 return expr_create_boolean(false);
1771 } else if (list_is_short(&or->andor)) {
1772 struct expr *cmp = expr_from_node(list_pop_front(&or->andor));
1774 if (list_is_empty(&expr->andor)) {
1776 return crush_cmps(cmp, symbol);
1778 return crush_cmps(expr_combine(EXPR_T_AND, cmp, expr), symbol);
1780 } else if (!list_is_empty(&expr->andor)) {
1781 struct expr *e = expr_combine(EXPR_T_AND, or, expr);
1782 ovs_assert(!list_is_short(&e->andor));
1783 return crush_cmps(e, symbol);
1786 return crush_cmps(or, symbol);
1792 compare_expr(const void *a_, const void *b_)
1794 const struct expr *const *ap = a_;
1795 const struct expr *const *bp = b_;
1796 const struct expr *a = *ap;
1797 const struct expr *b = *bp;
1798 int d = memcmp(&a->cmp.value, &b->cmp.value, sizeof a->cmp.value);
1800 d = memcmp(&a->cmp.mask, &b->cmp.mask, sizeof a->cmp.mask);
1805 static struct expr *
1806 crush_or(struct expr *expr, const struct expr_symbol *symbol)
1808 struct expr *sub, *next = NULL;
1810 /* First, crush all the subexpressions. That might eliminate the
1811 * OR-expression entirely; if so, return the result. */
1812 LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
1813 list_remove(&sub->node);
1814 expr_insert_andor(expr, next, crush_cmps(sub, symbol));
1816 expr = expr_fix(expr);
1817 if (expr->type != EXPR_T_OR) {
1821 /* Eliminate duplicates by sorting the subexpressions. */
1822 size_t n = list_size(&expr->andor);
1823 struct expr **subs = xmalloc(n * sizeof *subs);
1826 LIST_FOR_EACH (sub, node, &expr->andor) {
1831 qsort(subs, n, sizeof *subs, compare_expr);
1833 list_init(&expr->andor);
1834 list_push_back(&expr->andor, &subs[0]->node);
1835 for (i = 1; i < n; i++) {
1836 struct expr *a = expr_from_node(list_back(&expr->andor));
1837 struct expr *b = subs[i];
1838 if (memcmp(&a->cmp.value, &b->cmp.value, sizeof a->cmp.value)
1839 || memcmp(&a->cmp.mask, &b->cmp.mask, sizeof a->cmp.mask)) {
1840 list_push_back(&expr->andor, &b->node);
1846 return expr_fix(expr);
1849 /* Converts 'expr', which must be a cmp in the sense determined by
1850 * expr_is_cmp(). Returns a cmp, a disjunction of cmps, or a boolean. */
1851 static struct expr *
1852 crush_cmps(struct expr *expr, const struct expr_symbol *symbol)
1854 switch (expr->type) {
1856 return crush_or(expr, symbol);
1859 return crush_and(expr, symbol);
1864 case EXPR_T_BOOLEAN:
1872 static struct expr *
1873 expr_sort(struct expr *expr)
1875 size_t n = list_size(&expr->andor);
1876 struct expr_sort *subs = xmalloc(n * sizeof *subs);
1881 LIST_FOR_EACH (sub, node, &expr->andor) {
1883 subs[i].relop = expr_is_cmp(sub);
1884 subs[i].type = subs[i].relop ? EXPR_T_CMP : sub->type;
1889 qsort(subs, n, sizeof *subs, compare_expr_sort);
1891 list_init(&expr->andor);
1892 for (int i = 0; i < n; ) {
1893 if (subs[i].relop) {
1895 for (j = i + 1; j < n; j++) {
1896 if (subs[i].relop != subs[j].relop) {
1901 struct expr *crushed;
1903 crushed = crush_cmps(subs[i].expr, subs[i].relop);
1905 struct expr *combined = subs[i].expr;
1906 for (int k = i + 1; k < j; k++) {
1907 combined = expr_combine(EXPR_T_AND, combined,
1910 ovs_assert(!list_is_short(&combined->andor));
1911 crushed = crush_cmps(combined, subs[i].relop);
1913 if (crushed->type == EXPR_T_BOOLEAN) {
1914 if (!crushed->boolean) {
1915 for (int k = j; k < n; k++) {
1916 expr_destroy(subs[k].expr);
1925 expr = expr_combine(EXPR_T_AND, expr, crushed);
1929 expr = expr_combine(EXPR_T_AND, expr, subs[i++].expr);
1937 static struct expr *expr_normalize_or(struct expr *expr);
1939 /* Returns 'expr', which is an AND, reduced to OR(AND(clause)) where
1940 * a clause is a cmp or a disjunction of cmps on a single field. */
1941 static struct expr *
1942 expr_normalize_and(struct expr *expr)
1944 ovs_assert(expr->type == EXPR_T_AND);
1946 expr = expr_sort(expr);
1947 if (expr->type != EXPR_T_AND) {
1948 ovs_assert(expr->type == EXPR_T_BOOLEAN);
1953 LIST_FOR_EACH_SAFE (a, b, node, &expr->andor) {
1954 if (&b->node == &expr->andor
1955 || a->type != EXPR_T_CMP || b->type != EXPR_T_CMP) {
1956 } else if (a->cmp.symbol != b->cmp.symbol) {
1958 } else if (mf_subvalue_intersect(&a->cmp.value, &a->cmp.mask,
1959 &b->cmp.value, &b->cmp.mask,
1960 &b->cmp.value, &b->cmp.mask)) {
1961 list_remove(&a->node);
1965 return expr_create_boolean(false);
1968 if (list_is_short(&expr->andor)) {
1969 struct expr *sub = expr_from_node(list_front(&expr->andor));
1975 LIST_FOR_EACH (sub, node, &expr->andor) {
1976 if (sub->type == EXPR_T_CMP) {
1980 ovs_assert(sub->type == EXPR_T_OR);
1981 const struct expr_symbol *symbol = expr_is_cmp(sub);
1982 if (!symbol || symbol->must_crossproduct) {
1983 struct expr *or = expr_create_andor(EXPR_T_OR);
1986 LIST_FOR_EACH (k, node, &sub->andor) {
1987 struct expr *and = expr_create_andor(EXPR_T_AND);
1990 LIST_FOR_EACH (m, node, &expr->andor) {
1991 struct expr *term = m == sub ? k : m;
1992 if (term->type == EXPR_T_AND) {
1995 LIST_FOR_EACH (p, node, &term->andor) {
1996 struct expr *new = expr_clone(p);
1997 list_push_back(&and->andor, &new->node);
2000 struct expr *new = expr_clone(term);
2001 list_push_back(&and->andor, &new->node);
2004 list_push_back(&or->andor, &and->node);
2007 return expr_normalize_or(or);
2013 static struct expr *
2014 expr_normalize_or(struct expr *expr)
2016 struct expr *sub, *next;
2018 LIST_FOR_EACH_SAFE (sub, next, node, &expr->andor) {
2019 if (sub->type == EXPR_T_AND) {
2020 list_remove(&sub->node);
2022 struct expr *new = expr_normalize_and(sub);
2023 if (new->type == EXPR_T_BOOLEAN) {
2030 expr_insert_andor(expr, next, new);
2033 ovs_assert(sub->type == EXPR_T_CMP);
2036 if (list_is_empty(&expr->andor)) {
2038 return expr_create_boolean(false);
2040 if (list_is_short(&expr->andor)) {
2041 struct expr *sub = expr_from_node(list_pop_front(&expr->andor));
2049 /* Takes ownership of 'expr', which is either a constant "true" or "false" or
2050 * an expression in terms of only relationals, AND, and OR. Returns either a
2051 * constant "true" or "false" or 'expr' reduced to OR(AND(clause)) where a
2052 * clause is a cmp or a disjunction of cmps on a single field. This form is
2053 * significant because it is a form that can be directly converted to OpenFlow
2054 * flows with the Open vSwitch "conjunctive match" extension.
2056 * 'expr' must already have been simplified, with expr_simplify(). */
2058 expr_normalize(struct expr *expr)
2060 switch (expr->type) {
2065 return expr_normalize_and(expr);
2068 return expr_normalize_or(expr);
2070 case EXPR_T_BOOLEAN:
2076 /* Creates, initializes, and returns a new 'struct expr_match'. If 'm' is
2077 * nonnull then it is copied into the new expr_match, otherwise the new
2078 * expr_match's 'match' member is initialized to a catch-all match for the
2079 * caller to refine in-place.
2081 * If 'conj_id' is nonzero, adds one conjunction based on 'conj_id', 'clause',
2082 * and 'n_clauses' to the returned 'struct expr_match', otherwise the
2083 * expr_match will not have any conjunctions.
2085 * The caller should use expr_match_add() to add the expr_match to a hash table
2086 * after it is finalized. */
2087 static struct expr_match *
2088 expr_match_new(const struct match *m, uint8_t clause, uint8_t n_clauses,
2091 struct expr_match *match = xmalloc(sizeof *match);
2095 match_init_catchall(&match->match);
2098 match->conjunctions = xmalloc(sizeof *match->conjunctions);
2099 match->conjunctions[0].id = conj_id;
2100 match->conjunctions[0].clause = clause;
2101 match->conjunctions[0].n_clauses = n_clauses;
2103 match->allocated = 1;
2105 match->conjunctions = NULL;
2107 match->allocated = 0;
2112 /* Adds 'match' to hash table 'matches', which becomes the new owner of
2115 * This might actually destroy 'match' because it gets merged together with
2116 * some existing conjunction.*/
2118 expr_match_add(struct hmap *matches, struct expr_match *match)
2120 uint32_t hash = match_hash(&match->match, 0);
2121 struct expr_match *m;
2123 HMAP_FOR_EACH_WITH_HASH (m, hmap_node, hash, matches) {
2124 if (match_equal(&m->match, &match->match)) {
2125 if (!m->n || !match->n) {
2126 free(m->conjunctions);
2127 m->conjunctions = NULL;
2131 ovs_assert(match->n == 1);
2132 if (m->n >= m->allocated) {
2133 m->conjunctions = x2nrealloc(m->conjunctions,
2135 sizeof *m->conjunctions);
2137 m->conjunctions[m->n++] = match->conjunctions[0];
2139 free(match->conjunctions);
2145 hmap_insert(matches, &match->hmap_node, hash);
2149 constrain_match(const struct expr *expr, const struct simap *ports,
2152 ovs_assert(expr->type == EXPR_T_CMP);
2153 if (expr->cmp.symbol->width) {
2154 mf_mask_subfield(expr->cmp.symbol->field, &expr->cmp.value,
2155 &expr->cmp.mask, m);
2157 const struct simap_node *node;
2158 node = ports ? simap_find(ports, expr->cmp.string) : NULL;
2163 struct mf_subfield sf;
2164 sf.field = expr->cmp.symbol->field;
2166 sf.n_bits = expr->cmp.symbol->field->n_bits;
2168 union mf_subvalue x;
2169 memset(&x, 0, sizeof x);
2170 x.integer = htonll(node->data);
2172 mf_write_subfield(&sf, &x, m);
2178 add_disjunction(const struct expr *or, const struct simap *ports,
2179 struct match *m, uint8_t clause, uint8_t n_clauses,
2180 uint32_t conj_id, struct hmap *matches)
2185 ovs_assert(or->type == EXPR_T_OR);
2186 LIST_FOR_EACH (sub, node, &or->andor) {
2187 struct expr_match *match = expr_match_new(m, clause, n_clauses,
2189 if (constrain_match(sub, ports, &match->match)) {
2190 expr_match_add(matches, match);
2193 free(match->conjunctions);
2198 /* If n == 1, then this didn't really need to be a disjunction. Oh well,
2199 * that shouldn't happen much. */
2204 add_conjunction(const struct expr *and, const struct simap *ports,
2205 uint32_t *n_conjsp, struct hmap *matches)
2211 match_init_catchall(&match);
2213 ovs_assert(and->type == EXPR_T_AND);
2214 LIST_FOR_EACH (sub, node, &and->andor) {
2215 switch (sub->type) {
2217 if (!constrain_match(sub, ports, &match)) {
2225 case EXPR_T_BOOLEAN:
2231 expr_match_add(matches, expr_match_new(&match, 0, 0, 0));
2232 } else if (n_clauses == 1) {
2233 LIST_FOR_EACH (sub, node, &and->andor) {
2234 if (sub->type == EXPR_T_OR) {
2235 add_disjunction(sub, ports, &match, 0, 0, 0, matches);
2241 LIST_FOR_EACH (sub, node, &and->andor) {
2242 if (sub->type == EXPR_T_OR) {
2243 if (!add_disjunction(sub, ports, &match, clause++,
2244 n_clauses, *n_conjsp, matches)) {
2245 /* This clause can't ever match, so we might as well skip
2246 * adding the other clauses--the overall disjunctive flow
2247 * can't ever match. Ideally we would also back out all of
2248 * the clauses we already added, but that seems like a lot
2249 * of trouble for a case that might never occur in
2259 add_cmp_flow(const struct expr *cmp, const struct simap *ports,
2260 struct hmap *matches)
2262 struct expr_match *m = expr_match_new(NULL, 0, 0, 0);
2263 if (constrain_match(cmp, ports, &m->match)) {
2264 expr_match_add(matches, m);
2270 /* Converts 'expr', which must be in the form returned by expr_normalize(), to
2271 * a collection of Open vSwitch flows in 'matches', which this function
2272 * initializes to an hmap of "struct expr_match" structures. Returns the
2273 * number of conjunctive match IDs consumed by 'matches', which uses
2274 * conjunctive match IDs beginning with 0; the caller must offset or remap them
2275 * into the desired range as necessary.
2277 * 'ports' must be a map from strings (presumably names of ports) to integers.
2278 * Any comparisons against string fields in 'expr' are translated into integers
2279 * through this map. A comparison against a string that is not in 'ports' acts
2280 * like a Boolean "false"; that is, it will always fail to match. For a simple
2281 * expression, this means that the overall expression always fails to match,
2282 * but an expression with a disjunction on the string field might still match
2283 * on other port names.
2285 * (This treatment of string fields might be too simplistic in general, but it
2286 * seems reasonable for now when string fields are used only for ports.) */
2288 expr_to_matches(const struct expr *expr, const struct simap *ports,
2289 struct hmap *matches)
2291 uint32_t n_conjs = 0;
2294 switch (expr->type) {
2296 add_cmp_flow(expr, ports, matches);
2300 add_conjunction(expr, ports, &n_conjs, matches);
2304 if (expr_is_cmp(expr)) {
2307 LIST_FOR_EACH (sub, node, &expr->andor) {
2308 add_cmp_flow(sub, ports, matches);
2313 LIST_FOR_EACH (sub, node, &expr->andor) {
2314 if (sub->type == EXPR_T_AND) {
2315 add_conjunction(sub, ports, &n_conjs, matches);
2317 add_cmp_flow(sub, ports, matches);
2323 case EXPR_T_BOOLEAN:
2324 if (expr->boolean) {
2325 struct expr_match *m = expr_match_new(NULL, 0, 0, 0);
2326 expr_match_add(matches, m);
2335 /* Destroys all of the 'struct expr_match'es in 'matches', as well as the
2336 * 'matches' hmap itself. */
2338 expr_matches_destroy(struct hmap *matches)
2340 struct expr_match *m, *n;
2342 HMAP_FOR_EACH_SAFE (m, n, hmap_node, matches) {
2343 hmap_remove(matches, &m->hmap_node);
2344 free(m->conjunctions);
2347 hmap_destroy(matches);
2350 /* Prints a representation of the 'struct expr_match'es in 'matches' to
2353 expr_matches_print(const struct hmap *matches, FILE *stream)
2355 if (hmap_is_empty(matches)) {
2356 fputs("(no flows)\n", stream);
2360 const struct expr_match *m;
2361 HMAP_FOR_EACH (m, hmap_node, matches) {
2362 char *s = match_to_string(&m->match, OFP_DEFAULT_PRIORITY);
2367 for (int i = 0; i < m->n; i++) {
2368 const struct cls_conjunction *c = &m->conjunctions[i];
2369 fprintf(stream, "%c conjunction(%"PRIu32", %d/%d)",
2370 i == 0 ? ':' : ',', c->id, c->clause, c->n_clauses);
2377 /* Returns true if 'expr' honors the invariants for expressions (see the large
2378 * comment above "struct expr" in expr.h), false otherwise. */
2380 expr_honors_invariants(const struct expr *expr)
2382 const struct expr *sub;
2384 switch (expr->type) {
2386 if (expr->cmp.symbol->width) {
2387 for (int i = 0; i < ARRAY_SIZE(expr->cmp.value.be64); i++) {
2388 if (expr->cmp.value.be64[i] & ~expr->cmp.mask.be64[i]) {
2397 if (list_is_short(&expr->andor)) {
2400 LIST_FOR_EACH (sub, node, &expr->andor) {
2401 if (sub->type == expr->type || !expr_honors_invariants(sub)) {
2407 case EXPR_T_BOOLEAN:
2416 expr_is_normalized_and(const struct expr *expr)
2418 /* XXX should also check that no symbol is repeated. */
2419 const struct expr *sub;
2421 LIST_FOR_EACH (sub, node, &expr->andor) {
2422 if (!expr_is_cmp(sub)) {
2429 /* Returns true if 'expr' is in the form returned by expr_normalize(), false
2432 expr_is_normalized(const struct expr *expr)
2434 switch (expr->type) {
2439 return expr_is_normalized_and(expr);
2442 if (!expr_is_cmp(expr)) {
2443 const struct expr *sub;
2445 LIST_FOR_EACH (sub, node, &expr->andor) {
2446 if (!expr_is_cmp(sub) && !expr_is_normalized_and(sub)) {
2453 case EXPR_T_BOOLEAN: