Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(6)

Side by Side Diff: mojo/public/tools/bindings/generators/mojom_cpp_generator.py

Issue 2656583002: Remove unused typemap includes from generated C++ mojo bindings. (Closed)
Patch Set: Created 3 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 # Copyright 2013 The Chromium Authors. All rights reserved. 1 # Copyright 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be 2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file. 3 # found in the LICENSE file.
4 4
5 """Generates C++ source files from a mojom.Module.""" 5 """Generates C++ source files from a mojom.Module."""
6 6
7 import mojom.generate.generator as generator 7 import mojom.generate.generator as generator
8 import mojom.generate.module as mojom 8 import mojom.generate.module as mojom
9 import mojom.generate.pack as pack 9 import mojom.generate.pack as pack
10 from mojom.generate.template_expander import UseJinja 10 from mojom.generate.template_expander import UseJinja
(...skipping 23 matching lines...) Expand all
34 34
35 # TODO(rockot): Get rid of these globals. This requires some refactoring of the 35 # TODO(rockot): Get rid of these globals. This requires some refactoring of the
36 # generator library code so that filters can use the generator as context. 36 # generator library code so that filters can use the generator as context.
37 _current_typemap = {} 37 _current_typemap = {}
38 _for_blink = False 38 _for_blink = False
39 # TODO(rockot, yzshen): The variant handling is kind of a hack currently. Make 39 # TODO(rockot, yzshen): The variant handling is kind of a hack currently. Make
40 # it right. 40 # it right.
41 _variant = None 41 _variant = None
42 42
43 43
44 class _NameFormatter(object): 44 class _NameFormatter(generator.NameFormatter):
45 """A formatter for the names of kinds or values."""
46
47 def __init__(self, token, variant):
48 self._token = token
49 self._variant = variant
50 45
51 def Format(self, separator, prefixed=False, internal=False, 46 def Format(self, separator, prefixed=False, internal=False,
52 include_variant=False, add_same_module_namespaces=False, 47 include_variant=False, add_same_module_namespaces=False,
53 flatten_nested_kind=False): 48 flatten_nested_kind=False):
54 """Formats the name according to the given configuration. 49 """Formats the name according to the given configuration.
55 50
56 Args: 51 Args:
57 separator: Separator between different parts of the name. 52 separator: Separator between different parts of the name.
58 prefixed: Whether a leading separator should be added. 53 prefixed: Whether a leading separator should be added.
59 internal: Returns the name in the "internal" namespace. 54 internal: Returns the name in the "internal" namespace.
(...skipping 17 matching lines...) Expand all
77 return separator.join(parts) 72 return separator.join(parts)
78 73
79 def FormatForCpp(self, add_same_module_namespaces=False, internal=False, 74 def FormatForCpp(self, add_same_module_namespaces=False, internal=False,
80 flatten_nested_kind=False): 75 flatten_nested_kind=False):
81 return self.Format( 76 return self.Format(
82 "::", prefixed=True, 77 "::", prefixed=True,
83 add_same_module_namespaces=add_same_module_namespaces, 78 add_same_module_namespaces=add_same_module_namespaces,
84 internal=internal, include_variant=True, 79 internal=internal, include_variant=True,
85 flatten_nested_kind=flatten_nested_kind) 80 flatten_nested_kind=flatten_nested_kind)
86 81
87 def FormatForMojom(self): 82 def _MapKindName(self, token, internal=False):
88 return self.Format(".", add_same_module_namespaces=True)
89
90 def _MapKindName(self, token, internal):
91 if not internal: 83 if not internal:
92 return token.name 84 return super(_NameFormatter, self)._MapKindName(token)
93 if (mojom.IsStructKind(token) or mojom.IsUnionKind(token) or 85 if (mojom.IsStructKind(token) or mojom.IsUnionKind(token) or
94 mojom.IsEnumKind(token)): 86 mojom.IsEnumKind(token)):
95 return token.name + "_Data" 87 return token.name + "_Data"
96 return token.name 88 return super(_NameFormatter, self)._MapKindName(token)
97 89
98 def _GetName(self, internal, flatten_nested_kind): 90 def _GetName(self, internal, flatten_nested_kind):
99 if isinstance(self._token, mojom.EnumValue): 91 name = super(_NameFormatter, self)._GetName(
100 name_parts = _NameFormatter(self._token.enum, self._variant)._GetName( 92 internal=internal, flatten_nested_kind=flatten_nested_kind)
101 internal, flatten_nested_kind)
102 name_parts.append(self._token.name)
103 return name_parts
104
105 name_parts = []
106 if internal: 93 if internal:
107 name_parts.append("internal") 94 name.insert(0, 'internal')
108 95 return name
109 if (flatten_nested_kind and mojom.IsEnumKind(self._token) and
110 self._token.parent_kind):
111 name = "%s_%s" % (self._token.parent_kind.name,
112 self._MapKindName(self._token, internal))
113 name_parts.append(name)
114 return name_parts
115
116 if self._token.parent_kind:
117 name_parts.append(self._MapKindName(self._token.parent_kind, internal))
118 name_parts.append(self._MapKindName(self._token, internal))
119 return name_parts
120
121 def _ShouldIncludeNamespace(self, add_same_module_namespaces):
122 return add_same_module_namespaces or self._token.imported_from
123
124 def _GetNamespace(self):
125 if self._token.imported_from:
126 return NamespaceToArray(self._token.imported_from["namespace"])
127 elif hasattr(self._token, "module"):
128 return NamespaceToArray(self._token.module.namespace)
129 return []
130 96
131 97
132 def ConstantValue(constant): 98 def ConstantValue(constant):
133 return ExpressionToText(constant.value, kind=constant.kind) 99 return ExpressionToText(constant.value, kind=constant.kind)
134 100
135 # TODO(yzshen): Revisit the default value feature. It was designed prior to 101 # TODO(yzshen): Revisit the default value feature. It was designed prior to
136 # custom type mapping. 102 # custom type mapping.
137 def DefaultValue(field): 103 def DefaultValue(field):
138 if field.default: 104 if field.default:
139 if mojom.IsStructKind(field.kind): 105 if mojom.IsStructKind(field.kind):
140 assert field.default == "default" 106 assert field.default == "default"
141 if not IsTypemappedKind(field.kind): 107 if not IsTypemappedKind(field.kind):
142 return "%s::New()" % GetNameForKind(field.kind) 108 return "%s::New()" % GetNameForKind(field.kind)
143 return ExpressionToText(field.default, kind=field.kind) 109 return ExpressionToText(field.default, kind=field.kind)
144 return "" 110 return ""
145 111
146 def NamespaceToArray(namespace): 112 def NamespaceToArray(namespace):
yzshen1 2017/02/01 20:25:57 Could we remove this one? (There is one in generat
Sam McNally 2017/02/02 22:01:46 Removed the one in generator.py instead since I'm
147 return namespace.split(".") if namespace else [] 113 return namespace.split(".") if namespace else []
148 114
149 def GetNameForKind(kind, internal=False, flatten_nested_kind=False, 115 def GetNameForKind(kind, internal=False, flatten_nested_kind=False,
150 add_same_module_namespaces=False): 116 add_same_module_namespaces=False):
151 return _NameFormatter(kind, _variant).FormatForCpp( 117 return _NameFormatter(kind, _variant).FormatForCpp(
152 internal=internal, flatten_nested_kind=flatten_nested_kind, 118 internal=internal, flatten_nested_kind=flatten_nested_kind,
153 add_same_module_namespaces=add_same_module_namespaces) 119 add_same_module_namespaces=add_same_module_namespaces)
154 120
155 def GetQualifiedNameForKind(kind, internal=False, flatten_nested_kind=False): 121 def GetQualifiedNameForKind(kind, internal=False, flatten_nested_kind=False):
156 return _NameFormatter(kind, _variant).FormatForCpp( 122 return _NameFormatter(kind, _variant).FormatForCpp(
157 internal=internal, add_same_module_namespaces=True, 123 internal=internal, add_same_module_namespaces=True,
158 flatten_nested_kind=flatten_nested_kind) 124 flatten_nested_kind=flatten_nested_kind)
159 125
160 def GetFullMojomNameForKind(kind):
161 return _NameFormatter(kind, _variant).FormatForMojom()
162
163 def IsTypemappedKind(kind): 126 def IsTypemappedKind(kind):
164 return hasattr(kind, "name") and \ 127 return hasattr(kind, "name") and \
165 GetFullMojomNameForKind(kind) in _current_typemap 128 generator.GetFullMojomNameForKind(kind) in _current_typemap
166 129
167 def IsNativeOnlyKind(kind): 130 def IsNativeOnlyKind(kind):
168 return (mojom.IsStructKind(kind) or mojom.IsEnumKind(kind)) and \ 131 return (mojom.IsStructKind(kind) or mojom.IsEnumKind(kind)) and \
169 kind.native_only 132 kind.native_only
170 133
171 134
172 def IsHashableKind(kind): 135 def IsHashableKind(kind):
173 """Check if the kind can be hashed. 136 """Check if the kind can be hashed.
174 137
175 Args: 138 Args:
176 kind: {Kind} The kind to check. 139 kind: {Kind} The kind to check.
177 140
178 Returns: 141 Returns:
179 {bool} True if a value of this kind can be hashed. 142 {bool} True if a value of this kind can be hashed.
180 """ 143 """
181 checked = set() 144 checked = set()
182 def Check(kind): 145 def Check(kind):
183 if kind.spec in checked: 146 if kind.spec in checked:
184 return True 147 return True
185 checked.add(kind.spec) 148 checked.add(kind.spec)
186 if mojom.IsNullableKind(kind): 149 if mojom.IsNullableKind(kind):
187 return False 150 return False
188 elif mojom.IsStructKind(kind): 151 elif mojom.IsStructKind(kind):
189 if (IsTypemappedKind(kind) and 152 if (IsTypemappedKind(kind) and not _current_typemap[
190 not _current_typemap[GetFullMojomNameForKind(kind)]["hashable"]): 153 generator.GetFullMojomNameForKind(kind)]["hashable"]):
191 return False 154 return False
192 return all(Check(field.kind) for field in kind.fields) 155 return all(Check(field.kind) for field in kind.fields)
193 elif mojom.IsEnumKind(kind): 156 elif mojom.IsEnumKind(kind):
194 if (IsTypemappedKind(kind) and 157 return not (IsTypemappedKind(kind) and not _current_typemap[
195 not _current_typemap[GetFullMojomNameForKind(kind)]["hashable"]): 158 generator.GetFullMojomNameForKind(kind)]["hashable"])
196 return False
197 return True
198 elif mojom.IsUnionKind(kind): 159 elif mojom.IsUnionKind(kind):
199 return all(Check(field.kind) for field in kind.fields) 160 return all(Check(field.kind) for field in kind.fields)
200 elif mojom.IsAnyHandleKind(kind): 161 elif mojom.IsAnyHandleKind(kind):
201 return False 162 return False
202 elif mojom.IsAnyInterfaceKind(kind): 163 elif mojom.IsAnyInterfaceKind(kind):
203 return False 164 return False
204 # TODO(tibell): Arrays and maps could be made hashable. We just don't have a 165 # TODO(tibell): Arrays and maps could be made hashable. We just don't have a
205 # use case yet. 166 # use case yet.
206 elif mojom.IsArrayKind(kind): 167 elif mojom.IsArrayKind(kind):
207 return False 168 return False
208 elif mojom.IsMapKind(kind): 169 elif mojom.IsMapKind(kind):
209 return False 170 return False
210 else: 171 else:
211 return True 172 return True
212 return Check(kind) 173 return Check(kind)
213 174
214 175
215 def GetNativeTypeName(typemapped_kind): 176 def GetNativeTypeName(typemapped_kind):
216 return _current_typemap[GetFullMojomNameForKind(typemapped_kind)]["typename"] 177 return _current_typemap[
178 generator.GetFullMojomNameForKind(typemapped_kind)]["typename"]
217 179
218 def GetCppPodType(kind): 180 def GetCppPodType(kind):
219 return _kind_to_cpp_type[kind] 181 return _kind_to_cpp_type[kind]
220 182
221 def FormatConstantDeclaration(constant, nested=False): 183 def FormatConstantDeclaration(constant, nested=False):
222 if mojom.IsStringKind(constant.kind): 184 if mojom.IsStringKind(constant.kind):
223 if nested: 185 if nested:
224 return "const char %s[]" % constant.name 186 return "const char %s[]" % constant.name
225 return "extern const char %s[]" % constant.name 187 return "extern const char %s[]" % constant.name
226 return "constexpr %s %s = %s" % (GetCppPodType(constant.kind), constant.name, 188 return "constexpr %s %s = %s" % (GetCppPodType(constant.kind), constant.name,
227 ConstantValue(constant)) 189 ConstantValue(constant))
228 190
229 def GetCppWrapperType(kind, add_same_module_namespaces=False): 191 def GetCppWrapperType(kind, add_same_module_namespaces=False):
230 def _AddOptional(type_name): 192 def _AddOptional(type_name):
231 pattern = "WTF::Optional<%s>" if _for_blink else "base::Optional<%s>" 193 pattern = "WTF::Optional<%s>" if _for_blink else "base::Optional<%s>"
232 return pattern % type_name 194 return pattern % type_name
233 195
234 if IsTypemappedKind(kind): 196 if IsTypemappedKind(kind):
235 type_name = GetNativeTypeName(kind) 197 type_name = GetNativeTypeName(kind)
236 if (mojom.IsNullableKind(kind) and 198 if (mojom.IsNullableKind(kind) and
237 not _current_typemap[GetFullMojomNameForKind(kind)][ 199 not _current_typemap[generator.GetFullMojomNameForKind(kind)][
238 "nullable_is_same_type"]): 200 "nullable_is_same_type"]):
239 type_name = _AddOptional(type_name) 201 type_name = _AddOptional(type_name)
240 return type_name 202 return type_name
241 if mojom.IsEnumKind(kind): 203 if mojom.IsEnumKind(kind):
242 return GetNameForKind( 204 return GetNameForKind(
243 kind, add_same_module_namespaces=add_same_module_namespaces) 205 kind, add_same_module_namespaces=add_same_module_namespaces)
244 if mojom.IsStructKind(kind) or mojom.IsUnionKind(kind): 206 if mojom.IsStructKind(kind) or mojom.IsUnionKind(kind):
245 return "%sPtr" % GetNameForKind( 207 return "%sPtr" % GetNameForKind(
246 kind, add_same_module_namespaces=add_same_module_namespaces) 208 kind, add_same_module_namespaces=add_same_module_namespaces)
247 if mojom.IsArrayKind(kind): 209 if mojom.IsArrayKind(kind):
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
290 if mojom.IsSharedBufferKind(kind): 252 if mojom.IsSharedBufferKind(kind):
291 return "mojo::ScopedSharedBufferHandle" 253 return "mojo::ScopedSharedBufferHandle"
292 if not kind in _kind_to_cpp_type: 254 if not kind in _kind_to_cpp_type:
293 raise Exception("Unrecognized kind %s" % kind.spec) 255 raise Exception("Unrecognized kind %s" % kind.spec)
294 return _kind_to_cpp_type[kind] 256 return _kind_to_cpp_type[kind]
295 257
296 def IsMoveOnlyKind(kind): 258 def IsMoveOnlyKind(kind):
297 if IsTypemappedKind(kind): 259 if IsTypemappedKind(kind):
298 if mojom.IsEnumKind(kind): 260 if mojom.IsEnumKind(kind):
299 return False 261 return False
300 return _current_typemap[GetFullMojomNameForKind(kind)]["move_only"] 262 return _current_typemap[
263 generator.GetFullMojomNameForKind(kind)]["move_only"]
301 if mojom.IsStructKind(kind) or mojom.IsUnionKind(kind): 264 if mojom.IsStructKind(kind) or mojom.IsUnionKind(kind):
302 return True 265 return True
303 if mojom.IsArrayKind(kind): 266 if mojom.IsArrayKind(kind):
304 return IsMoveOnlyKind(kind.kind) 267 return IsMoveOnlyKind(kind.kind)
305 if mojom.IsMapKind(kind): 268 if mojom.IsMapKind(kind):
306 return IsMoveOnlyKind(kind.value_kind) 269 return IsMoveOnlyKind(kind.value_kind)
307 if mojom.IsAnyHandleOrInterfaceKind(kind): 270 if mojom.IsAnyHandleOrInterfaceKind(kind):
308 return True 271 return True
309 return False 272 return False
310 273
311 def IsCopyablePassByValue(kind): 274 def IsCopyablePassByValue(kind):
312 if not IsTypemappedKind(kind): 275 if not IsTypemappedKind(kind):
313 return False 276 return False
314 return _current_typemap[GetFullMojomNameForKind(kind)][ 277 return _current_typemap[generator.GetFullMojomNameForKind(kind)][
315 "copyable_pass_by_value"] 278 "copyable_pass_by_value"]
316 279
317 def ShouldPassParamByValue(kind): 280 def ShouldPassParamByValue(kind):
318 return ((not mojom.IsReferenceKind(kind)) or IsMoveOnlyKind(kind) or 281 return ((not mojom.IsReferenceKind(kind)) or IsMoveOnlyKind(kind) or
319 IsCopyablePassByValue(kind)) 282 IsCopyablePassByValue(kind))
320 283
321 def GetCppWrapperParamType(kind): 284 def GetCppWrapperParamType(kind):
322 cpp_wrapper_type = GetCppWrapperType(kind) 285 cpp_wrapper_type = GetCppWrapperType(kind)
323 return (cpp_wrapper_type if ShouldPassParamByValue(kind) 286 return (cpp_wrapper_type if ShouldPassParamByValue(kind)
324 else "const %s&" % cpp_wrapper_type) 287 else "const %s&" % cpp_wrapper_type)
(...skipping 87 matching lines...) Expand 10 before | Expand all | Expand 10 after
412 return "mojo::ScopedMessagePipeHandle" 375 return "mojo::ScopedMessagePipeHandle"
413 if mojom.IsSharedBufferKind(kind): 376 if mojom.IsSharedBufferKind(kind):
414 return "mojo::ScopedSharedBufferHandle" 377 return "mojo::ScopedSharedBufferHandle"
415 return _kind_to_cpp_type[kind] 378 return _kind_to_cpp_type[kind]
416 379
417 def GetUnmappedTypeForSerializer(kind): 380 def GetUnmappedTypeForSerializer(kind):
418 return GetCppDataViewType(kind, qualified=True) 381 return GetCppDataViewType(kind, qualified=True)
419 382
420 def TranslateConstants(token, kind): 383 def TranslateConstants(token, kind):
421 if isinstance(token, mojom.NamedValue): 384 if isinstance(token, mojom.NamedValue):
422 return _NameFormatter(token, _variant).FormatForCpp( 385 return GetNameForKind(token, flatten_nested_kind=True)
423 flatten_nested_kind=True)
424 386
425 if isinstance(token, mojom.BuiltinValue): 387 if isinstance(token, mojom.BuiltinValue):
426 if token.value == "double.INFINITY": 388 if token.value == "double.INFINITY":
427 return "std::numeric_limits<double>::infinity()" 389 return "std::numeric_limits<double>::infinity()"
428 if token.value == "float.INFINITY": 390 if token.value == "float.INFINITY":
429 return "std::numeric_limits<float>::infinity()" 391 return "std::numeric_limits<float>::infinity()"
430 if token.value == "double.NEGATIVE_INFINITY": 392 if token.value == "double.NEGATIVE_INFINITY":
431 return "-std::numeric_limits<double>::infinity()" 393 return "-std::numeric_limits<double>::infinity()"
432 if token.value == "float.NEGATIVE_INFINITY": 394 if token.value == "float.NEGATIVE_INFINITY":
433 return "-std::numeric_limits<float>::infinity()" 395 return "-std::numeric_limits<float>::infinity()"
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after
523 return "%d, %s" % (expected_num_elements, enum_validate_func) 485 return "%d, %s" % (expected_num_elements, enum_validate_func)
524 486
525 def GetNewContainerValidateParams(kind): 487 def GetNewContainerValidateParams(kind):
526 if (not mojom.IsArrayKind(kind) and not mojom.IsMapKind(kind) and 488 if (not mojom.IsArrayKind(kind) and not mojom.IsMapKind(kind) and
527 not mojom.IsStringKind(kind)): 489 not mojom.IsStringKind(kind)):
528 return "nullptr" 490 return "nullptr"
529 491
530 return "new mojo::internal::ContainerValidateParams(%s)" % ( 492 return "new mojo::internal::ContainerValidateParams(%s)" % (
531 GetContainerValidateParamsCtorArgs(kind)) 493 GetContainerValidateParamsCtorArgs(kind))
532 494
495
496 def QuoteHeader(header):
497 if header[0] == '<':
498 return header
499 return '"%s"' % header
500
501
502 def QuoteAndSortHeaders(headers):
503 return (QuoteHeader(header) for header in sorted(headers))
504
505
506 CHROMIUM_HEADERS = {
507 "array": ["<vector>"],
508 "interface": [
509 "base/callback.h",
510 "mojo/public/cpp/bindings/associated_interface_ptr.h",
511 "mojo/public/cpp/bindings/associated_interface_ptr_info.h",
512 "mojo/public/cpp/bindings/associated_interface_request.h",
513 "mojo/public/cpp/bindings/interface_ptr.h",
514 "mojo/public/cpp/bindings/interface_request.h",
515 "mojo/public/cpp/bindings/raw_ptr_impl_ref_traits.h",
516 "mojo/public/cpp/bindings/thread_safe_interface_ptr.h",
517 ],
518 "map": ["<unordered_map>"],
519 "native_enum": ["mojo/public/cpp/bindings/native_enum.h"],
520 "native_struct": ["mojo/public/cpp/bindings/native_struct.h"],
521 "optional": ["base/optional.h"],
522 "string": ["<string>"],
523 "struct": [
524 "<vector>",
525 "mojo/public/cpp/bindings/lib/clone_equals_util.h",
526 "mojo/public/cpp/bindings/lib/hash_util.h",
527 "mojo/public/cpp/bindings/struct_ptr.h",
528 "mojo/public/cpp/bindings/struct_traits.h",
529 ],
530 "union": [
531 "<vector>",
532 "mojo/public/cpp/bindings/lib/union_accessor.h",
533 "mojo/public/cpp/bindings/union_traits.h",
534 ],
535 }
536
537 BLINK_HEADERS = {
538 "array": ["third_party/WebKit/Source/wtf/Vector.h"],
539 "interface": [
540 "base/callback.h",
541 "mojo/public/cpp/bindings/associated_interface_ptr.h",
542 "mojo/public/cpp/bindings/associated_interface_ptr_info.h",
543 "mojo/public/cpp/bindings/associated_interface_request.h",
544 "mojo/public/cpp/bindings/interface_ptr.h",
545 "mojo/public/cpp/bindings/interface_request.h",
546 "mojo/public/cpp/bindings/raw_ptr_impl_ref_traits.h",
547 "mojo/public/cpp/bindings/thread_safe_interface_ptr.h",
548 ],
549 "map": ["third_party/WebKit/Source/wtf/HashMap.h"],
550 "native_enum": ["mojo/public/cpp/bindings/native_enum.h"],
551 "native_struct": ["mojo/public/cpp/bindings/native_struct.h"],
552 "optional": ["third_party/WebKit/Source/wtf/Optional.h"],
553 "string": ["third_party/WebKit/Source/wtf/text/WTFString.h"],
554 "struct": [
555 "third_party/WebKit/Source/wtf/Vector.h",
556 "mojo/public/cpp/bindings/struct_ptr.h",
557 "mojo/public/cpp/bindings/struct_traits.h",
558 "mojo/public/cpp/bindings/lib/wtf_clone_equals_util.h",
559 "mojo/public/cpp/bindings/lib/wtf_hash_util.h",
560 ],
561 "union": [
562 "mojo/public/cpp/bindings/lib/union_accessor.h",
563 "mojo/public/cpp/bindings/union_traits.h",
564 "third_party/WebKit/Source/wtf/Vector.h",
565 ],
566 }
567
568 SHARED_HEADERS = {
569 "array": ["mojo/public/cpp/bindings/array_data_view.h"],
570 "enum": ["mojo/public/cpp/bindings/enum_traits.h"],
571 "interface": ["mojo/public/cpp/bindings/interface_data_view.h"],
572 "map": ["mojo/public/cpp/bindings/map_data_view.h"],
573 "native_enum": ["mojo/public/cpp/bindings/native_enum.h"],
574 "native_struct": ["mojo/public/cpp/bindings/native_struct_data_view.h"],
575 "non_native_enum": ["<ostream>"],
576 "string": ["mojo/public/cpp/bindings/string_data_view.h"],
577 }
578
579
533 class Generator(generator.Generator): 580 class Generator(generator.Generator):
534 581
535 cpp_filters = { 582 cpp_filters = {
536 "constant_value": ConstantValue, 583 "constant_value": ConstantValue,
537 "contains_handles_or_interfaces": mojom.ContainsHandlesOrInterfaces, 584 "contains_handles_or_interfaces": mojom.ContainsHandlesOrInterfaces,
538 "contains_move_only_members": ContainsMoveOnlyMembers, 585 "contains_move_only_members": ContainsMoveOnlyMembers,
539 "cpp_wrapper_param_type": GetCppWrapperParamType, 586 "cpp_wrapper_param_type": GetCppWrapperParamType,
540 "cpp_data_view_type": GetCppDataViewType, 587 "cpp_data_view_type": GetCppDataViewType,
541 "cpp_field_type": GetCppFieldType, 588 "cpp_field_type": GetCppFieldType,
542 "cpp_union_field_type": GetCppUnionFieldType, 589 "cpp_union_field_type": GetCppUnionFieldType,
(...skipping 25 matching lines...) Expand all
568 "is_hashable": IsHashableKind, 615 "is_hashable": IsHashableKind,
569 "is_map_kind": mojom.IsMapKind, 616 "is_map_kind": mojom.IsMapKind,
570 "is_nullable_kind": mojom.IsNullableKind, 617 "is_nullable_kind": mojom.IsNullableKind,
571 "is_object_kind": mojom.IsObjectKind, 618 "is_object_kind": mojom.IsObjectKind,
572 "is_reference_kind": mojom.IsReferenceKind, 619 "is_reference_kind": mojom.IsReferenceKind,
573 "is_string_kind": mojom.IsStringKind, 620 "is_string_kind": mojom.IsStringKind,
574 "is_struct_kind": mojom.IsStructKind, 621 "is_struct_kind": mojom.IsStructKind,
575 "is_typemapped_kind": IsTypemappedKind, 622 "is_typemapped_kind": IsTypemappedKind,
576 "is_union_kind": mojom.IsUnionKind, 623 "is_union_kind": mojom.IsUnionKind,
577 "passes_associated_kinds": mojom.PassesAssociatedKinds, 624 "passes_associated_kinds": mojom.PassesAssociatedKinds,
578 "struct_size": lambda ps: ps.GetTotalSize() + _HEADER_SIZE,
579 "stylize_method": generator.StudlyCapsToCamel, 625 "stylize_method": generator.StudlyCapsToCamel,
580 "under_to_camel": generator.UnderToCamel, 626 "under_to_camel": generator.UnderToCamel,
581 "unmapped_type_for_serializer": GetUnmappedTypeForSerializer, 627 "unmapped_type_for_serializer": GetUnmappedTypeForSerializer,
582 } 628 }
583 629
584 def GetExtraTraitsHeaders(self): 630 def GetExtraTraitsHeaders(self):
585 extra_headers = set() 631 extra_headers = set()
586 for entry in self.typemap.itervalues(): 632 for typemap in self._GetAllUsedTypemaps():
587 extra_headers.update(entry.get("traits_headers", [])) 633 extra_headers.update(typemap.get("traits_headers", []))
588 return list(extra_headers) 634 return QuoteAndSortHeaders(extra_headers)
589 635
590 def GetExtraPublicHeaders(self): 636 def _GetAllUsedTypemaps(self):
591 extra_headers = set() 637 used_typemaps = []
592 for entry in self.typemap.itervalues(): 638 seen_types = set()
593 extra_headers.update(entry.get("public_headers", [])) 639 def AddKind(kind):
594 return list(extra_headers) 640 if (mojom.IsIntegralKind(kind) or mojom.IsStringKind(kind) or
641 mojom.IsDoubleKind(kind) or mojom.IsFloatKind(kind) or
642 mojom.IsAnyHandleKind(kind) or
643 mojom.IsInterfaceKind(kind) or
644 mojom.IsInterfaceRequestKind(kind) or
645 mojom.IsAssociatedKind(kind)):
646 pass
647 elif mojom.IsArrayKind(kind):
648 AddKind(kind.kind)
649 elif mojom.IsMapKind(kind):
650 AddKind(kind.key_kind)
651 AddKind(kind.value_kind)
652 else:
653 name = generator.GetFullMojomNameForKind(kind, self.variant)
654 if name in seen_types:
655 return
656 seen_types.add(name)
657
658 typemap = _current_typemap.get(name, None)
659 if typemap:
660 used_typemaps.append(typemap)
661 if mojom.IsStructKind(kind) or mojom.IsUnionKind(kind):
662 for field in kind.fields:
663 AddKind(field.kind)
664
665 for kind in self.module.structs + self.module.unions:
666 for field in kind.fields:
667 AddKind(field.kind)
668
669 for interface in self.module.interfaces:
670 for method in interface.methods:
671 for parameter in method.parameters + (method.response_parameters or []):
672 AddKind(parameter.kind)
673
674 return used_typemaps
675
676 def _GetPublicHeadersImpl(self, header_type_to_headers):
677 header_types = set()
678 headers = set()
679
680 if self.module.structs:
681 header_types.add('struct')
682 if self.module.unions:
683 header_types.add('union')
684 if self.module.interfaces:
685 header_types.add('interface')
686
687 all_enums = list(self.module.enums)
688 for struct in self.module.structs:
689 all_enums.extend(struct.enums)
690 for interface in self.module.interfaces:
691 all_enums.extend(interface.enums)
692
693 potential_types = set(
694 generator.GetFullMojomNameForKind(typename, self.variant)
695 for typename in
696 self.module.structs + all_enums + self.module.unions)
697 for key, entry in self.typemap.iteritems():
698 if key in potential_types:
699 headers.update(entry.get("public_headers", []))
700 if all_enums:
701 header_types.add('enum')
702 native_enums = [enum.native_only for enum in all_enums]
703 if native_enums:
704 header_types.add('native_enum')
705 if len(native_enums) != len(all_enums):
706 header_types.add('non_native_enum')
707
708 if any(struct.native_only for struct in self.module.structs):
709 header_types.add('native_struct')
710 for kind in self._GetDirectlyUsedKinds():
711 if hasattr(kind, 'is_nullable') and kind.is_nullable:
712 header_types.add('optional')
713 if mojom.IsStringKind(kind):
714 header_types.add('string')
715 elif mojom.IsArrayKind(kind):
716 header_types.add('array')
717 elif mojom.IsMapKind(kind):
718 header_types.add('map')
719 for header_type in header_types:
720 headers.update(header_type_to_headers.get(header_type, []))
721 return QuoteAndSortHeaders(headers)
722
723 def GetPublicHeaders(self):
724 return self._GetPublicHeadersImpl(
725 BLINK_HEADERS if self.for_blink else CHROMIUM_HEADERS)
726
727 def GetPublicSharedHeaders(self):
728 return self._GetPublicHeadersImpl(SHARED_HEADERS)
729
730 def _GetDirectlyUsedKinds(self):
731 for struct in self.module.structs + self.module.unions:
732 for field in struct.fields:
733 yield field.kind
734
735 for interface in self.module.interfaces:
736 for method in interface.methods:
737 for param in method.parameters + (method.response_parameters or []):
738 yield param.kind
595 739
596 def GetJinjaExports(self): 740 def GetJinjaExports(self):
597 structs = self.GetStructs() 741 structs = self.GetStructs()
598 interfaces = self.GetInterfaces() 742 interfaces = self.GetInterfaces()
599 all_enums = list(self.module.enums) 743 all_enums = list(self.module.enums)
600 for struct in structs: 744 for struct in structs:
601 all_enums.extend(struct.enums) 745 all_enums.extend(struct.enums)
602 for interface in interfaces: 746 for interface in interfaces:
603 all_enums.extend(interface.enums) 747 all_enums.extend(interface.enums)
604 748
605 return { 749 return {
606 "module": self.module, 750 "module": self.module,
607 "namespace": self.module.namespace, 751 "namespace": self.module.namespace,
608 "namespaces_as_array": NamespaceToArray(self.module.namespace), 752 "namespaces_as_array": generator.NamespaceToArray(self.module.namespace),
609 "imports": self.module.imports, 753 "imports": self.module.imports,
610 "kinds": self.module.kinds, 754 "kinds": self.module.kinds,
611 "enums": self.module.enums, 755 "enums": self.module.enums,
612 "all_enums": all_enums, 756 "all_enums": all_enums,
613 "structs": structs, 757 "structs": structs,
614 "unions": self.GetUnions(), 758 "unions": self.GetUnions(),
615 "interfaces": interfaces, 759 "interfaces": interfaces,
616 "variant": self.variant, 760 "variant": self.variant,
617 "extra_traits_headers": self.GetExtraTraitsHeaders(), 761 "extra_traits_headers": self.GetExtraTraitsHeaders(),
618 "extra_public_headers": self.GetExtraPublicHeaders(), 762 "public_headers": self.GetPublicHeaders(),
763 "public_shared_headers": self.GetPublicSharedHeaders(),
619 "for_blink": self.for_blink, 764 "for_blink": self.for_blink,
620 "use_once_callback": self.use_once_callback, 765 "use_once_callback": self.use_once_callback,
621 "export_attribute": self.export_attribute, 766 "export_attribute": self.export_attribute,
622 "export_header": self.export_header, 767 "export_header": self.export_header,
623 } 768 }
624 769
625 @staticmethod 770 @staticmethod
626 def GetTemplatePrefix(): 771 def GetTemplatePrefix():
627 return "cpp_templates" 772 return "cpp_templates"
628 773
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
667 global _use_once_callback 812 global _use_once_callback
668 _use_once_callback = self.use_once_callback 813 _use_once_callback = self.use_once_callback
669 global _variant 814 global _variant
670 _variant = self.variant 815 _variant = self.variant
671 suffix = "-%s" % self.variant if self.variant else "" 816 suffix = "-%s" % self.variant if self.variant else ""
672 self.Write(self.GenerateModuleHeader(), 817 self.Write(self.GenerateModuleHeader(),
673 self.MatchMojomFilePath("%s%s.h" % (self.module.name, suffix))) 818 self.MatchMojomFilePath("%s%s.h" % (self.module.name, suffix)))
674 self.Write( 819 self.Write(
675 self.GenerateModuleSource(), 820 self.GenerateModuleSource(),
676 self.MatchMojomFilePath("%s%s.cc" % (self.module.name, suffix))) 821 self.MatchMojomFilePath("%s%s.cc" % (self.module.name, suffix)))
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698