Exemple #1
0
class WrapperGen(Generator):
    """WrapperGen - An abstract class that generates wrappers for PPAPI methods.

  This generates a wrapper PPB and PPP GetInterface, which directs users
  to wrapper PPAPI methods. Wrapper PPAPI methods may perform arbitrary
  work before invoking the real PPAPI method (supplied by the original
  GetInterface functions).

  Subclasses must implement GenerateWrapperForPPBMethod (and PPP).
  Optionally, subclasses can implement InterfaceNeedsWrapper to
  filter out interfaces that do not actually need wrappers (those
  interfaces can jump directly to the original interface functions).
  """
    def __init__(self, wrapper_prefix, s1, s2, s3):
        Generator.__init__(self, s1, s2, s3)
        self.wrapper_prefix = wrapper_prefix
        self._skip_opt = False
        self.output_file = None
        self.cgen = CGen()

    def SetOutputFile(self, fname):
        self.output_file = fname

    def GenerateRelease(self, ast, release, options):
        return self.GenerateRange(ast, [release], options)

    @staticmethod
    def GetHeaderName(name):
        """Get the corresponding ppapi .h file from each IDL filename.
    """
        name = os.path.splitext(name)[0] + '.h'
        name = name.replace(os.sep, '/')
        return 'ppapi/c/' + name

    def WriteCopyrightGeneratedTime(self, out):
        now = datetime.now()
        c = """/* Copyright (c) %s The Chromium Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

/* Last generated from IDL: %s. */
""" % (now.year, datetime.ctime(now))
        out.Write(c)

    def GetWrapperMetadataName(self):
        return '__%sWrapperInfo' % self.wrapper_prefix

    def GenerateHelperFunctions(self, out):
        """Generate helper functions to avoid dependencies on libc.
    """
        out.Write("""/* Use local strcmp to avoid dependency on libc. */
static int mystrcmp(const char* s1, const char *s2) {
  while((*s1 && *s2) && (*s1++ == *s2++));
  return *(--s1) - *(--s2);
}\n
""")

    def GenerateFixedFunctions(self, out):
        """Write out the set of constant functions (those that do not depend on
    the current Pepper IDL).
    """
        out.Write(
            """

static PPB_GetInterface __real_PPBGetInterface;
static PPP_GetInterface_Type __real_PPPGetInterface;

void __set_real_%(wrapper_prefix)s_PPBGetInterface(PPB_GetInterface real) {
  __real_PPBGetInterface = real;
}

void __set_real_%(wrapper_prefix)s_PPPGetInterface(PPP_GetInterface_Type real) {
  __real_PPPGetInterface = real;
}

/* Map interface string -> wrapper metadata */
static struct %(wrapper_struct)s *%(wrapper_prefix)sPPBShimIface(
    const char *name) {
  struct %(wrapper_struct)s **next = s_ppb_wrappers;
  while (*next != NULL) {
    if (mystrcmp(name, (*next)->iface_macro) == 0) return *next;
    ++next;
  }
  return NULL;
}

/* Map interface string -> wrapper metadata */
static struct %(wrapper_struct)s *%(wrapper_prefix)sPPPShimIface(
    const char *name) {
  struct %(wrapper_struct)s **next = s_ppp_wrappers;
  while (*next != NULL) {
    if (mystrcmp(name, (*next)->iface_macro) == 0) return *next;
    ++next;
  }
  return NULL;
}

const void *__%(wrapper_prefix)s_PPBGetInterface(const char *name) {
  struct %(wrapper_struct)s *wrapper = %(wrapper_prefix)sPPBShimIface(name);
  if (wrapper == NULL) {
    /* We don't have an IDL for this, for some reason. Take our chances. */
    return (*__real_PPBGetInterface)(name);
  }

  /* Initialize the real_iface if it hasn't been. The wrapper depends on it. */
  if (wrapper->real_iface == NULL) {
    const void *iface = (*__real_PPBGetInterface)(name);
    if (NULL == iface) return NULL;
    wrapper->real_iface = iface;
  }

  if (wrapper->wrapped_iface) {
    return wrapper->wrapped_iface;
  } else {
    return wrapper->real_iface;
  }
}

const void *__%(wrapper_prefix)s_PPPGetInterface(const char *name) {
  struct %(wrapper_struct)s *wrapper = %(wrapper_prefix)sPPPShimIface(name);
  if (wrapper == NULL) {
    /* We don't have an IDL for this, for some reason. Take our chances. */
    return (*__real_PPPGetInterface)(name);
  }

  /* Initialize the real_iface if it hasn't been. The wrapper depends on it. */
  if (wrapper->real_iface == NULL) {
    const void *iface = (*__real_PPPGetInterface)(name);
    if (NULL == iface) return NULL;
    wrapper->real_iface = iface;
  }

  if (wrapper->wrapped_iface) {
    return wrapper->wrapped_iface;
  } else {
    return wrapper->real_iface;
  }
}
""" % {
                'wrapper_struct': self.GetWrapperMetadataName(),
                'wrapper_prefix': self.wrapper_prefix,
            })

    ############################################################

    def InterfaceNeedsWrapper(self, iface, releases):
        """Return true if the interface has ANY methods that need wrapping.
    """
        return True

    def OwnHeaderFile(self):
        """Return the header file that specifies the API of this wrapper.
    We do not generate the header files.  """
        raise Exception('Child class must implement this')

    ############################################################

    def DetermineInterfaces(self, ast, releases):
        """Get a list of interfaces along with whatever metadata we need.
    """
        iface_releases = []
        for filenode in ast.GetListOf('File'):
            # If this file has errors, skip it
            if filenode in self.skip_list:
                if GetOption('verbose'):
                    InfoOut.Log('WrapperGen: Skipping %s due to errors\n' %
                                filenode.GetName())
                continue

            file_name = self.GetHeaderName(filenode.GetName())
            ifaces = filenode.GetListOf('Interface')
            for iface in ifaces:
                releases_for_iface = iface.GetUniqueReleases(releases)
                for release in releases_for_iface:
                    version = iface.GetVersion(release)
                    struct_name = self.cgen.GetStructName(iface,
                                                          release,
                                                          include_version=True)
                    needs_wrap = self.InterfaceVersionNeedsWrapping(
                        iface, version)
                    if not needs_wrap:
                        if GetOption('verbose'):
                            InfoOut.Log(
                                'Interface %s ver %s does not need wrapping' %
                                (struct_name, version))
                    iface_releases.append(
                        Interface(iface, release, version, struct_name,
                                  needs_wrap, file_name))
        return iface_releases

    def GenerateIncludes(self, iface_releases, out):
        """Generate the list of #include that define the original interfaces.
    """
        self.WriteCopyrightGeneratedTime(out)
        # First include own header.
        out.Write('#include "%s"\n\n' % self.OwnHeaderFile())

        # Get typedefs for PPB_GetInterface.
        out.Write('#include "%s"\n' % self.GetHeaderName('ppb.h'))

        # Get a conservative list of all #includes that are needed,
        # whether it requires wrapping or not. We currently depend on the macro
        # string for comparison, even when it is not wrapped, to decide when
        # to use the original/real interface.
        header_files = set()
        for iface in iface_releases:
            header_files.add(iface.header_file)
        for header in sorted(header_files):
            out.Write('#include "%s"\n' % header)
        out.Write('\n')

    def WrapperMethodPrefix(self, iface, release):
        return '%s_%s_%s_' % (self.wrapper_prefix, release, iface.GetName())

    def GetReturnArgs(self, ret_type, args_spec):
        if ret_type != 'void':
            ret = 'return '
        else:
            ret = ''
        if args_spec:
            args = []
            for arg in args_spec:
                args.append(arg[1])
            args = ', '.join(args)
        else:
            args = ''
        return (ret, args)

    def GenerateWrapperForPPBMethod(self, iface, member):
        result = []
        func_prefix = self.WrapperMethodPrefix(iface.node, iface.release)
        sig = self.cgen.GetSignature(member, iface.release, 'store',
                                     func_prefix, False)
        result.append('static %s {\n' % sig)
        result.append(' while(1) { /* Not implemented */ } \n')
        result.append('}\n')
        return result

    def GenerateWrapperForPPPMethod(self, iface, member):
        result = []
        func_prefix = self.WrapperMethodPrefix(iface.node, iface.release)
        sig = self.cgen.GetSignature(member, iface.release, 'store',
                                     func_prefix, False)
        result.append('static %s {\n' % sig)
        result.append(' while(1) { /* Not implemented */ } \n')
        result.append('}\n')
        return result

    def GenerateWrapperForMethods(self, iface_releases, comments=True):
        """Return a string representing the code for each wrapper method
    (using a string rather than writing to the file directly for testing.)
    """
        result = []
        for iface in iface_releases:
            if not iface.needs_wrapping:
                if comments:
                    result.append(
                        '/* Not generating wrapper methods for %s */\n\n' %
                        iface.struct_name)
                continue
            if comments:
                result.append('/* Begin wrapper methods for %s */\n\n' %
                              iface.struct_name)
            generator = PPKind.ChoosePPFunc(iface,
                                            self.GenerateWrapperForPPBMethod,
                                            self.GenerateWrapperForPPPMethod)
            for member in iface.node.GetListOf('Member'):
                # Skip the method if it's not actually in the release.
                if not member.InReleases([iface.release]):
                    continue
                result.extend(generator(iface, member))
            if comments:
                result.append('/* End wrapper methods for %s */\n\n' %
                              iface.struct_name)
        return ''.join(result)

    def GenerateWrapperInterfaces(self, iface_releases, out):
        for iface in iface_releases:
            if not iface.needs_wrapping:
                out.Write('/* Not generating wrapper interface for %s */\n\n' %
                          iface.struct_name)
                continue

            out.Write(
                'struct %s %s_Wrappers_%s = {\n' %
                (iface.struct_name, self.wrapper_prefix, iface.struct_name))
            methods = []
            for member in iface.node.GetListOf('Member'):
                # Skip the method if it's not actually in the release.
                if not member.InReleases([iface.release]):
                    continue
                prefix = self.WrapperMethodPrefix(iface.node, iface.release)
                cast = self.cgen.GetSignature(member,
                                              iface.release,
                                              'return',
                                              prefix='',
                                              func_as_ptr=True,
                                              ptr_prefix='',
                                              include_name=False)
                methods.append(
                    '  .%s = (%s)&%s%s' %
                    (member.GetName(), cast, prefix, member.GetName()))
            out.Write('  ' + ',\n  '.join(methods) + '\n')
            out.Write('};\n\n')

    def GetWrapperInfoName(self, iface):
        return '%s_WrapperInfo_%s' % (self.wrapper_prefix, iface.struct_name)

    def GenerateWrapperInfoAndCollection(self, iface_releases, out):
        for iface in iface_releases:
            iface_macro = self.cgen.GetInterfaceMacro(iface.node,
                                                      iface.version)
            if iface.needs_wrapping:
                wrap_iface = '(void *) &%s_Wrappers_%s' % (self.wrapper_prefix,
                                                           iface.struct_name)
            else:
                wrap_iface = 'NULL /* Still need slot for real_iface */'
            out.Write("""static struct %s %s = {
  .iface_macro = %s,
  .wrapped_iface = %s,
  .real_iface = NULL
};\n\n""" % (self.GetWrapperMetadataName(), self.GetWrapperInfoName(iface),
             iface_macro, wrap_iface))

        # Now generate NULL terminated arrays of the above wrapper infos.
        ppb_wrapper_infos = []
        ppp_wrapper_infos = []
        for iface in iface_releases:
            appender = PPKind.ChoosePPFunc(iface, ppb_wrapper_infos.append,
                                           ppp_wrapper_infos.append)
            appender('  &%s' % self.GetWrapperInfoName(iface))
        ppb_wrapper_infos.append('  NULL')
        ppp_wrapper_infos.append('  NULL')
        out.Write(
            'static struct %s *s_ppb_wrappers[] = {\n%s\n};\n\n' %
            (self.GetWrapperMetadataName(), ',\n'.join(ppb_wrapper_infos)))
        out.Write(
            'static struct %s *s_ppp_wrappers[] = {\n%s\n};\n\n' %
            (self.GetWrapperMetadataName(), ',\n'.join(ppp_wrapper_infos)))

    def DeclareWrapperInfos(self, iface_releases, out):
        """The wrapper methods usually need access to the real_iface, so we must
    declare these wrapper infos ahead of time (there is a circular dependency).
    """
        out.Write('/* BEGIN Declarations for all Wrapper Infos */\n\n')
        for iface in iface_releases:
            out.Write('static struct %s %s;\n' %
                      (self.GetWrapperMetadataName(),
                       self.GetWrapperInfoName(iface)))
        out.Write('/* END Declarations for all Wrapper Infos. */\n\n')

    def GenerateRange(self, ast, releases, options):
        """Generate shim code for a range of releases.
    """

        # Remember to set the output filename before running this.
        out_filename = self.output_file
        if out_filename is None:
            ErrOut.Log('Did not set filename for writing out wrapper\n')
            return 1

        InfoOut.Log("Generating %s for %s" %
                    (out_filename, self.wrapper_prefix))

        out = IDLOutFile(out_filename)

        # Get a list of all the interfaces along with metadata.
        iface_releases = self.DetermineInterfaces(ast, releases)

        # Generate the includes.
        self.GenerateIncludes(iface_releases, out)

        out.Write(self.GetGuardStart())

        # Write out static helper functions (mystrcmp).
        self.GenerateHelperFunctions(out)

        # Declare list of WrapperInfo before actual wrapper methods, since
        # they reference each other.
        self.DeclareWrapperInfos(iface_releases, out)

        # Generate wrapper functions for each wrapped method in the interfaces.
        result = self.GenerateWrapperForMethods(iface_releases)
        out.Write(result)

        # Collect all the wrapper functions into interface structs.
        self.GenerateWrapperInterfaces(iface_releases, out)

        # Generate a table of the wrapped interface structs that can be looked up.
        self.GenerateWrapperInfoAndCollection(iface_releases, out)

        # Write out the IDL-invariant functions.
        self.GenerateFixedFunctions(out)

        out.Write(self.GetGuardEnd())
        out.Close()
        return 0
    def GenerateHead(self, out, filenode, releases, options):
        __pychecker__ = 'unusednames=options'

        proto = ProtoResolver()
        proto.Visit(filenode, None)

        cgen = CGen()
        gpath = GetOption('guard')
        def_guard = GetHeaderFromNode(filenode, relpath=gpath)
        def_guard = def_guard.replace(os.sep, '_').replace('.',
                                                           '_').upper() + '_'

        cright_node = filenode.GetChildren()[0]
        assert (cright_node.IsA('Copyright'))
        fileinfo = filenode.GetChildren()[1]
        assert (fileinfo.IsA('Comment'))

        out.Write('%s\n' % cgen.Copyright(cright_node))

        # Wrap the From ... modified ... comment if it would be >80 characters.
        from_text = 'From %s' % GetPathFromNode(filenode).replace(os.sep, '/')
        modified_text = 'modified %s.' % (filenode.GetProperty('DATETIME'))
        if len(from_text) + len(modified_text) < 74:
            out.Write('/* %s %s */\n\n' % (from_text, modified_text))
        else:
            out.Write('/* %s,\n *   %s\n */\n\n' % (from_text, modified_text))

        out.Write('#ifndef %s\n#define %s\n\n' % (def_guard, def_guard))
        # Generate set of includes

        deps = set()
        for release in releases:
            deps |= filenode.GetDeps(release)

        includes = set([])
        for dep in deps:
            depfile = dep.GetProperty('FILE')
            if depfile:
                includes.add(depfile)
        includes = [
            GetHeaderFromNode(include, relpath=gpath).replace(os.sep, '/')
            for include in includes
        ]
        includes.append('ppapi/c/pp_macros.h')

        # Assume we need stdint if we "include" C or C++ code
        if filenode.GetListOf('Include'):
            includes.append('ppapi/c/pp_stdint.h')

        includes = sorted(set(includes))
        cur_include = GetHeaderFromNode(filenode,
                                        relpath=gpath).replace(os.sep, '/')
        for include in includes:
            if include == cur_include: continue
            out.Write('#include "%s"\n' % include)

        # Generate Prototypes
        if proto.struct_map:
            out.Write('\n/* Struct prototypes */\n')
            for struct in proto.struct_map:
                out.Write('struct %s;\n' % struct)

        # Create a macro for the highest available release number.
        if filenode.GetProperty('NAME').endswith('pp_macros.idl'):
            releasestr = ' '.join(releases)
            if releasestr:
                release_numbers = re.findall('[\d\_]+', releasestr)
                release = re.findall('\d+', release_numbers[-1])[0]
                if release:
                    out.Write('\n#define PPAPI_RELEASE %s\n' % release)

        # Generate all interface defines
        out.Write('\n')
        for node in filenode.GetListOf('Interface'):
            idefs = ''
            macro = cgen.GetInterfaceMacro(node)
            unique = node.GetUniqueReleases(releases)

            # Skip this interface if there are no matching versions
            if not unique: continue

            for rel in unique:
                version = node.GetVersion(rel)
                name = cgen.GetInterfaceString(node, version)
                strver = str(version).replace('.', '_')
                idefs += cgen.GetDefine('%s_%s' % (macro, strver),
                                        '"%s"' % name)
            idefs += cgen.GetDefine(macro, '%s_%s' % (macro, strver)) + '\n'
            out.Write(idefs)

        # Generate the @file comment
        out.Write('%s\n' % Comment(fileinfo, prefix='*\n @file'))
Exemple #3
0
class PepperGen(WrapperGen):
    """PepperGen generates code entry points for C# PInvoking API.

  This subclass of WrapperGenerator takes the IDL sources and
  generates the DLL PInvoke entryp points between C# and the 
  the Native C++ PepperPlugin.
  """
    def __init__(self):
        WrapperGen.__init__(self, 'Pepper', 'Pepper Gen', 'pepper',
                            'Generate the Pepper DLL export.')
        self.cgen = CGen()
        self._skip_opt = False
        self._skip_region_gen = False

    #
    # RemapParameter
    #
    # A diction array of parameter types that need to be remappted
    #
    RemapParameter = {
        # 'struct PP_Var*': 'const char*',
    }

    #
    # WrapArgument
    #
    # A diction array of parameter types that need to be wrapped
    #
    WrapArgument = {
        'struct PP_Var': '%s',
        'struct PP_CompletionCallback': '%s',
        'struct PP_ArrayOutput': '%s'
    }

    #
    # WrapReturn
    #
    # A diction array of parameter types that need to be wrapped
    #
    WrapReturn = {
        #  'struct PP_Var': 'Var(%s).AsString().c_str()'
    }

    #
    # ExcludeInterface
    #
    # A dictionary of interfaces that we will not generate for
    #
    ExcludeInterface = ['PPB_Audio_1_0']

    ############################################################

    def OwnHeaderFile(self):
        """Return the header file that specifies the API of this wrapper.
    We do not generate the header files.  """
        return 'pepper_entrypoints.h'

    def WriteCopyright(self, out):
        now = datetime.now()
        c = """/* Copyright (c) %s Xamarin. */

/* NOTE: this is auto-generated from IDL */
""" % now.year
        out.Write(c)

    def GenerateHelperFunctions(self, out):
        """Generate helper functions.
    """
        out.Write("""#ifndef PEPPER_EXPORT
#define PEPPER_EXPORT __declspec(dllexport)
#endif

using namespace pp;

namespace Pepper {

	namespace {
		// Specialize this function to return the interface string corresponding to the
		// PP?_XXX structure.
		template <typename T> const char* interface_name() {
			return NULL;
		}

		template <typename T> inline T const* get_interface() {
			static T const* funcs = reinterpret_cast<T const*>(
				pp::Module::Get()->GetBrowserInterface(interface_name<T>()));
			return funcs;
		}

		template <typename T> inline bool has_interface() {
			return get_interface<T>() != NULL;
		}

	}
}
""")

    def GenerateFixedFunctions(self, out):
        """Write out the set of constant functions (those that do not depend on
    the current Pepper IDL).
    """

    def InterfaceVersionNeedsWrapping(self, iface, version):
        """Return true if the interface+version has ANY methods that
    need wrapping.
    """
        if self._skip_opt:
            return True
        if iface.GetName().endswith('Trusted'):
            return False
        # TODO(dmichael): We have no way to wrap PPP_ interfaces without an
        # interface string. If any ever need wrapping, we'll need to figure out a
        # way to get the plugin-side of the Pepper proxy (within the IRT) to access
        # and use the wrapper.
        if iface.GetProperty("no_interface_string"):
            return False
        for member in iface.GetListOf('Member'):
            release = member.GetRelease(version)
            if self.MemberNeedsWrapping(member, release):
                return True
        return False

    def MemberNeedsWrapping(self, member, release):
        """Return true if a particular member function at a particular
    release needs wrapping.
    """
        if self._skip_opt:
            return True
        if not member.InReleases([release]):
            return False
        ret, name, array, args_spec = self.cgen.GetComponents(
            member, release, 'store')
        return self.TypeNeedsWrapping(ret,
                                      []) or self.ArgsNeedWrapping(args_spec)

    def ArgsNeedWrapping(self, args):
        """Return true if any parameter in the list needs wrapping.
    """
        for arg in args:
            (type_str, name, array_dims, more_args) = arg
            if self.TypeNeedsWrapping(type_str, array_dims):
                return True
        # we always return true here so all interfaces are generated
        return True

    def TypeNeedsWrapping(self, type_node, array_dims):
        """Return true if a parameter type needs wrapping.
    Currently, this is true for byval aggregates.
    """
        #is_aggregate = type_node.startswith('struct') or \
        #    type_node.startswith('union')
        is_aggregate = type_node.startswith('union')

        is_reference = (type_node.find('*') != -1 or array_dims != [])
        return is_aggregate and not is_reference

    ############################################################

    def ConvertByValueReturnType(self, ret, args_spec):
        if self.TypeNeedsWrapping(ret, array_dims=[]):
            args_spec = [(ret, '_struct_result', [], None)] + args_spec
            ret2 = 'void'
            wrap_return = True
        else:
            ret2 = ret
            wrap_return = False
        return wrap_return, ret2, args_spec

    def ConvertByValueArguments(self, args_spec):
        args = []
        for type_str, name, array_dims, more_args in args_spec:
            if self.TypeNeedsWrapping(type_str, array_dims):
                type_str += '*'
            args.append((type_str, name, array_dims, more_args))
        return args

    def FormatArgs(self, c_operator, args_spec):
        args = []
        for type_str, name, array_dims, more_args in args_spec:
            if self.TypeNeedsWrapping(type_str, array_dims):
                if type_str in PepperGen.WrapArgument:
                    args.append(PepperGen.WrapArgument[type_str] % name)
                else:
                    args.append(c_operator + name)
            else:
                if type_str in PepperGen.WrapArgument:
                    args.append(PepperGen.WrapArgument[type_str] % name)
                else:
                    if type_str.startswith(
                            'struct ') and type_str.rfind('*') < 0:
                        args.append('&%s' % name)
                    else:
                        args.append(name)
        return ', '.join(args)

    def GenerateWrapperForMethodGroup(self, iface_releases, comments=True):

        result = []

        if len(iface_releases) == 0:
            return ''

        iface = iface_releases[len(iface_releases) - 1]

        if not iface.needs_wrapping:
            if comments:
                result.append(
                    '/* Not generating entry point methods for %s */\n\n' %
                    iface.struct_name)
            return ''.join(result)
        if self._skip_region_gen:
            result.append('\t\t/* Begin entry point methods for %s */\n\n' %
                          iface.node.GetName())
        else:
            result.append(
                '\t\t#pragma region /* Begin entry point methods for %s */\n\n'
                % iface.node.GetName())

        generator = PPKind.ChoosePPFunc(
            iface, self.GenerateWrapperForPPBMethodReleases,
            self.GenerateWrapperForPPPMethodReleases)

        for member in iface.node.GetListOf('Member'):
            # Skip the method if it's not actually in the release.
            if not member.InReleases([iface.release]):
                continue
            result.extend(generator(iface, member, iface_releases))

        if comments:
            if self._skip_region_gen:
                result.append(
                    '\t\t/* End entry point generation for %s */\n\n' %
                    iface.node.GetName())
            else:
                result.append(
                    '\t\t#pragma endregion /* End entry point generation for %s */\n\n'
                    % iface.node.GetName())

        return ''.join(result)

    def GenerateWrapperForMethods(self, iface_releases, comments=True):
        """Return a string representing the code for each wrapper method
    (using a string rather than writing to the file directly for testing.)
    """
        result = []

        result.append("""namespace Pepper {


	/* We don't want name mangling for these external functions.  We only need
	* 'extern "C"' if we're compiling with a C++ compiler.
	*/
#ifdef __cplusplus
	extern "C" {
#endif
	namespace {\n\n""")

        iface_release_group = []
        rangeName = iface_releases[0].node.GetName()
        for x in range(len(iface_releases)):
            if iface_releases[x].node.GetName() == rangeName:
                iface_release_group.append(iface_releases[x])
            else:
                print("Generating entry points for %s for %d release(s)." %
                      (rangeName, len(iface_release_group)))
                result.append(
                    self.GenerateWrapperForMethodGroup(iface_release_group,
                                                       comments))
                rangeName = iface_releases[x].node.GetName()
                iface_release_group = []
                iface_release_group.append(iface_releases[x])

        print("Generating entry points for %s for %d release(s)." %
              (rangeName, len(iface_release_group)))
        if len(iface_release_group) > 0:
            result.append(
                self.GenerateWrapperForMethodGroup(iface_release_group,
                                                   comments))

        result.append("""	}
#ifdef __cplusplus
	}  /* extern "C" */
#endif
}\n""")
        return ''.join(result)

    def WrapperMethodPrefix(self, iface, release):
        return '%s_' % (iface.GetName())

    def Compose(self, rtype, name, arrayspec, callspec, prefix, func_as_ptr,
                include_name, unsized_as_ptr):
        self.cgen.LogEnter('Compose: %s %s' % (rtype, name))
        arrayspec = ''.join(arrayspec)

        # Switch unsized array to a ptr. NOTE: Only last element can be unsized.
        if unsized_as_ptr and arrayspec[-2:] == '[]':
            prefix += '*'
            arrayspec = arrayspec[:-2]

        if not include_name:
            name = prefix + arrayspec
        else:
            name = prefix + name + arrayspec
        if callspec is None:
            if rtype in PepperGen.RemapParameter:
                rtype = PepperGen.RemapParameter[rtype]
            out = '%s %s' % (rtype, name)
        else:
            params = []
            for ptype, pname, parray, pspec in callspec:
                params.append(
                    self.Compose(ptype,
                                 pname,
                                 parray,
                                 pspec,
                                 '',
                                 True,
                                 include_name=True,
                                 unsized_as_ptr=unsized_as_ptr))
            if func_as_ptr:
                name = '(*%s)' % name
            if not params:
                params = ['void']
            out = '%s %s(%s)' % (rtype, name, ', '.join(params))
        self.cgen.LogExit('Exit Compose: %s' % out)
        return out

    def GenerateWrapperForPPBMethodReleases(self, iface, member,
                                            iface_releases):
        result = []
        func_prefix = self.WrapperMethodPrefix(iface.node, iface.release)
        if func_prefix == 'PPB_Graphics2D_':
            func_prefix = func_prefix
        ret, name, array, cspec = self.cgen.GetComponents(
            member, iface.release, 'store')
        wrap_return, ret2, cspec2 = self.ConvertByValueReturnType(ret, cspec)
        cspec2 = self.ConvertByValueArguments(cspec2)

        if ret2 in PepperGen.RemapParameter:
            ret2 = PepperGen.RemapParameter[ret2]
        sig = self.Compose(ret2,
                           name,
                           array,
                           cspec2,
                           prefix=func_prefix,
                           func_as_ptr=False,
                           include_name=True,
                           unsized_as_ptr=False)
        result.append('\t\tPEPPER_EXPORT %s {\n' % sig)

        return_prefix = ''
        if wrap_return:
            return_prefix = ''
        elif ret != 'void':
            return_prefix = 'return '

        first = True

        for iface_release in reversed(iface_releases):
            # Skip the method if it's not actually in the release.
            if not member.InReleases([iface_release.release]):
                continue

            if self.GetWrapperInfoName(
                    iface_release) in PepperGen.ExcludeInterface:
                continue

            if first:
                result.append('\t\t\tif (has_interface<%s>()) {\n' %
                              self.GetWrapperInfoName(iface_release))
                result.append(
                    '\t\t\t\t%sget_interface<%s>()->%s(%s);\n' %
                    (return_prefix, self.GetWrapperInfoName(iface_release),
                     member.GetName(), self.FormatArgs('*', cspec)))

                result.append('\t\t\t}\n')
                first = False
            else:
                result.append('\t\t\telse if (has_interface<%s>()) {\n' %
                              self.GetWrapperInfoName(iface_release))

                result.append(
                    '\t\t\t\t%sget_interface<%s>()->%s(%s);\n' %
                    (return_prefix, self.GetWrapperInfoName(iface_release),
                     member.GetName(), self.FormatArgs('*', cspec)))

                result.append('\t\t\t}\n')

        dfltValue = ''
        if ret2 in RemapDefaultValue:
            dfltValue = RemapDefaultValue[ret2]
        else:
            dfltValue = "NULL"

        result.append('\t\t\treturn %s;\n\t\t}\n\n' % dfltValue)

        return result

    def GenerateWrapperForPPPMethodReleases(self, iface, member,
                                            iface_releases):
        # We just call the PPB code from here unless something changes.
        return self.GenerateWrapperForPPBMethodReleases(
            iface, member, iface_releases)

    def DeclareWrapperInfos(self, iface_releases, out):
        """The wrapper methods usually need access to the real_iface, so we must
    declare these wrapper infos ahead of time (there is a circular dependency).
    """
        out.Write(
            '/* BEGIN Declarations for all Interface Definitions. */\n\n')
        out.Write('namespace Pepper {\n\tnamespace {\n')

        for iface in iface_releases:
            if iface.needs_wrapping:
                out.Write(
                    """\t\ttemplate <> const char*	interface_name<%s>() {\n\t\t\treturn %s;\n\t\t}\n"""
                    % (self.GetWrapperInfoName(iface),
                       self.cgen.GetInterfaceMacro(iface.node, iface.version)))

        out.Write('\t}\n}\n')
        out.Write('/* END Declarations for all Interface Definitions. */\n\n')

    def GetWrapperInfoName(self, iface):
        return '%s' % (iface.struct_name)

    def GetWrapperMetadataName(self):
        return '__%sWrapperInfo' % self.wrapper_prefix

    def GenerateWrapperInfoAndCollection(self, iface_releases, out):
        """Do not generate this as it is not needed"""

    def GenerateWrapperInterfaces(self, iface_releases, out):
        """Do not generate this as it is not needed"""

    def GenerateRange(self, ast, releases, options):
        """Generate entry point code for a range of releases.
    """
        self._skip_opt = GetOption('disable_pepper_opt')
        self._skip_region_gen = GetOption('disable_region_gen')
        self.SetOutputFile(GetOption('pepperfile'))
        return WrapperGen.GenerateRange(self, ast, releases, options)
Exemple #4
0
    def GenerateHead(self, out, filenode, releases, options):
        __pychecker__ = 'unusednames=options'
        cgen = CGen()
        gpath = GetOption('guard')
        def_guard = GetOutFileName(filenode, relpath=gpath)
        def_guard = def_guard.replace(os.sep, '_').replace('.',
                                                           '_').upper() + '_'

        cright_node = filenode.GetChildren()[0]
        assert (cright_node.IsA('Copyright'))
        fileinfo = filenode.GetChildren()[1]
        assert (fileinfo.IsA('Comment'))

        out.Write('%s\n' % cgen.Copyright(cright_node))

        # Wrap the From ... modified ... comment if it would be >80 characters.
        from_text = 'From %s' % (filenode.GetProperty('NAME').replace(
            os.sep, '/'))
        modified_text = 'modified %s.' % (filenode.GetProperty('DATETIME'))
        if len(from_text) + len(modified_text) < 74:
            out.Write('/* %s %s */\n\n' % (from_text, modified_text))
        else:
            out.Write('/* %s,\n *   %s\n */\n\n' % (from_text, modified_text))

        out.Write('#ifndef %s\n#define %s\n\n' % (def_guard, def_guard))
        # Generate set of includes

        deps = set()
        for release in releases:
            deps |= filenode.GetDeps(release)

        includes = set([])
        for dep in deps:
            depfile = dep.GetProperty('FILE')
            if depfile:
                includes.add(depfile)
        includes = [
            GetOutFileName(include, relpath=gpath).replace(os.sep, '/')
            for include in includes
        ]
        includes.append('ppapi/c/pp_macros.h')

        # Assume we need stdint if we "include" C or C++ code
        if filenode.GetListOf('Include'):
            includes.append('ppapi/c/pp_stdint.h')

        includes = sorted(set(includes))
        cur_include = GetOutFileName(filenode,
                                     relpath=gpath).replace(os.sep, '/')
        for include in includes:
            if include == cur_include: continue
            out.Write('#include "%s"\n' % include)

        # Generate all interface defines
        out.Write('\n')
        for node in filenode.GetListOf('Interface'):
            idefs = ''
            macro = cgen.GetInterfaceMacro(node)
            unique = node.GetUniqueReleases(releases)

            # Skip this interface if there are no matching versions
            if not unique: continue

            for rel in unique:
                version = node.GetVersion(rel)
                name = cgen.GetInterfaceString(node, version)
                strver = str(version).replace('.', '_')
                idefs += cgen.GetDefine('%s_%s' % (macro, strver),
                                        '"%s"' % name)
            idefs += cgen.GetDefine(macro, '%s_%s' % (macro, strver)) + '\n'
            out.Write(idefs)

        # Generate the @file comment
        out.Write('%s\n' % Comment(fileinfo, prefix='*\n @file'))