Пример #1
0
 def visitModule(self, node):
     module = id.mapID(node.identifier())
     self.module.append(module)
     for n in node.definitions():
         # enter tree inside this module
         n.accept(self)
     self.module.pop()
Пример #2
0
def visitModule(node):
    if self.__completedModules.has_key(node):
        return
    self.__completedModules[node] = 1
    
    name = id.mapID(node.identifier())

    if not config.state['Fragment']:
        stream.out(template.OBV_module_begin,
                   name = name,
                   OBV_prefix = OBV_prefix())
        stream.inc_indent()

    nested = self.__nested
    self.__nested = 1
    for n in node.definitions():
        n.accept(self)

    # Splice the continuations together if splice-modules flag is set
    # (This might be unnecessary as there (seems to be) no relationship
    #  between things in the POA module- they all point back into the main
    #  module?)
    if config.state['Splice Modules']:
        for c in node.continuations():
            for n in c.definitions():
                n.accept(self)
            self.__completedModules[c] = 1

    self.__nested = nested

    if not config.state['Fragment']:
        stream.dec_indent()
        stream.out(template.OBV_module_end)
    return
Пример #3
0
    def createMember(self, decl, member, env):
        dict = self.createDecl('member')
        cdict = dict['corba']
        ldict = dict['local']

        memberType = types.Type(member.memberType())
        memtype = memberType.member(env)

        (ctype, ltype, is_primitive) = self.getType(memberType)
        cdict['base_type'] = ctype
        cdict['tk'] = self.tk_map[memberType.kind()]
        ldict['base_type'] = ltype
        cdict['member_name'] = id.mapID(decl.identifier())
        cdict['member_dims'] = decl.sizes()
        ldict['member_name'] = cdict['member_name']
        ldict['member_dims'] = cdict['member_dims']

        if memberType.objref():
            corba_mtype = ctype
            local_mtype = ltype + '*'
        else:
            corba_mtype = ctype
            local_mtype = ltype

        cdict['member_type'] = corba_mtype
        ldict['member_type'] = local_mtype
        return dict
Пример #4
0
def visitTypedef(node):
    aliasType = types.Type(node.aliasType())
    d_type = aliasType.deref()

    if node.constrType():
        aliasType.type().decl().accept(self)

    for d in node.declarators():
        scopedName = id.Name(d.scopedName())
        
        if d_type.sequence() and not aliasType.typedef():
            seqType = types.Type(d_type.type().seqType())
            d_seqType = seqType.deref()

            if d_seqType.structforward() or d_seqType.unionforward():
                fqname  = scopedName.fullyQualify()
                name    = id.mapID(d.identifier())
                element = d_seqType.base()
                bound   = d_type.type().bound()
                derived = d_type.sequenceTemplate()
                
                if bound > 0:
                    stream.out(template.sequence_forward_bounded_defns,
                               bound=bound, fqname=fqname, name=name,
                               element=element, derived=derived)
                else:
                    stream.out(template.sequence_forward_unbounded_defns,
                               fqname=fqname, name=name,
                               element=element, derived=derived)

                stream.out(template.sequence_forward_defns,
                           fqname=fqname, name=name, element=element)
Пример #5
0
def operation(interface, operation):
    assert isinstance(operation, idlast.Operation)

    return Callable(interface, operation, operation.identifier(),
                    id.mapID(operation.identifier()), operation.returnType(),
                    operation.parameters(), operation.oneway(),
                    operation.raises(), operation.contexts())
Пример #6
0
def visitModule(node):
    if self.__completedModules.has_key(node):
        return
    self.__completedModules[node] = 1

    name = id.mapID(node.identifier())

    if not config.state['Fragment']:
        stream.out(template.POA_module_begin,
                   name=name,
                   POA_prefix=POA_prefix())
        stream.inc_indent()

    nested = self.__nested
    self.__nested = 1
    for n in node.definitions():
        n.accept(self)

    # Splice the continuations together if splice-modules flag is set
    # (This might be unnecessary as there (seems to be) no relationship
    #  between things in the POA module- they all point back into the main
    #  module?)
    if config.state['Splice Modules']:
        for c in node.continuations():
            for n in c.definitions():
                n.accept(self)
            self.__completedModules[c] = 1

    self.__nested = nested

    if not config.state['Fragment']:
        stream.dec_indent()
        stream.out(template.POA_module_end)
    return
Пример #7
0
def visitTypedef(node):
    aliasType = types.Type(node.aliasType())
    d_type = aliasType.deref()

    if node.constrType():
        aliasType.type().decl().accept(self)

    for d in node.declarators():
        scopedName = id.Name(d.scopedName())
        
        if d_type.sequence() and not aliasType.typedef():
            seqType = types.Type(d_type.type().seqType())
            d_seqType = seqType.deref()

            if d_seqType.structforward() or d_seqType.unionforward():
                fqname  = scopedName.fullyQualify()
                name    = id.mapID(d.identifier())
                element = d_seqType.base()
                bound   = d_type.type().bound()
                derived = d_type.sequenceTemplate()
                
                if bound > 0:
                    stream.out(template.sequence_forward_bounded_defns,
                               bound=bound, fqname=fqname, name=name,
                               element=element, derived=derived)
                else:
                    stream.out(template.sequence_forward_unbounded_defns,
                               fqname=fqname, name=name,
                               element=element, derived=derived)

                stream.out(template.sequence_forward_defns,
                           fqname=fqname, name=name, element=element)
Пример #8
0
    def createArgs(self, operation, env):
        """

        corba:
          base_type:
          arg_type:
          arg_name:
          var_name:
          decl_type:
          direction:
          tk:
        local:
          base_type:
          arg_type:
          arg_name:
          var_name:
          decl_type:
          direction:
          tk:


        """
        args = []
        direction = ['in', 'out', 'inout','return']
        for arg in operation.parameters():
            # corba args information
            dict = self.createDecl('arg')
            cdict = dict['corba']
            ldict = dict['local']

            paramType = types.Type(arg.paramType())
            (corba_type, local_type, is_primitive) = self.getType(paramType)

            cdict['base_type'] = corba_type
            ldict['base_type'] = local_type
            if is_primitive != None:
                cdict['is_primitive'] = is_primitive

            arg_name = id.mapID(arg.identifier())
            cdict['arg_name'] = arg_name
            ldict['arg_name'] = arg_name
            cdict['var_name'] = '_' + arg_name
            ldict['var_name'] = '_' + arg_name

            direction_val = direction[arg.direction()]
            cdict['direction'] = direction_val
            ldict['direction'] = direction_val

            cdict['tk'] = ldict['tk'] = self.tk_map[paramType.kind()]
            arg_type = paramType.op(types.direction(arg), use_out = 0)
            arg_type = arg_type.replace('CORBA', '::CORBA')
            arg_type = arg_type.replace('RTC', '::RTC')
            arg_type = arg_type.replace('SDOPackage', '::SDOPackage')
            arg_type = arg_type.replace('::::', '::')
            cdict['arg_type']  = arg_type
            out = arg.is_out()
            self.createArg(dict, paramType, out)
            args.append(dict)
        return args
Пример #9
0
def read_attributes(interface, attribute):
    assert isinstance(attribute, idlast.Attribute)
    callables = []
    for identifier in attribute.identifiers():
        callables.append(
            Callable(interface, "_get_" + identifier, id.mapID(identifier),
                     attribute.attrType(), [], 0, [], []))
    return callables
Пример #10
0
def visitInterface(node):
    if node.local():
        # No POA class for local interfaces
        return

    iname = id.mapID(node.identifier())
    environment = id.lookup(node)
    scopedName = id.Name(node.scopedName())
    impl_scopedName = scopedName.prefix("_impl_")
    scopedID = scopedName.fullyQualify()
    impl_scopedID = impl_scopedName.fullyQualify()

    POA_name = POA_prefix() + iname

    # deal with inheritance
    inherits = []
    for i in map(ast.remove_ast_typedefs, node.inherits()):
        name = id.Name(i.scopedName())
        i_POA_name = name.unambiguous(environment)

        if name.relName(environment) == None:
            # we need to fully qualify from the root
            i_POA_name = "::POA_" + name.fullyQualify(environment)
            
        elif name.relName(environment) == i.scopedName():
            # fully qualified (but not from root) POA name has a POA_ on the
            # front
            i_POA_name = "POA_" + i_POA_name
            
        inherits.append("public virtual " + i_POA_name)

    # Note that RefCountServantBase is a mixin class specified by the
    # implementor, not generated by the idl compiler.
    if node.inherits() == []:
        inherits.append("public virtual ::PortableServer::ServantBase")

    inherits_str = ",\n  ".join(inherits)

    # build the normal POA class first
    stream.out(template.POA_interface,
               POA_name = POA_name,
               scopedID = scopedID,
               impl_scopedID = impl_scopedID,
               inherits = inherits_str)

    if config.state['Normal Tie']:
        # Normal tie templates, inline (so already in relevant POA_
        # module)
        poa_name = ""
        if len(scopedName.fullName()) == 1:
            poa_name = "POA_"
        poa_name = poa_name + scopedName.simple()
        tie_name = poa_name + "_tie"

        tie.write_template(tie_name, poa_name, node, stream)

    return
Пример #11
0
def visitInterface(node):
    if node.local():
        # No POA class for local interfaces
        return

    iname = id.mapID(node.identifier())
    environment = id.lookup(node)
    scopedName = id.Name(node.scopedName())
    impl_scopedName = scopedName.prefix("_impl_")
    scopedID = scopedName.fullyQualify()
    impl_scopedID = impl_scopedName.fullyQualify()

    POA_name = POA_prefix() + iname

    # deal with inheritance
    inherits = []
    for i in map(ast.remove_ast_typedefs, node.inherits()):
        name = id.Name(i.scopedName())
        i_POA_name = name.unambiguous(environment)

        if name.relName(environment) == None:
            # we need to fully qualify from the root
            i_POA_name = "::POA_" + name.fullyQualify(environment)

        elif name.relName(environment) == i.scopedName():
            # fully qualified (but not from root) POA name has a POA_ on the
            # front
            i_POA_name = "POA_" + i_POA_name

        inherits.append("public virtual " + i_POA_name)

    # Note that RefCountServantBase is a mixin class specified by the
    # implementor, not generated by the idl compiler.
    if node.inherits() == []:
        inherits.append("public virtual ::PortableServer::ServantBase")

    inherits_str = ",\n  ".join(inherits)

    # build the normal POA class first
    stream.out(template.POA_interface,
               POA_name=POA_name,
               scopedID=scopedID,
               impl_scopedID=impl_scopedID,
               inherits=inherits_str)

    if config.state['Normal Tie']:
        # Normal tie templates, inline (so already in relevant POA_
        # module)
        poa_name = ""
        if len(scopedName.fullName()) == 1:
            poa_name = "POA_"
        poa_name = poa_name + scopedName.simple()
        tie_name = poa_name + "_tie"

        tie.write_template(tie_name, poa_name, node, stream)

    return
Пример #12
0
 def createOperation(self, operation):
     dict = {}
     dict['name'] = id.mapID(operation.identifier())
     dict['raises'] = []
     for r in operation.raises():
         edict = self.createDecl('exception')
         self.createExceptionIdent(edict, r)
         dict['raises'].append(edict)
     return dict
Пример #13
0
def visitModule(node):
    name = id.mapID(node.identifier())

    for n in node.definitions():
        nested = self.__nested
        self.__nested = 1

        n.accept(self)

        self.__nested = nested
Пример #14
0
def visitModule(node):
    name = id.mapID(node.identifier())

    for n in node.definitions():
        nested = self.__nested
        self.__nested = 1
        
        n.accept(self)

        self.__nested = nested
Пример #15
0
def visitInterface(node):
    if node.local():
        return
    
    name = id.mapID(node.identifier())
    fqname = id.Name(node.scopedName()).fullyQualify()
    stream.out(template.interface_POA,
               POA_prefix = POA_prefix(),
               name = name,
               fqname = fqname)
Пример #16
0
def read_attributes(interface, attribute):
    assert isinstance(attribute, idlast.Attribute)
    callables = []
    for identifier in attribute.identifiers():
        callables.append(Callable(interface,
                                  "_get_" + identifier,
                                  id.mapID(identifier),
                                  attribute.attrType(),
                                  [], 0, [], []))
    return callables
Пример #17
0
def visitInterface(node):
    if node.local():
        return

    name = id.mapID(node.identifier())
    fqname = id.Name(node.scopedName()).fullyQualify()
    stream.out(template.interface_POA,
               POA_prefix=POA_prefix(),
               name=name,
               fqname=fqname)
Пример #18
0
def operation(interface, operation):
    assert isinstance(operation, idlast.Operation)
    return Callable(interface,
                    operation.identifier(),
                    id.mapID(operation.identifier()),
                    operation.returnType(),
                    operation.parameters(),
                    operation.oneway(),
                    operation.raises(),
                    operation.contexts())
Пример #19
0
def visitTypedef(node):
    environment = id.lookup(node)
    is_global_scope = not (self.__insideModule or self.__insideInterface)

    aliasType = types.Type(node.aliasType())
    d_type = aliasType.deref()

    if node.constrType():
        aliasType.type().decl().accept(self)

    fq_aliased = aliasType.base(environment)

    for d in node.declarators():
        scopedName = id.Name(d.scopedName())

        decl_dims = d.sizes()
        decl_dims_str = cxx.dimsToString(decl_dims)
        decl_first_dim_str = ""
        if decl_dims != []:
            decl_first_dim_str = cxx.dimsToString([decl_dims[0]])

        full_dims = decl_dims + aliasType.dims()
        is_array = full_dims != []
        is_array_declarator = decl_dims != []

        fq_derived = scopedName.fullyQualify()

        if d_type.sequence() and not aliasType.typedef():
            seqType = types.Type(d_type.type().seqType())
            d_seqType = seqType.deref()
            if d_seqType.structforward() or d_seqType.unionforward():
                fqname = scopedName.fullyQualify()
                name = id.mapID(d.identifier())
                element = d_seqType.base()
                bound = d_type.type().bound()
                derived = d_type.sequenceTemplate()

                if (bound > 0):
                    stream.out(template.sequence_forward_bounded_defns,
                               bound=bound,
                               fqname=fqname,
                               name=name,
                               element=element,
                               derived=derived)
                else:
                    stream.out(template.sequence_forward_unbounded_defns,
                               fqname=fqname,
                               name=name,
                               element=element,
                               derived=derived)

                stream.out(template.sequence_forward_defns,
                           fqname=fqname,
                           name=name,
                           element=element)
Пример #20
0
def write_attributes(interface, attribute):
    assert isinstance(attribute, idlast.Attribute)
    voidType = idltype.Base(idltype.tk_void)
    callables = []
    param = idlast.Parameter(attribute.file(), attribute.line(),
                             attribute.mainFile(), [], [], 0,
                             attribute.attrType(), "_v")
    for identifier in attribute.identifiers():
        callables.append(
            Callable(interface, "_set_" + identifier, id.mapID(identifier),
                     voidType, [param], 0, [], []))
    return callables
Пример #21
0
def write_attributes(interface, attribute):
    assert isinstance(attribute, idlast.Attribute)
    voidType = idltype.Base(idltype.tk_void)
    callables = []
    param = idlast.Parameter(attribute.file(), attribute.line(),
                             attribute.mainFile(), [], [],
                             0, attribute.attrType(), "_v")
    for identifier in attribute.identifiers():
        callables.append(Callable(interface,
                                  "_set_" + identifier,
                                  id.mapID(identifier),
                                  voidType, [param], 0, [], []))
    return callables
Пример #22
0
    def createTypedef(self, aliasType, decl, env):
        """
        typedef宣言に関するディクショナリの生成

        corba:
          derived_type:    導出型名
          derived_fq_type: 完全修飾導出型名
          deref_type:      非参照型名
          deref_fq_type:   完全修飾非参型名
          tk: TypeCode
        local:
          derived_type:    導出型名
          derived_fq_type: 完全修飾導出型名
          deref_type:      非参照型名
          deref_fq_type:   完全修飾非参型名
        """

        dict = self.createDecl('typedef')
        cdict = dict['corba']
        ldict = dict['local']

        (cdict['base_type'], ldict['base_type'], is_primitive) = self.getType(aliasType)
        derivedName = id.mapID(decl.identifier())
        alias_dims = aliasType.dims()
        cdict['derived_type'] = derivedName
        ldict['derived_type'] = derivedName

        corba_ns = '::' + string.join(cdict['corba_ns'], '::')
        local_ns = '::' + string.join(ldict['iface_ns'], '::')
        cdict['derived_type_fq'] = corba_ns + '::' + derivedName
        ldict['derived_type_fq'] = local_ns + '::' + derivedName
        cdict['tk'] = tk = self.tk_map[aliasType.kind()]
        primitive = ["tk_short", "tk_long", "tk_ushort", 
                     "tk_ulong", "tk_float", "tk_double",
                     "tk_boolean", "tk_char", "tk_octet"]
        if primitive.count(tk) > 0:
            cdict['is_primitive'] = 'YES'

        if aliasType.sequence():
            seqType = types.Type(aliasType.type().seqType())
            # get type of element of sequence
            (corba_etype, local_etype, is_primitive) = self.getType(seqType)
            cdict['element_tk'] = self.tk_map[seqType.kind()]
            if seqType.objref():
                cdict['element_type_fq'] = corba_etype
                ldict['element_type_fq'] = local_etype + '*'
            else:
                cdict['element_type_fq'] = corba_etype
                ldict['element_type_fq'] = local_etype
        return dict
Пример #23
0
    def createIdent(self, dict, node):
        """
        宣言の識別子に関するディクショナリの生成
        主に、識別子のIDL、C++、Local名を生成する
        createDeclで生成したディクショナリとnodeを引数に取る

        corba:
          idl_name:       宣言のidl上の識別子
          name:           C++にマッピングされた識別子
          name_fq:        C++識別子の完全修飾名
          scoped_name: [] リスト形式の完全修飾名
        local:
          idl_name:       宣言のidl上の識別子
          name:           C++にマッピングされた識別子
          name_fq:        C++識別子の完全修飾名
          scoped_name: [] リスト形式の完全修飾名

        """
        cdict = dict['corba']
        ldict = dict['local']

        cdict['idl_name'] = idl_name = node.identifier()
        cdict['name'] = cxx_name = id.mapID(idl_name)
        ns = node.scopedName()[:-1]
        cdict['corba_ns'] = ns
        ldict['iface_ns'] = ns + self.config['IfaceNs']
        ldict['adapter_ns'] = ns + self.config['AdapterNs']
        ldict['proxy_ns'] = ns + self.config['ProxyNs']
        ldict['servant_ns'] = ns + self.config['ServantNs']
        cxx_fq_name = id.Name(node.scopedName()).fullyQualify()
        cdict['name_fq'] = '::' + cxx_fq_name
        cdict['scoped_name'] = node.scopedName()

        iface_ns = '::' + string.join(ldict['iface_ns'], '::')

        if self.typemap.has_key(cxx_fq_name):
            local_fq_name = self.typemap[cxx_fq_name]
            local_name = local_fq_name.split('::')[-1]
        elif self.corba_primitive.has_key(cxx_fq_name):
            local_fq_name = self.corba_primitive[cxx_fq_name]
            local_name    = local_fq_name
        else:
            local_name = cxx_name
            local_fq_name = iface_ns + '::' + local_name

        ldict['name'] = local_name
        ldict['name_fq'] = local_fq_name
        ldict['scoped_name'] = ldict['iface_ns'] + [local_name]
        return dict
Пример #24
0
def visitTypedef(node):
    environment = id.lookup(node)
    is_global_scope = not (self.__insideModule or self.__insideInterface)

    aliasType = types.Type(node.aliasType())
    d_type = aliasType.deref()

    if node.constrType():
        aliasType.type().decl().accept(self)

    fq_aliased = aliasType.base(environment)

    for d in node.declarators():
        scopedName = id.Name(d.scopedName())
        
        decl_dims = d.sizes()
        decl_dims_str = cxx.dimsToString(decl_dims)
        decl_first_dim_str = ""
        if decl_dims != []:
            decl_first_dim_str = cxx.dimsToString([decl_dims[0]])
        
        full_dims = decl_dims + aliasType.dims()
        is_array = full_dims != []
        is_array_declarator = decl_dims != []

        fq_derived = scopedName.fullyQualify()

        if d_type.sequence() and not aliasType.typedef():
            seqType = types.Type(d_type.type().seqType())
            d_seqType = seqType.deref()
            if d_seqType.structforward() or d_seqType.unionforward():
                fqname  = scopedName.fullyQualify()
                name    = id.mapID(d.identifier())
                element = d_seqType.base()
                bound   = d_type.type().bound()
                derived = d_type.sequenceTemplate()
                
                if (bound > 0):
                    stream.out(template.sequence_forward_bounded_defns,
                               bound=bound, fqname=fqname, name=name,
                               element=element, derived=derived)
                else:
                    stream.out(template.sequence_forward_unbounded_defns,
                               fqname=fqname, name=name,
                               element=element, derived=derived)

                stream.out(template.sequence_forward_defns,
                           fqname=fqname, name=name, element=element)
Пример #25
0
    def createMembers(self, dict, node):
        corba_name = dict['corba']['name']
        outer_environment = id.lookup(node)
        environment = outer_environment.enter(id.mapID(corba_name))
        scope = environment.scope()

        members = []
        for member in node.members():
            #------------------------------------------------------------
            # member
            # - type_d: type of a member
            # - decl_d: decralation list
            memberType = types.Type(member.memberType())

#            self.createType(memberType, environment)
            memtype = memberType.member(environment)
            for decl in member.declarators():
                m = self.createMember(decl, member, environment)
                if m != None:
                    members.append(m)
        dict['members'] = members
        return dict
Пример #26
0
    def _from_Callable(self, use_out):
        # Grab the IDL environment
        ifc = self.callable().interface()
        environment = ifc.environment().enter("_objref_" + ifc.name().simple())

        # Kept as a type object because in .cc part the _return_ type
        # must be fully qualified.
        self._return_type = types.Type(self.callable().returnType())

        # Parameters are always relative, both in .hh and .cc
        (param_types, param_names) = ([], [])
        for p in self.callable().parameters():
            pType = types.Type(p.paramType())
            direction = types.direction(p)
            param_types.append(pType.op(direction, environment,
                                        use_out = use_out))

            # Special ugly case. If the IDL says something like (in foo::bar
            # bar), the parameter name may be the same as the relative type
            # name. We mangle the parameter name if this happens.

            typeBase = pType.base(environment)
            ident    = id.mapID(p.identifier())

            if typeBase == ident:
                ident = "_" + ident

            param_names.append(ident)
            
        # an operation has optional context
        if self.callable().contexts() != []:
            param_types.append("::CORBA::Context_ptr")
            param_names.append("_ctxt")

        self._arg_types = param_types
        self._arg_names = param_names
        self._name = self.callable().method_name()
Пример #27
0
    def _from_Callable(self, use_out):
        # Grab the IDL environment
        ifc = self.callable().interface()
        environment = ifc.environment().enter("_objref_" + ifc.name().simple())

        # Kept as a type object because in .cc part the _return_ type
        # must be fully qualified.
        self._return_type = types.Type(self.callable().returnType())

        # Parameters are always relative, both in .hh and .cc
        (param_types, param_names) = ([], [])
        for p in self.callable().parameters():
            pType = types.Type(p.paramType())
            direction = types.direction(p)
            param_types.append(
                pType.op(direction, environment, use_out=use_out))

            # Special ugly case. If the IDL says something like (in foo::bar
            # bar), the parameter name may be the same as the relative type
            # name. We mangle the parameter name if this happens.

            typeBase = pType.base(environment)
            ident = id.mapID(p.identifier())

            if typeBase == ident:
                ident = "_" + ident

            param_names.append(ident)

        # an operation has optional context
        if self.callable().contexts() != []:
            param_types.append("::CORBA::Context_ptr")
            param_names.append("_ctxt")

        self._arg_types = param_types
        self._arg_names = param_names
        self._name = self.callable().method_name()
Пример #28
0
    def visitInterface(self, node):
        self.__allInterfaces.append(node)

        scopedName = id.Name(node.scopedName())

        cxx_fqname = scopedName.fullyQualify()
        impl_flat_name = impl_fullname(scopedName)

        fqname = scopedName.fullyQualify(cxx=0)

        # build methods corresponding to attributes, operations etc.
        # attributes[] and operations[] will contain lists of function
        # signatures eg
        #   [ char *echoString(const char *mesg) ]
        attributes = []

        # we need to consider all callables, including inherited ones
        # since this implementation class is not inheriting from anywhere
        # other than the IDL skeleton
        allInterfaces = [node] + ast.allInherits(node)

        allCallables = []
        for intf in allInterfaces:
            allCallables.extend(intf.callables())

        # declarations[] contains a list of in-class decl signatures
        # implementations[] contains a list of out of line impl signatures
        # (typically differ by classname::)
        declarations = []
        implementations = []

        for c in allCallables:
            if isinstance(c, idlast.Attribute):
                attrType = types.Type(c.attrType())

                for i in c.identifiers():
                    attribname = id.mapID(i)
                    returnType = attrType.op(types.RET)
                    inType = attrType.op(types.IN)
                    attributes.append(returnType + " " + attribname + "()")

                    # need a set method if not a readonly attribute
                    if not c.readonly():
                        args = attribname + "(" + inType + ")"
                        declarations.append("void " + args)
                        implementations.append("void " + impl_flat_name +\
                                               "::" + args)
                    declarations.append(returnType + " " + attribname + "()")
                    implementations.append(returnType + " " + impl_flat_name+\
                                           "::" + attribname + "()")

            elif isinstance(c, idlast.Operation):
                params = []
                for p in c.parameters():
                    paramType = types.Type(p.paramType())
                    cxx_type = paramType.op(types.direction(p), use_out=0)

                    argname = id.mapID(p.identifier())
                    params.append(cxx_type + " " + argname)

                # deal with possible "context"
                if c.contexts() != []:
                    params.append("CORBA::Context_ptr _ctxt")

                return_type = types.Type(c.returnType()).op(types.RET)

                opname = id.mapID(c.identifier())
                arguments = ", ".join(params)
                args = opname + "(" + arguments + ")"
                declarations.append(return_type + " " + args + ";")
                implementations.append(return_type + " " + impl_flat_name +
                                       "::" + args)
            else:
                util.fatalError("Internal error generating interface member")

        # the class definition has no actual code...
        defs = "\n".join(declarations)

        # Output the _i class definition definition
        self.stream.out(template.interface_def,
                        impl_fqname=impl_flat_name,
                        impl_name=impl_flat_name,
                        fq_name=fqname,
                        fq_POA_name="POA_" + cxx_fqname,
                        operations=defs)

        # Output the implementations of the class methods
        impls = "".join([
            """\
%s
{
  // insert code here and remove the warning
  #warning "Code missing in function <%s>"
}

""" % (impl, impl) for impl in implementations
        ])

        self.stream.out(template.interface_code,
                        fqname=fqname,
                        impl_name=impl_flat_name,
                        impl_fqname=impl_flat_name,
                        operations=impls)
Пример #29
0
    def buildCallables(interface, where, continuation, defined_so_far={}):
        interface = ast.remove_ast_typedefs(interface)

        callables = interface.callables()
        operations = filter(lambda x: isinstance(x, idlast.Operation),
                            callables)
        for operation in operations:
            returnType = types.Type(operation.returnType())
            identifier = operation.identifier()
            if (defined_so_far.has_key(identifier)):
                # don't repeat it
                continue
            defined_so_far[identifier] = 1

            parameters = operation.parameters()
            has_return_value = not returnType.void()
            # FIXME: return types are fully scoped but argument types
            # arent?
            returnType_name = returnType.op(types.RET)

            operation_name = id.mapID(identifier)

            signature = []
            call = []

            for parameter in parameters:
                paramType = types.Type(parameter.paramType())
                # Need to call the _impl operation not the _objref operation
                param_type_name = paramType.op(types.direction(parameter),
                                               use_out=0)
                param_id = id.mapID(parameter.identifier())
                signature.append(param_type_name + " " + param_id)
                call.append(param_id)

            # deal with call contextx
            if operation.contexts() != []:
                signature.append("::CORBA::Context_ptr _ctxt")
                call.append("_ctxt")

            if has_return_value:
                return_str = "return "
            else:
                return_str = ""

            where.out("""\
@return_type_name@ @operation_name@(@signature@) { @return_str@pd_obj->@operation_name@(@call@); }""",
                      return_type_name=returnType_name,
                      operation_name=operation_name,
                      return_str=return_str,
                      signature=", ".join(signature),
                      call=", ".join(call))

        attributes = filter(lambda x: isinstance(x, idlast.Attribute),
                            callables)
        for attribute in attributes:
            identifiers = attribute.identifiers()
            attrType = types.Type(attribute.attrType())

            attrType_name_RET = attrType.op(types.RET)
            attrType_name_IN = attrType.op(types.IN)

            for identifier in identifiers:
                if defined_so_far.has_key(identifier):
                    # don't repeat it
                    continue
                defined_so_far[identifier] = 1

                ident = id.mapID(identifier)
                where.out("""\
@attr_type_ret_name@ @attribute_name@() { return pd_obj->@attribute_name@(); }""",
                          attr_type_ret_name=attrType_name_RET,
                          attribute_name=ident)

                if not attribute.readonly():
                    where.out("""\
void @attribute_name@(@attr_type_in_name@ _value) { pd_obj->@attribute_name@(_value); }""",
                              attribute_name=ident,
                              attr_type_in_name=attrType_name_IN)
        # do the recursive bit
        for i in interface.inherits():
            i = i.fullDecl()
            continuation(i, where, continuation, defined_so_far)

        # done
        return
Пример #30
0
 def createAttribute(self, ident):
     dict = {}
     dict['name'] = id.mapID(ident)
     return dict
Пример #31
0
def visitException(node):
    scopedName = id.Name(node.scopedName())
    name = scopedName.simple()
    cxx_name = id.mapID(name)
    
    outer_environment = id.lookup(node)
    environment = outer_environment.enter(name)
    
    scoped_name = scopedName.fullyQualify()

    # build the default ctor, copy ctor, assignment operator
    copy_ctor_body = output.StringStream()
    default_ctor_body = output.StringStream()
    default_ctor_args = []
    assign_op_body = output.StringStream()
    has_default_ctor = 0

    for m in node.members():
        has_default_ctor = 1
        memberType = types.Type(m.memberType())
        if m.constrType():
            memberType.type().decl().accept(self)
        d_memberType = memberType.deref()

        memberType_fqname = memberType.base()
            
        for d in m.declarators():
            decl_scopedName = id.Name(d.scopedName())
            decl_name = decl_scopedName.simple()
            
            decl_dims = d.sizes()
            full_dims = decl_dims + memberType.dims()
            is_array = full_dims != []
            is_array_declarator = decl_dims != []

            memberType_name_arg = memberType.op(types.IN, environment)

            if is_array_declarator:
                # we use the internal typedef'ed type if the member is an array
                # declarator
                memberType_name_arg = "const "                       +\
                                      config.state['Private Prefix'] +\
                                      "_" + decl_name
            elif d_memberType.sequence():
                if memberType.typedef():
                    memberType_name_arg = "const " + id.Name(memberType.type().decl().scopedName()).unambiguous(environment)
                else:
                    memberType_name_arg = "const " + memberType.sequenceTemplate(environment)
            elif memberType.typecode():
                memberType_name_arg = "::CORBA::TypeCode_ptr"
                
            index = ""

            if is_array:
                blocks = [cxx.Block(copy_ctor_body),
                          cxx.Block(default_ctor_body),
                          cxx.Block(assign_op_body)]
                loops = [cxx.For(copy_ctor_body, full_dims),
                         cxx.For(default_ctor_body, full_dims),
                         cxx.For(assign_op_body, full_dims)]
                index = loops[0].index() # all the same

            copy_ctor_body.out("""\
@member_name@@index@ = _s.@member_name@@index@;""", member_name = decl_name,
                               index = index)

            if (d_memberType.interface() and not is_array):

                # these are special resources which need to be explicitly
                # duplicated (but not if an array?)
                duplicate = string.replace(memberType_fqname,"_ptr","") + \
                            "::_duplicate"
                if isinstance(d_memberType.type().decl(),idlast.Forward):
                    duplicate = string.replace(duplicate,"::_dup",\
                                               "_Helper::dup")
                default_ctor_body.out("""\
@duplicate@(_@member_name@@index@);""",
                                      duplicate = duplicate,
                                      member_name = decl_name,
                                      index = index)
            
            default_ctor_args.append(memberType_name_arg + " _" + decl_name)
            default_ctor_body.out("""\
@member_name@@index@ = _@member_name@@index@;""", member_name = decl_name,
                                  index = index)

            assign_op_body.out("""\
@member_name@@index@ = _s.@member_name@@index@;""", member_name = decl_name,
                               index = index)
            
            if is_array:
                for loop in loops: loop.end()
                for block in blocks: block.end()
          
        
    default_ctor = output.StringStream()
    if has_default_ctor:
        default_ctor.out(template.exception_default_ctor,
                         scoped_name = scoped_name,
                         name = name,
                         ctor_args = string.join(default_ctor_args, ", "),
                         default_ctor_body = str(default_ctor_body))

    # write the main chunk
    stream.out(template.exception,
               scoped_name = scoped_name,
               name = name,
               copy_ctor_body = str(copy_ctor_body),
               default_ctor = str(default_ctor),
               ctor_args = string.join(default_ctor_args, ", "),
               default_ctor_body = str(default_ctor_body),
               repoID = node.repoId(),
               assign_op_body = str(assign_op_body))
    

    # deal with marshalling and demarshalling
    needs_marshalling = node.members() != []
    marshal = output.StringStream()
    unmarshal = output.StringStream()
    
    for m in node.members():
        memberType = types.Type(m.memberType())
        d_memberType = memberType.deref()
        for d in m.declarators():
            decl_scopedName = id.Name(d.scopedName())
            decl_name = decl_scopedName.simple()
            is_array_declarator = d.sizes() != []
            
            skutil.unmarshall(unmarshal, environment,
                              memberType, d, decl_name, "_n")

            skutil.marshall(marshal, environment,
                            memberType, d, decl_name, "_n")

    if needs_marshalling:
        stream.out(template.exception_operators,
                   scoped_name = scoped_name,
                   marshal = str(marshal),
                   unmarshal = str(unmarshal))


    return
Пример #32
0
    def visitInterface(self, node):
        scopedName = id.Name(node.scopedName())
        openns, closens = namespaces(scopedName, self.environment)
        
        impl_name = scopedName.simple(cxx=1)
        impl_tpl_name = impl_tplname (scopedName)
        cxx_fqname = scopedName.fullyQualify()
        hpp_class = self.toCppNamespace (scopedName).fullyQualify(cxx=1)

        fqname = scopedName.fullyQualify(cxx = 0)

        is_base_class = not bool(node.inherits())
        ptr_t = self.toCppNamespace (scopedName.suffix("Ptr_t")).fullyQualify(cxx=1)
        if is_base_class:
            key = hpp_servant_name (scopedName)
            impl_base_name = "ServantBase"
            if key in self.storages:
                st = self.storages[key]
                # declare storage
                self.interface_declarations.out(st.decl)
                storage = st.sc.simple() + "< "+ptr_t+" >"
            else:
                storage = ptr_t
        else:
            baseScopedName = id.Name (node.inherits()[0].scopedName())
            key = hpp_servant_name (baseScopedName)
            impl_base_name = hpp_servant_name (baseScopedName.suffix('Servant'))
            if key in self.storages:
                st = self.storages[key]
                storage = st.sc.simple() + "< "+ptr_t+" >"
                self.storages[fqname] = st
            else:
                storage = ptr_t
        
        # build methods corresponding to attributes, operations etc.
        # attributes[] and operations[] will contain lists of function
        # signatures eg
        #   [ char *echoString(const char *mesg) ]
        attributes = []
        operations = []

        allCallables = node.callables()

        # declarations contains a list of in-class decl signatures
        # implementations contains a list of out of line impl signatures
        # (typically differ by classname::)
        declarations = output.StringStream()
        implementations = output.StringStream()
        
        for c in allCallables:
            comments = c.comments()
            hpp_opname = None
            comments_impl = []
            for comment in comments:
                if comment.text().startswith("// ") or comment.text().startswith("///"):
                    # Skip this comment
                    pass
                elif comment.text().startswith("//*"):
                    if not comments_impl:
                        comments_impl.append (" // generated from {}:{}\n".format(node.file(), node.line()))
                    comments_impl.append (comment.text()[3:])
                elif comment.text().startswith("//->"):
                    if hpp_opname is not None: raise makeError("Function was already renamed", comment.file(), comment.line())
                    hpp_opname = comment.text()[4:].strip()

            if isinstance(c, idlast.Attribute):
                attrType = types.Type(c.attrType())
                d_attrType = attrType.deref()

                for i in c.identifiers():
                    attribname = id.mapID(i)
                    returnType = attrType.op(types.RET)
                    inType = attrType.op(types.IN)
                    attributes.append(returnType + " " + attribname + "()")
                    # need a set method if not a readonly attribute
                    if not c.readonly():
                        declarations.out (template.operation_decl_code,
                                return_type = "void",
                                opname = attribname,
                                arg_defs = inType + " _" + attribname)

                        tmpVar, in_conv, out_conv = self.argConversion ("_" + attribname, attrType, True, False, c)
                        implementations.out (template.operation_impl_code,
                                return_type = "void",
                                impl_tpl_name = impl_tpl_name,
                                opname = attribname,
                                hpp_opname = hpp_opname if hpp_opname else attribname,
                                arg_defs = inType + " _" + attribname,
                                in_conversions = in_conv if in_conv else "",
                                out_conversions = out_conv if out_conv else "",
                                store_return = "",
                                do_return = "",
                                arg_calls = tmpVar)

                    declarations.out (template.operation_decl_code,
                            return_type = returnType,
                            opname = attribname,
                            arg_defs = "")

                    store_return, do_return = self.retConversion (attrType)
                    implementations.out (template.operation_impl_code,
                            return_type = returnType,
                            impl_tpl_name = impl_tpl_name,
                            opname = attribname,
                            hpp_opname = hpp_opname if hpp_opname else attribname,
                            arg_defs = "",
                            in_conversions = "",
                            out_conversions = "",
                            store_return = store_return,
                            do_return = do_return,
                            arg_calls = "")
            elif isinstance(c, idlast.Operation):
                params = []
                paramNames = []
                in_conversions = []
                out_conversions = []
                for p in c.parameters():
                    paramType = types.Type(p.paramType())
                    cxx_type = paramType.op(types.direction(p), use_out = 0)
                    
                    argname = id.mapID(p.identifier())
                    if not comments_impl:
                        tmpVar, in_conv, out_conv = self.argConversion (argname, paramType, p.is_in(), p.is_out(), p)
                        if in_conv:
                            in_conversions.append(in_conv)
                        if out_conv:
                            out_conversions.append(out_conv)
                    else:
                        tmpVar = argname

                    params.append(cxx_type + " " + argname)
                    paramNames.append(tmpVar)


                # deal with possible "context"
                if c.contexts() != []:
                    params.append("CORBA::Context_ptr _ctxt")

                store_return, do_return = self.retConversion (types.Type(c.returnType()))
                return_type = types.Type(c.returnType()).op(types.RET)

                opname = id.mapID(c.identifier())
                arguments = ", ".join(params)
                argumentsCall = ", ".join(paramNames)
                args = opname + "(" + arguments + ")"

                declarations.out (template.operation_decl_code,
                        return_type = return_type,
                        opname = opname,
                        arg_defs = arguments)

                if comments_impl:
                    implementations.out (template.provided_operation_impl_code,
                            return_type = return_type,
                            impl_tpl_name = impl_tpl_name,
                            opname = opname,
                            implementation = "".join(comments_impl),
                            arg_defs = arguments,)
                elif opname in template.predefined_operations_impl_code:
                    #assert not c.parameters(), "Interface operation str should not have arguments"
                    implementations.out (template.predefined_operations_impl_code[opname],
                            return_type = return_type,
                            impl_tpl_name = impl_tpl_name,
                            opname = opname,
                            conversions = "\n  ".join(in_conversions),
                            arg_defs = arguments,
                            store_return = store_return,
                            do_return = do_return,
                            arg_calls = argumentsCall)
                else:
                    implementations.out (template.operation_impl_code,
                            return_type = return_type,
                            impl_tpl_name = impl_tpl_name,
                            opname = opname,
                            hpp_opname = hpp_opname if hpp_opname is not None else opname,
                            in_conversions = "\n  ".join(in_conversions),
                            out_conversions = "\n  ".join(out_conversions),
                            arg_defs = arguments,
                            store_return = store_return,
                            do_return = do_return,
                            arg_calls = argumentsCall)

            else:
                util.fatalError("Internal error generating interface member")
                raise AssertionError("No code for interface member: "+repr(c))

        openns, closens = namespaces(scopedName, self.environment)

        # Output the _i class definition definition
        self.interface_declarations.out(
                template.base_interface_def if is_base_class else template.inherited_interface_def,
                fq_name = fqname,
                impl_tpl_name = impl_tpl_name,
                impl_base_name = impl_base_name,
                operations = str(declarations),
                impl_name = impl_name,
                fq_POA_name = "POA_" + cxx_fqname,

                hpp_class = hpp_class,
                storage = storage,
                open_namespaces = openns,
                close_namespaces = closens,
                )

        self.interface_implementations.out(
                template.base_interface_code if is_base_class else template.inherited_interface_code,
                fqname = fqname,
                impl_name = impl_name,
                impl_tpl_name = impl_tpl_name,
                impl_base_name = impl_base_name,
                hpp_class = hpp_class,
                operations = str(implementations),
                open_namespaces = openns,
                close_namespaces = closens,
                )
Пример #33
0
    def visitInterface(self, node):
        self.__allInterfaces.append(node)
    
        scopedName = id.Name(node.scopedName())
        
        cxx_fqname = scopedName.fullyQualify()
        impl_flat_name = impl_fullname(scopedName)

        fqname = scopedName.fullyQualify(cxx = 0)

        
        # build methods corresponding to attributes, operations etc.
        # attributes[] and operations[] will contain lists of function
        # signatures eg
        #   [ char *echoString(const char *mesg) ]
        attributes = []

        # we need to consider all callables, including inherited ones
        # since this implementation class is not inheriting from anywhere
        # other than the IDL skeleton
        allInterfaces = [node] + ast.allInherits(node)

        allCallables = []
        for intf in allInterfaces:
            allCallables.extend(intf.callables())

        # declarations[] contains a list of in-class decl signatures
        # implementations[] contains a list of out of line impl signatures
        # (typically differ by classname::)
        declarations = []
        implementations = []
        
        for c in allCallables:
            if isinstance(c, idlast.Attribute):
                attrType = types.Type(c.attrType())

                for i in c.identifiers():
                    attribname = id.mapID(i)
                    returnType = attrType.op(types.RET)
                    inType = attrType.op(types.IN)
                    attributes.append(returnType + " " + attribname + "()")

                    # need a set method if not a readonly attribute
                    if not c.readonly():
                        args = attribname + "(" + inType + ")"
                        declarations.append("void " + args)
                        implementations.append("void " + impl_flat_name +\
                                               "::" + args)
                    declarations.append(returnType + " " + attribname + "()")
                    implementations.append(returnType + " " + impl_flat_name+\
                                           "::" + attribname + "()")

            elif isinstance(c, idlast.Operation):
                params = []
                for p in c.parameters():
                    paramType = types.Type(p.paramType())
                    cxx_type = paramType.op(types.direction(p), use_out = 0)
                    
                    argname = id.mapID(p.identifier())
                    params.append(cxx_type + " " + argname)

                # deal with possible "context"
                if c.contexts() != []:
                    params.append("CORBA::Context_ptr _ctxt")

                return_type = types.Type(c.returnType()).op(types.RET)

                opname = id.mapID(c.identifier())
                arguments = ", ".join(params)
                args = opname + "(" + arguments + ")"
                declarations.append(return_type + " " + args + ";")
                implementations.append(return_type + " " + impl_flat_name +
                                       "::" + args)
            else:
                util.fatalError("Internal error generating interface member")

        # the class definition has no actual code...
        defs = "\n".join(declarations)

        # Output the _i class definition definition
        self.stream.out(template.interface_def,
                        impl_fqname = impl_flat_name,
                        impl_name = impl_flat_name,
                        fq_name = fqname,
                        fq_POA_name = "POA_" + cxx_fqname,
                        operations = defs)

        # Output the implementations of the class methods
        impls = "".join([ """\
%s
{
  // insert code here and remove the warning
  #warning "Code missing in function <%s>"
}

""" % (impl,impl) for impl in implementations ])
               
        self.stream.out(template.interface_code,
                        fqname = fqname,
                        impl_name = impl_flat_name,
                        impl_fqname = impl_flat_name,
                        operations = impls)
Пример #34
0
	def visitInterface(self, node):
		self.__allInterfaces.append(node)
	
		scopedName = id.Name(node.scopedName())
		
		cxx_fqname = scopedName.fullyQualify()
		impl_flat_name = impl_fullname(scopedName)

		fqname = scopedName.fullyQualify(cxx = 0)

		
		# build methods corresponding to attributes, operations etc.
		# attributes[] and operations[] will contain lists of function
		# signatures eg
		#   [ char *echoString(const char *mesg) ]
		attributes = []
		operations = []
		virtual_operations = []

		# we need to consider all callables, including inherited ones
		# since this implementation class is not inheriting from anywhere
		# other than the IDL skeleton
		allInterfaces = [node] + ast.allInherits(node)
		allCallables = util.fold( map(lambda x:x.callables(), allInterfaces),
								  [], lambda x, y: x + y )


		# declarations[] contains a list of in-class decl signatures
		# implementations[] contains a list of out of line impl signatures
		# (typically differ by classname::)
		declarations = []
		implementations = []
		
		for c in allCallables:

			if isinstance(c, idlast.Attribute) :
				attrType = types.Type(c.attrType())
				d_attrType = attrType.deref()

				for i in c.identifiers():
					attribname = id.mapID(i)
					returnType = attrType.op(types.RET)
					inType = attrType.op(types.IN)
					attributes.append(returnType + " " + attribname + "()")
					# need a set method if not a readonly attribute
					if not c.readonly():
						args = attribname + "(" + inType + ")"
						declarations.append("void " + args)
						implementations.append("void " + impl_flat_name +\
											   "::" + args)
					if not attribname in self.ignore_operations:
						declarations.append(returnType + " " + attribname + "()")
						implementations.append(returnType + " " + impl_flat_name+\
										   "::" + attribname + "()")
			elif isinstance(c, idlast.Operation):
				params = []
				for p in c.parameters():
					paramType = types.Type(p.paramType())
					cxx_type = paramType.op(types.direction(p), use_out = 0)
					
					argname = id.mapID(p.identifier())
					params.append(cxx_type + " " + argname)

				# deal with possible "context"
				if c.contexts() != []:
					params.append("CORBA::Context_ptr _ctxt")

				return_type = types.Type(c.returnType()).op(types.RET)

				opname = id.mapID(c.identifier())
				if not opname in self.ignore_operations:
					arguments = string.join(params, ", ")
					args = opname + "(" + arguments + ")"
					declarations.append(return_type + " " + args)
					implementations.append(return_type + " " + \
										   impl_flat_name + \
										   "::" + args)
			else:
				util.fatalError("Internal error generating interface member")
				raise "No code for interface member: " + repr(c)

		# the class definition has no actual code...
		defs = string.join(map(lambda x:x + ";\n", declarations), "")

		# Output the class definition of the implementation
		self.stream_h.out(interface_def,
						  impl_fqname = impl_flat_name,
						  impl_name = impl_flat_name,
						  fq_name = fqname,
						  fq_POA_name = "POA_" + cxx_fqname,
						  operations = defs)

		# Output the class methods implementations
		impls = string.join(map(lambda x: x + """\

{
  // Please insert your code here and remove the following warning pragma
#ifndef WIN32
  #warning "Code missing in function <""" + x + """>"
#endif
}

""",
								implementations), "")
		
		self.stream_cpp.out(interface_code,
							fqname = fqname,
							impl_name = impl_flat_name,
							impl_fqname = impl_flat_name,
							operations = impls)
Пример #35
0
    def visitInterface(self, node):
        self.__allInterfaces.append(node)
        # listed scope and interface name
        dict = self.createDecl('interface')
        self.createInterfaceIdent(dict, node)
        self.createInterfaceFileInfo(dict, node)

        dict['inherits'] = []
        for ihnode in ast.allInherits(node):
            idict = self.createDecl('inherit')
            self.createInterfaceIdent(idict, ihnode)
            self.createInterfaceFileInfo(idict, ihnode)
            dict['inherits'].append(idict)

        env = id.lookup(node)

        allInterfaces = [node]# + ast.allInherits(node)
        allCallables = util.fold( map(lambda x:x.callables(), allInterfaces),
                                  [], lambda x, y: x + y )

        dict['operations'] = []
        dict['attributes'] = []
        for c in allCallables:
            if isinstance(c, idlast.Attribute):
                attrType = types.Type(c.attrType())
                d_attrType = attrType.deref()
                (corba_atype, local_atype, is_primitive) = self.getType(attrType)

                for i in c.identifiers():
                    ident = id.mapID(i)
                    returnType = attrType.op(types.RET)
                    inType = attrType.op(types.IN)

                    adict = createDecl('attribute')
                    cdict = adict['corba']
                    ldict = adict['local']
                    cdict['base_type'] = corba_atype;
                    ldict['base_type'] = local_atype
                    cdict['name'] = ident
                    adict['return'] = self.createReturn(c)
                    adict['arg'] = {}
                    self.createArg(adict['arg'], attrType, False)

                    dict['attributes'].append(adict)
                    if c.readonly():
                        dict['readonly'] = 'yes'
                    dict['attributes'].append(gdict)

            elif isinstance(c, idlast.Operation):
                # operations
                op_dict           = self.createOperation(c)
                op_dict['return'] = self.createReturn(c)
                op_dict['args']   = self.createArgs(c, env)
                dict['operations'].append(op_dict)
            else:
                util.fatalError("Internal error generating interface member")
                raise "No code for interface member: " + repr(c)

#        self.dict['interfaces'].append(dict)
        self.dict['tree'].append(dict)
        return
Пример #36
0
    def visitInterface(self, node):
        scopedName = id.Name(node.scopedName())
        openns, closens = namespaces(scopedName, self.environment)
        
        impl_name = scopedName.simple(cxx=1)
        impl_tpl_name = impl_tplname (scopedName)
        cxx_fqname = scopedName.fullyQualify()
        hpp_class = self.toCppNamespace (scopedName).fullyQualify(cxx=1)

        fqname = scopedName.fullyQualify(cxx = 0)

        is_base_class = not bool(node.inherits())
        ptr_t = self.toCppNamespace (scopedName.suffix("Ptr_t")).fullyQualify(cxx=1)
        if is_base_class:
            key = hpp_servant_name (scopedName)
            impl_base_name = "ServantBase"
            if key in self.storages:
                st = self.storages[key]
                # declare storage
                self.interface_declarations.out(st.decl)
                storage = st.sc.simple() + "< "+ptr_t+" >"
            else:
                storage = ptr_t
        else:
            baseScopedName = id.Name (node.inherits()[0].scopedName())
            key = hpp_servant_name (baseScopedName)
            impl_base_name = hpp_servant_name (baseScopedName.suffix('Servant'))
            if key in self.storages:
                st = self.storages[key]
                storage = st.sc.simple() + "< "+ptr_t+" >"
                self.storages[fqname] = st
            else:
                storage = ptr_t
        
        # build methods corresponding to attributes, operations etc.
        # attributes[] and operations[] will contain lists of function
        # signatures eg
        #   [ char *echoString(const char *mesg) ]
        attributes = []
        operations = []

        allCallables = node.callables()

        # declarations contains a list of in-class decl signatures
        # implementations contains a list of out of line impl signatures
        # (typically differ by classname::)
        declarations = output.StringStream()
        implementations = output.StringStream()
        
        for c in allCallables:
            comments = c.comments()
            hpp_opname = None
            comments_impl = []
            for comment in comments:
                if comment.text().startswith("// ") or comment.text().startswith("///"):
                    # Skip this comment
                    pass
                elif comment.text().startswith("//*"):
                    if not comments_impl:
                        comments_impl.append (" // generated from {}:{}\n".format(node.file(), node.line()))
                    comments_impl.append (comment.text()[3:])
                elif comment.text().startswith("//->"):
                    if hpp_opname is not None: raise makeError("Function was already renamed", comment.file(), comment.line())
                    hpp_opname = comment.text()[4:].strip()

            if isinstance(c, idlast.Attribute):
                attrType = types.Type(c.attrType())
                d_attrType = attrType.deref()

                for i in c.identifiers():
                    attribname = id.mapID(i)
                    returnType = attrType.op(types.RET)
                    inType = attrType.op(types.IN)
                    attributes.append(returnType + " " + attribname + "()")
                    # need a set method if not a readonly attribute
                    if not c.readonly():
                        declarations.out (template.operation_decl_code,
                                return_type = "void",
                                opname = attribname,
                                arg_defs = inType + " _" + attribname)

                        tmpVar, conv = self.argConversion ("_" + attribname, attrType, True, False, c)
                        implementations.out (template.operation_impl_code,
                                return_type = "void",
                                impl_tpl_name = impl_tpl_name,
                                opname = attribname,
                                hpp_opname = hpp_opname if hpp_opname else attribname,
                                arg_defs = inType + " _" + attribname,
                                conversions = conv if conv else "",
                                store_return = "",
                                do_return = "",
                                arg_calls = tmpVar)

                    declarations.out (template.operation_decl_code,
                            return_type = returnType,
                            opname = attribname,
                            arg_defs = "")

                    store_return, do_return = self.retConversion (attrType)
                    implementations.out (template.operation_impl_code,
                            return_type = returnType,
                            impl_tpl_name = impl_tpl_name,
                            opname = attribname,
                            hpp_opname = hpp_opname if hpp_opname else attribname,
                            arg_defs = "",
                            conversions = "",
                            store_return = store_return,
                            do_return = do_return,
                            arg_calls = "")
            elif isinstance(c, idlast.Operation):
                params = []
                paramNames = []
                conversions = []
                for p in c.parameters():
                    paramType = types.Type(p.paramType())
                    cxx_type = paramType.op(types.direction(p), use_out = 0)
                    
                    argname = id.mapID(p.identifier())
                    if not comments_impl:
                        tmpVar, conv = self.argConversion (argname, paramType, p.is_in(), p.is_out(), p)
                        if conv:
                            conversions.append(conv)
                    else:
                        tmpVar = argname

                    params.append(cxx_type + " " + argname)
                    paramNames.append(tmpVar)


                # deal with possible "context"
                if c.contexts() != []:
                    params.append("CORBA::Context_ptr _ctxt")

                store_return, do_return = self.retConversion (types.Type(c.returnType()))
                return_type = types.Type(c.returnType()).op(types.RET)

                opname = id.mapID(c.identifier())
                arguments = ", ".join(params)
                argumentsCall = ", ".join(paramNames)
                args = opname + "(" + arguments + ")"

                declarations.out (template.operation_decl_code,
                        return_type = return_type,
                        opname = opname,
                        arg_defs = arguments)

                if comments_impl:
                    implementations.out (template.provided_operation_impl_code,
                            return_type = return_type,
                            impl_tpl_name = impl_tpl_name,
                            opname = opname,
                            implementation = "".join(comments_impl),
                            arg_defs = arguments,)
                elif opname in template.predefined_operations_impl_code:
                    #assert not c.parameters(), "Interface operation str should not have arguments"
                    implementations.out (template.predefined_operations_impl_code[opname],
                            return_type = return_type,
                            impl_tpl_name = impl_tpl_name,
                            opname = opname,
                            conversions = "\n  ".join(conversions),
                            arg_defs = arguments,
                            store_return = store_return,
                            do_return = do_return,
                            arg_calls = argumentsCall)
                else:
                    implementations.out (template.operation_impl_code,
                            return_type = return_type,
                            impl_tpl_name = impl_tpl_name,
                            opname = opname,
                            hpp_opname = hpp_opname if hpp_opname is not None else opname,
                            conversions = "\n  ".join(conversions),
                            arg_defs = arguments,
                            store_return = store_return,
                            do_return = do_return,
                            arg_calls = argumentsCall)

            else:
                util.fatalError("Internal error generating interface member")
                raise AssertionError("No code for interface member: "+repr(c))

        openns, closens = namespaces(scopedName, self.environment)

        # Output the _i class definition definition
        self.interface_declarations.out(
                template.base_interface_def if is_base_class else template.inherited_interface_def,
                fq_name = fqname,
                impl_tpl_name = impl_tpl_name,
                impl_base_name = impl_base_name,
                operations = str(declarations),
                impl_name = impl_name,
                fq_POA_name = "POA_" + cxx_fqname,

                hpp_class = hpp_class,
                storage = storage,
                open_namespaces = openns,
                close_namespaces = closens,
                )

        self.interface_implementations.out(
                template.base_interface_code if is_base_class else template.inherited_interface_code,
                fqname = fqname,
                impl_name = impl_name,
                impl_tpl_name = impl_tpl_name,
                impl_base_name = impl_base_name,
                hpp_class = hpp_class,
                operations = str(implementations),
                open_namespaces = openns,
                close_namespaces = closens,
                )
Пример #37
0
def visitException(node):
    scopedName = id.Name(node.scopedName())
    name = scopedName.simple()
    cxx_name = id.mapID(name)
    
    outer_environment = id.lookup(node)
    environment = outer_environment.enter(name)
    
    scoped_name = scopedName.fullyQualify()

    # build the default ctor, copy ctor, assignment operator
    copy_ctor_body = output.StringStream()
    default_ctor_body = output.StringStream()
    default_ctor_args = []
    assign_op_body = output.StringStream()
    has_default_ctor = 0

    for m in node.members():
        has_default_ctor = 1
        memberType = types.Type(m.memberType())
        if m.constrType():
            memberType.type().decl().accept(self)
        d_memberType = memberType.deref()

        memberType_fqname = memberType.base()
            
        for d in m.declarators():
            decl_scopedName = id.Name(d.scopedName())
            decl_name = decl_scopedName.simple()
            
            decl_dims = d.sizes()
            full_dims = decl_dims + memberType.dims()
            is_array = full_dims != []
            is_array_declarator = decl_dims != []

            memberType_name_arg = memberType.op(types.IN, environment)

            if is_array_declarator:
                # we use the internal typedef'ed type if the member is an array
                # declarator
                memberType_name_arg = "const "                       +\
                                      config.state['Private Prefix'] +\
                                      "_" + decl_name
            elif d_memberType.sequence():
                if memberType.typedef():
                    memberType_name_arg = "const " + id.Name(memberType.type().decl().scopedName()).unambiguous(environment)
                else:
                    memberType_name_arg = "const " + memberType.sequenceTemplate(environment)
            elif memberType.typecode():
                memberType_name_arg = "::CORBA::TypeCode_ptr"
                
            index = ""

            if is_array:
                blocks = [cxx.Block(copy_ctor_body),
                          cxx.Block(default_ctor_body),
                          cxx.Block(assign_op_body)]
                loops = [cxx.For(copy_ctor_body, full_dims),
                         cxx.For(default_ctor_body, full_dims),
                         cxx.For(assign_op_body, full_dims)]
                index = loops[0].index() # all the same

            copy_ctor_body.out("""\
@member_name@@index@ = _s.@member_name@@index@;""", member_name = decl_name,
                               index = index)

            if (d_memberType.interface() and not is_array):

                # these are special resources which need to be explicitly
                # duplicated (but not if an array?)
                duplicate = string.replace(memberType_fqname,"_ptr","") + \
                            "::_duplicate"
                if isinstance(d_memberType.type().decl(),idlast.Forward):
                    duplicate = string.replace(duplicate,"::_dup",\
                                               "_Helper::dup")
                default_ctor_body.out("""\
@duplicate@(_@member_name@@index@);""",
                                      duplicate = duplicate,
                                      member_name = decl_name,
                                      index = index)
            
            default_ctor_args.append(memberType_name_arg + " _" + decl_name)
            default_ctor_body.out("""\
@member_name@@index@ = _@member_name@@index@;""", member_name = decl_name,
                                  index = index)

            assign_op_body.out("""\
@member_name@@index@ = _s.@member_name@@index@;""", member_name = decl_name,
                               index = index)
            
            if is_array:
                for loop in loops: loop.end()
                for block in blocks: block.end()
          
        
    default_ctor = output.StringStream()
    if has_default_ctor:
        default_ctor.out(template.exception_default_ctor,
                         scoped_name = scoped_name,
                         name = name,
                         ctor_args = string.join(default_ctor_args, ", "),
                         default_ctor_body = str(default_ctor_body))

    # write the main chunk
    stream.out(template.exception,
               scoped_name = scoped_name,
               name = name,
               copy_ctor_body = str(copy_ctor_body),
               default_ctor = str(default_ctor),
               ctor_args = string.join(default_ctor_args, ", "),
               default_ctor_body = str(default_ctor_body),
               repoID = node.repoId(),
               assign_op_body = str(assign_op_body))
    

    # deal with marshalling and demarshalling
    needs_marshalling = node.members() != []
    marshal = output.StringStream()
    unmarshal = output.StringStream()
    
    for m in node.members():
        memberType = types.Type(m.memberType())
        d_memberType = memberType.deref()
        for d in m.declarators():
            decl_scopedName = id.Name(d.scopedName())
            decl_name = decl_scopedName.simple()
            is_array_declarator = d.sizes() != []
            
            skutil.unmarshall(unmarshal, environment,
                              memberType, d, decl_name, "_n")

            skutil.marshall(marshal, environment,
                            memberType, d, decl_name, "_n")

    if needs_marshalling:
        stream.out(template.exception_operators,
                   scoped_name = scoped_name,
                   marshal = str(marshal),
                   unmarshal = str(unmarshal))


    return
Пример #38
0
class BuildDictionaryFromAST(idlvisitor.AstVisitor):
    def get_dict(self):
        return self.dict

    def __init__(self, tree, config):
        # configuration parameters from command options
        self.config = config

        # module's namespace stack
        self.module = []

        # main dictionary
        self.dict = {}
        self.dict['tree'] = []

        # idl file name
        idl_fname = ast.mainFile()
        self.dict['idl_fname'] = idl_fname

        # included idl files
        incs = []
        idl_incs = ast.includes()
        for inc in idl_incs:
            d = self.createHeaderInfo(inc)
            if inc == idl_fname:
                self.dict.update(d)
            elif self.config['ImplicitInclude']:
                # -Wbimplicit option makes process included IDLs
                d = self.createHeaderInfo(inc)
                incs.append(d)
        self.dict['idl_includes'] = incs

        # other includes
        self.dict['include_h'] = self.config["IncludeHeaders"]

        # type mapping
        self.typemap = self.config['TypeMapping']
        # now configurations can be accessed by self.config["key"]

        # keep track of all interfaces for later use
        self.__allInterfaces = []
        self.tk_map = {
            idltype.tk_null               : "tk_null",
            idltype.tk_void               : "tk_void",
            idltype.tk_short              : "tk_short",
            idltype.tk_long               : "tk_long",
            idltype.tk_ushort             : "tk_ushort",
            idltype.tk_ulong              : "tk_ulong",
            idltype.tk_float              : "tk_float",
            idltype.tk_double             : "tk_double",
            idltype.tk_boolean            : "tk_boolean",
            idltype.tk_char               : "tk_char",
            idltype.tk_octet              : "tk_octet",
            idltype.tk_any                : "tk_any",
            idltype.tk_TypeCode           : "tk_TypeCode",
            idltype.tk_Principal          : "tk_Principal",
            idltype.tk_objref             : "tk_objref",
            idltype.tk_struct             : "tk_struct",
            idltype.tk_union              : "tk_union",
            idltype.tk_enum               : "tk_enum",
            idltype.tk_string             : "tk_string",
            idltype.tk_sequence           : "tk_sequence",
            idltype.tk_array              : "tk_array",
            idltype.tk_alias              : "tk_alias",
            idltype.tk_except             : "tk_except",
            idltype.tk_longlong           : "tk_longlong",
            idltype.tk_ulonglong          : "tk_ulonglong",
            idltype.tk_longdouble         : "tk_longdouble",
            idltype.tk_wchar              : "tk_wchar",
            idltype.tk_wstring            : "tk_wstring",
            idltype.tk_fixed              : "tk_fixed",
            idltype.tk_value              : "tk_value",
            idltype.tk_value_box          : "tk_value_box",
            idltype.tk_native             : "tk_native",
            idltype.tk_abstract_interface : "tk_abstract_interface",
            idltype.tk_local_interface    : "tk_local_interface"
            }

        self.corba_primitive = {
            "CORBA::Short"                : "short int",
            "CORBA::UShort"               : "unsigned short int",
            "CORBA::Long"                 : "int",
            "CORBA::ULong"                : "unsigned int",
            "CORBA::Float"                : "float",
            "CORBA::Double"               : "double",
            "CORBA::Char"                 : "char",
            "CORBA::Boolean"              : "bool",
            "char*"                       : "::std::string",
            "CORBA::Any"                  : "::std::string",
            "CORBA::TypeCode_ptr"         : "::std::string"
            }

    def createHeaderInfo(self, idl_path):
        dict = {}
        idl_path_list = idl_path.split('/')
        idl_fname     = idl_path_list[-1]

        dict['idl_fname']     = idl_fname
        dict['idl_fname_path'] = idl_path

        # types.h
        base_name                   = idl_fname.split('.')[0]
        inc_guard                   = base_name.upper() + 'TYPES_H'
        dict['types_h']             = types_h = base_name + 'Types.h'
        dict['typeconv_h']          = base_name + 'TypeConversion.h'
        dict['typeconv_cpp']        = base_name + 'TypeConversion.cpp'
        dict['types_include_guard'] = inc_guard
        if self.config['IfaceDir'] != "":
            inc_types_h_path = self.config['IfaceDir'] \
                + '/' + types_h
        else:
            inc_types_h_path = types_h
        dict['types_h_path'] = inc_types_h_path

        # typeconv.h
        dict['typeconv_h'] = typeconv_h = base_name + 'TypeConversion.h'
        dict['typeconv_cpp']            = base_name + 'TypeConversion.cpp'
        tc_inc_guard                    = base_name.upper() + 'TYPECONVERSION_H'
        dict['typeconv_include_guard']  = tc_inc_guard
        if self.config['ServantDir'] != "":
            inc_typeconv_h_path = self.config['ServantDir'] \
                + '/' + typeconv_h
        else:
            inc_typeconv_h_path = typeconv_h
        dict['typeconv_h_path'] = inc_typeconv_h_path
        return dict



    def createDecl(self, decl_type):
        """
        宣言情報の基本ディクショナリの生成

        decl_type:     宣言のタイプ, struct, interface, union など
        corba:
          decl_type:     宣言のタイプ, struct, interface, union など
          corba_ns: []   ネームスペースのリスト
        local:
          decl_type:     宣言のタイプ, struct, interface, union など
          local_ns: []   ローカルインターフェースのネームスペース
          adapter_ns: [] アダプタのネームスペース
          servant_ns: [] サーバントのネームスペース
        """
        cdict = {'decl_type': decl_type}
        ldict = {'decl_type': decl_type}
        cdict['corba_ns'] = self.module
        ldict['iface_ns'] = self.module + self.config['IfaceNs']
        ldict['adapter_ns'] = self.module + self.config['AdapterNs']
        ldict['proxy_ns'] = self.module + self.config['ProxyNs']
        ldict['servant_ns'] = self.module + self.config['ServantNs']
        return {'decl_type': decl_type, 'corba': cdict, 'local': ldict}


    def getType(self, typeobj):
        """
        CORBA と Local の型名を取得する
        """
        corba_type = typeobj.base()
        # for omniidl4 4.1.1-2
        if corba_type[:2] == "::":
            corba_type = corba_type[2:]
        is_primitive = None
        # if CORBA to Local mapping is specified explicitly
        if self.typemap.has_key(corba_type):
            local_type = self.typemap[corba_type]

        # if CORBA type is primitive, string or Any
        elif self.corba_primitive.has_key(corba_type):
            local_type = self.corba_primitive[corba_type]
            if corba_type[:5] == 'CORBA':
                corba_type = '::' + corba_type
            tk = self.tk_map[typeobj.kind()]
            primitive = ["tk_short", "tk_long", "tk_ushort", 
                         "tk_ulong", "tk_float", "tk_double",
                         "tk_boolean", "tk_char", "tk_octet"]
            if primitive.count(tk) > 0:
                is_primitive = 'YES'


        # other case
        else:
            corba_scoped_type = corba_type.split('::')
            corba_ns = corba_scoped_type[:-1]
            corba_base = corba_scoped_type[-1]
            local_ns = corba_ns + self.config['IfaceNs']
            local_scope = string.join(local_ns, '::')
            if typeobj.objref():
                corba_base = corba_base[:corba_base.rfind('_ptr')]
                local_type = local_scope + '::' + \
                    self.config['IfacePrefix'] + \
                    corba_base + \
                    self.config['IfaceSuffix']
            elif typeobj.sequence():
                seqType = types.Type(typeobj.type().seqType())
                # get type of element of sequence
                (corba_etype, local_etype, eis_primitive) = self.getType(seqType)
                if seqType.objref():
                    local_etype = local_etype + '*'
                local_type = "std::vector< " + local_etype + " >"

            else:
                local_type = local_scope + '::' + corba_base
            corba_type = '::' + corba_type
            local_type = '::' + local_type
        return (corba_type, local_type, is_primitive)       


    def createIdent(self, dict, node):
        """
        宣言の識別子に関するディクショナリの生成
        主に、識別子のIDL、C++、Local名を生成する
        createDeclで生成したディクショナリとnodeを引数に取る

        corba:
          idl_name:       宣言のidl上の識別子
          name:           C++にマッピングされた識別子
          name_fq:        C++識別子の完全修飾名
          scoped_name: [] リスト形式の完全修飾名
        local:
          idl_name:       宣言のidl上の識別子
          name:           C++にマッピングされた識別子
          name_fq:        C++識別子の完全修飾名
          scoped_name: [] リスト形式の完全修飾名

        """
        cdict = dict['corba']
        ldict = dict['local']

        cdict['idl_name'] = idl_name = node.identifier()
        cdict['name'] = cxx_name = id.mapID(idl_name)
        ns = node.scopedName()[:-1]
        cdict['corba_ns'] = ns
        ldict['iface_ns'] = ns + self.config['IfaceNs']
        ldict['adapter_ns'] = ns + self.config['AdapterNs']
        ldict['proxy_ns'] = ns + self.config['ProxyNs']
        ldict['servant_ns'] = ns + self.config['ServantNs']
        cxx_fq_name = id.Name(node.scopedName()).fullyQualify()
        cdict['name_fq'] = '::' + cxx_fq_name
        cdict['scoped_name'] = node.scopedName()

        iface_ns = '::' + string.join(ldict['iface_ns'], '::')

        if self.typemap.has_key(cxx_fq_name):
            local_fq_name = self.typemap[cxx_fq_name]
            local_name = local_fq_name.split('::')[-1]
        elif self.corba_primitive.has_key(cxx_fq_name):
            local_fq_name = self.corba_primitive[cxx_fq_name]
            local_name    = local_fq_name
        else:
            local_name = cxx_name
            local_fq_name = iface_ns + '::' + local_name

        ldict['name'] = local_name
        ldict['name_fq'] = local_fq_name
        ldict['scoped_name'] = ldict['iface_ns'] + [local_name]
        return dict


    def createInterfaceIdent(self, dict, node):
        """
        インターフェース宣言の識別子に関するディクショナリの生成
        interface/servant/adapter 名を作成しディクショナリに追加する

        corba:
          name_poa:            CORBA POAクラス名
        local:
          iface_name:          Interfaceの識別子
          iface_name_fq:       Interfaceの完全修飾名
          iface_scoped_name:   Interfaceのリスト形式完全修飾名
          servant_name:        Servantの識別子
          servant_name_fq:     Servantの完全修飾名
          servant_scoped_name: Servantのリスト形式完全修飾名
          adapter_name:        Adapterの識別子
          adapter_name_fq:     Adapterの完全修飾名
          adapter_scoped_name: Adapterのリスト形式完全修飾名

        """
        self.createIdent(dict, node)
        cdict = dict['corba']
        ldict = dict['local']
        cdict['name_poa'] = '::POA_' + cdict['name_fq'].strip(':')

        # set iface_name, servant_name adapter_name
        name = ldict['name']
        p = "Prefix"
        s = "Suffix"
        n = "Ns"
        for t in ['Iface', 'Servant', 'Adapter', 'Proxy']:
        #for t in ['Iface', 'Servant', 'Adapter']:
            key = t.lower() + '_name'
            local_name = self.config[t + p] + name + self.config[t + s]
            scoped_name = cdict['corba_ns'] + self.config[t + n] + [local_name]
            local_fq_name = '::' + string.join(scoped_name, '::')
            ldict[key] = local_name
            ldict[key + '_fq'] = local_fq_name
            ldict[key + '_scoped_name'] = scoped_name
        return dict


    def createInterfaceFileInfo(self, dict, node):
        """
        インターフェース関連ファイル名のディクショナリの生成

        local:
          iface_h:               Interfaceヘッダファイル名
          iface_cpp:             Interface実装ファイル名
          iface_h_path:          Interfaceヘッダのインクルードパス
          iface_include_guard:   Interfaceヘッダののインクルードガード
          servant_h:             Servantヘッダファイル名
          servant_cpp:           Servant実装ファイル名
          servant_h_path:        Servantヘッダのインクルードパス
          servant_include_guard: Servantヘッダののインクルードガード
          adapter_h:             Adapterヘッダファイル名
          adapter_cpp:           Adapter実装ファイル名
          adapter_h_path:        Adapterヘッダのインクルードパス
          adapter_include_guard: Adapterヘッダののインクルードガード

        """
        cdict = dict['corba']
        ldict = dict['local']
        ldict['include_h'] = self.config["IncludeHeaders"]

        # set [iface|servant|adapter]_[h|cpp|h_path|include_guard]
        
        for t in ['Iface', 'Servant', 'Adapter', 'Proxy']:
        #for t in ['Iface', 'Servant', 'Adapter']:
            k = t.lower()
            ldict[k + '_h']   = ldict[k + '_name'] + ".h"
            ldict[k + '_cpp'] = ldict[k + '_name'] + ".cpp"
            if self.config[t + 'Dir'] == '':
                ldict[k + '_h_path'] = ldict[k + '_h']
            else:
                ldict[k + '_h_path'] = \
                    self.config[t + 'Dir'] + '/' + ldict[k + '_h']
            ns = string.join(map(lambda x: x + '_',
                                 ldict[k + '_ns']), '')
            ns = ns.upper()
            name = ldict[k + '_name'].upper()
            ldict[k + '_include_guard'] = ns + name + "_H"
        return dict


    def createUnionIdent(self, dict, node):
        """
        共用体宣言のの識別子に関するディクショナリの生成
        
        corba:
          idl_name:          宣言のidl上の識別子
          name:              C++にマッピングされた識別子
          name_fq:           C++識別子の完全修飾名
          scoped_name: []    リスト形式の完全修飾名
          switch_type:       switchの型
          switch_fq_type:    switchの完全修飾型
          deref_switch_type: switchの非参照型
        local:
          idl_name:          宣言のidl上の識別子
          name:              C++にマッピングされた識別子
          name_fq:           C++識別子の完全修飾名
          scoped_name: []    リスト形式の完全修飾名

        """
        self.createIdent(dict, node)
        cdict = dict['corba']
        ldict = dict['local']

        switchType = types.Type(node.switchType())
        ast.markDefaultCase(node)
        hasDefault = ast.defaultCase(node) != None

        (ctype, ltype, is_primitive) = self.getType(switchType)
        cdict['switch_fq_type'] = ctype
        cdict['switch_type']    = ctype.split('::')[-1]
        ldict['switch_fq_type'] = ltype
        ldict['switch_type']    = ltype.split('::')[-1]
        return 


    def createStructIdent(self, dict, node):
        return self.createIdent(dict, node)


    def createEnumIdent(self, dict, node):
        return self.createIdent(dict, node)


    def createExceptionIdent(self, dict, node):
        return self.createIdent(dict, node)


    def createMembers(self, dict, node):
        corba_name = dict['corba']['name']
        outer_environment = id.lookup(node)
        environment = outer_environment.enter(id.mapID(corba_name))
        scope = environment.scope()

        members = []
        for member in node.members():
            #------------------------------------------------------------
            # member
            # - type_d: type of a member
            # - decl_d: decralation list
            memberType = types.Type(member.memberType())

#            self.createType(memberType, environment)
            memtype = memberType.member(environment)
            for decl in member.declarators():
                m = self.createMember(decl, member, environment)
                if m != None:
                    members.append(m)
        dict['members'] = members
        return dict


    def createMember(self, decl, member, env):
        dict = self.createDecl('member')
        cdict = dict['corba']
        ldict = dict['local']

        memberType = types.Type(member.memberType())
        memtype = memberType.member(env)

        (ctype, ltype, is_primitive) = self.getType(memberType)
        cdict['base_type'] = ctype
        cdict['tk'] = self.tk_map[memberType.kind()]
        ldict['base_type'] = ltype
        cdict['member_name'] = id.mapID(decl.identifier())
        cdict['member_dims'] = decl.sizes()
        ldict['member_name'] = cdict['member_name']
        ldict['member_dims'] = cdict['member_dims']

        if memberType.objref():
            corba_mtype = ctype
            local_mtype = ltype + '*'
        else:
            corba_mtype = ctype
            local_mtype = ltype

        cdict['member_type'] = corba_mtype
        ldict['member_type'] = local_mtype
        return dict


    def createUnionCases(self, dict, node):
        cases = []
        switchType = types.Type(node.switchType())
        ast.markDefaultCase(node) 
        outer_environment = id.lookup(node)
        environment = outer_environment.enter(node.identifier())

        for case in node.cases():
            c = self.createUnionCase(case, node, switchType, environment)
            if c != None:
                cases.append(c)
        dict['cases'] = cases
        return dict
            

    def createUnionCase(self, case, node, switchtype, environment):
        dict = self.createDecl('union_case')
        cdict = dict['corba']
        ldict = dict['local']

        caseType = types.Type(case.caseType())
        d_caseType = caseType.deref()
        (corba_ctype, local_ctype, is_primitive) = self.getType(caseType)
        cdict['case_type'] = corba_ctype
        ldict['case_type'] = local_ctype

        decl = case.declarator()
        case_member = id.mapID(decl.identifier())
        cdict['case_member'] = case_member
        ldict['case_member'] = case_member

        decl_dims = decl.sizes()
        full_dims = decl_dims + caseType.dims()
        is_array = full_dims != []
        if is_array: raise "array union case type is not supported."

        # ------------------------------------------------------------
        # generate default discriminator
        def choose(switchType = switchtype,
                   values = ast.allCaseLabelValues(node),
                   environment = environment):
            switchType = switchType.deref()
            def min_unused(start, used = values):
                x = start
                while x in used:
                    x = x + 1
                return x
            kind = switchType.type().kind()
            if switchType.integer():
                (low, high) = ast.integer_type_ranges[kind]
                s = switchType.literal(min_unused(low+1))
                return s
            elif kind == idltype.tk_char:
                all = map(chr, range(0, 255))
            elif kind == idltype.tk_boolean:
                all = [0, 1]
            elif kind == idltype.tk_enum:
                all = switchType.type().decl().enumerators()
            else:
                util.fatalError("Failed to generate a default union " +\
                                    "discriminator value")
            possibles = util.minus(all, values)
            return switchType.literal(possibles[0], environment)
        # ------------------------------------------------------------

        labels = case.labels()
        if labels != []:
            non_default_labels = filter(lambda x:not x.default(), labels)
            if non_default_labels == []:
                # only one label and it's the default
                label = labels[0]
                discrimvalue = choose()
            elif len(non_default_labels) > 1:
                # oooh, we have a choice. Let's pick the second one.
                # no-one will be expecting that
                label = non_default_labels[1]
            else:
                # just the one interesting label
                label = non_default_labels[0]

            if label.default():
                discrimvalue = choose()
            else:
                discrimvalue = switchtype.literal(label.value(),
                                                      environment)
        cdict['discriminator'] = discrimvalue
        ldict['discriminator'] = discrimvalue

        if switchtype.enum():
            corba_ns = '::' + string.join(cdict['corba_ns'], '::')
            local_ns = '::' + string.join(ldict['iface_ns'], '::')
            cdict['discriminator_fq'] = corba_ns + '::' + discrimvalue
            ldict['discriminator_fq'] = local_ns + '::' + discrimvalue
        else:
            cdict['discriminator_fq'] = discrimvalue
            ldict['discriminator_fq'] = discrimvalue
        non_default_labels = filter(lambda x:not x.default(), labels)
        return dict
Пример #39
0
    def buildCallables(interface, where, continuation, defined_so_far = {}):
        interface = ast.remove_ast_typedefs(interface)
        
        callables = interface.callables()
        operations = filter(lambda x:isinstance(x, idlast.Operation),
                            callables)
        for operation in operations:
            returnType = types.Type(operation.returnType())
            identifier = operation.identifier()
            if (defined_so_far.has_key(identifier)):
                # don't repeat it
                continue
            defined_so_far[identifier] = 1
            
            parameters = operation.parameters()
            has_return_value = not returnType.void()
            # FIXME: return types are fully scoped but argument types
            # arent?
            returnType_name = returnType.op(types.RET)

            operation_name = id.mapID(identifier)
            
            signature = []
            call = []

            for parameter in parameters:
                paramType = types.Type(parameter.paramType())
                # Need to call the _impl operation not the _objref operation
                param_type_name = paramType.op(types.direction(parameter),
                                               use_out = 0)
                param_id = id.mapID(parameter.identifier())
                signature.append(param_type_name + " " + param_id)
                call.append(param_id)

            # deal with call contextx
            if operation.contexts() != []:
                signature.append("::CORBA::Context_ptr _ctxt")
                call.append("_ctxt")

            if has_return_value:
                return_str = "return "
            else:
                return_str = ""
                
            where.out("""\
@return_type_name@ @operation_name@(@signature@) { @return_str@pd_obj->@operation_name@(@call@); }""", return_type_name = returnType_name,
                      operation_name = operation_name,
                      return_str = return_str,
                      signature = ", ".join(signature),
                      call = ", ".join(call))
                    
        attributes = filter(lambda x:isinstance(x, idlast.Attribute),
                            callables)
        for attribute in attributes:
            identifiers = attribute.identifiers()
            attrType = types.Type(attribute.attrType())

            attrType_name_RET = attrType.op(types.RET)
            attrType_name_IN = attrType.op(types.IN)
            
            for identifier in identifiers:
                if defined_so_far.has_key(identifier):
                    # don't repeat it
                    continue
                defined_so_far[identifier] = 1
                
                ident = id.mapID(identifier)
                where.out("""\
@attr_type_ret_name@ @attribute_name@() { return pd_obj->@attribute_name@(); }""", attr_type_ret_name = attrType_name_RET,
                          attribute_name = ident)

                if not attribute.readonly():
                    where.out("""\
void @attribute_name@(@attr_type_in_name@ _value) { pd_obj->@attribute_name@(_value); }""", attribute_name = ident,
                              attr_type_in_name = attrType_name_IN)                    
        # do the recursive bit
        for i in interface.inherits():
            i = i.fullDecl()
            continuation(i, where, continuation, defined_so_far)

        # done
        return
Пример #40
0
 def visitDeclarator(self, node):
     print "Declarator", id.mapID(node.identifier())
Пример #41
0
	def visitInterface(self, node):
		self.__allInterfaces.append(node)
	
		scopedName = id.Name(node.scopedName())
		
		cxx_fqname = scopedName.fullyQualify()
		impl_flat_name = impl_fullname(scopedName)

		fqname = scopedName.fullyQualify(cxx = 0)

		
		# build methods corresponding to attributes, operations etc.
		# attributes[] and operations[] will contain lists of function
		# signatures eg
		#   [ char *echoString(const char *mesg) ]
		attributes = []
		operations = []
		virtual_operations = []

		# we need to consider all callables, including inherited ones
		# since this implementation class is not inheriting from anywhere
		# other than the IDL skeleton
		allInterfaces = [node] + ast.allInherits(node)
		allCallables = util.fold( map(lambda x:x.callables(), allInterfaces),
								  [], lambda x, y: x + y )


		# declarations[] contains a list of in-class decl signatures
		# implementations[] contains a list of out of line impl signatures
		# (typically differ by classname::)
		declarations = []
		implementations = []
		
		for c in allCallables:

			if isinstance(c, idlast.Attribute) :
				attrType = types.Type(c.attrType())
				d_attrType = attrType.deref()

				for i in c.identifiers():
					attribname = id.mapID(i)
					returnType = attrType.op(types.RET)
					inType = attrType.op(types.IN)
					attributes.append(returnType + " " + attribname + "()")
					# need a set method if not a readonly attribute
					if not c.readonly():
						args = attribname + "(" + inType + ")"
						declarations.append("void " + args)
						implementations.append("void " + impl_flat_name +\
											   "::" + args)
					if not attribname in self.ignore_operations:
						declarations.append(returnType + " " + attribname + "()")
						implementations.append(returnType + " " + impl_flat_name+\
										   "::" + attribname + "()")
			elif isinstance(c, idlast.Operation):
				params = []
				for p in c.parameters():
					paramType = types.Type(p.paramType())
					cxx_type = paramType.op(types.direction(p), use_out = 0)
					
					argname = id.mapID(p.identifier())
					params.append(cxx_type + " " + argname)

				# deal with possible "context"
				if c.contexts() != []:
					params.append("CORBA::Context_ptr _ctxt")

				return_type = types.Type(c.returnType()).op(types.RET)

				opname = id.mapID(c.identifier())
				if not opname in self.ignore_operations:
					arguments = string.join(params, ", ")
					args = opname + "(" + arguments + ")"
					declarations.append(return_type + " " + args)
					implementations.append(return_type + " " + \
										   impl_flat_name + \
										   "::" + args)
			else:
				util.fatalError("Internal error generating interface member")
				raise "No code for interface member: " + repr(c)

		# the class definition has no actual code...
		defs = string.join(map(lambda x:x + ";\n", declarations), "")

		# Output the class definition of the implementation
		self.stream_h.out(interface_def,
						  impl_fqname = impl_flat_name,
						  impl_name = impl_flat_name,
						  fq_name = fqname,
						  fq_POA_name = "POA_" + cxx_fqname,
						  operations = defs)

		# Output the class methods implementations
		impls = string.join(map(lambda x: x + """\

{
  // Please insert your code here and remove the following warning pragma
#ifndef WIN32
  #warning "Code missing in function <""" + x + """>"
#endif
}

""",
								implementations), "")
		
		self.stream_cpp.out(interface_code,
							fqname = fqname,
							impl_name = impl_flat_name,
							impl_fqname = impl_flat_name,
							operations = impls)