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.
4
5import os.path
6
7from code import Code
8import cpp_util
9
10
11class HGenerator(object):
12  def Generate(self, features, source_file, namespace):
13    return _Generator(features, source_file, namespace).Generate()
14
15
16class _Generator(object):
17  """A .cc generator for features.
18  """
19  def __init__(self, features, source_file, namespace):
20    self._feature_defs = features
21    self._source_file = source_file
22    self._source_file_filename, _ = os.path.splitext(source_file)
23    self._class_name = cpp_util.ClassName(self._source_file_filename)
24    self._namespace = namespace
25
26  def Generate(self):
27    """Generates a Code object for features.
28    """
29    c = Code()
30    (c.Append(cpp_util.CHROMIUM_LICENSE)
31      .Append()
32      .Append(cpp_util.GENERATED_FEATURE_MESSAGE % self._source_file)
33      .Append()
34    )
35
36    # Hack: for the purpose of gyp the header file will always be the source
37    # file with its file extension replaced by '.h'. Assume so.
38    output_file = os.path.splitext(self._namespace.source_file)[0] + '.h'
39    ifndef_name = cpp_util.GenerateIfndefName(output_file)
40
41    (c.Append('#ifndef %s' % ifndef_name)
42      .Append('#define %s' % ifndef_name)
43      .Append()
44    )
45
46    (c.Append('#include <map>')
47      .Append('#include <string>')
48      .Append()
49      .Concat(cpp_util.OpenNamespace(self._namespace))
50      .Append()
51    )
52
53    (c.Append('class %s {' % self._class_name)
54      .Append(' public:')
55      .Sblock()
56      .Concat(self._GeneratePublicBody())
57      .Eblock()
58      .Append(' private:')
59      .Sblock()
60      .Concat(self._GeneratePrivateBody())
61      .Eblock('};')
62      .Append()
63      .Cblock(cpp_util.CloseNamespace(self._namespace))
64    )
65    (c.Append('#endif  // %s' % ifndef_name)
66      .Append()
67    )
68    return c
69
70  def _GeneratePublicBody(self):
71    c = Code()
72
73    (c.Append('%s();' % self._class_name)
74      .Append()
75      .Append('enum ID {')
76      .Concat(self._GenerateEnumConstants())
77      .Eblock('};')
78      .Append()
79      .Append('const char* ToString(ID id) const;')
80      .Append('ID FromString(const std::string& id) const;')
81      .Append()
82    )
83    return c
84
85  def _GeneratePrivateBody(self):
86    return Code().Append('std::map<std::string, '
87                         '%s::ID> features_;' % self._class_name)
88
89  def _GenerateEnumConstants(self):
90    c = Code()
91
92    (c.Sblock()
93      .Append('kUnknown,')
94    )
95    for feature in self._feature_defs:
96      c.Append('%s,' % cpp_util.ConstantName(feature.name))
97    c.Append('kEnumBoundary')
98
99    return c
100