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.
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.
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
27 """Generates a Code object for features.
30 (c
.Append(cpp_util
.CHROMIUM_LICENSE
)
32 .Append(cpp_util
.GENERATED_FEATURE_MESSAGE
% self
._source
_file
)
34 .Append('#include <string>')
36 .Append('#include "%s.h"' % self
._source
_file
_filename
)
38 .Append('#include "base/logging.h"')
40 .Concat(cpp_util
.OpenNamespace(self
._namespace
))
44 # Generate the constructor.
45 (c
.Append('%s::%s() {' % (self
._class
_name
, self
._class
_name
))
48 for feature
in self
._feature
_defs
:
49 c
.Append('features_["%s"] = %s;'
50 % (feature
.name
, cpp_util
.ConstantName(feature
.name
)))
56 # Generate the ToString function.
57 (c
.Append('const char* %s::ToString('
58 '%s::ID id) const {' % (self
._class
_name
, self
._class
_name
))
60 .Append('switch (id) {')
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;')
70 .Append('NOTREACHED();')
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
))
84 .Append('std::map<std::string, %s::ID>::const_iterator it'
85 ' = features_.find(id);' % self
._class
_name
)
86 .Append('if (it == features_.end())')
87 .Append(' return kUnknown;')
88 .Append('return it->second;')
92 .Cblock(cpp_util
.CloseNamespace(self
._namespace
))