1 /* Copyright (c) 2009 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 svec_init(&parser->used);
38 parser->json = (json && json->type == JSON_OBJECT ? json : NULL);
40 ovsdb_parser_raise_error(parser, "Object expected.");
45 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)
86 && value->type == JSON_STRING
87 && is_id(value->u.string))))
89 svec_add(&parser->used, name);
92 ovsdb_parser_raise_error(parser, "Type mismatch for member '%s'.",
99 ovsdb_parser_raise_error(struct ovsdb_parser *parser, const char *format, ...)
101 if (!parser->error) {
102 struct ovsdb_error *error;
106 va_start(args, format);
107 message = xvasprintf(format, args);
110 error = ovsdb_syntax_error(parser->json, NULL, "Parsing %s failed: %s",
111 parser->name, message);
114 parser->error = error;
119 ovsdb_parser_get_error(const struct ovsdb_parser *parser)
121 return parser->error ? ovsdb_error_clone(parser->error) : NULL;
125 ovsdb_parser_has_error(const struct ovsdb_parser *parser)
127 return parser->error != NULL;
131 ovsdb_parser_finish(struct ovsdb_parser *parser)
133 if (!parser->error) {
134 const struct shash *object = json_object(parser->json);
137 /* XXX this method of detecting unused members can be made cheaper */
138 svec_sort_unique(&parser->used);
139 n_unused = shash_count(object) - parser->used.n;
141 struct shash_node *node;
143 SHASH_FOR_EACH (node, object) {
144 if (!svec_contains(&parser->used, node->name)) {
146 ovsdb_parser_raise_error(
148 "Member '%s' and %zu other member%s "
149 "are present but not allowed here.",
150 node->name, n_unused - 1, n_unused > 2 ? "s" : "");
152 ovsdb_parser_raise_error(
154 "Member '%s' is present but not allowed here.",
164 svec_destroy(&parser->used);
166 return parser->error;