1 /* Copyright (c) 2009, 2011 Nicira Networks
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
18 #include "ovsdb-parser.h"
23 #include "ovsdb-error.h"
26 ovsdb_parser_init(struct ovsdb_parser *parser, const struct json *json,
27 const char *name, ...)
32 parser->name = xvasprintf(name, args);
35 sset_init(&parser->used);
38 parser->json = (json && json->type == JSON_OBJECT ? json : NULL);
40 ovsdb_parser_raise_error(parser, "Object expected.");
45 ovsdb_parser_is_id(const char *string)
50 if (!isalpha(c) && c != '_') {
58 } else if (!isalpha(c) && !isdigit(c) && c != '_') {
65 ovsdb_parser_member(struct ovsdb_parser *parser, const char *name,
66 enum ovsdb_parser_types types)
74 value = shash_find_data(json_object(parser->json), name);
76 if (!(types & OP_OPTIONAL)) {
77 ovsdb_parser_raise_error(parser,
78 "Required '%s' member is missing.", name);
83 if ((value->type >= 0 && value->type < JSON_N_TYPES
84 && types & (1u << value->type))
85 || (types & OP_ID && value->type == JSON_STRING
86 && ovsdb_parser_is_id(value->u.string)))
88 sset_add(&parser->used, name);
91 ovsdb_parser_raise_error(parser, "Type mismatch for member '%s'.",
98 ovsdb_parser_raise_error(struct ovsdb_parser *parser, const char *format, ...)
100 if (!parser->error) {
101 struct ovsdb_error *error;
105 va_start(args, format);
106 message = xvasprintf(format, args);
109 error = ovsdb_syntax_error(parser->json, NULL, "Parsing %s failed: %s",
110 parser->name, message);
113 parser->error = error;
118 ovsdb_parser_get_error(const struct ovsdb_parser *parser)
120 return parser->error ? ovsdb_error_clone(parser->error) : NULL;
124 ovsdb_parser_has_error(const struct ovsdb_parser *parser)
126 return parser->error != NULL;
130 ovsdb_parser_finish(struct ovsdb_parser *parser)
132 if (!parser->error) {
133 const struct shash *object = json_object(parser->json);
136 n_unused = shash_count(object) - sset_count(&parser->used);
138 struct shash_node *node;
140 SHASH_FOR_EACH (node, object) {
141 if (!sset_contains(&parser->used, node->name)) {
143 ovsdb_parser_raise_error(
145 "Member '%s' and %zu other member%s "
146 "are present but not allowed here.",
147 node->name, n_unused - 1, n_unused > 2 ? "s" : "");
149 ovsdb_parser_raise_error(
151 "Member '%s' is present but not allowed here.",
161 sset_destroy(&parser->used);
163 return parser->error;