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
11 import module as mojom
14 def GetStructFromMethod(method):
15 """Converts a method's parameters into the fields of a struct."""
16 params_class = "%s_%s_Params" % (method.interface.name, method.name)
17 struct = mojom.Struct(params_class, module=method.interface.module)
18 for param in method.parameters:
19 struct.AddField(param.name, param.kind, param.ordinal)
20 struct.packed = pack.PackedStruct(struct)
23 def GetResponseStructFromMethod(method):
24 """Converts a method's response_parameters into the fields of a struct."""
25 params_class = "%s_%s_ResponseParams" % (method.interface.name, method.name)
26 struct = mojom.Struct(params_class, module=method.interface.module)
27 for param in method.response_parameters:
28 struct.AddField(param.name, param.kind, param.ordinal)
29 struct.packed = pack.PackedStruct(struct)
32 def GetDataHeader(exported, struct):
33 struct.packed = pack.PackedStruct(struct)
34 struct.bytes = pack.GetByteLayout(struct.packed)
35 struct.exported = exported
38 def ExpectedArraySize(kind):
39 if mojom.IsFixedArrayKind(kind):
43 def StudlyCapsToCamel(studly):
44 return studly[0].lower() + studly[1:]
46 def CamelCaseToAllCaps(camel_case):
48 word for word in re.split(r'([A-Z][^A-Z]+)', camel_case) if word).upper()
50 class Generator(object):
51 # Pass |output_dir| to emit files to disk. Omit |output_dir| to echo all
53 def __init__(self, module, output_dir=None):
55 self.output_dir = output_dir
57 def GetStructsFromMethods(self):
59 for interface in self.module.interfaces:
60 for method in interface.methods:
61 result.append(GetStructFromMethod(method))
62 if method.response_parameters != None:
63 result.append(GetResponseStructFromMethod(method))
64 return map(partial(GetDataHeader, False), result)
67 return map(partial(GetDataHeader, True), self.module.structs)
69 def Write(self, contents, filename):
70 if self.output_dir is None:
73 with open(os.path.join(self.output_dir, filename), "w+") as f:
76 def GenerateFiles(self, args):
77 raise NotImplementedError("Subclasses must override/implement this method")
79 def GetJinjaParameters(self):
80 """Returns default constructor parameters for the jinja environment."""
84 """Returns global mappings for the template generation."""