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
3 # found in the LICENSE file.
5 """Code shared by the various language-specific code generators."""
7 from functools import partial
10 import module as mojom
13 def GetStructFromMethod(method):
14 """Converts a method's parameters into the fields of a struct."""
15 params_class = "%s_%s_Params" % (method.interface.name, method.name)
16 struct = mojom.Struct(params_class, module=method.interface.module)
17 for param in method.parameters:
18 struct.AddField(param.name, param.kind, param.ordinal)
19 struct.packed = pack.PackedStruct(struct)
22 def GetResponseStructFromMethod(method):
23 """Converts a method's response_parameters into the fields of a struct."""
24 params_class = "%s_%s_ResponseParams" % (method.interface.name, method.name)
25 struct = mojom.Struct(params_class, module=method.interface.module)
26 for param in method.response_parameters:
27 struct.AddField(param.name, param.kind, param.ordinal)
28 struct.packed = pack.PackedStruct(struct)
31 def GetDataHeader(exported, struct):
32 struct.packed = pack.PackedStruct(struct)
33 struct.bytes = pack.GetByteLayout(struct.packed)
34 struct.exported = exported
37 def IsStringKind(kind):
38 return kind.spec == 's'
41 return isinstance(kind, mojom.Enum)
43 def IsObjectKind(kind):
44 return isinstance(kind, (mojom.Struct, mojom.Array)) or IsStringKind(kind)
46 def IsHandleKind(kind):
47 return kind.spec.startswith('h') or \
48 isinstance(kind, mojom.Interface) or \
49 isinstance(kind, mojom.InterfaceRequest)
51 def IsInterfaceKind(kind):
52 return isinstance(kind, mojom.Interface)
54 def IsInterfaceRequestKind(kind):
55 return isinstance(kind, mojom.InterfaceRequest)
57 def IsMoveOnlyKind(kind):
58 return IsObjectKind(kind) or IsHandleKind(kind)
60 def StudlyCapsToCamel(studly):
61 return studly[0].lower() + studly[1:]
63 class Generator(object):
64 # Pass |output_dir| to emit files to disk. Omit |output_dir| to echo all
66 def __init__(self, module, output_dir=None):
68 self.output_dir = output_dir
70 def GetStructsFromMethods(self):
72 for interface in self.module.interfaces:
73 for method in interface.methods:
74 result.append(GetStructFromMethod(method))
75 if method.response_parameters != None:
76 result.append(GetResponseStructFromMethod(method))
77 return map(partial(GetDataHeader, False), result)
80 return map(partial(GetDataHeader, True), self.module.structs)
82 def Write(self, contents, filename):
83 if self.output_dir is None:
86 with open(os.path.join(self.output_dir, filename), "w+") as f:
89 def GenerateFiles(self, args):
90 raise NotImplementedError("Subclasses must override/implement this method")