示例#1
0
 def testNamespaceDeclaration(self):
   self.assertEquals('namespace extensions {',
                     cpp_util.OpenNamespace('extensions').Render())
   self.assertEquals('}  // namespace extensions',
                     cpp_util.CloseNamespace('extensions').Render())
   self.assertEquals('namespace extensions {\n'
                     'namespace gen {\n'
                     'namespace api {',
                     cpp_util.OpenNamespace('extensions::gen::api').Render())
   self.assertEquals('}  // namespace api\n'
                     '}  // namespace gen\n'
                     '}  // namespace extensions',
                     cpp_util.CloseNamespace('extensions::gen::api').Render())
示例#2
0
 def Generate(self, namespace):
     c = code.Code()
     c.Append(cpp_util.CHROMIUM_LICENSE)
     c.Append()
     c.Append('#include "%s"' %
              (os.path.join(SOURCE_BASE_PATH, 'generated_schemas.h')))
     c.Append()
     c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
     c.Append()
     c.Append('// static')
     c.Sblock('void GeneratedSchemas::Get('
              'std::map<std::string, base::StringPiece>* schemas) {')
     for api in self._bundle._api_defs:
         namespace = self._bundle._model.namespaces[api.get('namespace')]
         # JSON parsing code expects lists of schemas, so dump a singleton list.
         json_content = json.dumps([_RemoveDescriptions(api)],
                                   separators=(',', ':'))
         # Escape all double-quotes and backslashes. For this to output a valid
         # JSON C string, we need to escape \ and ".
         json_content = json_content.replace('\\',
                                             '\\\\').replace('"', '\\"')
         c.Append('(*schemas)["%s"] = "%s";' %
                  (namespace.name, json_content))
     c.Eblock('}')
     c.Append()
     c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
     c.Append()
     return c
示例#3
0
    def Generate(self):
        """Generates a Code object for features.
    """
        c = Code()
        (c.Append(cpp_util.CHROMIUM_LICENSE).Append().Append(
            cpp_util.GENERATED_FEATURE_MESSAGE % self._source_file).Append())

        # Hack: for the purpose of gyp the header file will always be the source
        # file with its file extension replaced by '.h'. Assume so.
        output_file = os.path.splitext(self._namespace.source_file)[0] + '.h'
        ifndef_name = cpp_util.GenerateIfndefName(output_file)

        (c.Append('#ifndef %s' % ifndef_name).Append('#define %s' %
                                                     ifndef_name).Append())

        (c.Append('#include <map>').Append(
            '#include <string>').Append().Concat(
                cpp_util.OpenNamespace(self._namespace)).Append())

        (c.Append('class %s {' %
                  self._class_name).Append(' public:').Sblock().Concat(
                      self._GeneratePublicBody()).Eblock().Append(' private:').
         Sblock().Concat(
             self._GeneratePrivateBody()).Eblock('};').Append().Cblock(
                 cpp_util.CloseNamespace(self._namespace)))
        (c.Append('#endif  // %s' % ifndef_name).Append())
        return c
示例#4
0
 def Generate(self, _):  # namespace not relevant, this is a bundle
   c = code.Code()
   c.Append(cpp_util.CHROMIUM_LICENSE)
   c.Append()
   c.Append('#include "%s"' % (os.path.join(self._bundle._source_file_dir,
                                            'generated_schemas.h')))
   c.Append()
   c.Append('#include "base/lazy_instance.h"')
   c.Append()
   c.Append('namespace {')
   for api in self._bundle._api_defs:
     namespace = self._bundle._model.namespaces[api.get('namespace')]
     json_content = json.dumps(_PrefixSchemaWithNamespace(
                                    _RemoveUnneededFields(api)),
                               separators=(',', ':'))
     # Escape all double-quotes and backslashes. For this to output a valid
     # JSON C string, we need to escape \ and ". Note that some schemas are
     # too large to compile on windows. Split the JSON up into several
     # strings, since apparently that helps.
     max_length = 8192
     segments = [json_content[i:i + max_length].replace('\\', '\\\\')
                                               .replace('"', '\\"')
                 for i in xrange(0, len(json_content), max_length)]
     c.Append('const char %s[] = "%s";' %
         (_FormatNameAsConstant(namespace.name), '" "'.join(segments)))
   c.Append()
   c.Sblock('struct Static {')
   c.Sblock('Static() {')
   for api in self._bundle._api_defs:
     namespace = self._bundle._model.namespaces[api.get('namespace')]
     c.Append('schemas["%s"] = %s;' % (namespace.name,
                                       _FormatNameAsConstant(namespace.name)))
   c.Eblock('}')
   c.Append()
   c.Append('std::map<std::string, const char*> schemas;')
   c.Eblock('};')
   c.Append()
   c.Append('base::LazyInstance<Static> g_lazy_instance;')
   c.Append()
   c.Append('}  // namespace')
   c.Append()
   c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
   c.Append()
   c.Append('// static')
   c.Sblock('base::StringPiece %s::Get(const std::string& name) {' %
            self._bundle._GenerateBundleClass('GeneratedSchemas'))
   c.Append('return IsGenerated(name) ? '
            'g_lazy_instance.Get().schemas[name] : "";')
   c.Eblock('}')
   c.Append()
   c.Append('// static')
   c.Sblock('bool %s::IsGenerated(std::string name) {' %
            self._bundle._GenerateBundleClass('GeneratedSchemas'))
   c.Append('return g_lazy_instance.Get().schemas.count(name) > 0;')
   c.Eblock('}')
   c.Append()
   c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
   c.Append()
   return c
 def Generate(self, _):  # namespace not relevant, this is a bundle
   c = code.Code()
   c.Append(cpp_util.CHROMIUM_LICENSE)
   c.Append()
   c.Append('#include "%s"' % (os.path.join(self._bundle._source_file_dir,
                                            'generated_schemas.h')))
   c.Append()
   c.Append('namespace {')
   for api in self._bundle._api_defs:
     namespace = self._bundle._model.namespaces[api.get('namespace')]
     json_content = json.dumps(_PrefixSchemaWithNamespace(
                                    _RemoveUnneededFields(api)),
                               separators=(',', ':'))
     # Escape all double-quotes and backslashes. For this to output a valid
     # JSON C string, we need to escape \ and ". Note that some schemas are
     # too large to compile on windows. Split the JSON up into several
     # strings, since apparently that helps.
     max_length = 8192
     segments = [json_content[i:i + max_length].replace('\\', '\\\\')
                                               .replace('"', '\\"')
                 for i in xrange(0, len(json_content), max_length)]
     c.Append('const char %s[] = "%s";' %
         (_FormatNameAsConstant(namespace.name), '" "'.join(segments)))
   c.Append('}  // namespace')
   c.Append()
   c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
   c.Append()
   c.Append('// static')
   c.Sblock('bool %s::IsGenerated(base::StringPiece name) {' %
            self._bundle._GenerateBundleClass('GeneratedSchemas'))
   c.Append('return !Get(name).empty();')
   c.Eblock('}')
   c.Append()
   c.Append('// static')
   c.Sblock('base::StringPiece %s::Get(base::StringPiece name) {' %
            self._bundle._GenerateBundleClass('GeneratedSchemas'))
   c.Append('static const struct {')
   c.Append('  base::StringPiece name;')
   c.Append('  base::StringPiece schema;')
   c.Sblock('} kSchemas[] = {')
   namespaces = [self._bundle._model.namespaces[api.get('namespace')].name
                 for api in self._bundle._api_defs]
   for namespace in sorted(namespaces):
     schema_constant_name = _FormatNameAsConstant(namespace)
     c.Append('{{"%s", %d}, {%s, sizeof(%s) - 1}},' %
              (namespace, len(namespace),
               schema_constant_name, schema_constant_name))
   c.Eblock('};')
   c.Sblock('for (const auto& schema : kSchemas) {')
   c.Sblock('if (schema.name == name)')
   c.Append('return schema.schema;')
   c.Eblock()
   c.Eblock('}')
   c.Append('return base::StringPiece();')
   c.Eblock('}')
   c.Append()
   c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
   c.Append()
   return c
示例#6
0
    def Generate(self):
        """Generates a Code object with the .h for a single namespace.
    """
        c = Code()
        (c.Append(cpp_util.CHROMIUM_LICENSE).Append().Append(
            cpp_util.GENERATED_FILE_MESSAGE %
            self._namespace.source_file).Append())

        # Hack: for the purpose of gyp the header file will always be the source
        # file with its file extension replaced by '.h'. Assume so.
        output_file = os.path.splitext(self._namespace.source_file)[0] + '.h'
        ifndef_name = cpp_util.GenerateIfndefName(output_file)

        (c.Append('#ifndef %s' % ifndef_name).Append(
            '#define %s' %
            ifndef_name).Append().Append('#include <map>').Append(
                '#include <string>').Append('#include <vector>').Append().
         Append('#include "base/basictypes.h"').Append(
             '#include "base/logging.h"').Append(
                 '#include "base/memory/linked_ptr.h"').Append(
                     '#include "base/memory/scoped_ptr.h"').Append(
                         '#include "base/values.h"').Cblock(
                             self._type_helper.GenerateIncludes()).Append())

        # TODO(calamity): These forward declarations should be #includes to allow
        # $ref types from other files to be used as required params. This requires
        # some detangling of windows and tabs which will currently lead to circular
        # #includes.
        c.Cblock(self._type_helper.GenerateForwardDeclarations())

        cpp_namespace = cpp_util.GetCppNamespace(
            self._namespace.environment.namespace_pattern,
            self._namespace.unix_name)
        c.Concat(cpp_util.OpenNamespace(cpp_namespace))
        c.Append()
        if self._namespace.properties:
            (c.Append('//').Append('// Properties').Append('//').Append())
            for prop in self._namespace.properties.values():
                property_code = self._type_helper.GeneratePropertyValues(
                    prop, 'extern const %(type)s %(name)s;')
                if property_code:
                    c.Cblock(property_code)
        if self._namespace.types:
            (c.Append('//').Append('// Types').Append('//').Append().Cblock(
                self._GenerateTypes(self._FieldDependencyOrder(),
                                    is_toplevel=True,
                                    generate_typedefs=True)))
        if self._namespace.functions:
            (c.Append('//').Append('// Functions').Append('//').Append())
            for function in self._namespace.functions.values():
                c.Cblock(self._GenerateFunction(function))
        if self._namespace.events:
            (c.Append('//').Append('// Events').Append('//').Append())
            for event in self._namespace.events.values():
                c.Cblock(self._GenerateEvent(event))
        (c.Concat(cpp_util.CloseNamespace(cpp_namespace)).Append(
            '#endif  // %s' % ifndef_name).Append())
        return c
示例#7
0
 def Generate(self):
   """Generates a Code object with the .cc for a single namespace.
   """
   c = Code()
   (c.Append(cpp_util.CHROMIUM_LICENSE)
     .Append()
     .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)
     .Append()
     .Append(self._util_cc_helper.GetIncludePath())
     .Append('#include "base/logging.h"')
     .Append('#include "base/strings/string_number_conversions.h"')
     .Append('#include "%s/%s.h"' %
         (self._namespace.source_file_dir, self._namespace.unix_name))
     .Cblock(self._type_helper.GenerateIncludes(include_soft=True))
     .Append()
     .Concat(cpp_util.OpenNamespace(self._cpp_namespace))
     .Cblock(self._type_helper.GetNamespaceStart())
   )
   if self._namespace.properties:
     (c.Append('//')
       .Append('// Properties')
       .Append('//')
       .Append()
     )
     for property in self._namespace.properties.values():
       property_code = self._type_helper.GeneratePropertyValues(
           property,
           'const %(type)s %(name)s = %(value)s;',
           nodoc=True)
       if property_code:
         c.Cblock(property_code)
   if self._namespace.types:
     (c.Append('//')
       .Append('// Types')
       .Append('//')
       .Append()
       .Cblock(self._GenerateTypes(None, self._namespace.types.values()))
     )
   if self._namespace.functions:
     (c.Append('//')
       .Append('// Functions')
       .Append('//')
       .Append()
     )
   for function in self._namespace.functions.values():
     c.Cblock(self._GenerateFunction(function))
   if self._namespace.events:
     (c.Append('//')
       .Append('// Events')
       .Append('//')
       .Append()
     )
     for event in self._namespace.events.values():
       c.Cblock(self._GenerateEvent(event))
   (c.Concat(self._type_helper.GetNamespaceEnd())
     .Cblock(cpp_util.CloseNamespace(self._cpp_namespace))
   )
   return c
示例#8
0
    def Generate(self):
        """Generates a Code object with the .h for a single namespace.
    """
        c = Code()
        (c.Append(cpp_util.CHROMIUM_LICENSE).Append().Append(
            cpp_util.GENERATED_FILE_MESSAGE %
            self._namespace.source_file).Append())

        ifndef_name = cpp_util.GenerateIfndefName(
            self._namespace.source_file_dir, self._target_namespace)
        (c.Append('#ifndef %s' % ifndef_name).Append(
            '#define %s' %
            ifndef_name).Append().Append('#include <map>').Append(
                '#include <string>').Append('#include <vector>').Append().
         Append('#include "base/basictypes.h"').Append(
             '#include "base/logging.h"').Append(
                 '#include "base/memory/linked_ptr.h"').Append(
                     '#include "base/memory/scoped_ptr.h"').Append(
                         '#include "base/values.h"').Cblock(
                             self._type_helper.GenerateIncludes()).Append())

        c.Concat(cpp_util.OpenNamespace(self._cpp_namespace))
        # TODO(calamity): These forward declarations should be #includes to allow
        # $ref types from other files to be used as required params. This requires
        # some detangling of windows and tabs which will currently lead to circular
        # #includes.
        forward_declarations = (
            self._type_helper.GenerateForwardDeclarations())
        if not forward_declarations.IsEmpty():
            (c.Append().Cblock(forward_declarations))

        c.Concat(self._type_helper.GetNamespaceStart())
        c.Append()
        if self._namespace.properties:
            (c.Append('//').Append('// Properties').Append('//').Append())
            for property in self._namespace.properties.values():
                property_code = self._type_helper.GeneratePropertyValues(
                    property, 'extern const %(type)s %(name)s;')
                if property_code:
                    c.Cblock(property_code)
        if self._namespace.types:
            (c.Append('//').Append('// Types').Append('//').Append().Cblock(
                self._GenerateTypes(self._FieldDependencyOrder(),
                                    is_toplevel=True,
                                    generate_typedefs=True)))
        if self._namespace.functions:
            (c.Append('//').Append('// Functions').Append('//').Append())
            for function in self._namespace.functions.values():
                c.Cblock(self._GenerateFunction(function))
        if self._namespace.events:
            (c.Append('//').Append('// Events').Append('//').Append())
            for event in self._namespace.events.values():
                c.Cblock(self._GenerateEvent(event))
        (c.Concat(self._type_helper.GetNamespaceEnd()).Concat(
            cpp_util.CloseNamespace(self._cpp_namespace)).Append(
                '#endif  // %s' % ifndef_name).Append())
        return c
 def Generate(self, namespace):
     c = code.Code()
     c.Append(cpp_util.CHROMIUM_LICENSE)
     c.Append()
     c.Append('#include "%s"' %
              (os.path.join(SOURCE_BASE_PATH, 'generated_schemas.h')))
     c.Append()
     c.Append('#include "base/lazy_instance.h"')
     c.Append()
     c.Append('namespace {')
     for api in self._bundle._api_defs:
         namespace = self._bundle._model.namespaces[api.get('namespace')]
         # JSON parsing code expects lists of schemas, so dump a singleton list.
         json_content = json.dumps([_RemoveDescriptions(api)],
                                   separators=(',', ':'))
         # Escape all double-quotes and backslashes. For this to output a valid
         # JSON C string, we need to escape \ and ".
         json_content = json_content.replace('\\',
                                             '\\\\').replace('"', '\\"')
         c.Append('const char %s[] = "%s";' %
                  (_FormatNameAsConstant(namespace.name), json_content))
     c.Append('}')
     c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
     c.Append()
     c.Sblock('struct Static {')
     c.Sblock('Static() {')
     for api in self._bundle._api_defs:
         namespace = self._bundle._model.namespaces[api.get('namespace')]
         c.Append('schemas["%s"] = %s;' %
                  (namespace.name, _FormatNameAsConstant(namespace.name)))
     c.Eblock('}')
     c.Append()
     c.Append('std::map<std::string, const char*> schemas;')
     c.Eblock('};')
     c.Append()
     c.Append('base::LazyInstance<Static> g_lazy_instance;')
     c.Append()
     c.Append('// static')
     c.Sblock('base::StringPiece GeneratedSchemas::Get('
              'const std::string& name) {')
     c.Append('return IsGenerated(name) ? '
              'g_lazy_instance.Get().schemas[name] : "";')
     c.Eblock('}')
     c.Append()
     c.Append('// static')
     c.Sblock('bool GeneratedSchemas::IsGenerated(std::string name) {')
     c.Append('return g_lazy_instance.Get().schemas.count(name) > 0;')
     c.Eblock('}')
     c.Append()
     c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
     c.Append()
     return c
示例#10
0
    def Generate(self, namespace):
        c = code.Code()
        c.Append(cpp_util.CHROMIUM_LICENSE)
        c.Append()
        c.Append('#include "%s"' %
                 (os.path.join(SOURCE_BASE_PATH, 'generated_api.h')))
        c.Append()
        for namespace in self._bundle._model.namespaces.values():
            namespace_name = namespace.unix_name.replace("experimental_", "")
            implementation_header = namespace.compiler_options.get(
                "implemented_in")
            # A hack to use our own Opera paths if they are hardcoded in .json API
            # definition files with the "implemented_in" declaration.
            if (implementation_header):
                implementation_header = implementation_header.replace(
                    DEFAULT_EXTENSIONS_INCLUDE_PATH,
                    self._extensions_include_path)
            else:
                implementation_header = "%s/api/%s/%s_api.h" % (
                    self._extensions_include_path, namespace_name,
                    namespace_name)
            if not os.path.exists(
                    os.path.join(self._bundle._root,
                                 os.path.normpath(implementation_header))):
                if "implemented_in" in namespace.compiler_options:
                    raise ValueError(
                        'Header file for namespace "%s" specified in '
                        'compiler_options not found: %s' %
                        (namespace.unix_name, implementation_header))
                continue
            ifdefs = self._bundle._GetPlatformIfdefs(namespace)
            if ifdefs is not None:
                c.Append("#if %s" % ifdefs, indent_level=0)

            c.Append('#include "%s"' % implementation_header)

            if ifdefs is not None:
                c.Append("#endif  // %s" % ifdefs, indent_level=0)
        c.Append()
        c.Append('#include '
                 '"%s/extension_function_registry.h"' %
                 self._extensions_include_path)
        c.Append()
        c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
        c.Append()
        c.Concat(self._bundle._GenerateFunctionRegistryRegisterAll())
        c.Append()
        c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
        c.Append()
        return c
示例#11
0
    def Generate(self):
        """Generates a Code object for features.
    """
        c = Code()
        (c.Append(cpp_util.CHROMIUM_LICENSE).Append().Append(
            cpp_util.GENERATED_FEATURE_MESSAGE % self._source_file).Append().
         Append('#include <string>').Append().Append(
             '#include "%s.h"' % self._source_file_filename).Append().Append(
                 '#include "base/notreached.h"').Append().Concat(
                     cpp_util.OpenNamespace(self._namespace)).Append())

        # Generate the constructor.
        (c.Append('%s::%s() {' %
                  (self._class_name, self._class_name)).Sblock())
        for feature in self._feature_defs:
            c.Append('features_["%s"] = %s;' %
                     (feature.name,
                      cpp_util.FeatureNameToConstantName(feature.name)))
        (c.Eblock().Append('}').Append())

        # Generate the ToString function.
        (c.Append(
            'const char* %s::ToString('
            '%s::ID id) const {' %
            (self._class_name,
             self._class_name)).Sblock().Append('switch (id) {').Sblock())
        for feature in self._feature_defs:
            c.Append('case %s: return "%s";' %
                     (cpp_util.FeatureNameToConstantName(
                         feature.name), feature.name))
        (c.Append('case kUnknown: break;').Append('case kEnumBoundary: break;')
         .Eblock().Append('}').Append('NOTREACHED();').Append('return "";'))
        (c.Eblock().Append('}').Append())

        # Generate the FromString function.

        (c.Append(
            '%s::ID %s::FromString('
            'const std::string& id) const {' %
            (self._class_name, self._class_name)).Sblock().Append(
                'const auto& it = features_.find(id);' %
                self._class_name).Append(
                    'return (it == features_.end()) ? kUnknown : it->second;').
         Eblock().Append('}').Append().Cblock(
             cpp_util.CloseNamespace(self._namespace)))

        return c
    def Generate(self, _):  # namespace not relevant, this is a bundle
        c = code.Code()
        c.Append(cpp_util.CHROMIUM_LICENSE)
        c.Append()
        c.Append('#include "%s"' % (cpp_util.ToPosixPath(
            os.path.join(self._bundle._impl_dir,
                         'generated_api_registration.h'))))
        c.Append()
        c.Append('#include "build/build_config.h"')
        c.Append('#include "build/chromeos_buildflags.h"')
        c.Append()
        for namespace in self._bundle._model.namespaces.values():
            namespace_name = namespace.unix_name.replace("experimental_", "")
            implementation_header = namespace.compiler_options.get(
                "implemented_in", "%s/%s/%s_api.h" %
                (self._bundle._impl_dir, namespace_name, namespace_name))
            if not os.path.exists(
                    os.path.join(self._bundle._root,
                                 os.path.normpath(implementation_header))):
                if "implemented_in" in namespace.compiler_options:
                    raise ValueError(
                        'Header file for namespace "%s" specified in '
                        'compiler_options not found: %s' %
                        (namespace.unix_name, implementation_header))
                continue
            ifdefs = self._bundle._GetPlatformIfdefs(namespace)
            if ifdefs is not None:
                c.Append("#if %s" % ifdefs, indent_level=0)

            c.Append('#include "%s"' %
                     cpp_util.ToPosixPath(implementation_header))

            if ifdefs is not None:
                c.Append("#endif  // %s" % ifdefs, indent_level=0)
        c.Append()
        c.Append('#include '
                 '"extensions/browser/extension_function_registry.h"')
        c.Append()
        c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
        c.Append()
        c.Concat(self._bundle._GenerateFunctionRegistryRegisterAll())
        c.Append()
        c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
        c.Append()
        return c
示例#13
0
 def Generate(self, namespace):
     c = code.Code()
     c.Append('#include <map>')
     c.Append('#include <string>')
     c.Append()
     c.Append('#include "base/string_piece.h"')
     c.Append()
     c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
     c.Append()
     c.Append('class GeneratedSchemas {')
     c.Sblock(' public:')
     c.Append('// Puts all API schemas in |schemas|.')
     c.Append('static void Get('
              'std::map<std::string, base::StringPiece>* schemas);')
     c.Eblock('};')
     c.Append()
     c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
     return self._bundle._GenerateHeader('generated_schemas', c)
 def Generate(self, _):  # namespace not relevant, this is a bundle
     c = code.Code()
     c.Append('#include "base/strings/string_piece.h"')
     c.Append()
     c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
     c.Append()
     c.Append('class %s {' %
              self._bundle._GenerateBundleClass('GeneratedSchemas'))
     c.Sblock(' public:')
     c.Append('// Determines if schema named |name| is generated.')
     c.Append('static bool IsGenerated(base::StringPiece name);')
     c.Append()
     c.Append('// Gets the API schema named |name|.')
     c.Append('static base::StringPiece Get(base::StringPiece name);')
     c.Eblock('};')
     c.Append()
     c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
     return self._bundle._GenerateHeader('generated_schemas', c)
示例#15
0
  def Generate(self, _):  # namespace not relevant, this is a bundle
    c = code.Code()

    c.Append('#include <string>')
    c.Append()
    c.Append("class ExtensionFunctionRegistry;")
    c.Append()
    c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
    c.Append()
    c.Append('class %s {' %
             self._bundle._GenerateBundleClass('GeneratedFunctionRegistry'))
    c.Sblock(' public:')
    c.Append('static void RegisterAll('
                 'ExtensionFunctionRegistry* registry);')
    c.Eblock('};')
    c.Append()
    c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
    return self._bundle._GenerateHeader('generated_api', c)
    def Generate(self, namespace):
        c = code.Code()

        c.Append('#include <string>')
        c.Append()
        c.Append('#include "base/basictypes.h"')
        c.Append()
        c.Append("class ExtensionFunctionRegistry;")
        c.Append()
        c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
        c.Append()
        c.Append('class GeneratedFunctionRegistry {')
        c.Sblock(' public:')
        c.Append('static void RegisterAll('
                 'ExtensionFunctionRegistry* registry);')
        c.Eblock('};')
        c.Append()
        c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
        return self._bundle._GenerateHeader('generated_api', c)
 def Generate(self, namespace):
     c = code.Code()
     c.Append('#include <map>')
     c.Append('#include <string>')
     c.Append()
     c.Append('#include "base/strings/string_piece.h"')
     c.Append()
     c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
     c.Append()
     c.Append('class GeneratedSchemas {')
     c.Sblock(' public:')
     c.Append('// Determines if schema named |name| is generated.')
     c.Append('static bool IsGenerated(std::string name);')
     c.Append()
     c.Append('// Gets the API schema named |name|.')
     c.Append('static base::StringPiece Get(const std::string& name);')
     c.Eblock('};')
     c.Append()
     c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
     return self._bundle._GenerateHeader('generated_schemas', c)
示例#18
0
    def GenerateForwardDeclarations(self):
        """Returns the forward declarations for self._default_namespace.
    """
        c = Code()
        for namespace, deps in self._NamespaceTypeDependencies().iteritems():
            filtered_deps = [
                dep for dep in deps
                # Add more ways to forward declare things as necessary.
                if (not dep.hard and dep.type_.property_type in (
                    PropertyType.CHOICES, PropertyType.OBJECT))
            ]
            if not filtered_deps:
                continue

            cpp_namespace = cpp_util.GetCppNamespace(
                namespace.environment.namespace_pattern, namespace.unix_name)
            c.Concat(cpp_util.OpenNamespace(cpp_namespace))
            for dep in filtered_deps:
                c.Append('struct %s;' % dep.type_.name)
            c.Concat(cpp_util.CloseNamespace(cpp_namespace))
        return c
    def Generate(self):
        """Generates a Code object for features.
    """
        c = Code()
        (c.Append(cpp_util.CHROMIUM_LICENSE).Append().Append(
            cpp_util.GENERATED_FEATURE_MESSAGE % self._source_file).Append())
        ifndef_name = cpp_util.GenerateIfndefName(self._source_file_filename,
                                                  self._class_name)
        (c.Append('#ifndef %s' % ifndef_name).Append('#define %s' %
                                                     ifndef_name).Append())

        (c.Append('#include <map>').Append(
            '#include <string>').Append().Concat(
                cpp_util.OpenNamespace(self._namespace)).Append())

        (c.Append('class %s {' %
                  self._class_name).Append(' public:').Sblock().Concat(
                      self._GeneratePublicBody()).Eblock().Append(' private:').
         Sblock().Concat(
             self._GeneratePrivateBody()).Eblock('};').Append().Cblock(
                 cpp_util.CloseNamespace(self._namespace)))
        (c.Append('#endif  // %s' % ifndef_name).Append())
        return c
    def Generate(self, _):  # namespace not relevant, this is a bundle
        c = code.Code()
        c.Append(cpp_util.CHROMIUM_LICENSE)
        c.Append()
        c.Append('#include "%s"' % (os.path.join(self._bundle._source_file_dir,
                                                 'generated_schemas.h')))
        c.Append()
        c.Append('#include <algorithm>')
        c.Append('#include <iterator>')
        c.Append()
        c.Append('#include "base/ranges/algorithm.h"')
        c.Append()
        c.Append('namespace {')
        for api in self._bundle._api_defs:
            namespace = self._bundle._model.namespaces[api.get('namespace')]
            json_content = json.dumps(_PrefixSchemaWithNamespace(
                _RemoveUnneededFields(api)),
                                      separators=(',', ':'))
            # This will output a valid JSON C string. Note that some schemas are
            # too large to compile on windows. Split the JSON up into several
            # strings, since apparently that helps.
            max_length = 8192
            segments = [
                json_content[i:i + max_length]
                for i in range(0, len(json_content), max_length)
            ]
            c.Append('constexpr char %s[] = R"R(%s)R";' %
                     (_FormatNameAsConstant(
                         namespace.name), ')R" R"R('.join(segments)))
        c.Append('}  // namespace')
        c.Append()
        c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
        c.Append()
        c.Append('// static')
        c.Sblock('bool %s::IsGenerated(base::StringPiece name) {' %
                 self._bundle._GenerateBundleClass('GeneratedSchemas'))
        c.Append('return !Get(name).empty();')
        c.Eblock('}')
        c.Append()
        c.Append('// static')
        c.Sblock('base::StringPiece %s::Get(base::StringPiece name) {' %
                 self._bundle._GenerateBundleClass('GeneratedSchemas'))
        c.Sblock('static constexpr struct kSchemaMapping {')
        c.Append('const base::StringPiece name;')
        c.Append('const base::StringPiece schema;')
        c.Sblock(
            'constexpr bool operator<(const kSchemaMapping& that) const {')
        c.Append('return name < that.name;')
        c.Eblock('}')
        c.Eblock()
        c.Sblock('} kSchemas[] = {')
        namespaces = [
            self._bundle._model.namespaces[api.get('namespace')].name
            for api in self._bundle._api_defs
        ]
        for namespace in sorted(namespaces):
            schema_constant_name = _FormatNameAsConstant(namespace)
            c.Append('{"%s", %s},' % (namespace, schema_constant_name))
        c.Eblock('};')
        c.Append(
            'static_assert(base::ranges::is_sorted(kSchemas), "|kSchemas| '
            'should be sorted.");')

        c.Sblock('auto it = std::lower_bound(std::begin(kSchemas), '
                 'std::end(kSchemas),')
        c.Append('kSchemaMapping{name, base::StringPiece()});')
        c.Eblock()

        c.Sblock('if (it != std::end(kSchemas) && it->name == name)')
        c.Append('return it->schema;')
        c.Eblock()

        c.Append('return base::StringPiece();')
        c.Eblock('}')
        c.Append()
        c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
        c.Append()
        return c
示例#21
0
  def Generate(self):
    """Generates a Code object with the .cc for a single namespace.
    """
    cpp_namespace = cpp_util.GetCppNamespace(
        self._namespace.environment.namespace_pattern,
        self._namespace.unix_name)

    c = Code()
    (c.Append(cpp_util.CHROMIUM_LICENSE)
      .Append()
      .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)
      .Append()
      .Append(self._util_cc_helper.GetIncludePath())
      .Append('#include "base/check.h"')
      .Append('#include "base/notreached.h"')
      .Append('#include "base/strings/string_number_conversions.h"')
      .Append('#include "base/strings/utf_string_conversions.h"')
      .Append('#include "base/values.h"')
      .Append('#include "%s/%s.h"' %
              (self._namespace.source_file_dir, self._namespace.short_filename))
      .Append('#include <set>')
      .Append('#include <utility>')
      .Cblock(self._type_helper.GenerateIncludes(include_soft=True))
      .Append()
      .Append('using base::UTF8ToUTF16;')
      .Append()
      .Concat(cpp_util.OpenNamespace(cpp_namespace))
    )
    if self._namespace.properties:
      (c.Append('//')
        .Append('// Properties')
        .Append('//')
        .Append()
      )
      for prop in self._namespace.properties.values():
        property_code = self._type_helper.GeneratePropertyValues(
            prop,
            'const %(type)s %(name)s = %(value)s;',
            nodoc=True)
        if property_code:
          c.Cblock(property_code)
    if self._namespace.types:
      (c.Append('//')
        .Append('// Types')
        .Append('//')
        .Append()
        .Cblock(self._GenerateTypes(None, self._namespace.types.values()))
      )
    if self._namespace.functions:
      (c.Append('//')
        .Append('// Functions')
        .Append('//')
        .Append()
      )
    for function in self._namespace.functions.values():
      c.Cblock(self._GenerateFunction(function))
    if self._namespace.events:
      (c.Append('//')
        .Append('// Events')
        .Append('//')
        .Append()
      )
      for event in self._namespace.events.values():
        c.Cblock(self._GenerateEvent(event))
    c.Cblock(cpp_util.CloseNamespace(cpp_namespace))
    c.Append()
    return c
示例#22
0
    def Generate(self):
        """Generates a Code object with the .h for a single namespace.
    """
        c = Code()
        (c.Append(cpp_util.CHROMIUM_LICENSE).Append().Append(
            cpp_util.GENERATED_FILE_MESSAGE %
            self._namespace.source_file).Append())

        # Hack: for the purpose of gyp the header file will always be the source
        # file with its file extension replaced by '.h'. Assume so.
        output_file = os.path.splitext(self._namespace.source_file)[0] + '.h'
        ifndef_name = cpp_util.GenerateIfndefName(output_file)

        # Hack: tabs and windows have circular references, so only generate hard
        # references for them (i.e. anything that can't be forward declared). In
        # other cases, generate soft dependencies so that they can include
        # non-optional types from other namespaces.
        include_soft = self._namespace.name not in ('tabs', 'windows')

        (c.Append('#ifndef %s' % ifndef_name).Append(
            '#define %s' % ifndef_name).Append().Append('#include <stdint.h>').
         Append().Append('#include <map>').Append('#include <memory>').Append(
             '#include <string>').Append('#include <vector>').Append().Append(
                 '#include "base/values.h"').Cblock(
                     self._type_helper.GenerateIncludes(
                         include_soft=include_soft)).Append())

        # Hack: we're not generating soft includes for tabs and windows, so we need
        # to generate forward declarations for them.
        if not include_soft:
            c.Cblock(self._type_helper.GenerateForwardDeclarations())

        cpp_namespace = cpp_util.GetCppNamespace(
            self._namespace.environment.namespace_pattern,
            self._namespace.unix_name)
        c.Concat(cpp_util.OpenNamespace(cpp_namespace))
        c.Append()
        if self._namespace.properties:
            (c.Append('//').Append('// Properties').Append('//').Append())
            for prop in self._namespace.properties.values():
                property_code = self._type_helper.GeneratePropertyValues(
                    prop, 'extern const %(type)s %(name)s;')
                if property_code:
                    c.Cblock(property_code)
        if self._namespace.types:
            (c.Append('//').Append('// Types').Append('//').Append().Cblock(
                self._GenerateTypes(self._FieldDependencyOrder(),
                                    is_toplevel=True,
                                    generate_typedefs=True)))
        if self._namespace.manifest_keys:
            c.Append('//')
            c.Append('// Manifest Keys')
            c.Append('//')
            c.Append()
            c.Cblock(self._GenerateManifestKeys())
        if self._namespace.functions:
            (c.Append('//').Append('// Functions').Append('//').Append())
            for function in self._namespace.functions.values():
                c.Cblock(self._GenerateFunction(function))
        if self._namespace.events:
            (c.Append('//').Append('// Events').Append('//').Append())
            for event in self._namespace.events.values():
                c.Cblock(self._GenerateEvent(event))
        (c.Concat(cpp_util.CloseNamespace(cpp_namespace)).Append().Append(
            '#endif  // %s' % ifndef_name).Append())
        return c
    def Generate(self, _):  # namespace not relevant, this is a bundle
        c = code.Code()
        c.Append(cpp_util.CHROMIUM_LICENSE)
        c.Append()
        c.Append('#include "%s"' % (cpp_util.ToPosixPath(
            os.path.join(self._bundle._source_file_dir,
                         'generated_schemas.h'))))
        c.Append()
        c.Append('#include <algorithm>')
        c.Append('#include <iterator>')
        c.Append()
        c.Append('#include "base/containers/fixed_flat_map.h"')
        c.Append('#include "base/strings/string_piece.h"')
        c.Append()
        c.Append('namespace {')
        for api in self._bundle._api_defs:
            namespace = self._bundle._model.namespaces[api.get('namespace')]
            json_content = json.dumps(_PrefixSchemaWithNamespace(
                _RemoveUnneededFields(api)),
                                      separators=(',', ':'))
            # This will output a valid JSON C string. Note that some schemas are
            # too large to compile on windows. Split the JSON up into several
            # strings, since apparently that helps.
            max_length = 8192
            segments = [
                json_content[i:i + max_length]
                for i in range(0, len(json_content), max_length)
            ]
            c.Append('constexpr char %s[] = R"R(%s)R";' %
                     (_FormatNameAsConstant(
                         namespace.name), ')R" R"R('.join(segments)))
        c.Append('}  // namespace')
        c.Append()
        c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
        c.Append()
        c.Append('// static')
        c.Sblock('bool %s::IsGenerated(base::StringPiece name) {' %
                 self._bundle._GenerateBundleClass('GeneratedSchemas'))
        c.Append('return !Get(name).empty();')
        c.Eblock('}')
        c.Append()
        c.Append('// static')
        c.Sblock('base::StringPiece %s::Get(base::StringPiece name) {' %
                 self._bundle._GenerateBundleClass('GeneratedSchemas'))

        c.Append(
            'static constexpr auto kSchemas = '
            'base::MakeFixedFlatMap<base::StringPiece, base::StringPiece>({')
        c.Sblock()
        namespaces = [
            self._bundle._model.namespaces[api.get('namespace')].name
            for api in self._bundle._api_defs
        ]
        for namespace in sorted(namespaces):
            schema_constant_name = _FormatNameAsConstant(namespace)
            c.Append('{"%s", %s},' % (namespace, schema_constant_name))
        c.Eblock('});')
        c.Append('auto it = kSchemas.find(name);')
        c.Append(
            'return it != kSchemas.end() ? it->second : base::StringPiece();')
        c.Eblock('}')
        c.Append()
        c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
        c.Append()
        return c