blob: 86716a550e58438b759e1f3d2d0cfdcb85e87b5f [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
[email protected]116f0a3a2012-04-19 04:22:389class ParseException(Exception):
10 """Thrown when data in the model is invalid.
11 """
12 def __init__(self, parent, message):
13 hierarchy = _GetModelHierarchy(parent)
14 hierarchy.append(message)
15 Exception.__init__(
16 self, 'Model parse exception at:\n' + '\n'.join(hierarchy))
17
[email protected]15f08dd2012-01-27 07:29:4818class Model(object):
19 """Model of all namespaces that comprise an API.
[email protected]cfe484902012-02-15 14:52:3220
21 Properties:
22 - |namespaces| a map of a namespace name to its model.Namespace
[email protected]15f08dd2012-01-27 07:29:4823 """
24 def __init__(self):
25 self.namespaces = {}
26
27 def AddNamespace(self, json, source_file):
[email protected]a1f774972012-04-17 02:11:0928 """Add a namespace's json to the model and returns the namespace.
[email protected]15f08dd2012-01-27 07:29:4829 """
[email protected]15f08dd2012-01-27 07:29:4830 namespace = Namespace(json, source_file)
31 self.namespaces[namespace.name] = namespace
32 return namespace
33
34class Namespace(object):
35 """An API namespace.
[email protected]cfe484902012-02-15 14:52:3236
37 Properties:
38 - |name| the name of the namespace
[email protected]712eca0f2012-02-21 01:13:0739 - |unix_name| the unix_name of the namespace
40 - |source_file| the file that contained the namespace definition
41 - |source_file_dir| the directory component of |source_file|
42 - |source_file_filename| the filename component of |source_file|
[email protected]cfe484902012-02-15 14:52:3243 - |types| a map of type names to their model.Type
44 - |functions| a map of function names to their model.Function
[email protected]116f0a3a2012-04-19 04:22:3845 - |properties| a map of property names to their model.Property
[email protected]15f08dd2012-01-27 07:29:4846 """
47 def __init__(self, json, source_file):
48 self.name = json['namespace']
[email protected]116f0a3a2012-04-19 04:22:3849 self.unix_name = _UnixName(self.name)
[email protected]15f08dd2012-01-27 07:29:4850 self.source_file = source_file
51 self.source_file_dir, self.source_file_filename = os.path.split(source_file)
[email protected]feba21e2012-03-02 15:05:2752 self.parent = None
[email protected]116f0a3a2012-04-19 04:22:3853 _AddTypes(self, json)
54 _AddFunctions(self, json)
55 _AddProperties(self, json)
[email protected]15f08dd2012-01-27 07:29:4856
57class Type(object):
58 """A Type defined in the json.
[email protected]cfe484902012-02-15 14:52:3259
60 Properties:
61 - |name| the type name
62 - |description| the description of the type (if provided)
[email protected]feba21e2012-03-02 15:05:2763 - |properties| a map of property unix_names to their model.Property
64 - |functions| a map of function names to their model.Function
[email protected]25cbf6012012-02-28 05:51:4465 - |from_client| indicates that instances of the Type can originate from the
66 users of generated code, such as top-level types and function results
67 - |from_json| indicates that instances of the Type can originate from the
68 JSON (as described by the schema), such as top-level types and function
69 parameters
[email protected]cf6d0b32012-04-12 04:30:2270 - |type_| the PropertyType of this Type
71 - |item_type| if this is an array, the type of items in the array
[email protected]15f08dd2012-01-27 07:29:4872 """
[email protected]feba21e2012-03-02 15:05:2773 def __init__(self, parent, name, json):
[email protected]cf6d0b32012-04-12 04:30:2274 if json.get('type') == 'array':
75 self.type_ = PropertyType.ARRAY
76 self.item_type = Property(self, name + "Element", json['items'],
77 from_json=True,
78 from_client=True)
[email protected]0ef7f5a12012-05-01 03:58:0679 elif json.get('type') == 'string':
80 self.type_ = PropertyType.STRING
[email protected]cf6d0b32012-04-12 04:30:2281 else:
82 if not (
83 'properties' in json or
84 'additionalProperties' in json or
85 'functions' in json):
[email protected]116f0a3a2012-04-19 04:22:3886 raise ParseException(self, name + " has no properties or functions")
[email protected]cf6d0b32012-04-12 04:30:2287 self.type_ = PropertyType.OBJECT
[email protected]feba21e2012-03-02 15:05:2788 self.name = name
[email protected]15f08dd2012-01-27 07:29:4889 self.description = json.get('description')
[email protected]25cbf6012012-02-28 05:51:4490 self.from_json = True
91 self.from_client = True
[email protected]feba21e2012-03-02 15:05:2792 self.parent = parent
[email protected]116f0a3a2012-04-19 04:22:3893 _AddFunctions(self, json)
94 _AddProperties(self, json, from_json=True, from_client=True)
[email protected]feba21e2012-03-02 15:05:2795
[email protected]116f0a3a2012-04-19 04:22:3896 additional_properties_key = 'additionalProperties'
97 additional_properties = json.get(additional_properties_key)
[email protected]feba21e2012-03-02 15:05:2798 if additional_properties:
[email protected]116f0a3a2012-04-19 04:22:3899 self.properties[additional_properties_key] = Property(
100 self,
101 additional_properties_key,
102 additional_properties,
103 is_additional_properties=True)
[email protected]15f08dd2012-01-27 07:29:48104
105class Callback(object):
106 """A callback parameter to a Function.
[email protected]cfe484902012-02-15 14:52:32107
108 Properties:
109 - |params| the parameters to this callback.
[email protected]15f08dd2012-01-27 07:29:48110 """
[email protected]feba21e2012-03-02 15:05:27111 def __init__(self, parent, json):
[email protected]15f08dd2012-01-27 07:29:48112 params = json['parameters']
[email protected]feba21e2012-03-02 15:05:27113 self.parent = parent
[email protected]cfe484902012-02-15 14:52:32114 self.params = []
[email protected]15f08dd2012-01-27 07:29:48115 if len(params) == 0:
[email protected]cfe484902012-02-15 14:52:32116 return
[email protected]15f08dd2012-01-27 07:29:48117 elif len(params) == 1:
118 param = params[0]
[email protected]feba21e2012-03-02 15:05:27119 self.params.append(Property(self, param['name'], param,
[email protected]25cbf6012012-02-28 05:51:44120 from_client=True))
[email protected]15f08dd2012-01-27 07:29:48121 else:
[email protected]116f0a3a2012-04-19 04:22:38122 raise ParseException(
123 self,
124 "Callbacks can have at most a single parameter")
[email protected]15f08dd2012-01-27 07:29:48125
126class Function(object):
127 """A Function defined in the API.
[email protected]cfe484902012-02-15 14:52:32128
129 Properties:
130 - |name| the function name
131 - |params| a list of parameters to the function (order matters). A separate
132 parameter is used for each choice of a 'choices' parameter.
133 - |description| a description of the function (if provided)
134 - |callback| the callback parameter to the function. There should be exactly
135 one
[email protected]15f08dd2012-01-27 07:29:48136 """
[email protected]feba21e2012-03-02 15:05:27137 def __init__(self, parent, json):
[email protected]15f08dd2012-01-27 07:29:48138 self.name = json['name']
139 self.params = []
[email protected]feba21e2012-03-02 15:05:27140 self.description = json.get('description')
[email protected]15f08dd2012-01-27 07:29:48141 self.callback = None
[email protected]feba21e2012-03-02 15:05:27142 self.parent = parent
[email protected]15f08dd2012-01-27 07:29:48143 for param in json['parameters']:
144 if param.get('type') == 'function':
[email protected]feba21e2012-03-02 15:05:27145 if self.callback:
[email protected]116f0a3a2012-04-19 04:22:38146 raise ParseException(self, self.name + " has more than one callback")
[email protected]feba21e2012-03-02 15:05:27147 self.callback = Callback(self, param)
[email protected]15f08dd2012-01-27 07:29:48148 else:
[email protected]feba21e2012-03-02 15:05:27149 self.params.append(Property(self, param['name'], param,
[email protected]25cbf6012012-02-28 05:51:44150 from_json=True))
[email protected]15f08dd2012-01-27 07:29:48151
[email protected]15f08dd2012-01-27 07:29:48152class Property(object):
153 """A property of a type OR a parameter to a function.
154
[email protected]cfe484902012-02-15 14:52:32155 Properties:
156 - |name| name of the property as in the json. This shouldn't change since
157 it is the key used to access DictionaryValues
158 - |unix_name| the unix_style_name of the property. Used as variable name
159 - |optional| a boolean representing whether the property is optional
160 - |description| a description of the property (if provided)
161 - |type_| the model.PropertyType of this property
162 - |ref_type| the type that the REF property is referencing. Can be used to
163 map to its model.Type
164 - |item_type| a model.Property representing the type of each element in an
165 ARRAY
166 - |properties| the properties of an OBJECT parameter
[email protected]15f08dd2012-01-27 07:29:48167 """
[email protected]feba21e2012-03-02 15:05:27168
169 def __init__(self, parent, name, json, is_additional_properties=False,
170 from_json=False, from_client=False):
[email protected]25cbf6012012-02-28 05:51:44171 """
172 Parameters:
173 - |from_json| indicates that instances of the Type can originate from the
174 JSON (as described by the schema), such as top-level types and function
175 parameters
176 - |from_client| indicates that instances of the Type can originate from the
177 users of generated code, such as top-level types and function results
178 """
[email protected]15f08dd2012-01-27 07:29:48179 self.name = name
[email protected]116f0a3a2012-04-19 04:22:38180 self._unix_name = _UnixName(self.name)
[email protected]cfe484902012-02-15 14:52:32181 self._unix_name_used = False
[email protected]15f08dd2012-01-27 07:29:48182 self.optional = json.get('optional', False)
[email protected]116f0a3a2012-04-19 04:22:38183 self.has_value = False
[email protected]15f08dd2012-01-27 07:29:48184 self.description = json.get('description')
[email protected]feba21e2012-03-02 15:05:27185 self.parent = parent
[email protected]116f0a3a2012-04-19 04:22:38186 _AddProperties(self, json)
[email protected]feba21e2012-03-02 15:05:27187 if is_additional_properties:
188 self.type_ = PropertyType.ADDITIONAL_PROPERTIES
189 elif '$ref' in json:
[email protected]15f08dd2012-01-27 07:29:48190 self.ref_type = json['$ref']
191 self.type_ = PropertyType.REF
[email protected]2111fff9b2012-02-22 12:06:51192 elif 'enum' in json:
193 self.enum_values = []
194 for value in json['enum']:
195 self.enum_values.append(value)
196 self.type_ = PropertyType.ENUM
[email protected]15f08dd2012-01-27 07:29:48197 elif 'type' in json:
198 json_type = json['type']
199 if json_type == 'string':
200 self.type_ = PropertyType.STRING
[email protected]cfe484902012-02-15 14:52:32201 elif json_type == 'any':
202 self.type_ = PropertyType.ANY
203 elif json_type == 'boolean':
[email protected]15f08dd2012-01-27 07:29:48204 self.type_ = PropertyType.BOOLEAN
205 elif json_type == 'integer':
206 self.type_ = PropertyType.INTEGER
[email protected]cfe484902012-02-15 14:52:32207 elif json_type == 'number':
[email protected]15f08dd2012-01-27 07:29:48208 self.type_ = PropertyType.DOUBLE
209 elif json_type == 'array':
[email protected]feba21e2012-03-02 15:05:27210 self.item_type = Property(self, name + "Element", json['items'],
211 from_json=from_json,
212 from_client=from_client)
[email protected]15f08dd2012-01-27 07:29:48213 self.type_ = PropertyType.ARRAY
214 elif json_type == 'object':
[email protected]15f08dd2012-01-27 07:29:48215 self.type_ = PropertyType.OBJECT
[email protected]25cbf6012012-02-28 05:51:44216 # These members are read when this OBJECT Property is used as a Type
[email protected]25cbf6012012-02-28 05:51:44217 self.from_json = from_json
218 self.from_client = from_client
[email protected]feba21e2012-03-02 15:05:27219 type_ = Type(self, self.name, json)
[email protected]116f0a3a2012-04-19 04:22:38220 # self.properties will already have some value from |_AddProperties|.
221 self.properties.update(type_.properties)
[email protected]feba21e2012-03-02 15:05:27222 self.functions = type_.functions
[email protected]bc69ec1a2012-04-24 03:17:19223 elif json_type == 'binary':
224 self.type_ = PropertyType.BINARY
[email protected]15f08dd2012-01-27 07:29:48225 else:
[email protected]feba21e2012-03-02 15:05:27226 raise ParseException(self, 'type ' + json_type + ' not recognized')
[email protected]15f08dd2012-01-27 07:29:48227 elif 'choices' in json:
[email protected]feba21e2012-03-02 15:05:27228 if not json['choices']:
[email protected]116f0a3a2012-04-19 04:22:38229 raise ParseException(self, 'Choices has no choices')
[email protected]15f08dd2012-01-27 07:29:48230 self.choices = {}
[email protected]cfe484902012-02-15 14:52:32231 self.type_ = PropertyType.CHOICES
232 for choice_json in json['choices']:
[email protected]feba21e2012-03-02 15:05:27233 choice = Property(self, self.name, choice_json,
234 from_json=from_json,
235 from_client=from_client)
[email protected]cfe484902012-02-15 14:52:32236 # A choice gets its unix_name set in
237 # cpp_type_generator.GetExpandedChoicesInParams
238 choice._unix_name = None
239 # The existence of any single choice is optional
240 choice.optional = True
241 self.choices[choice.type_] = choice
[email protected]116f0a3a2012-04-19 04:22:38242 elif 'value' in json:
243 self.has_value = True
244 self.value = json['value']
245 if type(self.value) == int:
246 self.type_ = PropertyType.INTEGER
247 else:
248 # TODO(kalman): support more types as necessary.
249 raise ParseException(
250 self, '"%s" is not a supported type' % type(self.value))
[email protected]cfe484902012-02-15 14:52:32251 else:
[email protected]116f0a3a2012-04-19 04:22:38252 raise ParseException(
253 self, 'Property has no type, $ref, choices, or value')
[email protected]cfe484902012-02-15 14:52:32254
255 def GetUnixName(self):
256 """Gets the property's unix_name. Raises AttributeError if not set.
257 """
[email protected]116f0a3a2012-04-19 04:22:38258 if not self._unix_name:
[email protected]cfe484902012-02-15 14:52:32259 raise AttributeError('No unix_name set on %s' % self.name)
260 self._unix_name_used = True
261 return self._unix_name
262
263 def SetUnixName(self, unix_name):
264 """Set the property's unix_name. Raises AttributeError if the unix_name has
265 already been used (GetUnixName has been called).
266 """
267 if unix_name == self._unix_name:
268 return
269 if self._unix_name_used:
270 raise AttributeError(
271 'Cannot set the unix_name on %s; '
272 'it is already used elsewhere as %s' %
273 (self.name, self._unix_name))
274 self._unix_name = unix_name
275
[email protected]712eca0f2012-02-21 01:13:07276 def Copy(self):
277 """Makes a copy of this model.Property object and allow the unix_name to be
278 set again.
279 """
280 property_copy = copy.copy(self)
281 property_copy._unix_name_used = False
282 return property_copy
283
[email protected]cfe484902012-02-15 14:52:32284 unix_name = property(GetUnixName, SetUnixName)
[email protected]15f08dd2012-01-27 07:29:48285
286class PropertyType(object):
287 """Enum of different types of properties/parameters.
288 """
289 class _Info(object):
[email protected]cfe484902012-02-15 14:52:32290 def __init__(self, is_fundamental, name):
[email protected]15f08dd2012-01-27 07:29:48291 self.is_fundamental = is_fundamental
[email protected]cfe484902012-02-15 14:52:32292 self.name = name
[email protected]15f08dd2012-01-27 07:29:48293
[email protected]cfe484902012-02-15 14:52:32294 def __repr__(self):
295 return self.name
296
297 INTEGER = _Info(True, "INTEGER")
298 DOUBLE = _Info(True, "DOUBLE")
299 BOOLEAN = _Info(True, "BOOLEAN")
300 STRING = _Info(True, "STRING")
[email protected]2111fff9b2012-02-22 12:06:51301 ENUM = _Info(False, "ENUM")
[email protected]cfe484902012-02-15 14:52:32302 ARRAY = _Info(False, "ARRAY")
303 REF = _Info(False, "REF")
304 CHOICES = _Info(False, "CHOICES")
305 OBJECT = _Info(False, "OBJECT")
[email protected]bc69ec1a2012-04-24 03:17:19306 BINARY = _Info(False, "BINARY")
[email protected]cfe484902012-02-15 14:52:32307 ANY = _Info(False, "ANY")
[email protected]feba21e2012-03-02 15:05:27308 ADDITIONAL_PROPERTIES = _Info(False, "ADDITIONAL_PROPERTIES")
[email protected]cfe484902012-02-15 14:52:32309
[email protected]116f0a3a2012-04-19 04:22:38310def _UnixName(name):
[email protected]712eca0f2012-02-21 01:13:07311 """Returns the unix_style name for a given lowerCamelCase string.
[email protected]cfe484902012-02-15 14:52:32312 """
[email protected]df74dc42012-04-03 07:08:04313 # First replace any lowerUpper patterns with lower_Upper.
314 s1 = re.sub('([a-z])([A-Z])', r'\1_\2', name)
315 # Now replace any ACMEWidgets patterns with ACME_Widgets
316 s2 = re.sub('([A-Z]+)([A-Z][a-z])', r'\1_\2', s1)
317 # Finally, replace any remaining periods, and make lowercase.
318 return s2.replace('.', '_').lower()
[email protected]cfe484902012-02-15 14:52:32319
[email protected]116f0a3a2012-04-19 04:22:38320def _GetModelHierarchy(entity):
[email protected]feba21e2012-03-02 15:05:27321 """Returns the hierarchy of the given model entity."""
322 hierarchy = []
323 while entity:
324 try:
325 hierarchy.append(entity.name)
326 except AttributeError:
327 hierarchy.append(repr(entity))
328 entity = entity.parent
329 hierarchy.reverse()
330 return hierarchy
[email protected]116f0a3a2012-04-19 04:22:38331
332def _AddTypes(model, json):
333 """Adds Type objects to |model| contained in the 'types' field of |json|.
334 """
335 model.types = {}
336 for type_json in json.get('types', []):
337 type_ = Type(model, type_json['id'], type_json)
338 model.types[type_.name] = type_
339
340def _AddFunctions(model, json):
341 """Adds Function objects to |model| contained in the 'types' field of |json|.
342 """
343 model.functions = {}
344 for function_json in json.get('functions', []):
345 function = Function(model, function_json)
346 model.functions[function.name] = function
347
348def _AddProperties(model, json, from_json=False, from_client=False):
349 """Adds model.Property objects to |model| contained in the 'properties' field
350 of |json|.
351 """
352 model.properties = {}
353 for name, property_json in json.get('properties', {}).items():
354 # TODO(calamity): support functions (callbacks) as properties. The model
355 # doesn't support it yet because the h/cc generators don't -- this is
356 # because we'd need to hook it into a base::Callback or something.
357 #
358 # However, pragmatically it's not necessary to support them anyway, since
359 # the instances of functions-on-properties in the extension APIs are all
360 # handled in pure Javascript on the render process (and .: never reach
361 # C++ let alone the browser).
362 if property_json.get('type') == 'function':
363 continue
364 model.properties[name] = Property(
365 model,
366 name,
367 property_json,
368 from_json=from_json,
369 from_client=from_client)