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

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

Issue 2855263002: Mojo bindings: support generating identifers using different style rules for different target langu…
Patch Set: . Created 3 years, 7 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 JavaScript source files from a mojom.Module.""" 5 """Generates JavaScript 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 import os 10 import os
(...skipping 24 matching lines...) Expand all
35 mojom.STRING: "null", 35 mojom.STRING: "null",
36 mojom.NULLABLE_STRING: "null" 36 mojom.NULLABLE_STRING: "null"
37 } 37 }
38 38
39 39
40 def JavaScriptType(kind): 40 def JavaScriptType(kind):
41 name = [] 41 name = []
42 if kind.imported_from: 42 if kind.imported_from:
43 name.append(kind.imported_from["unique_name"]) 43 name.append(kind.imported_from["unique_name"])
44 if kind.parent_kind: 44 if kind.parent_kind:
45 name.append(kind.parent_kind.name) 45 name.append(kind.parent_kind.stylized_name)
46 name.append(kind.name) 46 if not hasattr(kind, 'stylized_name'):
47 print kind
48 name.append(kind.stylized_name)
47 return ".".join(name) 49 return ".".join(name)
48 50
49 51
50 def JavaScriptDefaultValue(field): 52 def JavaScriptDefaultValue(field):
51 if field.default: 53 if field.default:
52 if mojom.IsStructKind(field.kind): 54 if mojom.IsStructKind(field.kind):
53 assert field.default == "default" 55 assert field.default == "default"
54 return "new %s()" % JavaScriptType(field.kind) 56 return "new %s()" % JavaScriptType(field.kind)
55 return ExpressionToText(field.default) 57 return ExpressionToText(field.default)
56 if field.kind in mojom.PRIMITIVES: 58 if field.kind in mojom.PRIMITIVES:
(...skipping 207 matching lines...) Expand 10 before | Expand all | Expand 10 after
264 266
265 267
266 def TranslateConstants(token): 268 def TranslateConstants(token):
267 if isinstance(token, (mojom.EnumValue, mojom.NamedValue)): 269 if isinstance(token, (mojom.EnumValue, mojom.NamedValue)):
268 # Both variable and enum constants are constructed like: 270 # Both variable and enum constants are constructed like:
269 # NamespaceUid.Struct[.Enum].CONSTANT_NAME 271 # NamespaceUid.Struct[.Enum].CONSTANT_NAME
270 name = [] 272 name = []
271 if token.imported_from: 273 if token.imported_from:
272 name.append(token.imported_from["unique_name"]) 274 name.append(token.imported_from["unique_name"])
273 if token.parent_kind: 275 if token.parent_kind:
274 name.append(token.parent_kind.name) 276 name.append(token.parent_kind.stylized_name)
275 if isinstance(token, mojom.EnumValue): 277 if isinstance(token, mojom.EnumValue):
276 name.append(token.enum.name) 278 name.append(token.enum.stylized_name)
277 name.append(token.name) 279 name.append(token.name)
278 return ".".join(name) 280 return ".".join(name)
279 281
280 if isinstance(token, mojom.BuiltinValue): 282 if isinstance(token, mojom.BuiltinValue):
281 if token.value == "double.INFINITY" or token.value == "float.INFINITY": 283 if token.value == "double.INFINITY" or token.value == "float.INFINITY":
282 return "Infinity"; 284 return "Infinity";
283 if token.value == "double.NEGATIVE_INFINITY" or \ 285 if token.value == "double.NEGATIVE_INFINITY" or \
284 token.value == "float.NEGATIVE_INFINITY": 286 token.value == "float.NEGATIVE_INFINITY":
285 return "-Infinity"; 287 return "-Infinity";
286 if token.value == "double.NAN" or token.value == "float.NAN": 288 if token.value == "double.NAN" or token.value == "float.NAN":
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
334 def IsAnyHandleOrInterfaceField(field): 336 def IsAnyHandleOrInterfaceField(field):
335 return mojom.IsAnyHandleOrInterfaceKind(field.kind) 337 return mojom.IsAnyHandleOrInterfaceKind(field.kind)
336 338
337 def IsEnumField(field): 339 def IsEnumField(field):
338 return mojom.IsEnumKind(field.kind) 340 return mojom.IsEnumKind(field.kind)
339 341
340 def GetRelativePath(module, base_module): 342 def GetRelativePath(module, base_module):
341 return os.path.relpath(module.path, os.path.dirname(base_module.path)) 343 return os.path.relpath(module.path, os.path.dirname(base_module.path))
342 344
343 345
346 class JsStylizer(generator.Stylizer):
347 def __init__(self, use_new_js_bindings):
348 self.use_new_js_bindings = use_new_js_bindings
349
350 def StylizeField(self, name):
351 if not self.use_new_js_bindings:
352 return name
353 return generator.ToCamel(name, lower_initial=True)
354
355 def StylizeParameter(self, name):
356 if not self.use_new_js_bindings:
357 return name
358 return generator.ToCamel(name, lower_initial=True)
359
360 def StylizeMethod(self, name):
361 return generator.ToCamel(name, lower_initial=True)
362
363 def StylizeModule(self, name):
364 if not self.use_new_js_bindings:
365 return name
366 return '.'.join(
367 generator.ToCamel(word, lower_initial=True) for word in name.split('.'))
368
369
344 class Generator(generator.Generator): 370 class Generator(generator.Generator):
345 371
346 js_filters = { 372 js_filters = {
347 "decode_snippet": JavaScriptDecodeSnippet, 373 "decode_snippet": JavaScriptDecodeSnippet,
348 "default_value": JavaScriptDefaultValue, 374 "default_value": JavaScriptDefaultValue,
349 "encode_snippet": JavaScriptEncodeSnippet, 375 "encode_snippet": JavaScriptEncodeSnippet,
350 "expression_to_text": ExpressionToText, 376 "expression_to_text": ExpressionToText,
351 "field_offset": JavaScriptFieldOffset, 377 "field_offset": JavaScriptFieldOffset,
378 "get_relative_path": GetRelativePath,
352 "has_callbacks": mojom.HasCallbacks, 379 "has_callbacks": mojom.HasCallbacks,
353 "is_any_handle_or_interface_field": IsAnyHandleOrInterfaceField, 380 "is_any_handle_or_interface_field": IsAnyHandleOrInterfaceField,
354 "is_array_pointer_field": IsArrayPointerField, 381 "is_array_pointer_field": IsArrayPointerField,
355 "is_associated_interface_field": IsAssociatedInterfaceField, 382 "is_associated_interface_field": IsAssociatedInterfaceField,
356 "is_associated_interface_request_field": IsAssociatedInterfaceRequestField, 383 "is_associated_interface_request_field": IsAssociatedInterfaceRequestField,
357 "is_bool_field": IsBoolField, 384 "is_bool_field": IsBoolField,
358 "is_enum_field": IsEnumField, 385 "is_enum_field": IsEnumField,
359 "is_handle_field": IsHandleField, 386 "is_handle_field": IsHandleField,
360 "is_interface_field": IsInterfaceField, 387 "is_interface_field": IsInterfaceField,
361 "is_interface_request_field": IsInterfaceRequestField, 388 "is_interface_request_field": IsInterfaceRequestField,
362 "is_map_pointer_field": IsMapPointerField, 389 "is_map_pointer_field": IsMapPointerField,
363 "is_object_field": IsObjectField, 390 "is_object_field": IsObjectField,
364 "is_string_pointer_field": IsStringPointerField, 391 "is_string_pointer_field": IsStringPointerField,
365 "is_struct_pointer_field": IsStructPointerField, 392 "is_struct_pointer_field": IsStructPointerField,
366 "is_union_field": IsUnionField, 393 "is_union_field": IsUnionField,
367 "js_type": JavaScriptType, 394 "js_type": JavaScriptType,
368 "method_passes_associated_kinds": mojom.MethodPassesAssociatedKinds, 395 "method_passes_associated_kinds": mojom.MethodPassesAssociatedKinds,
369 "payload_size": JavaScriptPayloadSize, 396 "payload_size": JavaScriptPayloadSize,
370 "get_relative_path": GetRelativePath, 397 "to_camel": generator.ToCamel,
371 "stylize_method": generator.StudlyCapsToCamel,
372 "union_decode_snippet": JavaScriptUnionDecodeSnippet, 398 "union_decode_snippet": JavaScriptUnionDecodeSnippet,
373 "union_encode_snippet": JavaScriptUnionEncodeSnippet, 399 "union_encode_snippet": JavaScriptUnionEncodeSnippet,
374 "validate_array_params": JavaScriptValidateArrayParams, 400 "validate_array_params": JavaScriptValidateArrayParams,
375 "validate_enum_params": JavaScriptValidateEnumParams, 401 "validate_enum_params": JavaScriptValidateEnumParams,
376 "validate_map_params": JavaScriptValidateMapParams, 402 "validate_map_params": JavaScriptValidateMapParams,
377 "validate_nullable_params": JavaScriptNullableParam, 403 "validate_nullable_params": JavaScriptNullableParam,
378 "validate_struct_params": JavaScriptValidateStructParams, 404 "validate_struct_params": JavaScriptValidateStructParams,
379 "validate_union_params": JavaScriptValidateUnionParams, 405 "validate_union_params": JavaScriptValidateUnionParams,
380 } 406 }
381 407
382 def GetParameters(self): 408 def GetParameters(self):
383 return { 409 return {
384 "namespace": self.module.namespace, 410 "enums": self.module.enums,
385 "imports": self.GetImports(), 411 "imports": self.module.imports,
412 "interfaces": self.module.interfaces,
386 "kinds": self.module.kinds, 413 "kinds": self.module.kinds,
387 "enums": self.module.enums,
388 "module": self.module, 414 "module": self.module,
389 "structs": self.GetStructs() + self.GetStructsFromMethods(), 415 "structs": self.module.structs + self.GetStructsFromMethods(),
390 "unions": self.GetUnions(), 416 "unions": self.module.unions,
391 "use_new_js_bindings": self.use_new_js_bindings, 417 "use_new_js_bindings": self.use_new_js_bindings,
392 "interfaces": self.GetInterfaces(),
393 "imported_interfaces": self.GetImportedInterfaces(),
394 } 418 }
395 419
396 @staticmethod 420 @staticmethod
397 def GetTemplatePrefix(): 421 def GetTemplatePrefix():
398 return "js_templates" 422 return "js_templates"
399 423
400 @classmethod 424 @classmethod
401 def GetFilters(cls): 425 def GetFilters(cls):
402 return cls.js_filters 426 return cls.js_filters
403 427
404 @UseJinja("module.amd.tmpl") 428 @UseJinja("module.amd.tmpl")
405 def GenerateAMDModule(self): 429 def GenerateAMDModule(self):
406 return self.GetParameters() 430 return self.GetParameters()
407 431
408 def GenerateFiles(self, args): 432 def GenerateFiles(self, args):
409 if self.variant: 433 if self.variant:
410 raise Exception("Variants not supported in JavaScript bindings.") 434 raise Exception("Variants not supported in JavaScript bindings.")
411 435
436 self.FinalizeModule(JsStylizer(self.use_new_js_bindings))
437
412 self.Write(self.GenerateAMDModule(), 438 self.Write(self.GenerateAMDModule(),
413 self.MatchMojomFilePath("%s.js" % self.module.name)) 439 self.MatchMojomFilePath("%s.js" % self.module.name))
414 440
415 def GetImports(self): 441 def FinalizeModule(self, stylizer=None):
442 super(Generator, self).FinalizeModule(stylizer)
443
416 used_names = set() 444 used_names = set()
417 for each_import in self.module.imports: 445 for each_import in self.module.imports:
418 simple_name = each_import["module_name"].split(".")[0] 446 simple_name = each_import["module_name"].split(".")[0]
419 447
420 # Since each import is assigned a variable in JS, they need to have unique 448 # Since each import is assigned a variable in JS, they need to have unique
421 # names. 449 # names.
422 unique_name = simple_name 450 unique_name = simple_name
423 counter = 0 451 counter = 0
424 while unique_name in used_names: 452 while unique_name in used_names:
425 counter += 1 453 counter += 1
426 unique_name = simple_name + str(counter) 454 unique_name = simple_name + str(counter)
427 455
428 used_names.add(unique_name) 456 used_names.add(unique_name)
429 each_import["unique_name"] = unique_name + "$" 457 each_import["unique_name"] = unique_name + "$"
430 counter += 1 458 counter += 1
431 return self.module.imports
432
433 def GetImportedInterfaces(self):
434 interface_to_import = {};
435 for each_import in self.module.imports:
436 for each_interface in each_import["module"].interfaces:
437 name = each_interface.name
438 interface_to_import[name] = each_import["unique_name"] + "." + name
439 return interface_to_import;
440
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698