python: Drop unicode type.
[cascardo/ovs.git] / python / ovs / db / parser.py
1 # Copyright (c) 2010, 2011 Nicira, Inc.
2 #
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:
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import re
16
17 import six
18
19 from ovs.db import error
20
21
22 class Parser(object):
23     def __init__(self, json, name):
24         self.name = name
25         self.json = json
26         if type(json) != dict:
27             self.__raise_error("Object expected.")
28         self.used = set()
29
30     def __get(self, name, types, optional, default=None):
31         if name in self.json:
32             self.used.add(name)
33             member = float_to_int(self.json[name])
34             if is_identifier(member) and "id" in types:
35                 return member
36             try:
37                 if len(types) and not isinstance(member, tuple(types)):
38                     self.__raise_error("Type mismatch for member '%s'." % name)
39             except TypeError:
40                 self.__raise_error("Type mismatch for member '%s'." % name)
41             return member
42         else:
43             if not optional:
44                 self.__raise_error("Required '%s' member is missing." % name)
45             return default
46
47     def get(self, name, types):
48         return self.__get(name, types, False)
49
50     def get_optional(self, name, types, default=None):
51         return self.__get(name, types, True, default)
52
53     def __raise_error(self, message):
54         raise error.Error("Parsing %s failed: %s" % (self.name, message),
55                           self.json)
56
57     def finish(self):
58         missing = set(self.json) - set(self.used)
59         if missing:
60             name = missing.pop()
61             if len(missing) > 1:
62                 present = "and %d other members are" % len(missing)
63             elif missing:
64                 present = "and 1 other member are"
65             else:
66                 present = "is"
67             self.__raise_error("Member '%s' %s present but not allowed here" %
68                                (name, present))
69
70
71 def float_to_int(x):
72     # XXX still needed?
73     if type(x) == float:
74         integer = int(x)
75         if integer == x and -2 ** 53 <= integer < 2 ** 53:
76             return integer
77     return x
78
79
80 id_re = re.compile("[_a-zA-Z][_a-zA-Z0-9]*$")
81
82
83 def is_identifier(s):
84     return isinstance(s, six.string_types) and id_re.match(s)
85
86
87 def json_type_to_string(type_):
88     number_types = list(six.integer_types)
89     number_types.extend([float])
90     number_types = tuple(number_types)
91     if type_ is None:
92         return "null"
93     elif issubclass(type_, bool):
94         return "boolean"
95     elif issubclass(type_, dict):
96         return "object"
97     elif issubclass(type_, list):
98         return "array"
99     elif issubclass(type_, number_types):
100         return "number"
101     elif issubclass(type_, six.string_types):
102         return "string"
103     else:
104         return "<invalid>"
105
106
107 def unwrap_json(json, name, types, desc):
108     if (not isinstance(json, (list, tuple))
109             or len(json) != 2 or json[0] != name
110             or not isinstance(json[1], tuple(types))):
111         raise error.Error('expected ["%s", <%s>]' % (name, desc), json)
112     return json[1]
113
114
115 def parse_json_pair(json):
116     if type(json) != list or len(json) != 2:
117         raise error.Error("expected 2-element array", json)
118     return json