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"
27 /* Returns a string that represents 'format'. */
29 lex_format_to_string(enum lex_format format)
34 case LEX_F_HEXADECIMAL:
47 /* Initializes 'token'. */
49 lex_token_init(struct lex_token *token)
51 token->type = LEX_T_END;
55 /* Frees memory owned by 'token'. */
57 lex_token_destroy(struct lex_token *token)
62 /* Exchanges 'a' and 'b'. */
64 lex_token_swap(struct lex_token *a, struct lex_token *b)
66 struct lex_token tmp = *a;
71 /* lex_token_format(). */
74 lex_token_n_zeros(enum lex_format format)
77 case LEX_F_DECIMAL: return offsetof(union mf_subvalue, integer);
78 case LEX_F_HEXADECIMAL: return 0;
79 case LEX_F_IPV4: return offsetof(union mf_subvalue, ipv4);
80 case LEX_F_IPV6: return offsetof(union mf_subvalue, ipv6);
81 case LEX_F_ETHERNET: return offsetof(union mf_subvalue, mac);
82 default: OVS_NOT_REACHED();
86 /* Returns the effective format for 'token', that is, the format in which it
87 * should actually be printed. This is ordinarily the same as 'token->format',
88 * but it's always possible that someone sets up a token with a format that
89 * won't work for a value, e.g. 'token->value' is wider than 32 bits but the
90 * format is LEX_F_IPV4. (The lexer itself won't do that; this is an attempt
91 * to avoid confusion in the future.) */
92 static enum lex_format
93 lex_token_get_format(const struct lex_token *token)
95 size_t n_zeros = lex_token_n_zeros(token->format);
96 return (is_all_zeros(&token->value, n_zeros)
97 && (token->type != LEX_T_MASKED_INTEGER
98 || is_all_zeros(&token->mask, n_zeros))
100 : LEX_F_HEXADECIMAL);
104 lex_token_format_value(const union mf_subvalue *value,
105 enum lex_format format, struct ds *s)
109 ds_put_format(s, "%"PRIu64, ntohll(value->integer));
112 case LEX_F_HEXADECIMAL:
113 mf_format_subvalue(value, s);
117 ds_put_format(s, IP_FMT, IP_ARGS(value->ipv4));
121 ipv6_format_addr(&value->ipv6, s);
125 ds_put_format(s, ETH_ADDR_FMT, ETH_ADDR_ARGS(value->mac));
135 lex_token_format_masked_integer(const struct lex_token *token, struct ds *s)
137 enum lex_format format = lex_token_get_format(token);
139 lex_token_format_value(&token->value, format, s);
142 const union mf_subvalue *mask = &token->mask;
143 if (format == LEX_F_IPV4 && ip_is_cidr(mask->ipv4)) {
144 ds_put_format(s, "%d", ip_count_cidr_bits(mask->ipv4));
145 } else if (token->format == LEX_F_IPV6 && ipv6_is_cidr(&mask->ipv6)) {
146 ds_put_format(s, "%d", ipv6_count_cidr_bits(&mask->ipv6));
148 lex_token_format_value(&token->mask, format, s);
152 /* Appends a string representation of 'token' to 's', in a format that can be
153 * losslessly parsed back by the lexer. (LEX_T_END and LEX_T_ERROR can't be
156 lex_token_format(const struct lex_token *token, struct ds *s)
158 switch (token->type) {
164 ds_put_cstr(s, token->s);
168 ds_put_cstr(s, "error(");
169 json_string_escape(token->s, s);
174 json_string_escape(token->s, s);
178 lex_token_format_value(&token->value, lex_token_get_format(token), s);
181 case LEX_T_MASKED_INTEGER:
182 lex_token_format_masked_integer(token, s);
204 ds_put_cstr(s, "==");
207 ds_put_cstr(s, "!=");
213 ds_put_cstr(s, "<=");
219 ds_put_cstr(s, ">=");
225 ds_put_cstr(s, "&&");
228 ds_put_cstr(s, "||");
231 ds_put_cstr(s, "..");
236 case LEX_T_SEMICOLON:
243 ds_put_cstr(s, "<->");
245 case LEX_T_DECREMENT:
246 ds_put_cstr(s, "--");
254 /* lex_token_parse(). */
256 static void OVS_PRINTF_FORMAT(2, 3)
257 lex_error(struct lex_token *token, const char *message, ...)
259 ovs_assert(!token->s);
260 token->type = LEX_T_ERROR;
263 va_start(args, message);
264 token->s = xvasprintf(message, args);
269 lex_parse_hex_integer(const char *start, size_t len, struct lex_token *token)
271 const char *in = start + (len - 1);
272 uint8_t *out = token->value.u8 + (sizeof token->value.u8 - 1);
274 for (int i = 0; i < len; i++) {
275 int hexit = hexit_value(in[-i]);
277 lex_error(token, "Invalid syntax in hexadecimal constant.");
280 if (hexit && i / 2 >= sizeof token->value.u8) {
281 lex_error(token, "Hexadecimal constant requires more than "
282 "%"PRIuSIZE" bits.", 8 * sizeof token->value.u8);
285 out[-(i / 2)] |= i % 2 ? hexit << 4 : hexit;
287 token->format = LEX_F_HEXADECIMAL;
291 lex_parse_integer__(const char *p, struct lex_token *token)
293 lex_token_init(token);
294 token->type = LEX_T_INTEGER;
295 memset(&token->value, 0, sizeof token->value);
296 const char *start = p;
297 const char *end = start;
298 while (isalnum((unsigned char) *end) || *end == ':'
299 || (*end == '.' && end[1] != '.')) {
302 size_t len = end - start;
308 lex_error(token, "Integer constant expected.");
310 && ovs_scan(start, ETH_ADDR_SCAN_FMT"%n",
311 ETH_ADDR_SCAN_ARGS(mac), &n)
313 token->value.mac = mac;
314 token->format = LEX_F_ETHERNET;
315 } else if (start + strspn(start, "0123456789") == end) {
316 if (p[0] == '0' && len > 1) {
317 lex_error(token, "Decimal constants must not have leading zeros.");
319 unsigned long long int integer;
323 integer = strtoull(p, &tail, 10);
324 if (tail != end || errno == ERANGE) {
325 lex_error(token, "Decimal constants must be less than 2**64.");
327 token->value.integer = htonll(integer);
328 token->format = LEX_F_DECIMAL;
331 } else if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
333 lex_parse_hex_integer(start + 2, len - 2, token);
335 lex_error(token, "Hex digits expected following 0%c.", p[1]);
337 } else if (len < INET6_ADDRSTRLEN) {
338 char copy[INET6_ADDRSTRLEN];
339 memcpy(copy, p, len);
342 if (ip_parse(copy, &token->value.ipv4)) {
343 token->format = LEX_F_IPV4;
344 } else if (ipv6_parse(copy, &token->value.ipv6)) {
345 token->format = LEX_F_IPV6;
347 lex_error(token, "Invalid numeric constant.");
350 lex_error(token, "Invalid numeric constant.");
353 ovs_assert(token->type == LEX_T_INTEGER || token->type == LEX_T_ERROR);
358 lex_parse_mask(const char *p, struct lex_token *token)
360 struct lex_token mask;
362 /* Parse just past the '/' as a second integer. Handle errors. */
363 p = lex_parse_integer__(p + 1, &mask);
364 if (mask.type == LEX_T_ERROR) {
365 lex_token_swap(&mask, token);
366 lex_token_destroy(&mask);
369 ovs_assert(mask.type == LEX_T_INTEGER);
371 /* Now convert the value and mask into a masked integer token.
372 * We have a few special cases. */
373 token->type = LEX_T_MASKED_INTEGER;
374 memset(&token->mask, 0, sizeof token->mask);
375 uint32_t prefix_bits = ntohll(mask.value.integer);
376 if (token->format == mask.format) {
377 /* Same format value and mask is always OK. */
378 token->mask = mask.value;
379 } else if (token->format == LEX_F_IPV4
380 && mask.format == LEX_F_DECIMAL
381 && prefix_bits <= 32) {
382 /* IPv4 address with decimal mask is a CIDR prefix. */
383 token->mask.integer = htonll(ntohl(be32_prefix_mask(prefix_bits)));
384 } else if (token->format == LEX_F_IPV6
385 && mask.format == LEX_F_DECIMAL
386 && prefix_bits <= 128) {
387 /* IPv6 address with decimal mask is a CIDR prefix. */
388 token->mask.ipv6 = ipv6_create_mask(prefix_bits);
389 } else if (token->format == LEX_F_DECIMAL
390 && mask.format == LEX_F_HEXADECIMAL
391 && token->value.integer == 0) {
392 /* Special case for e.g. 0/0x1234. */
393 token->format = LEX_F_HEXADECIMAL;
394 token->mask = mask.value;
396 lex_error(token, "Value and mask have incompatible formats.");
400 /* Check invariant that a 1-bit in the value corresponds to a 1-bit in the
402 for (int i = 0; i < ARRAY_SIZE(token->mask.be32); i++) {
403 ovs_be32 v = token->value.be32[i];
404 ovs_be32 m = token->mask.be32[i];
407 lex_error(token, "Value contains unmasked 1-bits.");
413 lex_token_destroy(&mask);
418 lex_parse_integer(const char *p, struct lex_token *token)
420 p = lex_parse_integer__(p, token);
421 if (token->type == LEX_T_INTEGER && *p == '/') {
422 p = lex_parse_mask(p, token);
428 lex_parse_string(const char *p, struct lex_token *token)
430 const char *start = ++p;
434 lex_error(token, "Input ends inside quoted string.");
438 token->type = (json_string_unescape(start, p - start, &token->s)
439 ? LEX_T_STRING : LEX_T_ERROR);
457 lex_is_id1(unsigned char c)
459 return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
460 || c == '_' || c == '.');
464 lex_is_idn(unsigned char c)
466 return lex_is_id1(c) || (c >= '0' && c <= '9');
470 lex_parse_id(const char *p, struct lex_token *token)
472 const char *start = p;
476 } while (lex_is_idn(*p));
478 token->type = LEX_T_ID;
479 token->s = xmemdup0(start, p - start);
483 /* Initializes 'token' and parses the first token from the beginning of
484 * null-terminated string 'p' into 'token'. Stores a pointer to the start of
485 * the token (after skipping white space and comments, if any) into '*startp'.
486 * Returns the character position at which to begin parsing the next token. */
488 lex_token_parse(struct lex_token *token, const char *p, const char **startp)
490 lex_token_init(token);
496 token->type = LEX_T_END;
499 case ' ': case '\t': case '\n': case '\r':
508 } while (*p != '\0' && *p != '\n');
510 } else if (*p == '*') {
513 if (*p == '*' && p[1] == '/') {
516 } else if (*p == '\0' || *p == '\n') {
517 lex_error(token, "`/*' without matching `*/'.");
526 "`/' is only valid as part of `//' or `/*'.");
531 token->type = LEX_T_LPAREN;
536 token->type = LEX_T_RPAREN;
541 token->type = LEX_T_LCURLY;
546 token->type = LEX_T_RCURLY;
551 token->type = LEX_T_LSQUARE;
556 token->type = LEX_T_RSQUARE;
563 token->type = LEX_T_EQ;
566 token->type = LEX_T_EQUALS;
573 token->type = LEX_T_NE;
576 token->type = LEX_T_LOG_NOT;
583 token->type = LEX_T_LOG_AND;
586 lex_error(token, "`&' is only valid as part of `&&'.");
593 token->type = LEX_T_LOG_OR;
596 lex_error(token, "`|' is only valid as part of `||'.");
603 token->type = LEX_T_LE;
605 } else if (*p == '-' && p[1] == '>') {
606 token->type = LEX_T_EXCHANGE;
609 token->type = LEX_T_LT;
616 token->type = LEX_T_GE;
619 token->type = LEX_T_GT;
626 token->type = LEX_T_ELLIPSIS;
629 lex_error(token, "`.' is only valid as part of `..' or a number.");
635 token->type = LEX_T_COMMA;
640 token->type = LEX_T_SEMICOLON;
646 token->type = LEX_T_DECREMENT;
649 lex_error(token, "`-' is only valid as part of `--'.");
653 case '0': case '1': case '2': case '3': case '4':
654 case '5': case '6': case '7': case '8': case '9':
656 p = lex_parse_integer(p, token);
660 p = lex_parse_string(p, token);
663 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
664 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
665 /* We need to distinguish an Ethernet address or IPv6 address from an
666 * identifier. Fortunately, Ethernet addresses and IPv6 addresses that
667 * are ambiguous based on the first character, always start with hex
668 * digits followed by a colon, but identifiers never do. */
669 p = (p[strspn(p, "0123456789abcdefABCDEF")] == ':'
670 ? lex_parse_integer(p, token)
671 : lex_parse_id(p, token));
675 if (lex_is_id1(*p)) {
676 p = lex_parse_id(p, token);
678 if (isprint((unsigned char) *p)) {
679 lex_error(token, "Invalid character `%c' in input.", *p);
681 lex_error(token, "Invalid byte 0x%d in input.", *p);
691 /* Initializes 'lexer' for parsing 'input'.
693 * While the lexer is in use, 'input' must remain available, but the caller
694 * otherwise retains ownership of 'input'.
696 * The caller must call lexer_get() to obtain the first token. */
698 lexer_init(struct lexer *lexer, const char *input)
700 lexer->input = input;
702 lex_token_init(&lexer->token);
705 /* Frees storage associated with 'lexer'. */
707 lexer_destroy(struct lexer *lexer)
709 lex_token_destroy(&lexer->token);
712 /* Obtains the next token from 'lexer' into 'lexer->token', and returns the
713 * token's type. The caller may examine 'lexer->token' directly to obtain full
714 * information about the token. */
716 lexer_get(struct lexer *lexer)
718 lex_token_destroy(&lexer->token);
719 lexer->input = lex_token_parse(&lexer->token, lexer->input, &lexer->start);
720 return lexer->token.type;
723 /* Returns the type of the next token that will be fetched by lexer_get(),
724 * without advancing 'lexer->token' to that token. */
726 lexer_lookahead(const struct lexer *lexer)
728 struct lex_token next;
732 lex_token_parse(&next, lexer->input, &start);
734 lex_token_destroy(&next);
738 /* If 'lexer''s current token has the given 'type', advances 'lexer' to the
739 * next token and returns true. Otherwise returns false. */
741 lexer_match(struct lexer *lexer, enum lex_type type)
743 if (lexer->token.type == type) {
751 /* If 'lexer''s current token is the identifier given in 'id', advances 'lexer'
752 * to the next token and returns true. Otherwise returns false. */
754 lexer_match_id(struct lexer *lexer, const char *id)
756 if (lexer->token.type == LEX_T_ID && !strcmp(lexer->token.s, id)) {
765 lexer_is_int(const struct lexer *lexer)
767 return (lexer->token.type == LEX_T_INTEGER
768 && lexer->token.format == LEX_F_DECIMAL
769 && ntohll(lexer->token.value.integer) <= INT_MAX);
773 lexer_get_int(struct lexer *lexer, int *value)
775 if (lexer_is_int(lexer)) {
776 *value = ntohll(lexer->token.value.integer);