blob: 42d38b05e94453e863de0a71fd631931809df8a1 [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]25cbf6012012-02-28 05:51:4467 - |from_client| indicates that instances of the Type can originate from the
68 users of generated code, such as top-level types and function results
69 - |from_json| indicates that instances of the Type can originate from the
70 JSON (as described by the schema), such as top-level types and function
71 parameters
[email protected]cf6d0b32012-04-12 04:30:2272 - |type_| the PropertyType of this Type
73 - |item_type| if this is an array, the type of items in the array
[email protected]15f08dd2012-01-27 07:29:4874 """
[email protected]feba21e2012-03-02 15:05:2775 def __init__(self, parent, name, json):
[email protected]cf6d0b32012-04-12 04:30:2276 if json.get('type') == 'array':
77 self.type_ = PropertyType.ARRAY
78 self.item_type = Property(self, name + "Element", json['items'],
79 from_json=True,
80 from_client=True)
[email protected]0ef7f5a12012-05-01 03:58:0681 elif json.get('type') == 'string':
82 self.type_ = PropertyType.STRING
[email protected]cf6d0b32012-04-12 04:30:2283 else:
84 if not (
85 'properties' in json or
86 'additionalProperties' in json or
87 'functions' in json):
[email protected]116f0a3a2012-04-19 04:22:3888 raise ParseException(self, name + " has no properties or functions")
[email protected]cf6d0b32012-04-12 04:30:2289 self.type_ = PropertyType.OBJECT
[email protected]feba21e2012-03-02 15:05:2790 self.name = name
[email protected]15f08dd2012-01-27 07:29:4891 self.description = json.get('description')
[email protected]25cbf6012012-02-28 05:51:4492 self.from_json = True
93 self.from_client = True
[email protected]feba21e2012-03-02 15:05:2794 self.parent = parent
[email protected]491e60d32012-07-20 01:03:1395 self.instance_of = json.get('isInstanceOf', None)
[email protected]116f0a3a2012-04-19 04:22:3896 _AddFunctions(self, json)
97 _AddProperties(self, json, from_json=True, from_client=True)
[email protected]feba21e2012-03-02 15:05:2798
[email protected]116f0a3a2012-04-19 04:22:3899 additional_properties_key = 'additionalProperties'
100 additional_properties = json.get(additional_properties_key)
[email protected]feba21e2012-03-02 15:05:27101 if additional_properties:
[email protected]116f0a3a2012-04-19 04:22:38102 self.properties[additional_properties_key] = Property(
103 self,
104 additional_properties_key,
105 additional_properties,
106 is_additional_properties=True)
[email protected]15f08dd2012-01-27 07:29:48107
[email protected]15f08dd2012-01-27 07:29:48108class Function(object):
109 """A Function defined in the API.
[email protected]cfe484902012-02-15 14:52:32110
111 Properties:
112 - |name| the function name
113 - |params| a list of parameters to the function (order matters). A separate
114 parameter is used for each choice of a 'choices' parameter.
115 - |description| a description of the function (if provided)
116 - |callback| the callback parameter to the function. There should be exactly
117 one
[email protected]4b3f7852012-07-17 06:33:30118 - |optional| whether the Function is "optional"; this only makes sense to be
119 present when the Function is representing a callback property.
[email protected]15f08dd2012-01-27 07:29:48120 """
[email protected]b741e8f2012-07-16 21:47:24121 def __init__(self, parent, json, from_json=False, from_client=False):
[email protected]15f08dd2012-01-27 07:29:48122 self.name = json['name']
123 self.params = []
[email protected]feba21e2012-03-02 15:05:27124 self.description = json.get('description')
[email protected]15f08dd2012-01-27 07:29:48125 self.callback = None
[email protected]4b3f7852012-07-17 06:33:30126 self.optional = json.get('optional', False)
[email protected]feba21e2012-03-02 15:05:27127 self.parent = parent
[email protected]a9ead752012-05-24 02:08:45128 self.nocompile = json.get('nocompile')
[email protected]b741e8f2012-07-16 21:47:24129 for param in json.get('parameters', []):
[email protected]15f08dd2012-01-27 07:29:48130 if param.get('type') == 'function':
[email protected]feba21e2012-03-02 15:05:27131 if self.callback:
[email protected]116f0a3a2012-04-19 04:22:38132 raise ParseException(self, self.name + " has more than one callback")
[email protected]b741e8f2012-07-16 21:47:24133 self.callback = Function(self, param, from_client=True)
[email protected]15f08dd2012-01-27 07:29:48134 else:
[email protected]feba21e2012-03-02 15:05:27135 self.params.append(Property(self, param['name'], param,
[email protected]b741e8f2012-07-16 21:47:24136 from_json=from_json, from_client=from_client))
[email protected]491e60d32012-07-20 01:03:13137 self.returns = None
138 if 'returns' in json:
139 self.returns = Property(self, 'return', json['returns'])
[email protected]15f08dd2012-01-27 07:29:48140
[email protected]15f08dd2012-01-27 07:29:48141class Property(object):
142 """A property of a type OR a parameter to a function.
143
[email protected]cfe484902012-02-15 14:52:32144 Properties:
145 - |name| name of the property as in the json. This shouldn't change since
146 it is the key used to access DictionaryValues
147 - |unix_name| the unix_style_name of the property. Used as variable name
148 - |optional| a boolean representing whether the property is optional
149 - |description| a description of the property (if provided)
150 - |type_| the model.PropertyType of this property
151 - |ref_type| the type that the REF property is referencing. Can be used to
152 map to its model.Type
153 - |item_type| a model.Property representing the type of each element in an
154 ARRAY
155 - |properties| the properties of an OBJECT parameter
[email protected]b741e8f2012-07-16 21:47:24156 - |from_client| indicates that instances of the Type can originate from the
157 users of generated code, such as top-level types and function results
158 - |from_json| indicates that instances of the Type can originate from the
159 JSON (as described by the schema), such as top-level types and function
160 parameters
[email protected]15f08dd2012-01-27 07:29:48161 """
[email protected]feba21e2012-03-02 15:05:27162
163 def __init__(self, parent, name, json, is_additional_properties=False,
164 from_json=False, from_client=False):
[email protected]15f08dd2012-01-27 07:29:48165 self.name = name
[email protected]4ba6bdc2012-06-18 20:40:14166 self._unix_name = UnixName(self.name)
[email protected]cfe484902012-02-15 14:52:32167 self._unix_name_used = False
[email protected]15f08dd2012-01-27 07:29:48168 self.optional = json.get('optional', False)
[email protected]3072d072012-07-19 00:35:33169 self.functions = {}
[email protected]116f0a3a2012-04-19 04:22:38170 self.has_value = False
[email protected]15f08dd2012-01-27 07:29:48171 self.description = json.get('description')
[email protected]feba21e2012-03-02 15:05:27172 self.parent = parent
[email protected]b741e8f2012-07-16 21:47:24173 self.from_json = from_json
174 self.from_client = from_client
[email protected]491e60d32012-07-20 01:03:13175 self.instance_of = json.get('isInstanceOf', None)
[email protected]116f0a3a2012-04-19 04:22:38176 _AddProperties(self, json)
[email protected]feba21e2012-03-02 15:05:27177 if is_additional_properties:
178 self.type_ = PropertyType.ADDITIONAL_PROPERTIES
179 elif '$ref' in json:
[email protected]15f08dd2012-01-27 07:29:48180 self.ref_type = json['$ref']
181 self.type_ = PropertyType.REF
[email protected]9d273182012-07-11 21:03:26182 elif 'enum' in json and json.get('type') == 'string':
183 # Non-string enums (as in the case of [legalValues=(1,2)]) should fall
184 # through to the next elif.
[email protected]2111fff9b2012-02-22 12:06:51185 self.enum_values = []
186 for value in json['enum']:
187 self.enum_values.append(value)
188 self.type_ = PropertyType.ENUM
[email protected]15f08dd2012-01-27 07:29:48189 elif 'type' in json:
190 json_type = json['type']
191 if json_type == 'string':
192 self.type_ = PropertyType.STRING
[email protected]cfe484902012-02-15 14:52:32193 elif json_type == 'any':
194 self.type_ = PropertyType.ANY
195 elif json_type == 'boolean':
[email protected]15f08dd2012-01-27 07:29:48196 self.type_ = PropertyType.BOOLEAN
197 elif json_type == 'integer':
198 self.type_ = PropertyType.INTEGER
[email protected]cfe484902012-02-15 14:52:32199 elif json_type == 'number':
[email protected]15f08dd2012-01-27 07:29:48200 self.type_ = PropertyType.DOUBLE
201 elif json_type == 'array':
[email protected]feba21e2012-03-02 15:05:27202 self.item_type = Property(self, name + "Element", json['items'],
203 from_json=from_json,
204 from_client=from_client)
[email protected]15f08dd2012-01-27 07:29:48205 self.type_ = PropertyType.ARRAY
206 elif json_type == 'object':
[email protected]15f08dd2012-01-27 07:29:48207 self.type_ = PropertyType.OBJECT
[email protected]25cbf6012012-02-28 05:51:44208 # These members are read when this OBJECT Property is used as a Type
[email protected]feba21e2012-03-02 15:05:27209 type_ = Type(self, self.name, json)
[email protected]116f0a3a2012-04-19 04:22:38210 # self.properties will already have some value from |_AddProperties|.
211 self.properties.update(type_.properties)
[email protected]feba21e2012-03-02 15:05:27212 self.functions = type_.functions
[email protected]bc69ec1a2012-04-24 03:17:19213 elif json_type == 'binary':
214 self.type_ = PropertyType.BINARY
[email protected]15f08dd2012-01-27 07:29:48215 else:
[email protected]feba21e2012-03-02 15:05:27216 raise ParseException(self, 'type ' + json_type + ' not recognized')
[email protected]15f08dd2012-01-27 07:29:48217 elif 'choices' in json:
[email protected]b741e8f2012-07-16 21:47:24218 if not json['choices'] or len(json['choices']) == 0:
[email protected]116f0a3a2012-04-19 04:22:38219 raise ParseException(self, 'Choices has no choices')
[email protected]15f08dd2012-01-27 07:29:48220 self.choices = {}
[email protected]cfe484902012-02-15 14:52:32221 self.type_ = PropertyType.CHOICES
222 for choice_json in json['choices']:
[email protected]feba21e2012-03-02 15:05:27223 choice = Property(self, self.name, choice_json,
224 from_json=from_json,
225 from_client=from_client)
[email protected]b741e8f2012-07-16 21:47:24226 choice.unix_name = UnixName(self.name + choice.type_.name)
[email protected]cfe484902012-02-15 14:52:32227 # The existence of any single choice is optional
228 choice.optional = True
229 self.choices[choice.type_] = choice
[email protected]116f0a3a2012-04-19 04:22:38230 elif 'value' in json:
231 self.has_value = True
232 self.value = json['value']
233 if type(self.value) == int:
234 self.type_ = PropertyType.INTEGER
235 else:
236 # TODO(kalman): support more types as necessary.
237 raise ParseException(
238 self, '"%s" is not a supported type' % type(self.value))
[email protected]cfe484902012-02-15 14:52:32239 else:
[email protected]116f0a3a2012-04-19 04:22:38240 raise ParseException(
241 self, 'Property has no type, $ref, choices, or value')
[email protected]cfe484902012-02-15 14:52:32242
243 def GetUnixName(self):
244 """Gets the property's unix_name. Raises AttributeError if not set.
245 """
[email protected]116f0a3a2012-04-19 04:22:38246 if not self._unix_name:
[email protected]cfe484902012-02-15 14:52:32247 raise AttributeError('No unix_name set on %s' % self.name)
248 self._unix_name_used = True
249 return self._unix_name
250
251 def SetUnixName(self, unix_name):
252 """Set the property's unix_name. Raises AttributeError if the unix_name has
253 already been used (GetUnixName has been called).
254 """
255 if unix_name == self._unix_name:
256 return
257 if self._unix_name_used:
258 raise AttributeError(
259 'Cannot set the unix_name on %s; '
260 'it is already used elsewhere as %s' %
261 (self.name, self._unix_name))
262 self._unix_name = unix_name
263
[email protected]712eca0f2012-02-21 01:13:07264 def Copy(self):
265 """Makes a copy of this model.Property object and allow the unix_name to be
266 set again.
267 """
268 property_copy = copy.copy(self)
269 property_copy._unix_name_used = False
270 return property_copy
271
[email protected]cfe484902012-02-15 14:52:32272 unix_name = property(GetUnixName, SetUnixName)
[email protected]15f08dd2012-01-27 07:29:48273
274class PropertyType(object):
275 """Enum of different types of properties/parameters.
276 """
277 class _Info(object):
[email protected]cfe484902012-02-15 14:52:32278 def __init__(self, is_fundamental, name):
[email protected]15f08dd2012-01-27 07:29:48279 self.is_fundamental = is_fundamental
[email protected]cfe484902012-02-15 14:52:32280 self.name = name
[email protected]15f08dd2012-01-27 07:29:48281
[email protected]cfe484902012-02-15 14:52:32282 def __repr__(self):
283 return self.name
284
285 INTEGER = _Info(True, "INTEGER")
286 DOUBLE = _Info(True, "DOUBLE")
287 BOOLEAN = _Info(True, "BOOLEAN")
288 STRING = _Info(True, "STRING")
[email protected]2111fff9b2012-02-22 12:06:51289 ENUM = _Info(False, "ENUM")
[email protected]cfe484902012-02-15 14:52:32290 ARRAY = _Info(False, "ARRAY")
291 REF = _Info(False, "REF")
292 CHOICES = _Info(False, "CHOICES")
293 OBJECT = _Info(False, "OBJECT")
[email protected]bc69ec1a2012-04-24 03:17:19294 BINARY = _Info(False, "BINARY")
[email protected]cfe484902012-02-15 14:52:32295 ANY = _Info(False, "ANY")
[email protected]feba21e2012-03-02 15:05:27296 ADDITIONAL_PROPERTIES = _Info(False, "ADDITIONAL_PROPERTIES")
[email protected]cfe484902012-02-15 14:52:32297
[email protected]4ba6bdc2012-06-18 20:40:14298def UnixName(name):
[email protected]712eca0f2012-02-21 01:13:07299 """Returns the unix_style name for a given lowerCamelCase string.
[email protected]cfe484902012-02-15 14:52:32300 """
[email protected]df74dc42012-04-03 07:08:04301 # First replace any lowerUpper patterns with lower_Upper.
302 s1 = re.sub('([a-z])([A-Z])', r'\1_\2', name)
303 # Now replace any ACMEWidgets patterns with ACME_Widgets
304 s2 = re.sub('([A-Z]+)([A-Z][a-z])', r'\1_\2', s1)
305 # Finally, replace any remaining periods, and make lowercase.
306 return s2.replace('.', '_').lower()
[email protected]cfe484902012-02-15 14:52:32307
[email protected]116f0a3a2012-04-19 04:22:38308def _GetModelHierarchy(entity):
[email protected]feba21e2012-03-02 15:05:27309 """Returns the hierarchy of the given model entity."""
310 hierarchy = []
311 while entity:
312 try:
313 hierarchy.append(entity.name)
314 except AttributeError:
315 hierarchy.append(repr(entity))
316 entity = entity.parent
317 hierarchy.reverse()
318 return hierarchy
[email protected]116f0a3a2012-04-19 04:22:38319
320def _AddTypes(model, json):
321 """Adds Type objects to |model| contained in the 'types' field of |json|.
322 """
323 model.types = {}
324 for type_json in json.get('types', []):
325 type_ = Type(model, type_json['id'], type_json)
326 model.types[type_.name] = type_
327
328def _AddFunctions(model, json):
[email protected]b741e8f2012-07-16 21:47:24329 """Adds Function objects to |model| contained in the 'functions' field of
330 |json|.
[email protected]116f0a3a2012-04-19 04:22:38331 """
332 model.functions = {}
333 for function_json in json.get('functions', []):
[email protected]b741e8f2012-07-16 21:47:24334 function = Function(model, function_json, from_json=True)
[email protected]116f0a3a2012-04-19 04:22:38335 model.functions[function.name] = function
336
[email protected]b741e8f2012-07-16 21:47:24337def _AddEvents(model, json):
338 """Adds Function objects to |model| contained in the 'events' field of |json|.
339 """
340 model.events = {}
341 for event_json in json.get('events', []):
342 event = Function(model, event_json, from_client=True)
343 model.events[event.name] = event
344
[email protected]116f0a3a2012-04-19 04:22:38345def _AddProperties(model, json, from_json=False, from_client=False):
346 """Adds model.Property objects to |model| contained in the 'properties' field
347 of |json|.
348 """
349 model.properties = {}
350 for name, property_json in json.get('properties', {}).items():
351 # TODO(calamity): support functions (callbacks) as properties. The model
352 # doesn't support it yet because the h/cc generators don't -- this is
353 # because we'd need to hook it into a base::Callback or something.
354 #
355 # However, pragmatically it's not necessary to support them anyway, since
356 # the instances of functions-on-properties in the extension APIs are all
357 # handled in pure Javascript on the render process (and .: never reach
358 # C++ let alone the browser).
359 if property_json.get('type') == 'function':
360 continue
361 model.properties[name] = Property(
362 model,
363 name,
364 property_json,
365 from_json=from_json,
366 from_client=from_client)