blob: b7a094a5b72ff289a5f18799296cb7ccdcf33473 [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]b741e8f2012-07-16 21:47:2445 - |events| a map of event names to their model.Function
[email protected]116f0a3a2012-04-19 04:22:3846 - |properties| a map of property names to their model.Property
[email protected]15f08dd2012-01-27 07:29:4847 """
48 def __init__(self, json, source_file):
49 self.name = json['namespace']
[email protected]4ba6bdc2012-06-18 20:40:1450 self.unix_name = UnixName(self.name)
[email protected]15f08dd2012-01-27 07:29:4851 self.source_file = source_file
52 self.source_file_dir, self.source_file_filename = os.path.split(source_file)
[email protected]feba21e2012-03-02 15:05:2753 self.parent = None
[email protected]116f0a3a2012-04-19 04:22:3854 _AddTypes(self, json)
55 _AddFunctions(self, json)
[email protected]b741e8f2012-07-16 21:47:2456 _AddEvents(self, json)
[email protected]116f0a3a2012-04-19 04:22:3857 _AddProperties(self, json)
[email protected]15f08dd2012-01-27 07:29:4858
59class Type(object):
60 """A Type defined in the json.
[email protected]cfe484902012-02-15 14:52:3261
62 Properties:
63 - |name| the type name
64 - |description| the description of the type (if provided)
[email protected]feba21e2012-03-02 15:05:2765 - |properties| a map of property unix_names to their model.Property
66 - |functions| a map of function names to their model.Function
[email protected]d32b8e52012-07-23 18:40:0867 - |events| a map of event names to their model.Event
[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)
[email protected]0ef7f5a12012-05-01 03:58:0682 elif json.get('type') == 'string':
83 self.type_ = PropertyType.STRING
[email protected]cf6d0b32012-04-12 04:30:2284 else:
85 if not (
86 'properties' in json or
87 'additionalProperties' in json or
[email protected]e975d112012-07-31 22:12:4388 'functions' in json or
89 'events' in json):
[email protected]116f0a3a2012-04-19 04:22:3890 raise ParseException(self, name + " has no properties or functions")
[email protected]cf6d0b32012-04-12 04:30:2291 self.type_ = PropertyType.OBJECT
[email protected]feba21e2012-03-02 15:05:2792 self.name = name
[email protected]15f08dd2012-01-27 07:29:4893 self.description = json.get('description')
[email protected]25cbf6012012-02-28 05:51:4494 self.from_json = True
95 self.from_client = True
[email protected]feba21e2012-03-02 15:05:2796 self.parent = parent
[email protected]491e60d32012-07-20 01:03:1397 self.instance_of = json.get('isInstanceOf', None)
[email protected]116f0a3a2012-04-19 04:22:3898 _AddFunctions(self, json)
[email protected]d32b8e52012-07-23 18:40:0899 _AddEvents(self, json)
[email protected]116f0a3a2012-04-19 04:22:38100 _AddProperties(self, json, from_json=True, from_client=True)
[email protected]feba21e2012-03-02 15:05:27101
[email protected]116f0a3a2012-04-19 04:22:38102 additional_properties_key = 'additionalProperties'
103 additional_properties = json.get(additional_properties_key)
[email protected]feba21e2012-03-02 15:05:27104 if additional_properties:
[email protected]116f0a3a2012-04-19 04:22:38105 self.properties[additional_properties_key] = Property(
106 self,
107 additional_properties_key,
108 additional_properties,
109 is_additional_properties=True)
[email protected]15f08dd2012-01-27 07:29:48110
[email protected]15f08dd2012-01-27 07:29:48111class Function(object):
112 """A Function defined in the API.
[email protected]cfe484902012-02-15 14:52:32113
114 Properties:
115 - |name| the function name
116 - |params| a list of parameters to the function (order matters). A separate
117 parameter is used for each choice of a 'choices' parameter.
118 - |description| a description of the function (if provided)
119 - |callback| the callback parameter to the function. There should be exactly
120 one
[email protected]4b3f7852012-07-17 06:33:30121 - |optional| whether the Function is "optional"; this only makes sense to be
122 present when the Function is representing a callback property.
[email protected]15f08dd2012-01-27 07:29:48123 """
[email protected]b741e8f2012-07-16 21:47:24124 def __init__(self, parent, json, from_json=False, from_client=False):
[email protected]15f08dd2012-01-27 07:29:48125 self.name = json['name']
126 self.params = []
[email protected]feba21e2012-03-02 15:05:27127 self.description = json.get('description')
[email protected]15f08dd2012-01-27 07:29:48128 self.callback = None
[email protected]4b3f7852012-07-17 06:33:30129 self.optional = json.get('optional', False)
[email protected]feba21e2012-03-02 15:05:27130 self.parent = parent
[email protected]a9ead752012-05-24 02:08:45131 self.nocompile = json.get('nocompile')
[email protected]b741e8f2012-07-16 21:47:24132 for param in json.get('parameters', []):
[email protected]15f08dd2012-01-27 07:29:48133 if param.get('type') == 'function':
[email protected]feba21e2012-03-02 15:05:27134 if self.callback:
[email protected]116f0a3a2012-04-19 04:22:38135 raise ParseException(self, self.name + " has more than one callback")
[email protected]b741e8f2012-07-16 21:47:24136 self.callback = Function(self, param, from_client=True)
[email protected]15f08dd2012-01-27 07:29:48137 else:
[email protected]feba21e2012-03-02 15:05:27138 self.params.append(Property(self, param['name'], param,
[email protected]b741e8f2012-07-16 21:47:24139 from_json=from_json, from_client=from_client))
[email protected]491e60d32012-07-20 01:03:13140 self.returns = None
141 if 'returns' in json:
142 self.returns = Property(self, 'return', json['returns'])
[email protected]15f08dd2012-01-27 07:29:48143
[email protected]15f08dd2012-01-27 07:29:48144class Property(object):
145 """A property of a type OR a parameter to a function.
146
[email protected]cfe484902012-02-15 14:52:32147 Properties:
148 - |name| name of the property as in the json. This shouldn't change since
149 it is the key used to access DictionaryValues
150 - |unix_name| the unix_style_name of the property. Used as variable name
151 - |optional| a boolean representing whether the property is optional
152 - |description| a description of the property (if provided)
153 - |type_| the model.PropertyType of this property
[email protected]1d0f57e2012-07-31 22:47:50154 - |compiled_type| the model.PropertyType that this property should be
155 compiled to from the JSON. Defaults to |type_|.
[email protected]cfe484902012-02-15 14:52:32156 - |ref_type| the type that the REF property is referencing. Can be used to
157 map to its model.Type
158 - |item_type| a model.Property representing the type of each element in an
159 ARRAY
160 - |properties| the properties of an OBJECT parameter
[email protected]b741e8f2012-07-16 21:47:24161 - |from_client| indicates that instances of the Type can originate from the
162 users of generated code, such as top-level types and function results
163 - |from_json| indicates that instances of the Type can originate from the
164 JSON (as described by the schema), such as top-level types and function
165 parameters
[email protected]15f08dd2012-01-27 07:29:48166 """
[email protected]feba21e2012-03-02 15:05:27167
168 def __init__(self, parent, name, json, is_additional_properties=False,
169 from_json=False, from_client=False):
[email protected]15f08dd2012-01-27 07:29:48170 self.name = name
[email protected]4ba6bdc2012-06-18 20:40:14171 self._unix_name = UnixName(self.name)
[email protected]cfe484902012-02-15 14:52:32172 self._unix_name_used = False
[email protected]15f08dd2012-01-27 07:29:48173 self.optional = json.get('optional', False)
[email protected]3072d072012-07-19 00:35:33174 self.functions = {}
[email protected]116f0a3a2012-04-19 04:22:38175 self.has_value = False
[email protected]15f08dd2012-01-27 07:29:48176 self.description = json.get('description')
[email protected]feba21e2012-03-02 15:05:27177 self.parent = parent
[email protected]b741e8f2012-07-16 21:47:24178 self.from_json = from_json
179 self.from_client = from_client
[email protected]491e60d32012-07-20 01:03:13180 self.instance_of = json.get('isInstanceOf', None)
[email protected]116f0a3a2012-04-19 04:22:38181 _AddProperties(self, json)
[email protected]feba21e2012-03-02 15:05:27182 if is_additional_properties:
183 self.type_ = PropertyType.ADDITIONAL_PROPERTIES
184 elif '$ref' in json:
[email protected]15f08dd2012-01-27 07:29:48185 self.ref_type = json['$ref']
186 self.type_ = PropertyType.REF
[email protected]9d273182012-07-11 21:03:26187 elif 'enum' in json and json.get('type') == 'string':
188 # Non-string enums (as in the case of [legalValues=(1,2)]) should fall
189 # through to the next elif.
[email protected]2111fff9b2012-02-22 12:06:51190 self.enum_values = []
191 for value in json['enum']:
192 self.enum_values.append(value)
193 self.type_ = PropertyType.ENUM
[email protected]15f08dd2012-01-27 07:29:48194 elif 'type' in json:
[email protected]1d0f57e2012-07-31 22:47:50195 self.type_ = self._JsonTypeToPropertyType(json['type'])
196 if self.type_ == PropertyType.ARRAY:
[email protected]feba21e2012-03-02 15:05:27197 self.item_type = Property(self, name + "Element", json['items'],
198 from_json=from_json,
199 from_client=from_client)
[email protected]1d0f57e2012-07-31 22:47:50200 elif self.type_ == PropertyType.OBJECT:
[email protected]25cbf6012012-02-28 05:51:44201 # These members are read when this OBJECT Property is used as a Type
[email protected]feba21e2012-03-02 15:05:27202 type_ = Type(self, self.name, json)
[email protected]116f0a3a2012-04-19 04:22:38203 # self.properties will already have some value from |_AddProperties|.
204 self.properties.update(type_.properties)
[email protected]feba21e2012-03-02 15:05:27205 self.functions = type_.functions
[email protected]15f08dd2012-01-27 07:29:48206 elif 'choices' in json:
[email protected]b741e8f2012-07-16 21:47:24207 if not json['choices'] or len(json['choices']) == 0:
[email protected]116f0a3a2012-04-19 04:22:38208 raise ParseException(self, 'Choices has no choices')
[email protected]15f08dd2012-01-27 07:29:48209 self.choices = {}
[email protected]cfe484902012-02-15 14:52:32210 self.type_ = PropertyType.CHOICES
[email protected]1d0f57e2012-07-31 22:47:50211 self.compiled_type = self.type_
[email protected]cfe484902012-02-15 14:52:32212 for choice_json in json['choices']:
[email protected]feba21e2012-03-02 15:05:27213 choice = Property(self, self.name, choice_json,
214 from_json=from_json,
215 from_client=from_client)
[email protected]b741e8f2012-07-16 21:47:24216 choice.unix_name = UnixName(self.name + choice.type_.name)
[email protected]cfe484902012-02-15 14:52:32217 # The existence of any single choice is optional
218 choice.optional = True
219 self.choices[choice.type_] = choice
[email protected]116f0a3a2012-04-19 04:22:38220 elif 'value' in json:
221 self.has_value = True
222 self.value = json['value']
223 if type(self.value) == int:
224 self.type_ = PropertyType.INTEGER
[email protected]1d0f57e2012-07-31 22:47:50225 self.compiled_type = self.type_
[email protected]116f0a3a2012-04-19 04:22:38226 else:
227 # TODO(kalman): support more types as necessary.
228 raise ParseException(
229 self, '"%s" is not a supported type' % type(self.value))
[email protected]cfe484902012-02-15 14:52:32230 else:
[email protected]116f0a3a2012-04-19 04:22:38231 raise ParseException(
232 self, 'Property has no type, $ref, choices, or value')
[email protected]1d0f57e2012-07-31 22:47:50233 if 'compiled_type' in json:
234 if 'type' in json:
235 self.compiled_type = self._JsonTypeToPropertyType(json['compiled_type'])
236 else:
237 raise ParseException(self, 'Property has compiled_type but no type')
238 else:
239 self.compiled_type = self.type_
240
241 def _JsonTypeToPropertyType(self, json_type):
242 try:
243 return {
244 'any': PropertyType.ANY,
245 'array': PropertyType.ARRAY,
246 'binary': PropertyType.BINARY,
247 'boolean': PropertyType.BOOLEAN,
248 'integer': PropertyType.INTEGER,
249 'int64': PropertyType.INT64,
250 'function': PropertyType.FUNCTION,
251 'number': PropertyType.DOUBLE,
252 'object': PropertyType.OBJECT,
253 'string': PropertyType.STRING,
254 }[json_type]
255 except KeyError:
256 raise NotImplementedError('Type %s not recognized' % json_type)
[email protected]cfe484902012-02-15 14:52:32257
258 def GetUnixName(self):
259 """Gets the property's unix_name. Raises AttributeError if not set.
260 """
[email protected]116f0a3a2012-04-19 04:22:38261 if not self._unix_name:
[email protected]cfe484902012-02-15 14:52:32262 raise AttributeError('No unix_name set on %s' % self.name)
263 self._unix_name_used = True
264 return self._unix_name
265
266 def SetUnixName(self, unix_name):
267 """Set the property's unix_name. Raises AttributeError if the unix_name has
268 already been used (GetUnixName has been called).
269 """
270 if unix_name == self._unix_name:
271 return
272 if self._unix_name_used:
273 raise AttributeError(
274 'Cannot set the unix_name on %s; '
275 'it is already used elsewhere as %s' %
276 (self.name, self._unix_name))
277 self._unix_name = unix_name
278
[email protected]712eca0f2012-02-21 01:13:07279 def Copy(self):
280 """Makes a copy of this model.Property object and allow the unix_name to be
281 set again.
282 """
283 property_copy = copy.copy(self)
284 property_copy._unix_name_used = False
285 return property_copy
286
[email protected]cfe484902012-02-15 14:52:32287 unix_name = property(GetUnixName, SetUnixName)
[email protected]15f08dd2012-01-27 07:29:48288
289class PropertyType(object):
290 """Enum of different types of properties/parameters.
291 """
292 class _Info(object):
[email protected]cfe484902012-02-15 14:52:32293 def __init__(self, is_fundamental, name):
[email protected]15f08dd2012-01-27 07:29:48294 self.is_fundamental = is_fundamental
[email protected]cfe484902012-02-15 14:52:32295 self.name = name
[email protected]15f08dd2012-01-27 07:29:48296
[email protected]cfe484902012-02-15 14:52:32297 def __repr__(self):
298 return self.name
299
300 INTEGER = _Info(True, "INTEGER")
[email protected]1d0f57e2012-07-31 22:47:50301 INT64 = _Info(True, "INT64")
[email protected]cfe484902012-02-15 14:52:32302 DOUBLE = _Info(True, "DOUBLE")
303 BOOLEAN = _Info(True, "BOOLEAN")
304 STRING = _Info(True, "STRING")
[email protected]2111fff9b2012-02-22 12:06:51305 ENUM = _Info(False, "ENUM")
[email protected]cfe484902012-02-15 14:52:32306 ARRAY = _Info(False, "ARRAY")
307 REF = _Info(False, "REF")
308 CHOICES = _Info(False, "CHOICES")
309 OBJECT = _Info(False, "OBJECT")
[email protected]3c6d1862012-07-26 02:18:15310 FUNCTION = _Info(False, "FUNCTION")
[email protected]bc69ec1a2012-04-24 03:17:19311 BINARY = _Info(False, "BINARY")
[email protected]cfe484902012-02-15 14:52:32312 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]4ba6bdc2012-06-18 20:40:14315def 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]116f0a3a2012-04-19 04:22:38325def _GetModelHierarchy(entity):
[email protected]feba21e2012-03-02 15:05:27326 """Returns the hierarchy of the given model entity."""
327 hierarchy = []
328 while entity:
329 try:
330 hierarchy.append(entity.name)
331 except AttributeError:
332 hierarchy.append(repr(entity))
333 entity = entity.parent
334 hierarchy.reverse()
335 return hierarchy
[email protected]116f0a3a2012-04-19 04:22:38336
337def _AddTypes(model, json):
338 """Adds Type objects to |model| contained in the 'types' field of |json|.
339 """
340 model.types = {}
341 for type_json in json.get('types', []):
342 type_ = Type(model, type_json['id'], type_json)
343 model.types[type_.name] = type_
344
345def _AddFunctions(model, json):
[email protected]b741e8f2012-07-16 21:47:24346 """Adds Function objects to |model| contained in the 'functions' field of
347 |json|.
[email protected]116f0a3a2012-04-19 04:22:38348 """
349 model.functions = {}
350 for function_json in json.get('functions', []):
[email protected]b741e8f2012-07-16 21:47:24351 function = Function(model, function_json, from_json=True)
[email protected]116f0a3a2012-04-19 04:22:38352 model.functions[function.name] = function
353
[email protected]b741e8f2012-07-16 21:47:24354def _AddEvents(model, json):
355 """Adds Function objects to |model| contained in the 'events' field of |json|.
356 """
357 model.events = {}
358 for event_json in json.get('events', []):
359 event = Function(model, event_json, from_client=True)
360 model.events[event.name] = event
361
[email protected]116f0a3a2012-04-19 04:22:38362def _AddProperties(model, json, from_json=False, from_client=False):
363 """Adds model.Property objects to |model| contained in the 'properties' field
364 of |json|.
365 """
366 model.properties = {}
367 for name, property_json in json.get('properties', {}).items():
[email protected]116f0a3a2012-04-19 04:22:38368 model.properties[name] = Property(
369 model,
370 name,
371 property_json,
372 from_json=from_json,
373 from_client=from_client)