Beispiel #1
0
def visitTypedef(node):
    if node.constrType():
        node.aliasType().decl().accept(self)

    aliasType = types.Type(node.aliasType())
    prefix = config.state['Private Prefix']

    for d in node.declarators():
        scopedName = id.Name(d.scopedName())
        guard_name = scopedName.guard()
        fqname = scopedName.fullyQualify()

        if d.sizes():
            # Array
            marshal = output.StringStream()
            skutil.marshall(marshal, None, aliasType, d, "_a", "_s")

            unmarshal = output.StringStream()
            skutil.unmarshall(unmarshal, None, aliasType, d, "_a", "_s")

            stream.out(template.array,
                       guard_name=guard_name,
                       fqname=fqname,
                       marshal=marshal,
                       unmarshal=unmarshal,
                       private_prefix=prefix)

        elif aliasType.sequence():
            stream.out(template.sequence,
                       guard_name=guard_name,
                       fqname=fqname,
                       private_prefix=prefix)
Beispiel #2
0
def run(tree):
	# The implementation template code stream
	impl_cpp = output.StringStream()
	# The implementation template header stream
	impl_h   = output.StringStream()
	bii = BuildInterfaceImplementations(impl_h, impl_cpp, self.ignore_op)
	tree.accept(bii)

	# Generate mplementation class template header
	stream_h.out(class_h,
				 atmark = "@",
				 impl_h = self.impl_h_filename,
				 include_guard = self.include_guard,
				 skel_h = self.skel_filename,
				 file = self.idl_filename,
				 interfaces = str(impl_h))
	
	# Generate implementation class template code
	stream_cpp.out(class_cpp,
				   atmark = "@",
				   impl_cpp = self.impl_cpp_filename,
				   impl_h = self.impl_h_filename,
				   file = self.idl_filename,
				   interfaces = str(impl_cpp))

	self.ifs = []
	for n in bii.allInterfaces():
		self.ifs.append(string.join(n.scopedName(), "_") + self.suffix)
	return self.ifs
Beispiel #3
0
def run(tree):
    # first thing is to build the interface implementations
    decl = output.StringStream()
    impl = output.StringStream()
    bii = BuildInterfaceImplementations(decl, impl)
    tree.accept(bii)

    object_downcasts_methods = output.StringStream()
    add_object_downcasts = output.StringStream()
    biod = BuildInterfaceObjectDowncasts(object_downcasts_methods,
                                         add_object_downcasts)
    tree.accept(biod)

    openns, closens = namespaces(bii.environment)
    guard = id.Name([config.state['Basename']]).guard()

    # Create header file.
    hpp_stream.out(
        template.hpp_file,
        guard_prefix=config.state['GuardPrefix'],
        guard=guard,
        includes=bii.includes,
        idl_hh=prefix + hh_filename,
        file=idl_filename,
        interface_declarations=str(decl),
        open_namespaces=openns,
        close_namespaces=closens,
    )

    # Create definition of templated functions.
    hxx_stream.out(
        template.hxx_file,
        guard_prefix=config.state['GuardPrefix'],
        guard=guard,
        idl_hpp=prefix + hpp_filename,
        file=idl_filename,
        interface_implementations=str(impl),
        open_namespaces=openns,
        close_namespaces=closens,
    )

    # Create other definition files.
    cc_stream.out(
        template.cc_file,
        idl_hxx=prefix + hxx_filename,
        file=idl_filename,
        object_downcasts_methods=object_downcasts_methods,
        add_object_downcasts=add_object_downcasts,
        open_namespaces=openns,
        close_namespaces=closens,
    )
Beispiel #4
0
def buildStateMembersStructure(node):
    struct = output.StringStream()
    mangled_name = mangleName(config.state['Private Prefix'] + \
                              "_valuemember_", node.scopedName())
    if alreadyDefined(mangled_name):
        # no need to regenerate
        return struct

    defineName(mangled_name)

    members = node.statemembers()
    array = []

    if members:
        for m in members:
            memberType = types.Type(m.memberType())
            access = m.memberAccess()
            for d in m.declarators():
                this_name = id.Name(d.scopedName()).simple()
                typecode = mkTypeCode(memberType, d, node)
                array.append('{"%s", %s, %d}' % (this_name, typecode, access))

        struct.out("""\
static CORBA::PR_valueMember @mangled_name@[] = {
  @members@
};""",
                   members=",\n".join(array),
                   mangled_name=mangled_name)
    else:
        struct.out("""\
static CORBA::PR_valueMember* @mangled_name@ = 0;""",
                   mangled_name=mangled_name)

    return struct
Beispiel #5
0
    def visitStruct(self, node):
        if not node.identifier().endswith("Storage"): return
        if not node.members(): return

        class Storage(object):
            pass

        storage = Storage()

        storage.members = []
        for m in node.members():
            type = self.toCppNamespace(id.Name(m.memberType().scopedName())).suffix("Ptr_t")
            for d in m.declarators():
                storage.members.append ((type, d.identifier()))

        storage.sc = hpp_servant_scope(id.Name(node.scopedName()))

        sc = node.scopedName()
        sc[-1] = sc[-1][:-7]
        storage.class_sc = hpp_servant_scope(id.Name(sc))

        st = output.StringStream()
        st.out (template.storage_decl,
                storage_class_name       = storage.sc.simple(),
                hpp_base_class           = storage.class_sc.simple(),
                storage_attributes       = "\n".join([ t.fullyQualify() + " " + n for t,n in storage.members ]),
                storage_constr_attr_decl = ", ".join([ t.fullyQualify() + " _" + n for t,n in storage.members ]) + ", ",
                storage_constr_attr_defs = ", " + ", ".join([ n + " (_" + n + ")" for t,n in storage.members ]),
                storage_attr_call        = ", ".join([ n for t,n in storage.members ]) + ", ",
                )
        storage.decl = str(st)

        self.storages[storage.class_sc.fullyQualify(cxx=0)] = storage
Beispiel #6
0
def buildMembersStructure(node):
    struct = output.StringStream()
    mangled_name = mangleName(config.state['Private Prefix'] + \
                              "_structmember_", node.scopedName())
    if alreadyDefined(mangled_name):
        # no need to regenerate
        return struct

    defineName(mangled_name)

    members = node.members()
    array = []

    for m in members:
        memberType = types.Type(m.memberType())
        for d in m.declarators():
            this_name = id.Name(d.scopedName()).simple()
            typecode = mkTypeCode(memberType, d, node)
            array.append("{\"" + this_name + "\", " + typecode + "}")

    if len(members) > 0:
        struct.out("""\
static CORBA::PR_structMember @mangled_name@[] = {
  @members@
};""",
                   members=",\n".join(array),
                   mangled_name=mangled_name)

    return struct
Beispiel #7
0
 def __out_contextDescriptor(self, stream):
     if self.__contexts:
         contexts = output.StringStream()
         for context in self.__contexts:
             contexts.out('"' + context + '",')
         stream.out(template.interface_context_array,
                    context_descriptor=self.__context_name,
                    contexts=str(contexts))
Beispiel #8
0
    def __out_unmarshalArgument(self,stream):
        if not self.__has_in_args: return

        marshal_block = output.StringStream()

        for n, argument in enumerate(self.__arguments):
            if not argument.is_in(): continue

            argtype = types.Type(argument.paramType())
            ((h_is_const,h_is_ptr),(s_is_holder,s_is_var)) = \
                         _arg_info(argtype,argument.direction())

            arg_n = "arg_%d" % n
            if s_is_holder:
                storage_n = arg_n
            else:
                storage_n = arg_n + "_"
                
            if s_is_var:
                alloc = ""
                d_type = argtype.deref(1)

                if argtype.array():
                    alloc = argtype.base() + "_alloc()"
                elif not (d_type.typecode()  or
                          d_type.string()    or
                          d_type.wstring()   or
                          d_type.interface() or
                          d_type.value()     or
                          d_type.valuebox()):
                    alloc = "new " + argtype.base()
                if alloc != "":
                    marshal_block.out(storage_n + " = " + alloc + ";")

            skutil.unmarshall(marshal_block, None,
                              argtype, None, storage_n, "_n")

            if not s_is_holder:
                if s_is_var:
                    if argument.direction() == 0:
                        lvalue = storage_n + ".in()"
                    else:
                        lvalue = storage_n + ".inout()"
                else:
                    lvalue = storage_n
                if argtype.array():
                    lvalue = "&" + lvalue + "[0]"
                if h_is_ptr:
                    marshal_block.out(arg_n + " = &" + lvalue + ";")
                else:
                    marshal_block.out(arg_n + " = " + lvalue + ";")

        if self.__contexts:
            marshal_block.out(template.interface_proxy_unmarshal_context)

        stream.out(template.interface_proxy_unmarshal_arguments,
                   call_descriptor = self.__name,
                   marshal_block = marshal_block)
Beispiel #9
0
def run(tree):
    # first thing is to build the interface implementations
    impl = output.StringStream()
    bii = BuildInterfaceImplementations(impl)
    tree.accept(bii)

    # for each interface we implement we require:
    # 1. heap allocation
    allocate = output.StringStream()
    # 2. POA activation
    activate = output.StringStream()
    # 3. reference generation, stringification and output
    reference = output.StringStream()

    for i in bii.allInterfaces():
        name = id.Name(i.scopedName())

        impl_name = impl_fullname(name)

        # for an implementation class A_B_C_i, generate an instance myA_B_C_i
        inst_name = "my" + impl_name

        # allocate an instance of the implementation on the heap
        allocate.out("@impl_name@* @inst_name@ = new @impl_name@();",
                     impl_name=impl_name,
                     inst_name=inst_name)

        # activate the object and get a T_var reference to it
        activate.out("PortableServer::ObjectId_var @inst_name@id = " +\
                     "poa->activate_object(@inst_name@);",
                     inst_name = inst_name)

        # get the reference and output it
        reference.out(template.interface_ior,
                      fqname=name.fullyQualify(cxx=0),
                      inst_name=inst_name)

    # output the main() routine (all ORB initialisation code etc)
    stream.out(template.main,
               idl_hh=self.hh_filename,
               file=self.idl_filename,
               interfaces=str(impl),
               allocate_objects=str(allocate),
               activate_objects=str(activate),
               output_references=str(reference))
Beispiel #10
0
    def hh(self, stream):
        # build the inheritance list

        objref_inherits = []

        inh = self.interface().inherits()
        if inh:
            for i in inh:
                objref_inherited_name = i.name().prefix("_objref_")
                uname = objref_inherited_name.unambiguous(self._environment)
                objref_inherits.append("public virtual " + uname)
        else:
            if self.interface().abstract():
                objref_inherits = [
                    "public virtual ::CORBA::_omni_AbstractBaseObjref",
                    "public virtual omniObjRef"
                    ]
            else:
                objref_inherits = [
                    "public virtual ::CORBA::Object",
                    "public virtual omniObjRef"
                    ]

        if self.interface().abstract():
            objref_inherits.append("public virtual " +
                                   self.interface().name().simple())

        methods = []
        for method in self.methods():
            if config.state['Virtual Objref Methods']:
                methods.append(method.hh(virtual = 1, pure = 0))
            else:
                methods.append(method.hh())

        if self.ami_methods():
            methods.append("\n// AMI methods")

            for method in self.ami_methods():
                methods.append(method.hh())


        if config.state['Shortcut']:
            shortcut = output.StringStream()
            shortcut.out(header_template.interface_shortcut,
                         name = self.interface().name().simple())
            shortcut = str(shortcut)
            init_shortcut = ": _shortcut(0)"
        else:
            shortcut = ""
            init_shortcut = ""

        stream.out(header_template.interface_objref,
                   name          = self.interface().name().simple(),
                   inherits      = ",\n".join(objref_inherits),
                   operations    = "\n".join(methods),
                   shortcut      = shortcut,
                   init_shortcut = init_shortcut)
Beispiel #11
0
    def __out_marshalArgument(self, stream):
        if not (self.__has_in_args or self.__contexts): return
        marshal_block = output.StringStream()
        self.__out_marshalArgument_shared(marshal_block, 1)

        if self.__contexts:
            marshal_block.out(template.interface_proxy_marshal_context,
                              name=self.__context_name,
                              count=str(len(self.__contexts)))

        stream.out(template.interface_proxy_marshal_arguments,
                   call_descriptor=self.__name,
                   marshal_block=marshal_block)
Beispiel #12
0
  def cc(self, stream):
    inherits = output.StringStream()
    for i in self.interface().allInherits():
      ancestor = i.name().fullyQualify()
      inherits.out(omniidl_be.cxx.skel.template.interface_pof_repoID, inherited = ancestor)

    node_name = self.interface().name()
    objref_name = node_name.prefix("_objref_")
    pof_name = node_name.prefix("_pof_")
    stream.out(omniidl_be.cxx.skel.template.interface_pof,
               pof_name = pof_name.fullyQualify(),
               objref_fqname = objref_name.fullyQualify(),
               name = node_name.fullyQualify(),
               uname = pof_name.simple(),
               Other_repoIDs = inherits,
               idname = node_name.guard())
Beispiel #13
0
    def __out_marshalReturnedValues(self, stream):
        if not (self.__has_out_args or self.__has_return_value): return
        marshal_block = output.StringStream()

        if self.__has_return_value:
            argtype = types.Type(self.__returntype)
            ((h_is_const,h_is_ptr),(s_is_holder,s_is_var)) = \
                         _arg_info(argtype,3)
            argname = "result"
            if (h_is_ptr):
                argname = "*" + argname
            skutil.marshall(marshal_block, None, argtype, None, argname, "_n")

        self.__out_marshalArgument_shared(marshal_block, 0)
        stream.out(template.interface_proxy_marshal_returnedvalues,
                   call_descriptor=self.__name,
                   marshal_block=marshal_block)
Beispiel #14
0
    def __out_userException(self, stream):
        if self.__exceptions:
            block = output.StringStream()
            exceptions = skutil.sort_exceptions(self.__exceptions)
            repoIDs = []
            for exception in exceptions:
                scopedName = exception.scopedName()
                repoID = scopedName + ["_PD_repoId"]
                repoID_str = id.Name(repoID).fullyQualify()
                repoIDs.append(repoID_str)
                exname = id.Name(scopedName).fullyQualify()
                block.out(template.interface_proxy_exn_handle,
                          repoID_str = repoID_str, exname = exname)

            # write the user exception template
            stream.out(template.interface_proxy_exn,
                       call_descriptor = self.__name,
                       exception_block = str(block),
                       exception_namelist = ",\n".join(repoIDs))
        else:
            stream.out(template.interface_proxy_empty_exn,
                       call_descriptor = self.__name)
Beispiel #15
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,
                )
Beispiel #16
0
    def cc(self, stream):
        def _ptrToObjRef_ptr(self=self, stream=stream):
            has_abstract = self.interface().abstract()

            for i in self.interface().allInherits():
                if i.abstract(): has_abstract = 1

                stream.out(
                    omniidl_be.cxx.skel.template.interface_objref_repoID_ptr,
                    inherits_fqname=i.name().fullyQualify())

            if has_abstract:
                stream.out(
                    omniidl_be.cxx.skel.template.interface_objref_repoID_ptr,
                    inherits_fqname="CORBA::AbstractBase")

        def _ptrToObjRef_str(self=self, stream=stream):
            has_abstract = self.interface().abstract()

            for i in self.interface().allInherits():
                if i.abstract(): has_abstract = 1

                stream.out(
                    omniidl_be.cxx.skel.template.interface_objref_repoID_str,
                    inherits_fqname=i.name().fullyQualify())

            if has_abstract:
                stream.out(
                    omniidl_be.cxx.skel.template.interface_objref_repoID_str,
                    inherits_fqname="CORBA::AbstractBase")

        # build the inherits list

        inherits_str_list = []
        for i in self.interface().inherits():
            objref_name = i.name().prefix("_objref_")

            objref_str = objref_name.unambiguous(self._environment)

            if objref_name.needFlatName(self._environment):
                objref_str = objref_name.flatName()

            this_inherits_str = objref_str + "(ior, id)"

            # FIXME:
            # The powerpc-aix OMNIORB_BASE_CTOR workaround still works here
            # (in precendence to the flattened base name) but lacking a
            # powerpc-aix test machine I can't properly test it. It's probably
            # not required any more.
            if objref_name.relName(self._environment) != i.name().fullName():
                prefix = []
                for x in objref_name.fullName():
                    if x == "_objref_" + objref_name.relName(
                            self._environment)[0]:
                        break
                    prefix.append(x)
                inherits_scope_prefix = string.join(prefix, "::") + "::"
                this_inherits_str = "OMNIORB_BASE_CTOR(" + inherits_scope_prefix +\
                                    ")" + this_inherits_str

            inherits_str_list.append(this_inherits_str)

        inherits_str = string.join(inherits_str_list, ",\n")
        if inherits_str:
            comma = ","
        else:
            comma = ""

        if config.state['Shortcut']:
            inherits_str = inherits_str + ","
            init_shortcut = "_shortcut(0)"
        else:
            init_shortcut = ""

        if config.state['Shortcut'] == 2:
            release_shortcut = omniidl_be.cxx.skel.template.\
                               interface_release_refcount_shortcut
        else:
            release_shortcut = ""

        stream.out(omniidl_be.cxx.skel.template.interface_objref,
                   name=self.interface().name().fullyQualify(),
                   fq_objref_name=self.name().fullyQualify(),
                   objref_name=self.name().simple(),
                   inherits_str=inherits_str,
                   comma=comma,
                   _ptrToObjRef_ptr=_ptrToObjRef_ptr,
                   _ptrToObjRef_str=_ptrToObjRef_str,
                   init_shortcut=init_shortcut,
                   release_shortcut=release_shortcut)

        shortcut_mode = config.state['Shortcut']

        if shortcut_mode:
            inherited = output.StringStream()
            for i in self.interface().inherits():
                objref_name = i.name().prefix("_objref_")

                objref_str = objref_name.unambiguous(self._environment)

                if objref_name.needFlatName(self._environment):
                    objref_str = objref_name.flatName()

                inherited.out(
                    omniidl_be.cxx.skel.template.interface_shortcut_inh,
                    parent=objref_str)

            if shortcut_mode == 1:
                tmpl = omniidl_be.cxx.skel.template.interface_shortcut
            else:
                tmpl = omniidl_be.cxx.skel.template.interface_shortcut_refcount

            stream.out(tmpl,
                       name=self.interface().name().fullyQualify(),
                       basename=self.interface().name().simple(),
                       fq_objref_name=self.name().fullyQualify(),
                       inherited=str(inherited))

        for method in self.methods():
            callable = self._callables[method]

            # signature is a text string form of the complete operation signature
            signature = callable.signature()

            # we only need one descriptor for each _signature_ (not operation)
            if _proxy_call_descriptors.has_key(signature):
                call_descriptor = _proxy_call_descriptors[signature]
            else:
                call_descriptor = call.CallDescriptor(signature, callable)
                call_descriptor.out_desc(stream)
                _proxy_call_descriptors[signature] = call_descriptor

            # produce a localcall function
            node_name = self.interface().name()
            localcall_fn = descriptor.local_callback_fn(
                node_name, callable.operation_name(), signature)
            call_descriptor.out_localcall(stream, node_name,
                                          callable.method_name(), localcall_fn)

            # produce member function for this operation/attribute.
            body = output.StringStream()

            argnames = method.arg_names()

            if config.state['Shortcut']:
                if method.return_type().kind() != idltype.tk_void:
                    callreturn = "return "
                    voidreturn = ""
                else:
                    callreturn = ""
                    voidreturn = " return;"

                objref_class = method.parent_class()
                interface = objref_class.interface()
                implname = interface.name().prefix("_impl_").unambiguous(
                    self._environment)

                if config.state['Shortcut'] == 2:
                    tmpl = omniidl_be.cxx.skel.template.\
                           interface_operation_shortcut_refcount
                else:
                    tmpl = omniidl_be.cxx.skel.template.\
                           interface_operation_shortcut

                body.out(tmpl,
                         impl_type=implname,
                         callreturn=callreturn,
                         voidreturn=voidreturn,
                         args=string.join(argnames, ", "),
                         name=method.name())

            intf_env = self._environment.enter(
                "_objref_" + self.interface().name().simple())

            call_descriptor.out_objrefcall(body, callable.operation_name(),
                                           argnames, localcall_fn, intf_env)
            method.cc(stream, body)
Beispiel #17
0
def visitException(node):
    scopedName = id.Name(node.scopedName())
    name = scopedName.simple()

    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 = memberType_fqname.replace("_ptr", "") + \
                            "::_duplicate"

                if isinstance(d_memberType.type().decl(), idlast.Forward):
                    duplicate = duplicate.replace("::_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=", ".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=", ".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
Beispiel #18
0
def visitUnion(node):
    outer_environment = id.lookup(node)
    environment = outer_environment.enter(node.identifier())

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

    switchType = types.Type(node.switchType())

    exhaustive = ast.exhaustiveMatch(switchType, ast.allCaseLabelValues(node))
    defaultCase = ast.defaultCase(node)
    ast.markDefaultCase(node)

    hasDefault = defaultCase != None

    # deal with types constructed here
    if node.constrType():
        node.switchType().decl().accept(self)
    for n in node.cases():
        if n.constrType():
            n.caseType().decl().accept(self)

    # --------------------------------------------------------------
    # union::operator{>>, <<}= (cdrStream& _n) [const]
    #
    # marshal/ unmarshal individual cases
    marshal_discriminator = output.StringStream()
    unmarshal_discriminator = output.StringStream()

    skutil.marshall(marshal_discriminator, environment, switchType, None,
                    "_pd__d", "_n")

    skutil.unmarshall(unmarshal_discriminator, environment, switchType, None,
                      "_pd__d", "_n")

    marshal_cases = output.StringStream()
    unmarshal_cases = output.StringStream()

    for c in node.cases():
        caseType = types.Type(c.caseType())
        decl = c.declarator()
        decl_scopedName = id.Name(decl.scopedName())
        decl_name = decl_scopedName.simple()

        if defaultCase == c:
            isDefault = 1
        else:
            isDefault = 0

        for l in c.labels():
            value = l.value()
            discrim_value = switchType.literal(value, environment)
            if l.default():
                unmarshal_cases.out("default:")
                marshal_cases.out("default:")
            else:
                unmarshal_cases.out("case " + discrim_value + ":")
                marshal_cases.out("case " + discrim_value + ":")

        marshal_cases.inc_indent()
        skutil.marshall(marshal_cases,
                        environment,
                        caseType,
                        decl,
                        "_pd_" + decl_name,
                        "_n",
                        is_union=1)
        marshal_cases.out("break;")
        marshal_cases.dec_indent()

        unmarshal_cases.inc_indent()
        unmarshal_cases.out("_pd__default = %d;" % isDefault)
        skutil.unmarshall(unmarshal_cases,
                          environment,
                          caseType,
                          decl,
                          "_pd_" + decl_name,
                          "_n",
                          is_union=1)
        unmarshal_cases.out("break;")
        unmarshal_cases.dec_indent()

    if not hasDefault and not exhaustive:
        unmarshal_cases.out("""\
default:
  _pd__default = 1;
  break;""")

    # write the operators
    stream.out(template.union_operators,
               name=name,
               marshal_discriminator=str(marshal_discriminator),
               unmarshal_discriminator=str(unmarshal_discriminator),
               marshal_cases=str(marshal_cases),
               unmarshal_cases=str(unmarshal_cases))

    return
Beispiel #19
0
    def __out_unmarshalReturnedValues(self, stream):

        if not (self.__has_out_args or self.__has_return_value): return

        marshal_block = output.StringStream()

        if self.__has_return_value:
            argtype = types.Type(self.__returntype)
            ((h_is_const,h_is_ptr),(s_is_holder,s_is_var)) = \
                         _arg_info(argtype,3)
            argname = "result"
            if s_is_var:
                alloc = ""
                d_type = argtype.deref(1)
                if argtype.array():
                    alloc = argtype.base() + "_alloc()"
                elif not (d_type.typecode() or d_type.string()
                          or d_type.wstring() or d_type.interface()
                          or d_type.value() or d_type.valuebox()):
                    alloc = "new " + argtype.base()
                if alloc != "":
                    marshal_block.out(argname + " = " + alloc + ";")
            skutil.unmarshall(marshal_block, None, argtype, None, argname,
                              "_n")

        for n, argument in enumerate(self.__arguments):
            if not argument.is_out(): continue

            argtype = types.Type(argument.paramType())
            ((h_is_const,h_is_ptr),(s_is_holder,s_is_var)) = \
                         _arg_info(argtype,argument.direction())

            arg_n = "arg_" + str(n)

            d_type = argtype.deref(1)
            if s_is_holder:
                if s_is_var:
                    alloc = ""
                    if argtype.array():
                        alloc = argtype.base() + "_alloc()"
                    elif not (d_type.typecode() or d_type.string()
                              or d_type.wstring() or d_type.interface()
                              or d_type.value() or d_type.valuebox()):
                        alloc = "new " + argtype.base()
                    if alloc != "":
                        marshal_block.out(arg_n + " = " + alloc + ";")
            elif h_is_ptr:
                if d_type.typecode():
                    marshal_block.out(arg_n + "_ = *" + arg_n + ";\n"+ \
                                      "*" + arg_n + " = " + \
                                      "::CORBA::TypeCode::_nil();")
                elif d_type.interface():
                    nilobjref = d_type.base().replace("_ptr", "::_nil()")
                    if isinstance(d_type.type().decl(), idlast.Forward):
                        nilobjref = nilobjref.replace("::_nil()",
                                                      "_Helper::_nil()")

                    marshal_block.out(arg_n + "_ = *" + arg_n + ";\n" + \
                                      "*" + arg_n + " = " + \
                                      nilobjref + ";")
                elif d_type.string():
                    marshal_block.out(arg_n + "_ = *" + arg_n + ";\n"+ \
                                      "*" + arg_n + " = " + \
                                      "(char*) _CORBA_String_helper::empty_string;")
                elif d_type.wstring():
                    marshal_block.out(arg_n + "_ = *" + arg_n + ";\n" + \
                                      "*" + arg_n + " = " + \
                                      "(::CORBA::WChar*) _CORBA_WString_helper::empty_wstring;")
                arg_n = "*" + arg_n
            skutil.unmarshall(marshal_block, None, argtype, None, arg_n, "_n")

        stream.out(template.interface_proxy_unmarshal_returnedvalues,
                   call_descriptor=self.__name,
                   marshal_block=marshal_block)
Beispiel #20
0
def visitUnion(node):
    scopedName = node.scopedName()
    mangled_name = mangleName(config.state['Private Prefix'] +\
                              "_tc_", scopedName)
    if alreadyDefined(mangled_name):
        return

    startingNode(node)

    # the key here is to redirect the bottom half to a buffer
    # just for now
    oldbottomhalf = self.bottomhalf
    self.bottomhalf = output.StringStream()

    insideModule = self.__immediatelyInsideModule
    self.__immediatelyInsideModule = 0

    # need to build a static array of node members in a similar fashion
    # to structs
    array = []
    switchType = types.Type(node.switchType())
    deref_switchType = switchType.deref()
    if isinstance(switchType.type(), idltype.Declared):
        save_resolving_dependency = self.__resolving_dependency
        if not node.constrType():
            self.__resolving_dependency = 1
        switchType.type().decl().accept(self)
        self.__resolving_dependency = save_resolving_dependency

    numlabels = 0
    numcases = 0
    hasDefault = None

    for c in node.cases():
        numcases = numcases + 1
        decl = c.declarator()
        caseType = types.Type(c.caseType())

        save_resolving_dependency = self.__resolving_dependency

        if not c.constrType():
            self.__resolving_dependency = 1

        if isinstance(caseType.type(), idltype.Declared):
            caseType.type().decl().accept(self)

        elif caseType.sequence():
            # anonymous sequence
            seqType = caseType.type().seqType()
            while isinstance(seqType, idltype.Sequence):
                seqType = seqType.seqType()
            if isinstance(seqType, idltype.Declared):
                # don't loop forever
                if not currently_being_defined(seqType.decl()):
                    seqType.decl().accept(self)

        self.__resolving_dependency = save_resolving_dependency

        typecode = mkTypeCode(caseType, decl, node)
        case_name = id.Name(decl.scopedName()).simple()

        for l in c.labels():
            if l.default():
                label = "0"
                hasDefault = numlabels
            else:
                label = switchType.literal(l.value())

            array.append('{"%s", %s, (CORBA::PR_unionDiscriminator)%s}' %
                         (case_name, typecode, label))
            numlabels = numlabels + 1

    discrim_tc = mkTypeCode(deref_switchType)
    repoID = node.repoId()

    union_name = id.Name(scopedName).simple()
    unionmember_mangled_name = mangleName(
        config.state['Private Prefix'] + "_unionMember_", scopedName)

    default_str = ""
    if hasDefault is None:
        default_str = "-1"
    else:
        default_str = str(hasDefault)

    tophalf.out("""\
static CORBA::PR_unionMember @unionmember_mangled_name@[] = {
  @members@
};
#ifdef @mangled_name@
#  undef @mangled_name@
#endif
static CORBA::TypeCode_ptr @mangled_name@ = CORBA::TypeCode::PR_union_tc("@repoID@", "@name@", @discrim_tc@, @unionmember_mangled_name@, @labels@, @default_str@, &@pprefix@_tcTrack);""",
                mangled_name=mangled_name,
                repoID=repoID,
                discrim_tc=discrim_tc,
                unionmember_mangled_name=unionmember_mangled_name,
                name=union_name,
                labels=str(numlabels),
                default_str=default_str,
                members=",\n".join(array),
                pprefix=config.state['Private Prefix'])

    defineName(unionmember_mangled_name)
    defineName(mangled_name)

    self.__immediatelyInsideModule = insideModule

    external_linkage(node)

    # restore the old bottom half
    oldbottomhalf.out(str(self.bottomhalf))
    self.bottomhalf = oldbottomhalf

    finishingNode()
Beispiel #21
0
def visitUnion(node):
    outer_environment = id.lookup(node)
    environment = outer_environment.enter(node.identifier())

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

    switchType = types.Type(node.switchType())

    exhaustive = ast.exhaustiveMatch(switchType, ast.allCaseLabelValues(node))
    defaultCase = ast.defaultCase(node)
    ast.markDefaultCase(node)

    defaultMember = ""
    if defaultCase:
        defaultLabel = ast.defaultLabel(defaultCase)
        default_scopedName = id.Name(defaultCase.declarator().scopedName())
        defaultMember = default_scopedName.simple()
        
    hasDefault = defaultCase != None

    # Booleans are a special case (isn't everything?)
    booleanWrap = switchType.boolean() and exhaustive


    # deal with types constructed here
    if node.constrType():
        node.switchType().decl().accept(self)
    for n in node.cases():
        if n.constrType():
            n.caseType().decl().accept(self)

    # --------------------------------------------------------------
    # union::operator{>>, <<}= (cdrStream& _n) [const]
    #
    # marshal/ unmarshal individual cases
    marshal_discriminator = output.StringStream()
    unmarshal_discriminator = output.StringStream()
    
    skutil.marshall(marshal_discriminator,environment,
                    switchType, None, "_pd__d", "_n")
    skutil.unmarshall(unmarshal_discriminator,environment,
                      switchType, None, "_pd__d", "_n")

    marshal_cases = output.StringStream()
    unmarshal_cases = output.StringStream()
    for c in node.cases():
        caseType = types.Type(c.caseType())
        decl = c.declarator()
        decl_scopedName = id.Name(decl.scopedName())
        decl_name = decl_scopedName.simple()

        # *** HERE: only output code once for each case, no matter how
        # *** many labels; don't bother with the default check -- do
        # *** it with the switch. Don't think we need _pd__default
        # *** member.

        if defaultCase == c:
            isDefault = 1
        else:
            isDefault = 0
        
        for l in c.labels():
            value = l.value()
            discrim_value = switchType.literal(value, environment)
            if l.default():
                unmarshal_cases.out("default:")
            else:
                unmarshal_cases.out("case " + discrim_value + ":")
                marshal_cases.out("case " + discrim_value + ":")

                marshal_cases.inc_indent()
                skutil.marshall(marshal_cases, environment,
                                caseType, decl, "_pd_" + decl_name, "_n")
                marshal_cases.out("break;")
                marshal_cases.dec_indent()

            unmarshal_cases.inc_indent()
            unmarshal_cases.out("_pd__default = " + str(isDefault) + ";")
            skutil.unmarshall(unmarshal_cases, environment,
                              caseType, decl, "_pd_" + decl_name, "_n")
            unmarshal_cases.out("break;")
            unmarshal_cases.dec_indent()

    if not hasDefault and not exhaustive:
        unmarshal_cases.out("""\
default:
  _pd__default = 1;
  break;""")

            
    if booleanWrap:
        marshal_cases.out(template.union_default_bool)
    else:
        marshal_cases.out(template.union_default)


    def marshal(stream = stream, exhaustive = exhaustive,
                hasDefault = hasDefault, defaultCase = defaultCase,
                environment = environment, defaultMember = defaultMember,
                marshal_cases = marshal_cases):
        if not exhaustive:

            def default(stream = stream, exhaustive = exhaustive,
                        hasDefault = hasDefault, defaultCase = defaultCase,
                        environment = environment,
                        defaultMember = defaultMember):
                if hasDefault:
                    caseType = types.Type(defaultCase.caseType())
                    decl = defaultCase.declarator()
                    decl_scopedName = id.Name(decl.scopedName())
                    decl_name = decl_scopedName.simple()
                    skutil.marshall(stream, environment, caseType,
                                    decl, "_pd_" + decl_name, "_n")
            stream.out(template.union_operators_nonexhaustive,
                       default = default,
                       cases = str(marshal_cases))
        else:
            stream.out(template.union_operators_exhaustive,
                       cases = str(marshal_cases))

    # write the operators
    stream.out(template.union_operators,
               name = name,
               marshal_discriminator = str(marshal_discriminator),
               unmarshal_discriminator = str(unmarshal_discriminator),
               marshal_cases = marshal,
               unmarshal_cases = str(unmarshal_cases))
                
        
    return
Beispiel #22
0
def monolithic(stream, tree):
    """Creates one large header with all definitions inside"""

    guard = id.Name([config.state['Basename']]).guard()

    header(stream, guard)

    # Extra DLL include stuff?
    if config.state['DLLIncludes']:
        sub_include_pre = output.StringStream()
        sub_include_post = output.StringStream()
        sub_include_pre.out(template.sub_include_pre, guard=guard)
        sub_include_post.out(template.sub_include_post, guard=guard)
    else:
        sub_include_pre = ""
        sub_include_post = ""

    # Add in any direct C++ from toplevel pragma if present
    cxx_direct_include = []
    directive = "hh "
    for pragma in tree.pragmas():
        # ignore all pragmas but those in the main file
        if pragma.file() != tree.file(): continue

        if pragma.text()[:len(directive)] == directive:
            cxx_direct_include.append(pragma.text()[len(directive):])

    includes = output.StringStream()

    # produce #includes for all files included by the IDL
    for include in ast.includes():
        # skip the main file
        if ast.mainFile() == include:
            continue

        # the old C++ BE makes orb.idl a special case
        # (might now be a redundant test)

        # dirname  == directory containing the include file
        # filename == extensionless filename
        # ext      == extension (typically .idl)
        (root, ext) = os.path.splitext(include)
        (dirname, filename) = os.path.split(root)

        # Name for external include guard. Always use the same suffix,
        # rather than taking suffix from the config.
        guardname = id.Name([filename]).guard() + "_hh"

        if config.state['Keep Include Path']:
            filename = root

        cxx_include = filename + config.state['HH Suffix']

        if config.state['Use Quotes']:
            cxx_include = '"' + cxx_include + '"'
        else:
            cxx_include = "<" + cxx_include + ">"

        includes.out(template.main_include,
                     guardname=guardname,
                     guard_prefix=config.state['GuardPrefix'],
                     filename=cxx_include)

    # generate the header definitions
    def forward_dec(stream=stream, tree=tree):
        forward = omniidl_be.cxx.header.forward.init(stream)
        tree.accept(forward)

    def main_defs(stream=stream, tree=tree):
        defs = omniidl_be.cxx.header.defs.init(stream)
        tree.accept(defs)

    def main_poa(stream=stream, tree=tree):
        # includes inline (non-flat) tie templates
        poa = omniidl_be.cxx.header.poa.init(stream)
        tree.accept(poa)

    def main_obv(stream=stream, tree=tree):
        obv = omniidl_be.cxx.header.obv.init(stream)
        tree.accept(obv)

    def other_tie(stream=stream, tree=tree):
        if config.state['Normal Tie'] and config.state['BOA Skeletons']:
            tie = omniidl_be.cxx.header.tie.BOATieTemplates(stream)
            tree.accept(tie)

        if config.state['Flattened Tie']:
            tie = omniidl_be.cxx.header.tie.FlatTieTemplates(stream)
            tree.accept(tie)

    def main_opers(stream=stream, tree=tree):
        opers = omniidl_be.cxx.header.opers.init(stream)
        tree.accept(opers)

    def main_marshal(stream=stream, tree=tree):
        marshal = omniidl_be.cxx.header.marshal.init(stream)
        tree.accept(marshal)

    # other stuff
    stream.out(template.main,
               cxx_direct_include="\n".join(cxx_direct_include),
               includes=includes,
               forward_declarations=forward_dec,
               defs=main_defs,
               poa=main_poa,
               obv=main_obv,
               other_tie=other_tie,
               operators=main_opers,
               marshalling=main_marshal,
               guard=guard,
               sub_include_pre=sub_include_pre,
               sub_include_post=sub_include_post)
Beispiel #23
0
    def out_localcall(self, stream, interface_name, operation, function_name):
        assert isinstance(stream, output.Stream)
        assert isinstance(interface_name, id.Name)

        impl_args = []

        for n, argument in enumerate(self.__arguments):
            arg_n = "tcd->arg_" + str(n)
            argtype = types.Type(argument.paramType())
            ((h_is_const,h_is_ptr),(s_is_holder,s_is_var)) = \
                         _arg_info(argtype,argument.direction())
            if h_is_ptr:
                arg_n = "*" + arg_n
            if s_is_holder and s_is_var:
                if argument.is_in():
                    if argument.is_out():
                        arg_n = arg_n + ".inout()"
                    else:
                        arg_n = arg_n + ".in()"
                else:
                    arg_n = arg_n + ".out()"
            impl_args.append(arg_n)

        if self.__has_return_value:
            result_string = "tcd->result = "
        else:
            result_string = ""

        if self.__contexts:
            impl_args.append("ctxt")

        # If we have no return value, no arguments, no exceptions, and
        # no contexts, we don't use the call descriptor argument at
        # all, so we do not give it a name, so as to avoid warnings on
        # some compilers.
        if result_string or impl_args or self.__exceptions or self.__contexts:
            cd_arg = " cd"
        else:
            cd_arg = ""

        # If we have no return value and no arguments at all then we don't
        # need to fetch the call descriptor. This suppresses a warning in gcc
        # about an unused variable.
        if result_string or impl_args:
            get_cd = self.__name + "* tcd = (" + self.__name + "*)cd;"
        else:
            get_cd = ""

        impl_call = output.StringStream()
        catch = output.StringStream()

        # Deal with context
        if self.__contexts:
            impl_call.out(template.interface_callback_context,
                          cname=self.__context_name,
                          count=str(len(self.__contexts)))

        # Deal with user exceptions
        raises = self.__exceptions
        if raises:
            for exception in raises:
                ex_scopedName = id.Name(exception.scopedName())
                catch.out(template.interface_operation_catch_exn,
                          exname=ex_scopedName.fullyQualify())

            impl_call.out(template.interface_callback_tryblock,
                          result=result_string,
                          cxx_operation_name=operation,
                          operation_arguments=", ".join(impl_args),
                          catch=str(catch))
        else:
            impl_call.out(template.interface_callback_invoke,
                          result=result_string,
                          cxx_operation_name=operation,
                          operation_arguments=", ".join(impl_args))

        stream.out(template.interface_callback,
                   local_call_descriptor=function_name,
                   cd_arg=cd_arg,
                   get_call_descriptor=get_cd,
                   impl_fqname=interface_name.prefix("_impl_").fullyQualify(),
                   name=interface_name.fullyQualify(),
                   impl_call=str(impl_call))
Beispiel #24
0
def visitValue(node):
    # Used for abstract value too

    startingNode(node)

    scopedName = node.scopedName()
    mangled_name = mangleName(config.state['Private Prefix'] + "_tc_",
                              scopedName)

    visitValueForward(node)

    # the key here is to redirect the bottom half to a buffer
    # just for now
    oldbottomhalf = self.bottomhalf
    self.bottomhalf = output.StringStream()

    insideModule = self.__immediatelyInsideModule
    self.__immediatelyInsideModule = 0

    # handle nested types
    for n in node.declarations():
        n.accept(self)

    # create the static typecodes for constructed types by setting
    # the resolving_dependency flag and recursing
    save_resolving_dependency = self.__resolving_dependency

    for child in node.statemembers():
        memberType = child.memberType()

        if child.constrType():
            self.__resolving_dependency = save_resolving_dependency
        else:
            self.__resolving_dependency = 1

        if isinstance(memberType, idltype.Declared):
            decl = memberType.decl()
            if not currently_being_defined(decl):
                decl.accept(self)

        elif isinstance(memberType, idltype.Sequence):
            # anonymous sequence (maybe sequence<sequence<...<T>>>)
            # Find the ultimate base type, and if it's user declared then
            # produce a typecode definition for it.
            base_type = memberType.seqType()
            while isinstance(base_type, idltype.Sequence):
                base_type = base_type.seqType()

            if isinstance(base_type, idltype.Declared):
                decl = base_type.decl()
                if not currently_being_defined(decl):
                    decl.accept(self)

    self.__resolving_dependency = save_resolving_dependency

    tophalf.out(str(buildStateMembersStructure(node)))

    if not alreadyDefined(mangled_name):
        # only define the name once
        defineName(mangled_name)

        valuemember_mangled_name = mangleName(
            config.state['Private Prefix'] + "_valuemember_", scopedName)
        assert alreadyDefined(valuemember_mangled_name)

        num = numStateMembers(node)
        repoID = node.repoId()
        value_name = id.Name(scopedName).simple()

        # Value modifiers
        modifierl = []
        if isinstance(node, idlast.Value):
            if node.custom():
                modifierl.append("CORBA::VM_CUSTOM")
            if node.truncatable():
                modifierl.append("CORBA::VM_TRUNCATABLE")
        else:
            assert isinstance(node, idlast.ValueAbs)
            modifierl.append("CORBA::VM_ABSTRACT")

        if modifierl:
            modifiers = "|".join(modifierl)
        else:
            modifiers = "CORBA::VM_NONE"

        # Concrete base
        inherits = node.inherits()
        if (isinstance(node, idlast.Value) and inherits
                and isinstance(inherits[0], idlast.Value)):

            visitValueForward(inherits[0])
            bscopedName = inherits[0].scopedName()
            concrete_base = mangleName(config.state['Private Prefix'] + "_tc_",
                                       bscopedName)
        else:
            concrete_base = "CORBA::TypeCode::PR_null_tc()"

        tophalf.out("""\
#ifdef @mangled_name@
#  undef @mangled_name@
#endif
static CORBA::TypeCode_ptr @mangled_name@ = CORBA::TypeCode::PR_value_tc("@repoID@", "@name@", @modifiers@, @concrete_base@, @valuemember_mangled_name@, @n@, &@pprefix@_tcTrack);
""",
                    mangled_name=mangled_name,
                    modifiers=modifiers,
                    concrete_base=concrete_base,
                    valuemember_mangled_name=valuemember_mangled_name,
                    name=value_name,
                    n=str(num),
                    repoID=repoID,
                    pprefix=config.state['Private Prefix'])

    self.__immediatelyInsideModule = insideModule

    external_linkage(node)
    # restore the old bottom half
    oldbottomhalf.out(str(self.bottomhalf))
    self.bottomhalf = oldbottomhalf
    finishingNode()
Beispiel #25
0
    def cc(self, stream):
        def _ptrToObjRef_ptr(self=self, stream=stream):
            has_abstract = self.interface().abstract()

            for i in self.interface().allInherits():
                if i.abstract(): has_abstract = 1

                stream.out(skel_template.interface_objref_repoID_ptr,
                           inherits_fqname=i.name().fullyQualify())

            if has_abstract:
                stream.out(skel_template.interface_objref_repoID_ptr,
                           inherits_fqname="CORBA::AbstractBase")

        def _ptrToObjRef_str(self=self, stream=stream):
            has_abstract = self.interface().abstract()

            for i in self.interface().allInherits():
                if i.abstract(): has_abstract = 1

                stream.out(skel_template.interface_objref_repoID_str,
                           inherits_fqname=i.name().fullyQualify())

            if has_abstract:
                stream.out(skel_template.interface_objref_repoID_str,
                           inherits_fqname="CORBA::AbstractBase")

        #
        # Build the inherits list

        inherits_str_list = []
        for i in self.interface().inherits():
            objref_name = i.name().prefix("_objref_")

            objref_str = objref_name.unambiguous(self._environment)

            if objref_name.needFlatName(self._environment):
                objref_str = objref_name.flatName()

            this_inherits_str = objref_str + "(ior, id)"
            inherits_str_list.append(this_inherits_str)

        inherits_str = ",\n".join(inherits_str_list)
        if inherits_str:
            comma = ","
        else:
            comma = ""

        if config.state['Shortcut']:
            inherits_str = inherits_str + ","
            init_shortcut = "_shortcut(0)"
        else:
            init_shortcut = ""

        if config.state['Shortcut'] == 2:
            release_shortcut = skel_template.interface_release_refcount_shortcut
        else:
            release_shortcut = ""

        stream.out(skel_template.interface_objref,
                   name=self.interface().name().fullyQualify(),
                   fq_objref_name=self.name().fullyQualify(),
                   objref_name=self.name().simple(),
                   inherits_str=inherits_str,
                   comma=comma,
                   _ptrToObjRef_ptr=_ptrToObjRef_ptr,
                   _ptrToObjRef_str=_ptrToObjRef_str,
                   init_shortcut=init_shortcut,
                   release_shortcut=release_shortcut)

        #
        # Shortcut

        shortcut_mode = config.state['Shortcut']

        if shortcut_mode:
            inherited = output.StringStream()
            for i in self.interface().inherits():
                objref_name = i.name().prefix("_objref_")

                objref_str = objref_name.unambiguous(self._environment)

                if objref_name.needFlatName(self._environment):
                    objref_str = objref_name.flatName()

                inherited.out(skel_template.interface_shortcut_inh,
                              parent=objref_str)

            if shortcut_mode == 1:
                tmpl = skel_template.interface_shortcut
            else:
                tmpl = skel_template.interface_shortcut_refcount

            stream.out(tmpl,
                       name=self.interface().name().fullyQualify(),
                       basename=self.interface().name().simple(),
                       fq_objref_name=self.name().fullyQualify(),
                       inherited=str(inherited))

        #
        # AMI poller

        poller = self.interface().amiPoller()
        poller_impl_name = None
        poller_methods = {}

        if poller is not None:
            astdecl = poller.astdecl()

            poller_impl_name = descriptor.ami_poller_impl(poller.name())
            poller_class = AMIPoller(poller_impl_name)

            method_decls = []
            inherited_methods = []
            direct_callables = astdecl.callables()

            for c in astdecl.all_callables():
                op = call.operation(poller, c)
                method_decl = _impl_Method(op, poller_class)
                method_decls.append(method_decl.hh())

                if c not in direct_callables:
                    inherited_methods.append(method_decl)
                else:
                    poller_methods[op.operation_name()] = method_decl

            stream.out(skel_template.interface_ami_poller_impl,
                       poller_impl_name=poller_impl_name,
                       poller_name=poller.name().fullyQualify(),
                       method_decls="\n".join(method_decls))

            for method in inherited_methods:
                method.cc(stream, "_wrongOperation();")

        #
        # Methods

        ami_descriptors = {}

        for method in self.methods():
            callable = self._callables[method]

            stream.out(skel_template.interface_operation_marker,
                       iface=self.interface().name().fullyQualify(),
                       operation=callable.operation_name())

            # signature is a text string form of the complete
            # operation signature
            signature = callable.signature()

            # we only need one descriptor for each _signature_ (not operation)

            if signature in _proxy_call_descriptors:
                call_descriptor = _proxy_call_descriptors[signature]
            else:
                call_descriptor = call.CallDescriptor(signature, callable)
                call_descriptor.out_desc(stream)
                _proxy_call_descriptors[signature] = call_descriptor

            # produce a localcall function
            node_name = self.interface().name()
            localcall_fn = descriptor.\
                           local_callback_fn(node_name,
                                             callable.operation_name(),
                                             signature)
            call_descriptor.out_localcall(stream, node_name,
                                          callable.method_name(), localcall_fn)

            # produce member function for this operation/attribute.
            body = output.StringStream()

            argnames = method.arg_names()

            if config.state['Shortcut']:
                if method.return_type().kind() != idltype.tk_void:
                    callreturn = "return "
                    voidreturn = ""
                else:
                    callreturn = ""
                    voidreturn = " return;"

                objref_class = method.parent_class()
                interface = objref_class.interface()
                implname = interface.name().prefix("_impl_").\
                           unambiguous(self._environment)

                if config.state['Shortcut'] == 2:
                    tmpl = skel_template.interface_operation_shortcut_refcount
                else:
                    tmpl = skel_template.interface_operation_shortcut

                body.out(tmpl,
                         impl_type=implname,
                         callreturn=callreturn,
                         voidreturn=voidreturn,
                         args=", ".join(argnames),
                         name=method.name())

            intf_env = self._environment.enter(
                "_objref_" + self.interface().name().simple())

            call_descriptor.out_objrefcall(body, callable.operation_name(),
                                           argnames, localcall_fn, intf_env)
            method.cc(stream, body)

            # Generate AMI descriptor
            if callable.ami():
                cd_names = call_descriptor.out_ami_descriptor(
                    stream, callable, node_name, localcall_fn,
                    poller_impl_name)

                for ami_method in method._ami_methods:

                    ami_callable = ami_method.callable()

                    body = output.StringStream()

                    ami_op_name = ami_callable.operation_name()
                    if ami_op_name.startswith("sendc_"):
                        call_descriptor.out_ami_sendc(body, ami_method,
                                                      cd_names, intf_env)

                    else:
                        # sendp
                        call_descriptor.out_ami_sendp(body, ami_method,
                                                      cd_names, intf_env)

                        poller_body = output.StringStream()
                        poller_method = poller_methods[ami_op_name[6:]]

                        call_descriptor.out_ami_poller(poller_body, ami_method,
                                                       poller_method, cd_names)

                        poller_method.cc(stream, poller_body)

                    ami_method.cc(stream, body)
Beispiel #26
0
    def cc(self, stream):
        def _ptrToObjRef_ptr(self=self, stream=stream):
            has_abstract = 0

            for i in self.interface().allInherits():
                if i.abstract():
                    has_abstract = 1

                stream.out(skel_template.interface_objref_repoID_ptr,
                           inherits_fqname=i.name().fullyQualify())

            stream.out(skel_template.interface_objref_repoID_ptr,
                       inherits_fqname="CORBA::LocalObject")

            if has_abstract:
                stream.out(skel_template.interface_objref_repoID_ptr,
                           inherits_fqname="CORBA::AbstractBase")

        def _ptrToObjRef_str(self=self, stream=stream):
            has_abstract = 0

            for i in self.interface().allInherits():
                if i.abstract():
                    has_abstract = 1

                stream.out(skel_template.interface_objref_repoID_str,
                           inherits_fqname=i.name().fullyQualify())

            stream.out(skel_template.interface_objref_repoID_str,
                       inherits_fqname="CORBA::LocalObject")

            if has_abstract:
                stream.out(skel_template.interface_objref_repoID_str,
                           inherits_fqname="CORBA::AbstractBase")

        stream.out(skel_template.local_interface_objref,
                   name=self.interface().name().fullyQualify(),
                   sname=self.interface().name().simple(),
                   fq_nil_name=self.name().fullyQualify(),
                   nil_name=self.name().simple(),
                   _ptrToObjRef_ptr=_ptrToObjRef_ptr,
                   _ptrToObjRef_str=_ptrToObjRef_str)

        for method in self.methods():
            callable = self._callables[method]

            # signature is a text string form of the complete
            # operation signature
            signature = callable.signature()

            # produce member function for this operation/attribute.
            body = output.StringStream()

            argnames = method.arg_names()

            body.out(skel_template.local_interface_nil_operation)

            if not method.return_type().void():
                body.out(skel_template.local_interface_nil_dummy_return,
                         method=method.name(),
                         args=", ".join(method.arg_names()))

            method.cc(stream, body)
            stream.out("\n")
Beispiel #27
0
def write_template(name,
                   inherits,
                   node,
                   stream,
                   Template=template.tie_template):
    # build methods which bind the interface operations and attributes
    # note that this includes inherited callables since tie
    # templates are outside the normal inheritance structure
    where = output.StringStream()

    # defined_so_far contains keys corresponding to method names which
    # have been defined already (and which should not be included twice)
    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

    buildCallables(node, where, buildCallables)

    stream.out(Template,
               tie_name=name,
               inherits=inherits,
               callables=str(where))
    return
Beispiel #28
0
def visitException(node):
    scopedName = node.scopedName()
    mangled_name = mangleName(config.state['Private Prefix'] + "_tc_",
                              scopedName)
    if alreadyDefined(mangled_name):
        return
    defineName(mangled_name)

    startingNode(node)

    # the key here is to redirect the bottom half to a buffer
    # just for now
    oldbottomhalf = self.bottomhalf
    self.bottomhalf = output.StringStream()

    # create the static typecodes for constructed types by setting
    # the resolving_dependency flag and recursing
    save_resolving_dependency = self.__resolving_dependency

    insideModule = self.__immediatelyInsideModule
    self.__immediatelyInsideModule = 0

    for child in node.members():
        memberType = child.memberType()

        if child.constrType():
            self.__resolving_dependency = save_resolving_dependency
        else:
            self.__resolving_dependency = 1

        if isinstance(memberType, idltype.Declared):
            memberType.decl().accept(self)

    self.__resolving_dependency = save_resolving_dependency
    self.__immediatelyInsideModule = insideModule

    # output the structure of members
    tophalf.out(str(buildMembersStructure(node)))

    num = numMembers(node)

    repoID = node.repoId()
    ex_name = id.Name(scopedName).simple()
    structmember_mangled_name = mangleName(config.state['Private Prefix'] + \
                                           "_structmember_", scopedName)
    if num == 0:
        structmember_mangled_name = "(CORBA::PR_structMember*) 0"
    tophalf.out("""\
static CORBA::TypeCode_ptr @mangled_name@ = CORBA::TypeCode::PR_exception_tc("@repoID@", "@name@", @structmember_mangled_name@, @n@, &@pprefix@_tcTrack);""",
                mangled_name=mangled_name,
                name=ex_name,
                n=str(num),
                structmember_mangled_name=structmember_mangled_name,
                repoID=repoID,
                pprefix=config.state['Private Prefix'])

    external_linkage(node)

    # restore the old bottom half
    oldbottomhalf.out(str(self.bottomhalf))
    self.bottomhalf = oldbottomhalf

    finishingNode()
Beispiel #29
0
def visitStruct(node):
    startingNode(node)

    # the key here is to redirect the bottom half to a buffer
    # just for now
    oldbottomhalf = self.bottomhalf
    self.bottomhalf = output.StringStream()

    insideModule = self.__immediatelyInsideModule
    self.__immediatelyInsideModule = 0

    # create the static typecodes for constructed types by setting
    # the resolving_dependency flag and recursing
    save_resolving_dependency = self.__resolving_dependency

    for child in node.members():
        memberType = child.memberType()

        if child.constrType():
            self.__resolving_dependency = save_resolving_dependency
        else:
            self.__resolving_dependency = 1

        if isinstance(memberType, idltype.Declared):
            memberType.decl().accept(self)

        elif isinstance(memberType, idltype.Sequence):
            # anonymous sequence (maybe sequence<sequence<...<T>>>)
            # Find the ultimate base type, and if it's user declared then
            # produce a typecode definition for it.
            base_type = memberType.seqType()
            while isinstance(base_type, idltype.Sequence):
                base_type = base_type.seqType()

            # if a struct is recursive, don't loop forever :)
            if isinstance(base_type, idltype.Declared):
                decl = base_type.decl()
                if not currently_being_defined(decl):
                    base_type.decl().accept(self)

    self.__resolving_dependency = save_resolving_dependency

    tophalf.out(str(buildMembersStructure(node)))

    scopedName = node.scopedName()
    mangled_name = mangleName(config.state['Private Prefix'] + "_tc_",
                              scopedName)
    if not alreadyDefined(mangled_name):
        # only define the name once

        defineName(mangled_name)

        structmember_mangled_name =\
                                  mangleName(config.state['Private Prefix'] + \
                                             "_structmember_", scopedName)
        assert alreadyDefined(structmember_mangled_name)

        num = numMembers(node)
        repoID = node.repoId()
        struct_name = id.Name(scopedName).simple()

        tophalf.out("""\
#ifdef @mangled_name@
#  undef @mangled_name@
#endif
static CORBA::TypeCode_ptr @mangled_name@ = CORBA::TypeCode::PR_struct_tc("@repoID@", "@name@", @structmember_mangled_name@, @n@, &@pprefix@_tcTrack);
""",
                    mangled_name=mangled_name,
                    structmember_mangled_name=structmember_mangled_name,
                    name=struct_name,
                    n=str(num),
                    repoID=repoID,
                    pprefix=config.state['Private Prefix'])

    self.__immediatelyInsideModule = insideModule

    external_linkage(node)

    # restore the old bottom half
    oldbottomhalf.out(str(self.bottomhalf))
    self.bottomhalf = oldbottomhalf
    finishingNode()