1 # 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.
6 from model
import PropertyType
10 class HGenerator(object):
11 def __init__(self
, type_generator
, cpp_namespace
):
12 self
._type
_generator
= type_generator
13 self
._cpp
_namespace
= cpp_namespace
15 def Generate(self
, namespace
):
16 return _Generator(namespace
,
18 self
._cpp
_namespace
).Generate()
21 class _Generator(object):
22 """A .h generator for a namespace.
24 def __init__(self
, namespace
, cpp_type_generator
, cpp_namespace
):
25 self
._namespace
= namespace
26 self
._type
_helper
= cpp_type_generator
27 self
._cpp
_namespace
= cpp_namespace
28 self
._target
_namespace
= (
29 self
._type
_helper
.GetCppNamespaceName(self
._namespace
))
30 self
._generate
_error
_messages
= namespace
.compiler_options
.get(
31 'generate_error_messages', False)
34 """Generates a Code object with the .h for a single namespace.
37 (c
.Append(cpp_util
.CHROMIUM_LICENSE
)
39 .Append(cpp_util
.GENERATED_FILE_MESSAGE
% self
._namespace
.source_file
)
43 ifndef_name
= cpp_util
.GenerateIfndefName(self
._namespace
.source_file_dir
,
44 self
._target
_namespace
)
45 (c
.Append('#ifndef %s' % ifndef_name
)
46 .Append('#define %s' % ifndef_name
)
48 .Append('#include <map>')
49 .Append('#include <string>')
50 .Append('#include <vector>')
52 .Append('#include "base/basictypes.h"')
53 .Append('#include "base/logging.h"')
54 .Append('#include "base/memory/linked_ptr.h"')
55 .Append('#include "base/memory/scoped_ptr.h"')
56 .Append('#include "base/values.h"')
57 .Cblock(self
._type
_helper
.GenerateIncludes())
61 c
.Concat(cpp_util
.OpenNamespace(self
._cpp
_namespace
))
62 # TODO(calamity): These forward declarations should be #includes to allow
63 # $ref types from other files to be used as required params. This requires
64 # some detangling of windows and tabs which will currently lead to circular
66 forward_declarations
= (
67 self
._type
_helper
.GenerateForwardDeclarations())
68 if not forward_declarations
.IsEmpty():
70 .Cblock(forward_declarations
)
73 c
.Concat(self
._type
_helper
.GetNamespaceStart())
75 if self
._namespace
.properties
:
77 .Append('// Properties')
81 for property in self
._namespace
.properties
.values():
82 property_code
= self
._type
_helper
.GeneratePropertyValues(
84 'extern const %(type)s %(name)s;')
86 c
.Cblock(property_code
)
87 if self
._namespace
.types
:
92 .Cblock(self
._GenerateTypes
(self
._FieldDependencyOrder
(),
94 generate_typedefs
=True))
96 if self
._namespace
.functions
:
98 .Append('// Functions')
102 for function
in self
._namespace
.functions
.values():
103 c
.Cblock(self
._GenerateFunction
(function
))
104 if self
._namespace
.events
:
110 for event
in self
._namespace
.events
.values():
111 c
.Cblock(self
._GenerateEvent
(event
))
112 (c
.Concat(self
._type
_helper
.GetNamespaceEnd())
113 .Concat(cpp_util
.CloseNamespace(self
._cpp
_namespace
))
114 .Append('#endif // %s' % ifndef_name
)
119 def _FieldDependencyOrder(self
):
120 """Generates the list of types in the current namespace in an order in which
121 depended-upon types appear before types which depend on them.
123 dependency_order
= []
125 def ExpandType(path
, type_
):
127 raise ValueError("Illegal circular dependency via cycle " +
128 ", ".join(map(lambda x
: x
.name
, path
+ [type_
])))
129 for prop
in type_
.properties
.values():
130 if (prop
.type_
== PropertyType
.REF
and
131 schema_util
.GetNamespace(prop
.ref_type
) == self
._namespace
.name
):
132 ExpandType(path
+ [type_
], self
._namespace
.types
[prop
.ref_type
])
133 if not type_
in dependency_order
:
134 dependency_order
.append(type_
)
136 for type_
in self
._namespace
.types
.values():
137 ExpandType([], type_
)
138 return dependency_order
140 def _GenerateEnumDeclaration(self
, enum_name
, type_
):
141 """Generate a code object with the declaration of a C++ enum.
144 c
.Sblock('enum %s {' % enum_name
)
145 c
.Append(self
._type
_helper
.GetEnumNoneValue(type_
) + ',')
146 for value
in type_
.enum_values
:
147 current_enum_string
= self
._type
_helper
.GetEnumValue(type_
, value
)
148 c
.Append(current_enum_string
+ ',')
149 c
.Append('%s = %s,' % (
150 self
._type
_helper
.GetEnumLastValue(type_
), current_enum_string
))
154 def _GenerateFields(self
, props
):
155 """Generates the field declarations when declaring a type.
158 needs_blank_line
= False
162 needs_blank_line
= True
164 c
.Comment(prop
.description
)
165 # ANY is a base::Value which is abstract and cannot be a direct member, so
166 # we always need to wrap it in a scoped_ptr.
167 is_ptr
= prop
.optional
or prop
.type_
.property_type
== PropertyType
.ANY
168 (c
.Append('%s %s;' % (
169 self
._type
_helper
.GetCppType(prop
.type_
, is_ptr
=is_ptr
),
174 def _GenerateType(self
, type_
, is_toplevel
=False, generate_typedefs
=False):
175 """Generates a struct for |type_|.
177 |is_toplevel| implies that the type was declared in the "types" field
178 of an API schema. This determines the correct function
180 |generate_typedefs| controls whether primitive types should be generated as
181 a typedef. This may not always be desired. If false,
182 primitive types are ignored.
184 classname
= cpp_util
.Classname(schema_util
.StripNamespace(type_
.name
))
188 # Wrap functions within types in the type's namespace.
189 (c
.Append('namespace %s {' % classname
)
192 for function
in type_
.functions
.values():
193 c
.Cblock(self
._GenerateFunction
(function
))
194 c
.Append('} // namespace %s' % classname
)
195 elif type_
.property_type
== PropertyType
.ARRAY
:
196 if generate_typedefs
and type_
.description
:
197 c
.Comment(type_
.description
)
198 c
.Cblock(self
._GenerateType
(type_
.item_type
))
199 if generate_typedefs
:
200 (c
.Append('typedef std::vector<%s > %s;' % (
201 self
._type
_helper
.GetCppType(type_
.item_type
),
204 elif type_
.property_type
== PropertyType
.STRING
:
205 if generate_typedefs
:
206 if type_
.description
:
207 c
.Comment(type_
.description
)
208 c
.Append('typedef std::string %(classname)s;')
209 elif type_
.property_type
== PropertyType
.ENUM
:
210 if type_
.description
:
211 c
.Comment(type_
.description
)
212 c
.Cblock(self
._GenerateEnumDeclaration
(classname
, type_
));
213 # Top level enums are in a namespace scope so the methods shouldn't be
214 # static. On the other hand, those declared inline (e.g. in an object) do.
215 maybe_static
= '' if is_toplevel
else 'static '
217 .Append('%sstd::string ToString(%s as_enum);' %
218 (maybe_static
, classname
))
219 .Append('%s%s Parse%s(const std::string& as_string);' %
220 (maybe_static
, classname
, classname
))
222 elif type_
.property_type
in (PropertyType
.CHOICES
,
223 PropertyType
.OBJECT
):
224 if type_
.description
:
225 c
.Comment(type_
.description
)
226 (c
.Sblock('struct %(classname)s {')
227 .Append('%(classname)s();')
228 .Append('~%(classname)s();')
230 if type_
.origin
.from_json
:
232 .Comment('Populates a %s object from a base::Value. Returns'
233 ' whether |out| was successfully populated.' % classname
)
234 .Append('static bool Populate(%s);' % self
._GenerateParams
(
235 ('const base::Value& value', '%s* out' % classname
)))
239 .Comment('Creates a %s object from a base::Value, or NULL on '
240 'failure.' % classname
)
241 .Append('static scoped_ptr<%s> FromValue(%s);' % (
242 classname
, self
._GenerateParams
(('const base::Value& value',))))
244 if type_
.origin
.from_client
:
245 value_type
= ('base::Value'
246 if type_
.property_type
is PropertyType
.CHOICES
else
247 'base::DictionaryValue')
249 .Comment('Returns a new %s representing the serialized form of this '
250 '%s object.' % (value_type
, classname
))
251 .Append('scoped_ptr<%s> ToValue() const;' % value_type
)
253 if type_
.property_type
== PropertyType
.CHOICES
:
254 # Choices are modelled with optional fields for each choice. Exactly one
255 # field of the choice is guaranteed to be set by the compiler.
256 c
.Cblock(self
._GenerateTypes
(type_
.choices
))
257 c
.Append('// Choices:')
258 for choice_type
in type_
.choices
:
259 c
.Append('%s as_%s;' % (
260 self
._type
_helper
.GetCppType(choice_type
, is_ptr
=True),
261 choice_type
.unix_name
))
263 properties
= type_
.properties
.values()
265 .Cblock(self
._GenerateTypes
(p
.type_
for p
in properties
))
266 .Cblock(self
._GenerateFields
(properties
)))
267 if type_
.additional_properties
is not None:
268 # Most additionalProperties actually have type "any", which is better
269 # modelled as a DictionaryValue rather than a map of string -> Value.
270 if type_
.additional_properties
.property_type
== PropertyType
.ANY
:
271 c
.Append('base::DictionaryValue additional_properties;')
273 (c
.Cblock(self
._GenerateType
(type_
.additional_properties
))
274 .Append('std::map<std::string, %s> additional_properties;' %
275 cpp_util
.PadForGenerics(
276 self
._type
_helper
.GetCppType(type_
.additional_properties
,
277 is_in_container
=True)))
282 .Append('DISALLOW_COPY_AND_ASSIGN(%(classname)s);')
285 return c
.Substitute({'classname': classname
})
287 def _GenerateEvent(self
, event
):
288 """Generates the namespaces for an event.
291 # TODO(kalman): use event.unix_name not Classname.
292 event_namespace
= cpp_util
.Classname(event
.name
)
293 (c
.Append('namespace %s {' % event_namespace
)
295 .Concat(self
._GenerateEventNameConstant
(event
))
296 .Concat(self
._GenerateCreateCallbackArguments
(event
))
297 .Eblock('} // namespace %s' % event_namespace
)
301 def _GenerateFunction(self
, function
):
302 """Generates the namespaces and structs for a function.
305 # TODO(kalman): Use function.unix_name not Classname here.
306 function_namespace
= cpp_util
.Classname(function
.name
)
307 # Windows has a #define for SendMessage, so to avoid any issues, we need
308 # to not use the name.
309 if function_namespace
== 'SendMessage':
310 function_namespace
= 'PassMessage'
311 (c
.Append('namespace %s {' % function_namespace
)
313 .Cblock(self
._GenerateFunctionParams
(function
))
315 if function
.callback
:
316 c
.Cblock(self
._GenerateFunctionResults
(function
.callback
))
317 c
.Append('} // namespace %s' % function_namespace
)
320 def _GenerateFunctionParams(self
, function
):
321 """Generates the struct for passing parameters from JSON to a function.
323 if not function
.params
:
327 (c
.Sblock('struct Params {')
328 .Append('static scoped_ptr<Params> Create(%s);' % self
._GenerateParams
(
329 ('const base::ListValue& args',)))
330 .Append('~Params();')
332 .Cblock(self
._GenerateTypes
(p
.type_
for p
in function
.params
))
333 .Cblock(self
._GenerateFields
(function
.params
))
339 .Append('DISALLOW_COPY_AND_ASSIGN(Params);')
344 def _GenerateTypes(self
, types
, is_toplevel
=False, generate_typedefs
=False):
345 """Generate the structures required by a property such as OBJECT classes
350 c
.Cblock(self
._GenerateType
(type_
,
351 is_toplevel
=is_toplevel
,
352 generate_typedefs
=generate_typedefs
))
355 def _GenerateCreateCallbackArguments(self
, function
):
356 """Generates functions for passing parameters to a callback.
359 params
= function
.params
360 c
.Cblock(self
._GenerateTypes
((p
.type_
for p
in params
), is_toplevel
=True))
362 declaration_list
= []
364 if param
.description
:
365 c
.Comment(param
.description
)
366 declaration_list
.append(cpp_util
.GetParameterDeclaration(
367 param
, self
._type
_helper
.GetCppType(param
.type_
)))
368 c
.Append('scoped_ptr<base::ListValue> Create(%s);' %
369 ', '.join(declaration_list
))
372 def _GenerateEventNameConstant(self
, event
):
373 """Generates a constant string array for the event name.
376 c
.Append('extern const char kEventName[]; // "%s.%s"' % (
377 self
._namespace
.name
, event
.name
))
381 def _GenerateFunctionResults(self
, callback
):
382 """Generates namespace for passing a function's result back.
385 (c
.Append('namespace Results {')
387 .Concat(self
._GenerateCreateCallbackArguments
(callback
))
388 .Append('} // namespace Results')
392 def _GenerateParams(self
, params
):
393 """Builds the parameter list for a function, given an array of parameters.
395 # |error| is populated with warnings and/or errors found during parsing.
396 # |error| being set does not necessarily imply failure and may be
398 # For example, optional properties may have failed to parse, but the
399 # parser was able to continue.
400 if self
._generate
_error
_messages
:
401 params
+= ('base::string16* error',)
402 return ', '.join(str(p
) for p
in params
)