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
, Type
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()
20 class _Generator(object):
21 """A .h generator for a namespace.
23 def __init__(self
, namespace
, cpp_type_generator
, cpp_namespace
):
24 self
._namespace
= namespace
25 self
._type
_helper
= cpp_type_generator
26 self
._cpp
_namespace
= cpp_namespace
27 self
._target
_namespace
= (
28 self
._type
_helper
.GetCppNamespaceName(self
._namespace
))
31 """Generates a Code object with the .h for a single namespace.
34 (c
.Append(cpp_util
.CHROMIUM_LICENSE
)
36 .Append(cpp_util
.GENERATED_FILE_MESSAGE
% self
._namespace
.source_file
)
40 ifndef_name
= cpp_util
.GenerateIfndefName(self
._namespace
.source_file_dir
,
41 self
._target
_namespace
)
42 (c
.Append('#ifndef %s' % ifndef_name
)
43 .Append('#define %s' % ifndef_name
)
45 .Append('#include <map>')
46 .Append('#include <string>')
47 .Append('#include <vector>')
49 .Append('#include "base/basictypes.h"')
50 .Append('#include "base/logging.h"')
51 .Append('#include "base/memory/linked_ptr.h"')
52 .Append('#include "base/memory/scoped_ptr.h"')
53 .Append('#include "base/values.h"')
54 .Cblock(self
._type
_helper
.GenerateIncludes())
58 c
.Concat(cpp_util
.OpenNamespace(self
._cpp
_namespace
))
59 # TODO(calamity): These forward declarations should be #includes to allow
60 # $ref types from other files to be used as required params. This requires
61 # some detangling of windows and tabs which will currently lead to circular
63 forward_declarations
= (
64 self
._type
_helper
.GenerateForwardDeclarations())
65 if not forward_declarations
.IsEmpty():
67 .Cblock(forward_declarations
)
70 c
.Concat(self
._type
_helper
.GetNamespaceStart())
72 if self
._namespace
.properties
:
74 .Append('// Properties')
78 for property in self
._namespace
.properties
.values():
79 property_code
= self
._type
_helper
.GeneratePropertyValues(
81 'extern const %(type)s %(name)s;')
83 c
.Cblock(property_code
)
84 if self
._namespace
.types
:
89 .Cblock(self
._GenerateTypes
(self
._FieldDependencyOrder
(),
91 generate_typedefs
=True))
93 if self
._namespace
.functions
:
95 .Append('// Functions')
99 for function
in self
._namespace
.functions
.values():
100 c
.Cblock(self
._GenerateFunction
(function
))
101 if self
._namespace
.events
:
107 for event
in self
._namespace
.events
.values():
108 c
.Cblock(self
._GenerateEvent
(event
))
109 (c
.Concat(self
._type
_helper
.GetNamespaceEnd())
110 .Concat(cpp_util
.CloseNamespace(self
._cpp
_namespace
))
111 .Append('#endif // %s' % ifndef_name
)
116 def _FieldDependencyOrder(self
):
117 """Generates the list of types in the current namespace in an order in which
118 depended-upon types appear before types which depend on them.
120 dependency_order
= []
122 def ExpandType(path
, type_
):
124 raise ValueError("Illegal circular dependency via cycle " +
125 ", ".join(map(lambda x
: x
.name
, path
+ [type_
])))
126 for prop
in type_
.properties
.values():
127 if (prop
.type_
== PropertyType
.REF
and
128 schema_util
.GetNamespace(prop
.ref_type
) == self
._namespace
.name
):
129 ExpandType(path
+ [type_
], self
._namespace
.types
[prop
.ref_type
])
130 if not type_
in dependency_order
:
131 dependency_order
.append(type_
)
133 for type_
in self
._namespace
.types
.values():
134 ExpandType([], type_
)
135 return dependency_order
137 def _GenerateEnumDeclaration(self
, enum_name
, type_
):
138 """Generate the declaration of a C++ enum.
141 c
.Sblock('enum %s {' % enum_name
)
142 c
.Append(self
._type
_helper
.GetEnumNoneValue(type_
) + ',')
143 for value
in type_
.enum_values
:
144 c
.Append(self
._type
_helper
.GetEnumValue(type_
, value
) + ',')
145 return c
.Eblock('};')
147 def _GenerateFields(self
, props
):
148 """Generates the field declarations when declaring a type.
151 needs_blank_line
= False
155 needs_blank_line
= True
157 c
.Comment(prop
.description
)
158 # ANY is a base::Value which is abstract and cannot be a direct member, so
159 # we always need to wrap it in a scoped_ptr.
160 is_ptr
= prop
.optional
or prop
.type_
.property_type
== PropertyType
.ANY
161 (c
.Append('%s %s;' % (
162 self
._type
_helper
.GetCppType(prop
.type_
, is_ptr
=is_ptr
),
167 def _GenerateType(self
, type_
, is_toplevel
=False, generate_typedefs
=False):
168 """Generates a struct for |type_|.
170 |is_toplevel| implies that the type was declared in the "types" field
171 of an API schema. This determines the correct function
173 |generate_typedefs| controls whether primitive types should be generated as
174 a typedef. This may not always be desired. If false,
175 primitive types are ignored.
177 classname
= cpp_util
.Classname(schema_util
.StripNamespace(type_
.name
))
181 # Wrap functions within types in the type's namespace.
182 (c
.Append('namespace %s {' % classname
)
185 for function
in type_
.functions
.values():
186 c
.Cblock(self
._GenerateFunction
(function
))
187 c
.Append('} // namespace %s' % classname
)
188 elif type_
.property_type
== PropertyType
.ARRAY
:
189 if generate_typedefs
and type_
.description
:
190 c
.Comment(type_
.description
)
191 c
.Cblock(self
._GenerateType
(type_
.item_type
))
192 if generate_typedefs
:
193 (c
.Append('typedef std::vector<%s > %s;' % (
194 self
._type
_helper
.GetCppType(type_
.item_type
),
197 elif type_
.property_type
== PropertyType
.STRING
:
198 if generate_typedefs
:
199 if type_
.description
:
200 c
.Comment(type_
.description
)
201 c
.Append('typedef std::string %(classname)s;')
202 elif type_
.property_type
== PropertyType
.ENUM
:
203 if type_
.description
:
204 c
.Comment(type_
.description
)
205 c
.Sblock('enum %(classname)s {')
206 c
.Append('%s,' % self
._type
_helper
.GetEnumNoneValue(type_
))
207 for value
in type_
.enum_values
:
208 c
.Append('%s,' % self
._type
_helper
.GetEnumValue(type_
, value
))
209 # Top level enums are in a namespace scope so the methods shouldn't be
210 # static. On the other hand, those declared inline (e.g. in an object) do.
211 maybe_static
= '' if is_toplevel
else 'static '
214 .Append('%sstd::string ToString(%s as_enum);' %
215 (maybe_static
, classname
))
216 .Append('%s%s Parse%s(const std::string& as_string);' %
217 (maybe_static
, classname
, classname
))
219 elif type_
.property_type
== PropertyType
.OBJECT
:
220 if type_
.description
:
221 c
.Comment(type_
.description
)
222 (c
.Sblock('struct %(classname)s {')
223 .Append('%(classname)s();')
224 .Append('~%(classname)s();')
226 if type_
.origin
.from_json
:
228 .Comment('Populates a %s object from a base::Value. Returns'
229 ' whether |out| was successfully populated.' % classname
)
230 .Append('static bool Populate(const base::Value& value, '
231 '%(classname)s* out);')
233 if type_
.origin
.from_client
:
235 .Comment('Returns a new base::DictionaryValue representing the'
236 ' serialized form of this %s object.' % classname
)
237 .Append('scoped_ptr<base::DictionaryValue> ToValue() const;')
239 properties
= type_
.properties
.values()
241 .Cblock(self
._GenerateTypes
(p
.type_
for p
in properties
))
242 .Cblock(self
._GenerateFields
(properties
)))
243 if type_
.additional_properties
is not None:
244 # Most additionalProperties actually have type "any", which is better
245 # modelled as a DictionaryValue rather than a map of string -> Value.
246 if type_
.additional_properties
.property_type
== PropertyType
.ANY
:
247 c
.Append('base::DictionaryValue additional_properties;')
249 (c
.Cblock(self
._GenerateType
(type_
.additional_properties
))
250 .Append('std::map<std::string, %s> additional_properties;' %
251 cpp_util
.PadForGenerics(
252 self
._type
_helper
.GetCppType(type_
.additional_properties
,
253 is_in_container
=True)))
258 .Append('DISALLOW_COPY_AND_ASSIGN(%(classname)s);')
261 elif type_
.property_type
== PropertyType
.CHOICES
:
262 if type_
.description
:
263 c
.Comment(type_
.description
)
264 # Choices are modelled with optional fields for each choice. Exactly one
265 # field of the choice is guaranteed to be set by the compiler.
266 (c
.Sblock('struct %(classname)s {')
267 .Append('%(classname)s();')
268 .Append('~%(classname)s();')
270 c
.Cblock(self
._GenerateTypes
(type_
.choices
))
271 if type_
.origin
.from_json
:
272 (c
.Comment('Populates a %s object from a base::Value. Returns'
273 ' whether |out| was successfully populated.' % classname
)
274 .Append('static bool Populate(const base::Value& value, '
275 '%(classname)s* out);')
278 if type_
.origin
.from_client
:
279 (c
.Comment('Returns a new base::Value representing the'
280 ' serialized form of this %s object.' % classname
)
281 .Append('scoped_ptr<base::Value> ToValue() const;')
284 c
.Append('// Choices:')
285 for choice_type
in type_
.choices
:
286 c
.Append('%s as_%s;' % (
287 self
._type
_helper
.GetCppType(choice_type
, is_ptr
=True),
288 choice_type
.unix_name
))
290 c
.Substitute({'classname': classname
})
293 def _GenerateEvent(self
, event
):
294 """Generates the namespaces for an event.
297 # TODO(kalman): use event.unix_name not Classname.
298 event_namespace
= cpp_util
.Classname(event
.name
)
299 (c
.Append('namespace %s {' % event_namespace
)
301 .Concat(self
._GenerateCreateCallbackArguments
(event
))
302 .Eblock('} // namespace %s' % event_namespace
)
306 def _GenerateFunction(self
, function
):
307 """Generates the namespaces and structs for a function.
310 # TODO(kalman): Use function.unix_name not Classname here.
311 function_namespace
= cpp_util
.Classname(function
.name
)
312 (c
.Append('namespace %s {' % function_namespace
)
314 .Cblock(self
._GenerateFunctionParams
(function
))
316 if function
.callback
:
317 c
.Cblock(self
._GenerateFunctionResults
(function
.callback
))
318 c
.Append('} // namespace %s' % function_namespace
)
321 def _GenerateFunctionParams(self
, function
):
322 """Generates the struct for passing parameters from JSON to a function.
324 if not function
.params
:
328 (c
.Sblock('struct Params {')
329 .Append('static scoped_ptr<Params> Create(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 _GenerateFunctionResults(self
, callback
):
373 """Generates namespace for passing a function's result back.
376 (c
.Append('namespace Results {')
378 .Concat(self
._GenerateCreateCallbackArguments
(callback
))
379 .Append('} // namespace Results')