Migrate SiteSettingsPreferencesTest from ChromeShell to ChromePublic.
[chromium-blink-merge.git] / tools / json_schema_compiler / features_cc_generator.py
blob4af9aa71eff780d9f4ccf7dfefae7fdc9941f550
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 import os.path
7 from code import Code
8 import cpp_util
11 class CCGenerator(object):
12 def Generate(self, feature_defs, source_file, namespace):
13 return _Generator(feature_defs, source_file, namespace).Generate()
16 class _Generator(object):
17 """A .cc generator for features.
18 """
19 def __init__(self, feature_defs, source_file, namespace):
20 self._feature_defs = feature_defs
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
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 .Append('#include <string>')
35 .Append()
36 .Append('#include "%s.h"' % self._source_file_filename)
37 .Append()
38 .Append('#include "base/logging.h"')
39 .Append()
40 .Concat(cpp_util.OpenNamespace(self._namespace))
41 .Append()
44 # Generate the constructor.
45 (c.Append('%s::%s() {' % (self._class_name, self._class_name))
46 .Sblock()
48 for feature in self._feature_defs:
49 c.Append('features_["%s"] = %s;'
50 % (feature.name, cpp_util.ConstantName(feature.name)))
51 (c.Eblock()
52 .Append('}')
53 .Append()
56 # Generate the ToString function.
57 (c.Append('const char* %s::ToString('
58 '%s::ID id) const {' % (self._class_name, self._class_name))
59 .Sblock()
60 .Append('switch (id) {')
61 .Sblock()
63 for feature in self._feature_defs:
64 c.Append('case %s: return "%s";' %
65 (cpp_util.ConstantName(feature.name), feature.name))
66 (c.Append('case kUnknown: break;')
67 .Append('case kEnumBoundary: break;')
68 .Eblock()
69 .Append('}')
70 .Append('NOTREACHED();')
71 .Append('return "";')
73 (c.Eblock()
74 .Append('}')
75 .Append()
78 # Generate the FromString function.
80 (c.Append('%s::ID %s::FromString('
81 'const std::string& id) const {'
82 % (self._class_name, self._class_name))
83 .Sblock()
84 .Append('const auto& it = features_.find(id);' % self._class_name)
85 .Append('return (it == features_.end()) ? kUnknown : it->second;')
86 .Eblock()
87 .Append('}')
88 .Append()
89 .Cblock(cpp_util.CloseNamespace(self._namespace))
92 return c