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.
22 #include "dynamic-string.h"
26 /* Returns a string that represents 'format'. */
28 lex_format_to_string(enum lex_format format)
33 case LEX_F_HEXADECIMAL:
46 /* Initializes 'token'. */
48 lex_token_init(struct lex_token *token)
50 token->type = LEX_T_END;
54 /* Frees memory owned by 'token'. */
56 lex_token_destroy(struct lex_token *token)
61 /* Exchanges 'a' and 'b'. */
63 lex_token_swap(struct lex_token *a, struct lex_token *b)
65 struct lex_token tmp = *a;
70 /* lex_token_format(). */
73 lex_token_n_zeros(enum lex_format format)
76 case LEX_F_DECIMAL: return offsetof(union mf_subvalue, integer);
77 case LEX_F_HEXADECIMAL: return 0;
78 case LEX_F_IPV4: return offsetof(union mf_subvalue, ipv4);
79 case LEX_F_IPV6: return offsetof(union mf_subvalue, ipv6);
80 case LEX_F_ETHERNET: return offsetof(union mf_subvalue, mac);
81 default: OVS_NOT_REACHED();
85 /* Returns the effective format for 'token', that is, the format in which it
86 * should actually be printed. This is ordinarily the same as 'token->format',
87 * but it's always possible that someone sets up a token with a format that
88 * won't work for a value, e.g. 'token->value' is wider than 32 bits but the
89 * format is LEX_F_IPV4. (The lexer itself won't do that; this is an attempt
90 * to avoid confusion in the future.) */
91 static enum lex_format
92 lex_token_get_format(const struct lex_token *token)
94 size_t n_zeros = lex_token_n_zeros(token->format);
95 return (is_all_zeros(&token->value, n_zeros)
96 && (token->type != LEX_T_MASKED_INTEGER
97 || is_all_zeros(&token->mask, n_zeros))
103 lex_token_format_value(const union mf_subvalue *value,
104 enum lex_format format, struct ds *s)
108 ds_put_format(s, "%"PRIu64, ntohll(value->integer));
111 case LEX_F_HEXADECIMAL:
112 mf_format_subvalue(value, s);
116 ds_put_format(s, IP_FMT, IP_ARGS(value->ipv4));
120 print_ipv6_addr(s, &value->ipv6);
124 ds_put_format(s, ETH_ADDR_FMT, ETH_ADDR_ARGS(value->mac));
134 lex_token_format_masked_integer(const struct lex_token *token, struct ds *s)
136 enum lex_format format = lex_token_get_format(token);
138 lex_token_format_value(&token->value, format, s);
141 const union mf_subvalue *mask = &token->mask;
142 if (format == LEX_F_IPV4 && ip_is_cidr(mask->ipv4)) {
143 ds_put_format(s, "%d", ip_count_cidr_bits(mask->ipv4));
144 } else if (token->format == LEX_F_IPV6 && ipv6_is_cidr(&mask->ipv6)) {
145 ds_put_format(s, "%d", ipv6_count_cidr_bits(&mask->ipv6));
147 lex_token_format_value(&token->mask, format, s);
151 /* Appends a string representation of 'token' to 's', in a format that can be
152 * losslessly parsed back by the lexer. (LEX_T_END and LEX_T_ERROR can't be
155 lex_token_format(const struct lex_token *token, struct ds *s)
157 switch (token->type) {
163 ds_put_cstr(s, token->s);
167 ds_put_cstr(s, "error(");
168 json_string_escape(token->s, s);
173 json_string_escape(token->s, s);
177 lex_token_format_value(&token->value, lex_token_get_format(token), s);
180 case LEX_T_MASKED_INTEGER:
181 lex_token_format_masked_integer(token, s);
203 ds_put_cstr(s, "==");
206 ds_put_cstr(s, "!=");
212 ds_put_cstr(s, "<=");
218 ds_put_cstr(s, ">=");
224 ds_put_cstr(s, "&&");
227 ds_put_cstr(s, "||");
230 ds_put_cstr(s, "..");
235 case LEX_T_SEMICOLON:
242 ds_put_cstr(s, "<->");
244 case LEX_T_DECREMENT:
245 ds_put_cstr(s, "--");
253 /* lex_token_parse(). */
255 static void OVS_PRINTF_FORMAT(2, 3)
256 lex_error(struct lex_token *token, const char *message, ...)
258 ovs_assert(!token->s);
259 token->type = LEX_T_ERROR;
262 va_start(args, message);
263 token->s = xvasprintf(message, args);
268 lex_parse_hex_integer(const char *start, size_t len, struct lex_token *token)
270 const char *in = start + (len - 1);
271 uint8_t *out = token->value.u8 + (sizeof token->value.u8 - 1);
273 for (int i = 0; i < len; i++) {
274 int hexit = hexit_value(in[-i]);
276 lex_error(token, "Invalid syntax in hexadecimal constant.");
279 if (hexit && i / 2 >= sizeof token->value.u8) {
280 lex_error(token, "Hexadecimal constant requires more than "
281 "%"PRIuSIZE" bits.", 8 * sizeof token->value.u8);
284 out[-(i / 2)] |= i % 2 ? hexit << 4 : hexit;
286 token->format = LEX_F_HEXADECIMAL;
290 lex_parse_integer__(const char *p, struct lex_token *token)
292 lex_token_init(token);
293 token->type = LEX_T_INTEGER;
294 memset(&token->value, 0, sizeof token->value);
295 const char *start = p;
296 const char *end = start;
297 while (isalnum((unsigned char) *end) || *end == ':'
298 || (*end == '.' && end[1] != '.')) {
301 size_t len = end - start;
307 lex_error(token, "Integer constant expected.");
309 && ovs_scan(start, ETH_ADDR_SCAN_FMT"%n",
310 ETH_ADDR_SCAN_ARGS(mac), &n)
312 token->value.mac = mac;
313 token->format = LEX_F_ETHERNET;
314 } else if (start + strspn(start, "0123456789") == end) {
315 if (p[0] == '0' && len > 1) {
316 lex_error(token, "Decimal constants must not have leading zeros.");
318 unsigned long long int integer;
322 integer = strtoull(p, &tail, 10);
323 if (tail != end || errno == ERANGE) {
324 lex_error(token, "Decimal constants must be less than 2**64.");
326 token->value.integer = htonll(integer);
327 token->format = LEX_F_DECIMAL;
330 } else if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
332 lex_parse_hex_integer(start + 2, len - 2, token);
334 lex_error(token, "Hex digits expected following 0%c.", p[1]);
336 } else if (len < INET6_ADDRSTRLEN) {
337 char copy[INET6_ADDRSTRLEN];
338 memcpy(copy, p, len);
342 struct in6_addr ipv6;
343 if (inet_pton(AF_INET, copy, &ipv4) == 1) {
344 token->value.ipv4 = ipv4.s_addr;
345 token->format = LEX_F_IPV4;
346 } else if (inet_pton(AF_INET6, copy, &ipv6) == 1) {
347 token->value.ipv6 = ipv6;
348 token->format = LEX_F_IPV6;
350 lex_error(token, "Invalid numeric constant.");
353 lex_error(token, "Invalid numeric constant.");
356 ovs_assert(token->type == LEX_T_INTEGER || token->type == LEX_T_ERROR);
361 lex_parse_mask(const char *p, struct lex_token *token)
363 struct lex_token mask;
365 /* Parse just past the '/' as a second integer. Handle errors. */
366 p = lex_parse_integer__(p + 1, &mask);
367 if (mask.type == LEX_T_ERROR) {
368 lex_token_swap(&mask, token);
369 lex_token_destroy(&mask);
372 ovs_assert(mask.type == LEX_T_INTEGER);
374 /* Now convert the value and mask into a masked integer token.
375 * We have a few special cases. */
376 token->type = LEX_T_MASKED_INTEGER;
377 memset(&token->mask, 0, sizeof token->mask);
378 uint32_t prefix_bits = ntohll(mask.value.integer);
379 if (token->format == mask.format) {
380 /* Same format value and mask is always OK. */
381 token->mask = mask.value;
382 } else if (token->format == LEX_F_IPV4
383 && mask.format == LEX_F_DECIMAL
384 && prefix_bits <= 32) {
385 /* IPv4 address with decimal mask is a CIDR prefix. */
386 token->mask.integer = htonll(ntohl(be32_prefix_mask(prefix_bits)));
387 } else if (token->format == LEX_F_IPV6
388 && mask.format == LEX_F_DECIMAL
389 && prefix_bits <= 128) {
390 /* IPv6 address with decimal mask is a CIDR prefix. */
391 token->mask.ipv6 = ipv6_create_mask(prefix_bits);
392 } else if (token->format == LEX_F_DECIMAL
393 && mask.format == LEX_F_HEXADECIMAL
394 && token->value.integer == 0) {
395 /* Special case for e.g. 0/0x1234. */
396 token->format = LEX_F_HEXADECIMAL;
397 token->mask = mask.value;
399 lex_error(token, "Value and mask have incompatible formats.");
403 /* Check invariant that a 1-bit in the value corresponds to a 1-bit in the
405 for (int i = 0; i < ARRAY_SIZE(token->mask.be32); i++) {
406 ovs_be32 v = token->value.be32[i];
407 ovs_be32 m = token->mask.be32[i];
410 lex_error(token, "Value contains unmasked 1-bits.");
416 lex_token_destroy(&mask);
421 lex_parse_integer(const char *p, struct lex_token *token)
423 p = lex_parse_integer__(p, token);
424 if (token->type == LEX_T_INTEGER && *p == '/') {
425 p = lex_parse_mask(p, token);
431 lex_parse_string(const char *p, struct lex_token *token)
433 const char *start = ++p;
437 lex_error(token, "Input ends inside quoted string.");
441 token->type = (json_string_unescape(start, p - start, &token->s)
442 ? LEX_T_STRING : LEX_T_ERROR);
460 lex_is_id1(unsigned char c)
462 return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
463 || c == '_' || c == '.');
467 lex_is_idn(unsigned char c)
469 return lex_is_id1(c) || (c >= '0' && c <= '9');
473 lex_parse_id(const char *p, struct lex_token *token)
475 const char *start = p;
479 } while (lex_is_idn(*p));
481 token->type = LEX_T_ID;
482 token->s = xmemdup0(start, p - start);
486 /* Initializes 'token' and parses the first token from the beginning of
487 * null-terminated string 'p' into 'token'. Stores a pointer to the start of
488 * the token (after skipping white space and comments, if any) into '*startp'.
489 * Returns the character position at which to begin parsing the next token. */
491 lex_token_parse(struct lex_token *token, const char *p, const char **startp)
493 lex_token_init(token);
499 token->type = LEX_T_END;
502 case ' ': case '\t': case '\n': case '\r':
511 } while (*p != '\0' && *p != '\n');
513 } else if (*p == '*') {
516 if (*p == '*' && p[1] == '/') {
519 } else if (*p == '\0' || *p == '\n') {
520 lex_error(token, "`/*' without matching `*/'.");
529 "`/' is only valid as part of `//' or `/*'.");
534 token->type = LEX_T_LPAREN;
539 token->type = LEX_T_RPAREN;
544 token->type = LEX_T_LCURLY;
549 token->type = LEX_T_RCURLY;
554 token->type = LEX_T_LSQUARE;
559 token->type = LEX_T_RSQUARE;
566 token->type = LEX_T_EQ;
569 token->type = LEX_T_EQUALS;
576 token->type = LEX_T_NE;
579 token->type = LEX_T_LOG_NOT;
586 token->type = LEX_T_LOG_AND;
589 lex_error(token, "`&' is only valid as part of `&&'.");
596 token->type = LEX_T_LOG_OR;
599 lex_error(token, "`|' is only valid as part of `||'.");
606 token->type = LEX_T_LE;
608 } else if (*p == '-' && p[1] == '>') {
609 token->type = LEX_T_EXCHANGE;
612 token->type = LEX_T_LT;
619 token->type = LEX_T_GE;
622 token->type = LEX_T_GT;
629 token->type = LEX_T_ELLIPSIS;
632 lex_error(token, "`.' is only valid as part of `..' or a number.");
638 token->type = LEX_T_COMMA;
643 token->type = LEX_T_SEMICOLON;
649 token->type = LEX_T_DECREMENT;
652 lex_error(token, "`-' is only valid as part of `--'.");
656 case '0': case '1': case '2': case '3': case '4':
657 case '5': case '6': case '7': case '8': case '9':
659 p = lex_parse_integer(p, token);
663 p = lex_parse_string(p, token);
666 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
667 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
668 /* We need to distinguish an Ethernet address or IPv6 address from an
669 * identifier. Fortunately, Ethernet addresses and IPv6 addresses that
670 * are ambiguous based on the first character, always start with hex
671 * digits followed by a colon, but identifiers never do. */
672 p = (p[strspn(p, "0123456789abcdefABCDEF")] == ':'
673 ? lex_parse_integer(p, token)
674 : lex_parse_id(p, token));
678 if (lex_is_id1(*p)) {
679 p = lex_parse_id(p, token);
681 if (isprint((unsigned char) *p)) {
682 lex_error(token, "Invalid character `%c' in input.", *p);
684 lex_error(token, "Invalid byte 0x%d in input.", *p);
694 /* Initializes 'lexer' for parsing 'input'.
696 * While the lexer is in use, 'input' must remain available, but the caller
697 * otherwise retains ownership of 'input'.
699 * The caller must call lexer_get() to obtain the first token. */
701 lexer_init(struct lexer *lexer, const char *input)
703 lexer->input = input;
705 lex_token_init(&lexer->token);
708 /* Frees storage associated with 'lexer'. */
710 lexer_destroy(struct lexer *lexer)
712 lex_token_destroy(&lexer->token);
715 /* Obtains the next token from 'lexer' into 'lexer->token', and returns the
716 * token's type. The caller may examine 'lexer->token' directly to obtain full
717 * information about the token. */
719 lexer_get(struct lexer *lexer)
721 lex_token_destroy(&lexer->token);
722 lexer->input = lex_token_parse(&lexer->token, lexer->input, &lexer->start);
723 return lexer->token.type;
726 /* Returns the type of the next token that will be fetched by lexer_get(),
727 * without advancing 'lexer->token' to that token. */
729 lexer_lookahead(const struct lexer *lexer)
731 struct lex_token next;
735 lex_token_parse(&next, lexer->input, &start);
737 lex_token_destroy(&next);
741 /* If 'lexer''s current token has the given 'type', advances 'lexer' to the
742 * next token and returns true. Otherwise returns false. */
744 lexer_match(struct lexer *lexer, enum lex_type type)
746 if (lexer->token.type == type) {
754 /* If 'lexer''s current token is the identifier given in 'id', advances 'lexer'
755 * to the next token and returns true. Otherwise returns false. */
757 lexer_match_id(struct lexer *lexer, const char *id)
759 if (lexer->token.type == LEX_T_ID && !strcmp(lexer->token.s, id)) {
768 lexer_is_int(const struct lexer *lexer)
770 return (lexer->token.type == LEX_T_INTEGER
771 && lexer->token.format == LEX_F_DECIMAL
772 && ntohll(lexer->token.value.integer) <= INT_MAX);
776 lexer_get_int(struct lexer *lexer, int *value)
778 if (lexer_is_int(lexer)) {
779 *value = ntohll(lexer->token.value.integer);