blob: 53b3aee124c0d60736afabd9dd0bde3656c76759 [file] [log] [blame]
[email protected]15f08dd2012-01-27 07:29:481# Copyright (c) 2012 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
[email protected]df74dc42012-04-03 07:08:045import copy
[email protected]15f08dd2012-01-27 07:29:486import os.path
[email protected]cfe484902012-02-15 14:52:327import re
[email protected]15f08dd2012-01-27 07:29:488
9class Model(object):
10 """Model of all namespaces that comprise an API.
[email protected]cfe484902012-02-15 14:52:3211
12 Properties:
13 - |namespaces| a map of a namespace name to its model.Namespace
[email protected]15f08dd2012-01-27 07:29:4814 """
15 def __init__(self):
16 self.namespaces = {}
17
18 def AddNamespace(self, json, source_file):
[email protected]cfe484902012-02-15 14:52:3219 """Add a namespace's json to the model if it doesn't have "nocompile"
20 property set to true. Returns the new namespace or None if a namespace
21 wasn't added.
[email protected]15f08dd2012-01-27 07:29:4822 """
[email protected]cfe484902012-02-15 14:52:3223 if json.get('nocompile', False):
[email protected]15f08dd2012-01-27 07:29:4824 return None
25 namespace = Namespace(json, source_file)
26 self.namespaces[namespace.name] = namespace
27 return namespace
28
29class Namespace(object):
30 """An API namespace.
[email protected]cfe484902012-02-15 14:52:3231
32 Properties:
33 - |name| the name of the namespace
[email protected]712eca0f2012-02-21 01:13:0734 - |unix_name| the unix_name of the namespace
35 - |source_file| the file that contained the namespace definition
36 - |source_file_dir| the directory component of |source_file|
37 - |source_file_filename| the filename component of |source_file|
[email protected]cfe484902012-02-15 14:52:3238 - |types| a map of type names to their model.Type
39 - |functions| a map of function names to their model.Function
[email protected]15f08dd2012-01-27 07:29:4840 """
41 def __init__(self, json, source_file):
42 self.name = json['namespace']
[email protected]feba21e2012-03-02 15:05:2743 self.unix_name = UnixName(self.name)
[email protected]15f08dd2012-01-27 07:29:4844 self.source_file = source_file
45 self.source_file_dir, self.source_file_filename = os.path.split(source_file)
[email protected]15f08dd2012-01-27 07:29:4846 self.types = {}
47 self.functions = {}
[email protected]feba21e2012-03-02 15:05:2748 self.parent = None
49 # TODO(calamity): Implement properties on namespaces for shared structures
50 # or constants across a namespace (e.g Windows::WINDOW_ID_NONE).
51 for property_json in json.get('properties', []):
52 pass
[email protected]712eca0f2012-02-21 01:13:0753 for type_json in json.get('types', []):
[email protected]feba21e2012-03-02 15:05:2754 type_ = Type(self, type_json['id'], type_json)
[email protected]15f08dd2012-01-27 07:29:4855 self.types[type_.name] = type_
[email protected]712eca0f2012-02-21 01:13:0756 for function_json in json.get('functions', []):
[email protected]cfe484902012-02-15 14:52:3257 if not function_json.get('nocompile', False):
[email protected]feba21e2012-03-02 15:05:2758 self.functions[function_json['name']] = Function(self, function_json)
[email protected]15f08dd2012-01-27 07:29:4859
60class Type(object):
61 """A Type defined in the json.
[email protected]cfe484902012-02-15 14:52:3262
63 Properties:
64 - |name| the type name
65 - |description| the description of the type (if provided)
[email protected]feba21e2012-03-02 15:05:2766 - |properties| a map of property unix_names to their model.Property
67 - |functions| a map of function names to their model.Function
[email protected]25cbf6012012-02-28 05:51:4468 - |from_client| indicates that instances of the Type can originate from the
69 users of generated code, such as top-level types and function results
70 - |from_json| indicates that instances of the Type can originate from the
71 JSON (as described by the schema), such as top-level types and function
72 parameters
[email protected]cf6d0b32012-04-12 04:30:2273 - |type_| the PropertyType of this Type
74 - |item_type| if this is an array, the type of items in the array
[email protected]15f08dd2012-01-27 07:29:4875 """
[email protected]feba21e2012-03-02 15:05:2776 def __init__(self, parent, name, json):
[email protected]cf6d0b32012-04-12 04:30:2277 if json.get('type') == 'array':
78 self.type_ = PropertyType.ARRAY
79 self.item_type = Property(self, name + "Element", json['items'],
80 from_json=True,
81 from_client=True)
82 else:
83 if not (
84 'properties' in json or
85 'additionalProperties' in json or
86 'functions' in json):
87 raise ParseException(name + " has no properties or functions")
88 self.type_ = PropertyType.OBJECT
[email protected]feba21e2012-03-02 15:05:2789 self.name = name
[email protected]15f08dd2012-01-27 07:29:4890 self.description = json.get('description')
[email protected]25cbf6012012-02-28 05:51:4491 self.from_json = True
92 self.from_client = True
[email protected]15f08dd2012-01-27 07:29:4893 self.properties = {}
[email protected]feba21e2012-03-02 15:05:2794 self.functions = {}
95 self.parent = parent
96 for function_json in json.get('functions', []):
97 if not function_json.get('nocompile', False):
98 self.functions[function_json['name']] = Function(self, function_json)
99 props = []
100 for prop_name, prop_json in json.get('properties', {}).items():
101 # TODO(calamity): support functions (callbacks) as properties. The model
[email protected]750b8362012-03-07 02:33:35102 # doesn't support it yet because the h/cc generators don't -- this is
[email protected]feba21e2012-03-02 15:05:27103 # because we'd need to hook it into a base::Callback or something.
104 #
105 # However, pragmatically it's not necessary to support them anyway, since
106 # the instances of functions-on-properties in the extension APIs are all
107 # handled in pure Javascript on the render process (and .: never reach
108 # C++ let alone the browser).
109 if prop_json.get('type') == 'function':
110 continue
111 props.append(Property(self, prop_name, prop_json,
[email protected]25cbf6012012-02-28 05:51:44112 from_json=True,
[email protected]feba21e2012-03-02 15:05:27113 from_client=True))
114
115 additional_properties = json.get('additionalProperties')
116 if additional_properties:
117 props.append(Property(self, 'additionalProperties', additional_properties,
118 is_additional_properties=True))
119
120 for prop in props:
121 if prop.unix_name in self.properties:
122 raise ParseException(
123 self.properties[prop.unix_name].name + ' and ' + prop.name +
124 ' are both named ' + prop.unix_name)
125 self.properties[prop.unix_name] = prop
[email protected]15f08dd2012-01-27 07:29:48126
127class Callback(object):
128 """A callback parameter to a Function.
[email protected]cfe484902012-02-15 14:52:32129
130 Properties:
131 - |params| the parameters to this callback.
[email protected]15f08dd2012-01-27 07:29:48132 """
[email protected]feba21e2012-03-02 15:05:27133 def __init__(self, parent, json):
[email protected]15f08dd2012-01-27 07:29:48134 params = json['parameters']
[email protected]feba21e2012-03-02 15:05:27135 self.parent = parent
[email protected]cfe484902012-02-15 14:52:32136 self.params = []
[email protected]15f08dd2012-01-27 07:29:48137 if len(params) == 0:
[email protected]cfe484902012-02-15 14:52:32138 return
[email protected]15f08dd2012-01-27 07:29:48139 elif len(params) == 1:
140 param = params[0]
[email protected]feba21e2012-03-02 15:05:27141 self.params.append(Property(self, param['name'], param,
[email protected]25cbf6012012-02-28 05:51:44142 from_client=True))
[email protected]15f08dd2012-01-27 07:29:48143 else:
[email protected]feba21e2012-03-02 15:05:27144 raise ParseException("Callbacks can have at most a single parameter")
[email protected]15f08dd2012-01-27 07:29:48145
146class Function(object):
147 """A Function defined in the API.
[email protected]cfe484902012-02-15 14:52:32148
149 Properties:
150 - |name| the function name
151 - |params| a list of parameters to the function (order matters). A separate
152 parameter is used for each choice of a 'choices' parameter.
153 - |description| a description of the function (if provided)
154 - |callback| the callback parameter to the function. There should be exactly
155 one
[email protected]15f08dd2012-01-27 07:29:48156 """
[email protected]feba21e2012-03-02 15:05:27157 def __init__(self, parent, json):
[email protected]15f08dd2012-01-27 07:29:48158 self.name = json['name']
159 self.params = []
[email protected]feba21e2012-03-02 15:05:27160 self.description = json.get('description')
[email protected]15f08dd2012-01-27 07:29:48161 self.callback = None
[email protected]feba21e2012-03-02 15:05:27162 self.parent = parent
[email protected]15f08dd2012-01-27 07:29:48163 for param in json['parameters']:
164 if param.get('type') == 'function':
[email protected]feba21e2012-03-02 15:05:27165 if self.callback:
166 raise ParseException(self.name + " has more than one callback")
167 self.callback = Callback(self, param)
[email protected]15f08dd2012-01-27 07:29:48168 else:
[email protected]feba21e2012-03-02 15:05:27169 self.params.append(Property(self, param['name'], param,
[email protected]25cbf6012012-02-28 05:51:44170 from_json=True))
[email protected]15f08dd2012-01-27 07:29:48171
[email protected]15f08dd2012-01-27 07:29:48172class Property(object):
173 """A property of a type OR a parameter to a function.
174
[email protected]cfe484902012-02-15 14:52:32175 Properties:
176 - |name| name of the property as in the json. This shouldn't change since
177 it is the key used to access DictionaryValues
178 - |unix_name| the unix_style_name of the property. Used as variable name
179 - |optional| a boolean representing whether the property is optional
180 - |description| a description of the property (if provided)
181 - |type_| the model.PropertyType of this property
182 - |ref_type| the type that the REF property is referencing. Can be used to
183 map to its model.Type
184 - |item_type| a model.Property representing the type of each element in an
185 ARRAY
186 - |properties| the properties of an OBJECT parameter
[email protected]15f08dd2012-01-27 07:29:48187 """
[email protected]feba21e2012-03-02 15:05:27188
189 def __init__(self, parent, name, json, is_additional_properties=False,
190 from_json=False, from_client=False):
[email protected]25cbf6012012-02-28 05:51:44191 """
192 Parameters:
193 - |from_json| indicates that instances of the Type can originate from the
194 JSON (as described by the schema), such as top-level types and function
195 parameters
196 - |from_client| indicates that instances of the Type can originate from the
197 users of generated code, such as top-level types and function results
198 """
[email protected]15f08dd2012-01-27 07:29:48199 self.name = name
[email protected]feba21e2012-03-02 15:05:27200 self._unix_name = UnixName(self.name)
[email protected]cfe484902012-02-15 14:52:32201 self._unix_name_used = False
[email protected]15f08dd2012-01-27 07:29:48202 self.optional = json.get('optional', False)
203 self.description = json.get('description')
[email protected]feba21e2012-03-02 15:05:27204 self.parent = parent
205 if is_additional_properties:
206 self.type_ = PropertyType.ADDITIONAL_PROPERTIES
207 elif '$ref' in json:
[email protected]15f08dd2012-01-27 07:29:48208 self.ref_type = json['$ref']
209 self.type_ = PropertyType.REF
[email protected]2111fff9b2012-02-22 12:06:51210 elif 'enum' in json:
211 self.enum_values = []
212 for value in json['enum']:
213 self.enum_values.append(value)
214 self.type_ = PropertyType.ENUM
[email protected]15f08dd2012-01-27 07:29:48215 elif 'type' in json:
216 json_type = json['type']
217 if json_type == 'string':
218 self.type_ = PropertyType.STRING
[email protected]cfe484902012-02-15 14:52:32219 elif json_type == 'any':
220 self.type_ = PropertyType.ANY
221 elif json_type == 'boolean':
[email protected]15f08dd2012-01-27 07:29:48222 self.type_ = PropertyType.BOOLEAN
223 elif json_type == 'integer':
224 self.type_ = PropertyType.INTEGER
[email protected]cfe484902012-02-15 14:52:32225 elif json_type == 'number':
[email protected]15f08dd2012-01-27 07:29:48226 self.type_ = PropertyType.DOUBLE
227 elif json_type == 'array':
[email protected]feba21e2012-03-02 15:05:27228 self.item_type = Property(self, name + "Element", json['items'],
229 from_json=from_json,
230 from_client=from_client)
[email protected]15f08dd2012-01-27 07:29:48231 self.type_ = PropertyType.ARRAY
232 elif json_type == 'object':
[email protected]15f08dd2012-01-27 07:29:48233 self.type_ = PropertyType.OBJECT
[email protected]25cbf6012012-02-28 05:51:44234 # These members are read when this OBJECT Property is used as a Type
235 self.properties = {}
236 self.from_json = from_json
237 self.from_client = from_client
[email protected]feba21e2012-03-02 15:05:27238 type_ = Type(self, self.name, json)
239 self.properties = type_.properties
240 self.functions = type_.functions
[email protected]15f08dd2012-01-27 07:29:48241 else:
[email protected]feba21e2012-03-02 15:05:27242 raise ParseException(self, 'type ' + json_type + ' not recognized')
[email protected]15f08dd2012-01-27 07:29:48243 elif 'choices' in json:
[email protected]feba21e2012-03-02 15:05:27244 if not json['choices']:
245 raise ParseException('Choices has no choices')
[email protected]15f08dd2012-01-27 07:29:48246 self.choices = {}
[email protected]cfe484902012-02-15 14:52:32247 self.type_ = PropertyType.CHOICES
248 for choice_json in json['choices']:
[email protected]feba21e2012-03-02 15:05:27249 choice = Property(self, self.name, choice_json,
250 from_json=from_json,
251 from_client=from_client)
[email protected]cfe484902012-02-15 14:52:32252 # A choice gets its unix_name set in
253 # cpp_type_generator.GetExpandedChoicesInParams
254 choice._unix_name = None
255 # The existence of any single choice is optional
256 choice.optional = True
257 self.choices[choice.type_] = choice
258 else:
[email protected]feba21e2012-03-02 15:05:27259 raise ParseException('Property has no type, $ref or choices')
[email protected]cfe484902012-02-15 14:52:32260
261 def GetUnixName(self):
262 """Gets the property's unix_name. Raises AttributeError if not set.
263 """
264 if self._unix_name is None:
265 raise AttributeError('No unix_name set on %s' % self.name)
266 self._unix_name_used = True
267 return self._unix_name
268
269 def SetUnixName(self, unix_name):
270 """Set the property's unix_name. Raises AttributeError if the unix_name has
271 already been used (GetUnixName has been called).
272 """
273 if unix_name == self._unix_name:
274 return
275 if self._unix_name_used:
276 raise AttributeError(
277 'Cannot set the unix_name on %s; '
278 'it is already used elsewhere as %s' %
279 (self.name, self._unix_name))
280 self._unix_name = unix_name
281
[email protected]712eca0f2012-02-21 01:13:07282 def Copy(self):
283 """Makes a copy of this model.Property object and allow the unix_name to be
284 set again.
285 """
286 property_copy = copy.copy(self)
287 property_copy._unix_name_used = False
288 return property_copy
289
[email protected]cfe484902012-02-15 14:52:32290 unix_name = property(GetUnixName, SetUnixName)
[email protected]15f08dd2012-01-27 07:29:48291
292class PropertyType(object):
293 """Enum of different types of properties/parameters.
294 """
295 class _Info(object):
[email protected]cfe484902012-02-15 14:52:32296 def __init__(self, is_fundamental, name):
[email protected]15f08dd2012-01-27 07:29:48297 self.is_fundamental = is_fundamental
[email protected]cfe484902012-02-15 14:52:32298 self.name = name
[email protected]15f08dd2012-01-27 07:29:48299
[email protected]cfe484902012-02-15 14:52:32300 def __repr__(self):
301 return self.name
302
303 INTEGER = _Info(True, "INTEGER")
304 DOUBLE = _Info(True, "DOUBLE")
305 BOOLEAN = _Info(True, "BOOLEAN")
306 STRING = _Info(True, "STRING")
[email protected]2111fff9b2012-02-22 12:06:51307 ENUM = _Info(False, "ENUM")
[email protected]cfe484902012-02-15 14:52:32308 ARRAY = _Info(False, "ARRAY")
309 REF = _Info(False, "REF")
310 CHOICES = _Info(False, "CHOICES")
311 OBJECT = _Info(False, "OBJECT")
312 ANY = _Info(False, "ANY")
[email protected]feba21e2012-03-02 15:05:27313 ADDITIONAL_PROPERTIES = _Info(False, "ADDITIONAL_PROPERTIES")
[email protected]cfe484902012-02-15 14:52:32314
[email protected]feba21e2012-03-02 15:05:27315def UnixName(name):
[email protected]712eca0f2012-02-21 01:13:07316 """Returns the unix_style name for a given lowerCamelCase string.
[email protected]cfe484902012-02-15 14:52:32317 """
[email protected]df74dc42012-04-03 07:08:04318 # First replace any lowerUpper patterns with lower_Upper.
319 s1 = re.sub('([a-z])([A-Z])', r'\1_\2', name)
320 # Now replace any ACMEWidgets patterns with ACME_Widgets
321 s2 = re.sub('([A-Z]+)([A-Z][a-z])', r'\1_\2', s1)
322 # Finally, replace any remaining periods, and make lowercase.
323 return s2.replace('.', '_').lower()
[email protected]cfe484902012-02-15 14:52:32324
[email protected]feba21e2012-03-02 15:05:27325class ParseException(Exception):
326 """Thrown when data in the model is invalid."""
327 def __init__(self, parent, message):
328 hierarchy = GetModelHierarchy(parent)
329 hierarchy.append(message)
330 Exception.__init__(
331 self, 'Model parse exception at:\n' + '\n'.join(hierarchy))
332
333def GetModelHierarchy(entity):
334 """Returns the hierarchy of the given model entity."""
335 hierarchy = []
336 while entity:
337 try:
338 hierarchy.append(entity.name)
339 except AttributeError:
340 hierarchy.append(repr(entity))
341 entity = entity.parent
342 hierarchy.reverse()
343 return hierarchy