blob: 6dc20fe3ced9b70e6ad0f4c264517e3f0d270280 [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)
79 else:
80 if not (
81 'properties' in json or
82 'additionalProperties' in json or
83 'functions' in json):
[email protected]116f0a3a2012-04-19 04:22:3884 raise ParseException(self, name + " has no properties or functions")
[email protected]cf6d0b32012-04-12 04:30:2285 self.type_ = PropertyType.OBJECT
[email protected]feba21e2012-03-02 15:05:2786 self.name = name
[email protected]15f08dd2012-01-27 07:29:4887 self.description = json.get('description')
[email protected]25cbf6012012-02-28 05:51:4488 self.from_json = True
89 self.from_client = True
[email protected]feba21e2012-03-02 15:05:2790 self.parent = parent
[email protected]116f0a3a2012-04-19 04:22:3891 _AddFunctions(self, json)
92 _AddProperties(self, json, from_json=True, from_client=True)
[email protected]feba21e2012-03-02 15:05:2793
[email protected]116f0a3a2012-04-19 04:22:3894 additional_properties_key = 'additionalProperties'
95 additional_properties = json.get(additional_properties_key)
[email protected]feba21e2012-03-02 15:05:2796 if additional_properties:
[email protected]116f0a3a2012-04-19 04:22:3897 self.properties[additional_properties_key] = Property(
98 self,
99 additional_properties_key,
100 additional_properties,
101 is_additional_properties=True)
[email protected]15f08dd2012-01-27 07:29:48102
103class Callback(object):
104 """A callback parameter to a Function.
[email protected]cfe484902012-02-15 14:52:32105
106 Properties:
107 - |params| the parameters to this callback.
[email protected]15f08dd2012-01-27 07:29:48108 """
[email protected]feba21e2012-03-02 15:05:27109 def __init__(self, parent, json):
[email protected]15f08dd2012-01-27 07:29:48110 params = json['parameters']
[email protected]feba21e2012-03-02 15:05:27111 self.parent = parent
[email protected]cfe484902012-02-15 14:52:32112 self.params = []
[email protected]15f08dd2012-01-27 07:29:48113 if len(params) == 0:
[email protected]cfe484902012-02-15 14:52:32114 return
[email protected]15f08dd2012-01-27 07:29:48115 elif len(params) == 1:
116 param = params[0]
[email protected]feba21e2012-03-02 15:05:27117 self.params.append(Property(self, param['name'], param,
[email protected]25cbf6012012-02-28 05:51:44118 from_client=True))
[email protected]15f08dd2012-01-27 07:29:48119 else:
[email protected]116f0a3a2012-04-19 04:22:38120 raise ParseException(
121 self,
122 "Callbacks can have at most a single parameter")
[email protected]15f08dd2012-01-27 07:29:48123
124class Function(object):
125 """A Function defined in the API.
[email protected]cfe484902012-02-15 14:52:32126
127 Properties:
128 - |name| the function name
129 - |params| a list of parameters to the function (order matters). A separate
130 parameter is used for each choice of a 'choices' parameter.
131 - |description| a description of the function (if provided)
132 - |callback| the callback parameter to the function. There should be exactly
133 one
[email protected]15f08dd2012-01-27 07:29:48134 """
[email protected]feba21e2012-03-02 15:05:27135 def __init__(self, parent, json):
[email protected]15f08dd2012-01-27 07:29:48136 self.name = json['name']
137 self.params = []
[email protected]feba21e2012-03-02 15:05:27138 self.description = json.get('description')
[email protected]15f08dd2012-01-27 07:29:48139 self.callback = None
[email protected]feba21e2012-03-02 15:05:27140 self.parent = parent
[email protected]15f08dd2012-01-27 07:29:48141 for param in json['parameters']:
142 if param.get('type') == 'function':
[email protected]feba21e2012-03-02 15:05:27143 if self.callback:
[email protected]116f0a3a2012-04-19 04:22:38144 raise ParseException(self, self.name + " has more than one callback")
[email protected]feba21e2012-03-02 15:05:27145 self.callback = Callback(self, param)
[email protected]15f08dd2012-01-27 07:29:48146 else:
[email protected]feba21e2012-03-02 15:05:27147 self.params.append(Property(self, param['name'], param,
[email protected]25cbf6012012-02-28 05:51:44148 from_json=True))
[email protected]15f08dd2012-01-27 07:29:48149
[email protected]15f08dd2012-01-27 07:29:48150class Property(object):
151 """A property of a type OR a parameter to a function.
152
[email protected]cfe484902012-02-15 14:52:32153 Properties:
154 - |name| name of the property as in the json. This shouldn't change since
155 it is the key used to access DictionaryValues
156 - |unix_name| the unix_style_name of the property. Used as variable name
157 - |optional| a boolean representing whether the property is optional
158 - |description| a description of the property (if provided)
159 - |type_| the model.PropertyType of this property
160 - |ref_type| the type that the REF property is referencing. Can be used to
161 map to its model.Type
162 - |item_type| a model.Property representing the type of each element in an
163 ARRAY
164 - |properties| the properties of an OBJECT parameter
[email protected]15f08dd2012-01-27 07:29:48165 """
[email protected]feba21e2012-03-02 15:05:27166
167 def __init__(self, parent, name, json, is_additional_properties=False,
168 from_json=False, from_client=False):
[email protected]25cbf6012012-02-28 05:51:44169 """
170 Parameters:
171 - |from_json| indicates that instances of the Type can originate from the
172 JSON (as described by the schema), such as top-level types and function
173 parameters
174 - |from_client| indicates that instances of the Type can originate from the
175 users of generated code, such as top-level types and function results
176 """
[email protected]15f08dd2012-01-27 07:29:48177 self.name = name
[email protected]116f0a3a2012-04-19 04:22:38178 self._unix_name = _UnixName(self.name)
[email protected]cfe484902012-02-15 14:52:32179 self._unix_name_used = False
[email protected]15f08dd2012-01-27 07:29:48180 self.optional = json.get('optional', False)
[email protected]116f0a3a2012-04-19 04:22:38181 self.has_value = False
[email protected]15f08dd2012-01-27 07:29:48182 self.description = json.get('description')
[email protected]feba21e2012-03-02 15:05:27183 self.parent = parent
[email protected]116f0a3a2012-04-19 04:22:38184 _AddProperties(self, json)
[email protected]feba21e2012-03-02 15:05:27185 if is_additional_properties:
186 self.type_ = PropertyType.ADDITIONAL_PROPERTIES
187 elif '$ref' in json:
[email protected]15f08dd2012-01-27 07:29:48188 self.ref_type = json['$ref']
189 self.type_ = PropertyType.REF
[email protected]2111fff9b2012-02-22 12:06:51190 elif 'enum' in json:
191 self.enum_values = []
192 for value in json['enum']:
193 self.enum_values.append(value)
194 self.type_ = PropertyType.ENUM
[email protected]15f08dd2012-01-27 07:29:48195 elif 'type' in json:
196 json_type = json['type']
197 if json_type == 'string':
198 self.type_ = PropertyType.STRING
[email protected]cfe484902012-02-15 14:52:32199 elif json_type == 'any':
200 self.type_ = PropertyType.ANY
201 elif json_type == 'boolean':
[email protected]15f08dd2012-01-27 07:29:48202 self.type_ = PropertyType.BOOLEAN
203 elif json_type == 'integer':
204 self.type_ = PropertyType.INTEGER
[email protected]cfe484902012-02-15 14:52:32205 elif json_type == 'number':
[email protected]15f08dd2012-01-27 07:29:48206 self.type_ = PropertyType.DOUBLE
207 elif json_type == 'array':
[email protected]feba21e2012-03-02 15:05:27208 self.item_type = Property(self, name + "Element", json['items'],
209 from_json=from_json,
210 from_client=from_client)
[email protected]15f08dd2012-01-27 07:29:48211 self.type_ = PropertyType.ARRAY
212 elif json_type == 'object':
[email protected]15f08dd2012-01-27 07:29:48213 self.type_ = PropertyType.OBJECT
[email protected]25cbf6012012-02-28 05:51:44214 # These members are read when this OBJECT Property is used as a Type
[email protected]25cbf6012012-02-28 05:51:44215 self.from_json = from_json
216 self.from_client = from_client
[email protected]feba21e2012-03-02 15:05:27217 type_ = Type(self, self.name, json)
[email protected]116f0a3a2012-04-19 04:22:38218 # self.properties will already have some value from |_AddProperties|.
219 self.properties.update(type_.properties)
[email protected]feba21e2012-03-02 15:05:27220 self.functions = type_.functions
[email protected]15f08dd2012-01-27 07:29:48221 else:
[email protected]feba21e2012-03-02 15:05:27222 raise ParseException(self, 'type ' + json_type + ' not recognized')
[email protected]15f08dd2012-01-27 07:29:48223 elif 'choices' in json:
[email protected]feba21e2012-03-02 15:05:27224 if not json['choices']:
[email protected]116f0a3a2012-04-19 04:22:38225 raise ParseException(self, 'Choices has no choices')
[email protected]15f08dd2012-01-27 07:29:48226 self.choices = {}
[email protected]cfe484902012-02-15 14:52:32227 self.type_ = PropertyType.CHOICES
228 for choice_json in json['choices']:
[email protected]feba21e2012-03-02 15:05:27229 choice = Property(self, self.name, choice_json,
230 from_json=from_json,
231 from_client=from_client)
[email protected]cfe484902012-02-15 14:52:32232 # A choice gets its unix_name set in
233 # cpp_type_generator.GetExpandedChoicesInParams
234 choice._unix_name = None
235 # The existence of any single choice is optional
236 choice.optional = True
237 self.choices[choice.type_] = choice
[email protected]116f0a3a2012-04-19 04:22:38238 elif 'value' in json:
239 self.has_value = True
240 self.value = json['value']
241 if type(self.value) == int:
242 self.type_ = PropertyType.INTEGER
243 else:
244 # TODO(kalman): support more types as necessary.
245 raise ParseException(
246 self, '"%s" is not a supported type' % type(self.value))
[email protected]cfe484902012-02-15 14:52:32247 else:
[email protected]116f0a3a2012-04-19 04:22:38248 raise ParseException(
249 self, 'Property has no type, $ref, choices, or value')
[email protected]cfe484902012-02-15 14:52:32250
251 def GetUnixName(self):
252 """Gets the property's unix_name. Raises AttributeError if not set.
253 """
[email protected]116f0a3a2012-04-19 04:22:38254 if not self._unix_name:
[email protected]cfe484902012-02-15 14:52:32255 raise AttributeError('No unix_name set on %s' % self.name)
256 self._unix_name_used = True
257 return self._unix_name
258
259 def SetUnixName(self, unix_name):
260 """Set the property's unix_name. Raises AttributeError if the unix_name has
261 already been used (GetUnixName has been called).
262 """
263 if unix_name == self._unix_name:
264 return
265 if self._unix_name_used:
266 raise AttributeError(
267 'Cannot set the unix_name on %s; '
268 'it is already used elsewhere as %s' %
269 (self.name, self._unix_name))
270 self._unix_name = unix_name
271
[email protected]712eca0f2012-02-21 01:13:07272 def Copy(self):
273 """Makes a copy of this model.Property object and allow the unix_name to be
274 set again.
275 """
276 property_copy = copy.copy(self)
277 property_copy._unix_name_used = False
278 return property_copy
279
[email protected]cfe484902012-02-15 14:52:32280 unix_name = property(GetUnixName, SetUnixName)
[email protected]15f08dd2012-01-27 07:29:48281
282class PropertyType(object):
283 """Enum of different types of properties/parameters.
284 """
285 class _Info(object):
[email protected]cfe484902012-02-15 14:52:32286 def __init__(self, is_fundamental, name):
[email protected]15f08dd2012-01-27 07:29:48287 self.is_fundamental = is_fundamental
[email protected]cfe484902012-02-15 14:52:32288 self.name = name
[email protected]15f08dd2012-01-27 07:29:48289
[email protected]cfe484902012-02-15 14:52:32290 def __repr__(self):
291 return self.name
292
293 INTEGER = _Info(True, "INTEGER")
294 DOUBLE = _Info(True, "DOUBLE")
295 BOOLEAN = _Info(True, "BOOLEAN")
296 STRING = _Info(True, "STRING")
[email protected]2111fff9b2012-02-22 12:06:51297 ENUM = _Info(False, "ENUM")
[email protected]cfe484902012-02-15 14:52:32298 ARRAY = _Info(False, "ARRAY")
299 REF = _Info(False, "REF")
300 CHOICES = _Info(False, "CHOICES")
301 OBJECT = _Info(False, "OBJECT")
302 ANY = _Info(False, "ANY")
[email protected]feba21e2012-03-02 15:05:27303 ADDITIONAL_PROPERTIES = _Info(False, "ADDITIONAL_PROPERTIES")
[email protected]cfe484902012-02-15 14:52:32304
[email protected]116f0a3a2012-04-19 04:22:38305def _UnixName(name):
[email protected]712eca0f2012-02-21 01:13:07306 """Returns the unix_style name for a given lowerCamelCase string.
[email protected]cfe484902012-02-15 14:52:32307 """
[email protected]df74dc42012-04-03 07:08:04308 # First replace any lowerUpper patterns with lower_Upper.
309 s1 = re.sub('([a-z])([A-Z])', r'\1_\2', name)
310 # Now replace any ACMEWidgets patterns with ACME_Widgets
311 s2 = re.sub('([A-Z]+)([A-Z][a-z])', r'\1_\2', s1)
312 # Finally, replace any remaining periods, and make lowercase.
313 return s2.replace('.', '_').lower()
[email protected]cfe484902012-02-15 14:52:32314
[email protected]116f0a3a2012-04-19 04:22:38315def _GetModelHierarchy(entity):
[email protected]feba21e2012-03-02 15:05:27316 """Returns the hierarchy of the given model entity."""
317 hierarchy = []
318 while entity:
319 try:
320 hierarchy.append(entity.name)
321 except AttributeError:
322 hierarchy.append(repr(entity))
323 entity = entity.parent
324 hierarchy.reverse()
325 return hierarchy
[email protected]116f0a3a2012-04-19 04:22:38326
327def _AddTypes(model, json):
328 """Adds Type objects to |model| contained in the 'types' field of |json|.
329 """
330 model.types = {}
331 for type_json in json.get('types', []):
332 type_ = Type(model, type_json['id'], type_json)
333 model.types[type_.name] = type_
334
335def _AddFunctions(model, json):
336 """Adds Function objects to |model| contained in the 'types' field of |json|.
337 """
338 model.functions = {}
339 for function_json in json.get('functions', []):
340 function = Function(model, function_json)
341 model.functions[function.name] = function
342
343def _AddProperties(model, json, from_json=False, from_client=False):
344 """Adds model.Property objects to |model| contained in the 'properties' field
345 of |json|.
346 """
347 model.properties = {}
348 for name, property_json in json.get('properties', {}).items():
349 # TODO(calamity): support functions (callbacks) as properties. The model
350 # doesn't support it yet because the h/cc generators don't -- this is
351 # because we'd need to hook it into a base::Callback or something.
352 #
353 # However, pragmatically it's not necessary to support them anyway, since
354 # the instances of functions-on-properties in the extension APIs are all
355 # handled in pure Javascript on the render process (and .: never reach
356 # C++ let alone the browser).
357 if property_json.get('type') == 'function':
358 continue
359 model.properties[name] = Property(
360 model,
361 name,
362 property_json,
363 from_json=from_json,
364 from_client=from_client)