Ejemplo n.º 1
0
    def typeName(type):
        assert isinstance(type, types.Type)
        d_type = type.deref()
        # dereference the type, until just -before- it becomes a
        # sequence. Since a sequence doesn't have a scopedName(),
        # we use the scopedName() of the immediately preceeding
        # typedef which is an instance of idltype.Declared
        while type.typedef() and \
              not types.Type(type.type().decl().alias().aliasType()).sequence():
            type = types.Type(type.type().decl().alias().aliasType())

        if name_map.has_key(type.type().kind()):
            return name_map[type.type().kind()]
        if type.string():
            bound = ""
            if type.type().bound() != 0:
                bound = str(type.type().bound())
            return bound + "string"
        if type.wstring():
            bound = ""
            if type.type().bound() != 0:
                bound = str(type.type().bound())
            return bound + "wstring"

        if isinstance(type.type(), idltype.Fixed):
            return str(type.type().digits()) + "_" + \
                   str(type.type().scale()) + "fixed"

        if isinstance(type.type(), idltype.Declared):
            return id.Name(type.type().scopedName()).guard()

        util.fatalError("Error generating mangled name")
Ejemplo n.º 2
0
    def __var_argmapping(self, direction):
        # __var_argmapping(types.Type, direction): const * reference * pointer
        #  Returns info on argument mapping for a type in a _var
        #  context
        
        # CORBA2.3 P1-204 Table 1-4 T_var argument and result mapping
        kind = self.__type.kind()

        if (kind in [ idltype.tk_objref,
                      idltype.tk_struct,
                      idltype.tk_union,
                      idltype.tk_string,
                      idltype.tk_wstring,
                      idltype.tk_sequence,
                      idltype.tk_any,
                      idltype.tk_value,
                      idltype.tk_value_box,
                      idltype.tk_abstract_interface,
                      idltype.tk_local_interface ]
            or
            self.array()):

            return ( (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0) )[direction]

        util.fatalError("T_var argmapping requested for type with no such "
                        "concept")
        return
Ejemplo n.º 3
0
def run(tree, args):
    """Entrypoint to the C++ backend"""

    global run_before

    if run_before:
        util.fatalError("Sorry, the C++ backend cannot process more "
                        "than one IDL file at a time.")
    run_before = 1

    # Initialise modules that would otherwise contain circular imports
    call.init()
    iface.init()

    dirname, filename = os.path.split(tree.file())
    basename,ext      = os.path.splitext(filename)
    config.state['Basename']  = basename
    config.state['Directory'] = dirname

    process_args(args)

    try:
        # Check the input tree only contains stuff we understand
        support.checkIDL(tree)

        # Add AMI implied IDL if required
        if config.state['AMI']:
            from omniidl_be import ami
            tree.accept(ami.AMIVisitor())
        
        # initialise the handy ast module
        ast.__init__(tree)

        # Initialise the descriptor generating code
        descriptor.__init__(tree)

        # Build the map of AST nodes to Environments
        tree.accept(id.WalkTree())

        header.run(tree)
        
        skel.run(tree)
        
        # if we're generating code for Typecodes and Any then
        # we need to create the DynSK.cc file
        if config.state['Typecode']:
            dynskel.run(tree)

        if config.state['Example Code']:
            impl.run(tree)

    except SystemExit:
        # fatalError function throws SystemExit exception
        # delete all possibly partial output files
        for file in output.listAllCreatedFiles():
            os.unlink(file)
        
        raise
Ejemplo n.º 4
0
def lookup(node):
    """lookup : AST node -> Environment"""
    try:
        return _environments[node]
    except KeyError:
        try:
            nname = node.scopedName()
        except:
            nname = repr(node)

        util.fatalError("Failed to find environment corresponding to node (%s)"
                        % nname)
Ejemplo n.º 5
0
    def variable(self):
        """variable(types.Type): boolean
           Returns whether the type has a variable length representation
           under the C++ mapping"""
        type = self.__type

        if already_Variable.has_key(type.kind()):
            return already_Variable[type.kind()]

        if isinstance(type, idltype.Declared):
            decl = type.decl()
            return variableDecl(decl)

        util.fatalError("Error while computing the variable-ness of a type")
Ejemplo n.º 6
0
def direction(param):
    if param.is_in() and param.is_out():
        return INOUT
    elif param.is_in():
        return IN
    elif param.is_out():
        return OUT

    # Top 12 things likely to be overheard from a Klingon Programmer: 
    # ...
    #
    #   7) "Klingon function calls do not have 'parameters' - they
    #       have 'arguments' - and they ALWAYS WIN THEM."
    # ...

    util.fatalError("Illegal parameter direction")
Ejemplo n.º 7
0
def variableDecl(decl):
    """types.variableDecl(idlast.Decl): boolean
        Returns true if the declaration represents a variable type"""
    # interfaces are mapped to objects, which are always
    # variable types. same goes for exceptions.
    if isinstance(decl, idlast.Interface)       or \
       isinstance(decl, idlast.Forward)         or \
       isinstance(decl, idlast.Exception):
        return 1
    elif isinstance(decl, idlast.Const)         or \
         isinstance(decl, idlast.Enum):
        return 0
    
    # a typedef is only a type alias- as such it has no storage
    # at all. However it eventually points to something that would.
    elif isinstance(decl, idlast.Typedef):
        return Type(decl.aliasType()).variable()
    
    # a structure is variable if any one of its constituents
    # is also variable
    elif isinstance(decl, idlast.Struct):
        for m in decl.members():
            if Type(m.memberType()).variable():
                return 1
        return 0
        
    # a union is variable if any one if its constituents
    # is also variable
    elif isinstance(decl, idlast.Union):
        for c in decl.cases():
            if Type(c.caseType()).variable():
                return 1
        return 0

    # a declarator is variable if it is an alias to a variable
    # type
    elif isinstance(decl, idlast.Declarator) and \
         decl.alias() != None:
        return Type(decl.alias().aliasType()).variable()

    util.fatalError("Unknown AST node, scopedName = " +repr(decl.scopedName()))
Ejemplo n.º 8
0
def unsupportedType(found):
    error = "Unsupported IDL type found in input (" + found + ")\n\n"
    error = error + error_body
    util.fatalError(error)
Ejemplo n.º 9
0
    def _argmapping(self, direction):
        # _argmapping(types.Type, int direction): const * reference * pointer
        #   Returns info on operation argument mapping for a type for
        #   a particular direction.

        # CORBA2.3 P1-204 Table 1-3 Basic argument and result mapping
        array = self.array()
        variable = self.variable()

        if array and not variable:
            # array of fixed size elements
            return ( (1, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 1) )[direction]

        if array and variable:
            # array of variable size elements
            return ( (1, 0, 0), (0, 1, 1), (0, 0, 0), (0, 0, 1) )[direction]

        type = self.deref().__type
        kind = type.kind()

        if kind in [ idltype.tk_short, idltype.tk_long, idltype.tk_longlong,
                     idltype.tk_ushort, idltype.tk_ulong, idltype.tk_ulonglong,
                     idltype.tk_float, idltype.tk_double, idltype.tk_enum,
                     idltype.tk_longdouble, idltype.tk_boolean,
                     idltype.tk_char, idltype.tk_wchar, idltype.tk_octet ]:
            # from short to enum the entries are the same
            return ( (0, 0, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0) )[direction]

        if kind in [ idltype.tk_objref,
                     idltype.tk_TypeCode,
                     idltype.tk_abstract_interface,
                     idltype.tk_local_interface ]:

            # objref_ptr objref_ptr& objref_ptr& objref_ptr
            return ( (0, 0, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0) )[direction]

        if kind in [ idltype.tk_struct, idltype.tk_union ]:
            if variable:
                # variable struct or union
                return ((1, 1, 0), (0, 1, 1), (0, 1, 0), (0, 0, 1))[direction]
            else:
                # fixed struct or union
                return ((1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0))[direction]
                
        if kind in [ idltype.tk_string, idltype.tk_wstring ]:
            return ( (1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0) )[direction]

        if kind in [ idltype.tk_sequence, idltype.tk_any ]:
            return ( (1, 1, 0), (0, 1, 1), (0, 1, 0), (0, 0, 1) )[direction]

        if kind == idltype.tk_fixed:
            return ( (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0) )[direction]

        if kind in [ idltype.tk_value,
                     idltype.tk_value_box ]:

            return ( (0, 0, 1), (0, 1, 1), (0, 1, 1), (0, 0, 1) )[direction]

        if kind == idltype.tk_void:
            return (0, 0, 0)

        if kind in unsupported_typecodes:
            util.unsupportedIDL()

        util.fatalError("Unknown type encountered (kind = " + str(kind) + ")")
        return
Ejemplo n.º 10
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)
                    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 = 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 AssertionError("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 _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 = string.join(map(lambda x: x + """\
{
  // insert code here and remove the warning
  #warning "Code missing in function <""" + x + """>"
}

""",
                                implementations), "")
               
        self.stream.out(template.interface_code,
                        fqname = fqname,
                        impl_name = impl_flat_name,
                        impl_fqname = impl_flat_name,
                        operations = impls)
Ejemplo n.º 11
0
 def _cache(self, node):
     if _environments.has_key(node):
         util.fatalError("Unexpected inconsistency: encountered node " +\
                          "more than once while walking the tree")
     _environments[node] = self._env
Ejemplo n.º 12
0
def unsupportedIDL(found):
    error = "Unsupported IDL construct found in input (" + found + ")\n\n"
    error = error + error_body
    util.fatalError(error)
Ejemplo n.º 13
0
 def __setitem__(self, key, value):
     if self._config.has_key(key):
         self._config[key] = value
         return
     util.fatalError("Configuration key not found (" + key + ")")
Ejemplo n.º 14
0
 def __setitem__(self, key, value):
     if self._config.has_key(key):
         self._config[key] = value
         return
     util.fatalError("Configuration key not found (" + key + ")")
Ejemplo n.º 15
0
def unsupportedType(found):
    error = "Unsupported IDL type found in input (" + found + ")\n\n"
    error = error + error_body
    util.fatalError(error)
Ejemplo n.º 16
0
def mkTypeCode(type, declarator=None, node=None):
    assert isinstance(type, types.Type)

    prefix = "CORBA::TypeCode::PR_"
    tctrack = ", &" + config.state['Private Prefix'] + "_tcTrack"

    if declarator:
        assert isinstance(declarator, idlast.Declarator)
        dims = declarator.sizes()
        pre_str = ""
        post_str = ""
        for dim in dims:
            pre_str = pre_str + prefix + "array_tc(" + str(dim) + ", "
            post_str = post_str + tctrack + ")"

        return pre_str + mkTypeCode(type, None, node) + post_str

    type = type.type()

    basic = {
        idltype.tk_short: "short",
        idltype.tk_long: "long",
        idltype.tk_ushort: "ushort",
        idltype.tk_ulong: "ulong",
        idltype.tk_float: "float",
        idltype.tk_double: "double",
        idltype.tk_boolean: "boolean",
        idltype.tk_char: "char",
        idltype.tk_wchar: "wchar",
        idltype.tk_octet: "octet",
        idltype.tk_any: "any",
        idltype.tk_TypeCode: "TypeCode",
        idltype.tk_longlong: "longlong",
        idltype.tk_ulonglong: "ulonglong",
        idltype.tk_longdouble: "longdouble"
    }

    if type.kind() in basic:
        return prefix + basic[type.kind()] + "_tc()"

    if isinstance(type, idltype.Base):
        util.fatalError("Internal error generating TypeCode data")

    if isinstance(type, idltype.String):
        return prefix + "string_tc(" + str(type.bound()) + tctrack + ")"

    if isinstance(type, idltype.WString):
        return prefix + "wstring_tc(" + str(type.bound()) + tctrack + ")"

    if isinstance(type, idltype.Sequence):
        seqType = type.seqType()
        if isinstance(seqType, idltype.Declared):
            decl = seqType.decl()
            if hasattr(decl, "recursive") and decl.recursive() and \
                 currently_being_defined(decl):

                depth = recursive_Depth(decl)
                return prefix + "recursive_sequence_tc(" +\
                       str(type.bound()) + ", " + str(depth) + tctrack + ")"

        startingNode(type)
        ret = prefix + "sequence_tc(" + str(type.bound()) + ", " +\
              mkTypeCode(types.Type(type.seqType())) + tctrack + ")"
        finishingNode()
        return ret

    if isinstance(type, idltype.Fixed):
        return (prefix + "fixed_tc(%d,%d%s)" %
                (type.digits(), type.scale(), tctrack))

    assert isinstance(type, idltype.Declared)

    if type.kind() == idltype.tk_objref:
        scopedName = type.decl().scopedName()
        if scopedName == ["CORBA", "Object"]:
            return prefix + "Object_tc()"
        scopedName = id.Name(scopedName)

        repoID = type.decl().repoId()
        iname = scopedName.simple()
        return (prefix + 'interface_tc("' + repoID + '", "' + iname + '"' +
                tctrack + ')')

    elif type.kind() == idltype.tk_abstract_interface:
        scopedName = id.Name(type.decl().scopedName())

        repoID = type.decl().repoId()
        iname = scopedName.simple()
        return (prefix + 'abstract_interface_tc("' + repoID + '", "' + iname +
                '"' + tctrack + ')')

    elif type.kind() == idltype.tk_local_interface:
        scopedName = id.Name(type.decl().scopedName())

        repoID = type.decl().repoId()
        iname = scopedName.simple()
        return (prefix + 'local_interface_tc("' + repoID + '", "' + iname +
                '"' + tctrack + ')')

    guard_name = id.Name(type.scopedName()).guard()

    return config.state['Private Prefix'] + "_tc_" + guard_name
Ejemplo n.º 17
0
    def visitInterface(self, node):
        scopedName = id.Name(node.scopedName())
        openns, closens = namespaces(scopedName)

        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)
        wkptr_t = "hpp::weak_ptr<{}>".format(
            self.toCppNamespace(scopedName).fullyQualify(cxx=1))
        if is_base_class:
            key = hpp_servant_name(scopedName)
            impl_base_name = "hpp::corbaServer::ServantBase"
            if key in self.storages:
                st = self.storages[key]
                # declare storage
                self.interface_declarations.out(st.decl)
                storage = st.sc.simple() + "< " + wkptr_t + " >"
            else:
                storage = wkptr_t
            hpp_base_class = None
        else:
            baseScopedName = id.Name(node.inherits()[0].scopedName())
            hpp_base_class = self.toCppNamespace(baseScopedName).fullyQualify(
                cxx=1)
            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() + "< " + wkptr_t + " >"
                self.storages[fqname] = st
            else:
                storage = wkptr_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)

                error_type = "::hpp::Error"
                if len(c.raises()) > 0:
                    error_type = "::" + "::".join(c.raises()[0].scopedName())

                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,
                        error_type=error_type,
                        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,
                        error_type=error_type,
                        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,
                        error_type=error_type,
                        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)

        # 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,
            hpp_base_class=hpp_base_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,
        )
Ejemplo n.º 18
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,
                )
Ejemplo n.º 19
0
def process_args(args):
    for arg in args:
        if False:
            pass
        # if arg == "a":
        #    config.state['Typecode']          = 1
        # elif arg == "tp":
        #    config.state['Normal Tie']        = 1
        # elif arg == "tf":
        #    config.state['Flattened Tie']     = 1
        # elif arg == "splice-modules":
        #    config.state['Splice Modules']    = 1
        # elif arg == "example":
        #    config.state['Example Code']      = 1
        # elif arg == "F":
        #    config.state['Fragment']          = 1
        # elif arg == "BOA":
        #    config.state['BOA Skeletons']     = 1
        # elif arg == "old":
        #    config.state['Old Signatures']    = 1
        # elif arg == "old_prefix":
        #    config.state['Reserved Prefix']   = "_"
        # elif arg == "keep_inc_path":
        #    config.state['Keep Include Path'] = 1
        # elif arg == "use_quotes":
        #    config.state['Use Quotes']        = 1
        # elif arg == "virtual_objref":
        #    config.state['Virtual Objref Methods'] = 1
        # elif arg == "impl_mapping":
        #    config.state['Impl Mapping'] = 1
        # elif arg == "debug":
        #    config.state['Debug']             = 1
        elif arg[:2] == "h=":
            config.state["HH Suffix"] = arg[2:]
        elif arg[:3] == "hh=":
            config.state["HPP Suffix"] = arg[3:]
        elif arg[:2] == "i=":
            config.state["HXX Suffix"] = arg[2:]
        elif arg[:2] == "c=":
            config.state["CC Suffix"] = arg[2:]
        # elif arg[:2] == "s=":
        #    config.state['SK Suffix']         = arg[2:]
        # elif arg[:2] == "d=":
        #    config.state['DYNSK Suffix']      = arg[2:]
        # elif arg[:2] == "e=":
        #    config.state['IMPL Suffix']       = arg[2:]
        # elif arg == "inline":
        #    config.state['Inline Includes']   = 1
        # elif arg == "shortcut":
        #    config.state['Shortcut']          = 1
        # elif arg[:9] == "shortcut=":
        #    if arg[9:] == "refcount":
        #        config.state['Shortcut']      = 2
        #    elif arg[9:] == "simple":
        #        config.state['Shortcut']      = 1
        #    else:
        #        util.fatalError('Unknown shortcut option "%s"' % arg[9:])
        # elif arg == "dll_includes":
        #    config.state['DLLIncludes']       = 1
        elif arg[:len("guard_prefix=")] == "guard_prefix=":
            config.state["GuardPrefix"] = arg[len("guard_prefix="):]
        elif arg[:len("inc_prefix=")] == "inc_prefix=":
            config.state["Include Prefix"] = arg[len("inc_prefix="):]
        elif arg == "c++11":
            config.state["CC Suffix"] = arg[2:]
        else:
            util.fatalError('Argument "' + str(arg) + '" is unknown')
Ejemplo n.º 20
0
    def literal(self, value, environment = None):
        """literal(types.Type, value any, id.Environment option): string
           Returns a C++ representation of a value"""

        type = self.deref()
        kind = type.__type.kind()

        # (unsigned) short ints are themselves
        if kind in [ idltype.tk_short, idltype.tk_ushort ]:
            return str(value)

        # careful with long ints to avoid "L" postfix
        if kind in [ idltype.tk_long, idltype.tk_ulong ]:
            s = str(value)
            if s[-1] == 'L':             s = s[0:-1]
            if kind == idltype.tk_ulong: s = s + "U"
            return s

        if kind in [ idltype.tk_longlong, idltype.tk_ulonglong ]:
            s = str(value)
            if s[-1] == 'L':                 s = s[:-1]
            if kind == idltype.tk_ulonglong: s = s + "U"
            return "_CORBA_LONGLONG_CONST(" + s + ")"

        if kind in [ idltype.tk_float ]:
            return idlutil.reprFloat(value) + "F"

        if kind in [ idltype.tk_double ]:
            return idlutil.reprFloat(value)

        if kind in [ idltype.tk_longdouble ]:
            return idlutil.reprFloat(value) + "L"

        # chars are single-quoted
        if kind in [ idltype.tk_char ]:
            return "'" + idlutil.escapifyString(value) + "'"

        if kind in [ idltype.tk_wchar ]:
            return "L'" + idlutil.escapifyWString([value], "x") + "'"
        
        # booleans are straightforward
        if kind in [ idltype.tk_boolean ]:
            return str(value)

        if kind in [ idltype.tk_enum ]:
            # value is an enumerator
            enum_name = id.Name(value.scopedName())
            #enum_name = id.Name(type.__type.decl().scopedName() + [str(value)])
            return enum_name.unambiguous(environment)

        if kind in [ idltype.tk_string ]:
            return '"' + idlutil.escapifyString(value) + '"'

        if kind in [ idltype.tk_wstring ]:
            return 'L"' + idlutil.escapifyWString(value, "x") + '"'

        if kind in [ idltype.tk_octet ]:
            return str(value)

        if kind in [ idltype.tk_fixed ]:
            return '"' + value + '"'

        util.fatalError("Internal error when handling value (" +\
                        repr(value) +")" )
Ejemplo n.º 21
0
 def __getitem__(self, key):
     if self._config.has_key(key):
         return self._config[key]
     util.fatalError("Configuration key not found (" + key + ")")
Ejemplo n.º 22
0
def process_args(args):
    for arg in args:
        if arg == "a":
            config.state['Typecode'] = 1

        elif arg == "tp":
            config.state['Normal Tie'] = 1

        elif arg == "tf":
            config.state['Flattened Tie'] = 1

        elif arg == "splice-modules":
            config.state['Splice Modules'] = 1

        elif arg == "example":
            config.state['Example Code'] = 1

        elif arg == "F":
            config.state['Fragment'] = 1

        elif arg == "BOA":
            config.state['BOA Skeletons'] = 1

        elif arg == "old":
            config.state['Old Signatures'] = 1

        elif arg == "old-prefix" or arg == "old_prefix":
            config.state['Reserved Prefix'] = "_"

        elif arg == "keep-inc-path" or arg == "keep_inc_path":
            config.state['Keep Include Path'] = 1

        elif arg == "use-quotes" or arg == "use_quotes":
            config.state['Use Quotes'] = 1

        elif arg == "virtual-objref" or arg == "virtual_objref":
            config.state['Virtual Objref Methods'] = 1

        elif arg == "impl-mapping" or arg == "impl_mapping":
            config.state['Impl Mapping'] = 1

        elif arg == "debug":
            config.state['Debug'] = 1

        elif arg[:2] == "h=":
            config.state['HH Suffix'] = arg[2:]

        elif arg[:2] == "s=":
            config.state['SK Suffix'] = arg[2:]

        elif arg[:2] == "d=":
            config.state['DYNSK Suffix'] = arg[2:]

        elif arg[:2] == "e=":
            config.state['IMPL Suffix'] = arg[2:]

        elif arg == "inline":
            config.state['Inline Includes'] = 1

        elif arg == "shortcut":
            config.state['Shortcut'] = 1

        elif arg[:9] == "shortcut=":
            if arg[9:] == "refcount":
                config.state['Shortcut'] = 2
            elif arg[9:] == "simple":
                config.state['Shortcut'] = 1
            else:
                util.fatalError('Unknown shortcut option "%s"' % arg[9:])

        elif arg == "dll-includes" or arg == "dll_includes":
            config.state['DLLIncludes'] = 1

        elif arg[:13] == "guard-prefix=" or arg[:13] == "guard_prefix=":
            config.state['GuardPrefix'] = arg[14:]

        elif arg == "ami":
            config.state['AMI'] = 1

        else:
            util.fatalError('Argument "%s" is unknown' % arg)
Ejemplo n.º 23
0
 def __getitem__(self, key):
     if self._config.has_key(key):
         return self._config[key]
     util.fatalError("Configuration key not found (" + key + ")")
Ejemplo n.º 24
0
def unsupportedIDL(found):
    error = "Unsupported IDL construct found in input (" + found + ")\n\n"
    error = error + error_body
    util.fatalError(error)
Ejemplo n.º 25
0
def mkTypeCode(type, declarator = None, node = None):
    assert isinstance(type, types.Type)

    prefix   = "CORBA::TypeCode::PR_"
    tctrack  = ", &" + config.state['Private Prefix'] + "_tcTrack"

    if declarator:
        assert isinstance(declarator, idlast.Declarator)
        dims = declarator.sizes()
        pre_str = ""
        post_str = ""
        for dim in dims:
            pre_str = pre_str + prefix + "array_tc(" + str(dim) + ", "
            post_str = post_str + tctrack + ")"

        return pre_str + mkTypeCode(type, None, node) + post_str

    type = type.type()
    

    basic = {
        idltype.tk_short:      "short",
        idltype.tk_long:       "long",
        idltype.tk_ushort:     "ushort",
        idltype.tk_ulong:      "ulong",
        idltype.tk_float:      "float",
        idltype.tk_double:     "double",
        idltype.tk_boolean:    "boolean",
        idltype.tk_char:       "char",
        idltype.tk_wchar:      "wchar",
        idltype.tk_octet:      "octet",
        idltype.tk_any:        "any",
        idltype.tk_TypeCode:   "TypeCode",
        idltype.tk_longlong:   "longlong",
        idltype.tk_ulonglong:  "ulonglong",
        idltype.tk_longdouble: "longdouble"
        }
    if basic.has_key(type.kind()):
        return prefix + basic[type.kind()] + "_tc()"

    if isinstance(type, idltype.Base):
        util.fatalError("Internal error generating TypeCode data")
        raise AssertionError("Don't know how to generate TypeCode for"
                             "Base kind = " + repr(type.kind()))

    if isinstance(type, idltype.String):
        return prefix + "string_tc(" + str(type.bound()) + tctrack + ")"

    if isinstance(type, idltype.WString):
        return prefix + "wstring_tc(" + str(type.bound()) + tctrack + ")"

    if isinstance(type, idltype.Sequence):
        seqType = type.seqType()
        if isinstance(seqType, idltype.Declared):
            decl = seqType.decl()
            if hasattr(decl, "recursive") and decl.recursive() and \
                 currently_being_defined(decl):

                depth = recursive_Depth(decl)
                return prefix + "recursive_sequence_tc(" +\
                       str(type.bound()) + ", " + str(depth) + tctrack + ")"
            
        startingNode(type)
        ret = prefix + "sequence_tc(" + str(type.bound()) + ", " +\
              mkTypeCode(types.Type(type.seqType())) + tctrack + ")"
        finishingNode()
        return ret

    if isinstance(type, idltype.Fixed):
        return (prefix + "fixed_tc(%d,%d%s)" %
                (type.digits(),type.scale(),tctrack))

    assert isinstance(type, idltype.Declared)

    if type.kind() == idltype.tk_objref:
        scopedName = type.decl().scopedName()
        if scopedName == ["CORBA", "Object"]:
            return prefix + "Object_tc()"
        scopedName = id.Name(scopedName)
        
        repoID = type.decl().repoId()
        iname = scopedName.simple()
        return (prefix + 'interface_tc("' + repoID + '", "' +
                iname + '"' + tctrack + ')')

    elif type.kind() == idltype.tk_abstract_interface:
        scopedName = id.Name(type.decl().scopedName())
        
        repoID = type.decl().repoId()
        iname = scopedName.simple()
        return (prefix + 'abstract_interface_tc("' + repoID + '", "' +
                iname + '"' + tctrack + ')')

    elif type.kind() == idltype.tk_local_interface:
        scopedName = id.Name(type.decl().scopedName())
        
        repoID = type.decl().repoId()
        iname = scopedName.simple()
        return (prefix + 'local_interface_tc("' + repoID + '", "' +
                iname + '"' + tctrack + ')')

    guard_name = id.Name(type.scopedName()).guard()

    return config.state['Private Prefix'] + "_tc_" + guard_name
def process_args(args):
    for arg in args:
        if False:
            pass
        #if arg == "a":
        #    config.state['Typecode']          = 1
        #elif arg == "tp":
        #    config.state['Normal Tie']        = 1
        #elif arg == "tf":
        #    config.state['Flattened Tie']     = 1
        #elif arg == "splice-modules":
        #    config.state['Splice Modules']    = 1
        #elif arg == "example":
        #    config.state['Example Code']      = 1
        #elif arg == "F":
        #    config.state['Fragment']          = 1
        #elif arg == "BOA":
        #    config.state['BOA Skeletons']     = 1
        #elif arg == "old":
        #    config.state['Old Signatures']    = 1
        #elif arg == "old_prefix":
        #    config.state['Reserved Prefix']   = "_"
        #elif arg == "keep_inc_path":
        #    config.state['Keep Include Path'] = 1
        #elif arg == "use_quotes":
        #    config.state['Use Quotes']        = 1
        #elif arg == "virtual_objref":
        #    config.state['Virtual Objref Methods'] = 1
        #elif arg == "impl_mapping":
        #    config.state['Impl Mapping'] = 1
        #elif arg == "debug":
        #    config.state['Debug']             = 1
        elif arg[:2] == "h=":
            config.state['HH Suffix']         = arg[2:]
        elif arg[:3] == "hh=":
            config.state['HPP Suffix']        = arg[3:]
        elif arg[:2] == "i=":
            config.state['HXX Suffix']        = arg[2:]
        elif arg[:2] == "c=":
            config.state['CC Suffix']         = arg[2:]
        #elif arg[:2] == "s=":
        #    config.state['SK Suffix']         = arg[2:]
        #elif arg[:2] == "d=":
        #    config.state['DYNSK Suffix']      = arg[2:]
        #elif arg[:2] == "e=":
        #    config.state['IMPL Suffix']       = arg[2:]
        #elif arg == "inline":
        #    config.state['Inline Includes']   = 1
        #elif arg == "shortcut":
        #    config.state['Shortcut']          = 1
        #elif arg[:9] == "shortcut=":
        #    if arg[9:] == "refcount":
        #        config.state['Shortcut']      = 2
        #    elif arg[9:] == "simple":
        #        config.state['Shortcut']      = 1
        #    else:
        #        util.fatalError('Unknown shortcut option "%s"' % arg[9:])
        #elif arg == "dll_includes":
        #    config.state['DLLIncludes']       = 1
        elif arg[:len('guard_prefix=')] == "guard_prefix=":
            config.state['GuardPrefix']       = arg[len('guard_prefix='):]
        elif arg[:len('inc_prefix=')]   == "inc_prefix=":
            config.state['Include Prefix']    = arg[len('inc_prefix='):]
        else:
            util.fatalError("Argument \"" + str(arg) + "\" is unknown")
Ejemplo n.º 27
0
    def _argmapping(self, direction):
        # _argmapping(types.Type, int direction): const * reference * pointer
        #   Returns info on operation argument mapping for a type for
        #   a particular direction.

        # CORBA2.3 P1-204 Table 1-3 Basic argument and result mapping
        array = self.array()
        variable = self.variable()

        if array and not variable:
            # array of fixed size elements
            return ((1, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 1))[direction]

        if array and variable:
            # array of variable size elements
            return ((1, 0, 0), (0, 1, 1), (0, 0, 0), (0, 0, 1))[direction]

        type = self.deref().__type
        kind = type.kind()

        if kind in [
                idltype.tk_short, idltype.tk_long, idltype.tk_longlong,
                idltype.tk_ushort, idltype.tk_ulong, idltype.tk_ulonglong,
                idltype.tk_float, idltype.tk_double, idltype.tk_enum,
                idltype.tk_longdouble, idltype.tk_boolean, idltype.tk_char,
                idltype.tk_wchar, idltype.tk_octet
        ]:
            # from short to enum the entries are the same
            return ((0, 0, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0))[direction]

        if kind in [
                idltype.tk_objref, idltype.tk_TypeCode,
                idltype.tk_abstract_interface, idltype.tk_local_interface
        ]:

            # objref_ptr objref_ptr& objref_ptr& objref_ptr
            return ((0, 0, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0))[direction]

        if kind in [idltype.tk_struct, idltype.tk_union]:
            if variable:
                # variable struct or union
                return ((1, 1, 0), (0, 1, 1), (0, 1, 0), (0, 0, 1))[direction]
            else:
                # fixed struct or union
                return ((1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0))[direction]

        if kind in [idltype.tk_string, idltype.tk_wstring]:
            return ((1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0))[direction]

        if kind in [idltype.tk_sequence, idltype.tk_any]:
            return ((1, 1, 0), (0, 1, 1), (0, 1, 0), (0, 0, 1))[direction]

        if kind == idltype.tk_fixed:
            return ((1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 0))[direction]

        if kind in [idltype.tk_value, idltype.tk_value_box]:

            return ((0, 0, 1), (0, 1, 1), (0, 1, 1), (0, 0, 1))[direction]

        if kind == idltype.tk_void:
            return (0, 0, 0)

        if kind in unsupported_typecodes:
            util.unsupportedIDL()

        util.fatalError("Unknown type encountered (kind = " + str(kind) + ")")
        return
Ejemplo n.º 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)
Ejemplo n.º 29
0
    def literal(self, value, environment=None):
        """literal(types.Type, value any, id.Environment option): string
           Returns a C++ representation of a value"""

        type = self.deref()
        kind = type.__type.kind()

        # (unsigned) short ints are themselves
        if kind in [idltype.tk_short, idltype.tk_ushort]:
            return str(value)

        # careful with long ints to avoid "L" postfix
        if kind in [idltype.tk_long, idltype.tk_ulong]:
            s = str(value)
            if s[-1] == 'L': s = s[0:-1]
            if kind == idltype.tk_ulong: s = s + "U"
            return s

        if kind in [idltype.tk_longlong, idltype.tk_ulonglong]:
            s = str(value)
            if s[-1] == 'L': s = s[:-1]
            if kind == idltype.tk_ulonglong: s = s + "U"
            return "_CORBA_LONGLONG_CONST(" + s + ")"

        if kind in [idltype.tk_float]:
            return idlutil.reprFloat(value) + "F"

        if kind in [idltype.tk_double]:
            return idlutil.reprFloat(value)

        if kind in [idltype.tk_longdouble]:
            return idlutil.reprFloat(value) + "L"

        # chars are single-quoted
        if kind in [idltype.tk_char]:
            return "'" + idlutil.escapifyString(value) + "'"

        if kind in [idltype.tk_wchar]:
            return "L'" + idlutil.escapifyWString([value], "x") + "'"

        # booleans are straightforward
        if kind in [idltype.tk_boolean]:
            return str(value)

        if kind in [idltype.tk_enum]:
            # value is an enumerator
            enum_name = id.Name(value.scopedName())
            #enum_name = id.Name(type.__type.decl().scopedName() + [str(value)])
            return enum_name.unambiguous(environment)

        if kind in [idltype.tk_string]:
            return '"' + idlutil.escapifyString(value) + '"'

        if kind in [idltype.tk_wstring]:
            return 'L"' + idlutil.escapifyWString(value, "x") + '"'

        if kind in [idltype.tk_octet]:
            return str(value)

        if kind in [idltype.tk_fixed]:
            return '"' + value + '"'

        util.fatalError("Internal error when handling value (" +\
                        repr(value) +")" )
Ejemplo n.º 30
0
def process_args(args):
    for arg in args:
        if arg == "a":
            config.state['Typecode']          = 1

        elif arg == "tp":
            config.state['Normal Tie']        = 1

        elif arg == "tf":
            config.state['Flattened Tie']     = 1

        elif arg == "splice-modules":
            config.state['Splice Modules']    = 1

        elif arg == "example":
            config.state['Example Code']      = 1

        elif arg == "F":
            config.state['Fragment']          = 1

        elif arg == "BOA":
            config.state['BOA Skeletons']     = 1

        elif arg == "old":
            config.state['Old Signatures']    = 1

        elif arg == "old-prefix" or arg == "old_prefix":
            config.state['Reserved Prefix']   = "_"

        elif arg == "keep-inc-path" or arg == "keep_inc_path":
            config.state['Keep Include Path'] = 1

        elif arg == "use-quotes" or arg == "use_quotes":
            config.state['Use Quotes']        = 1

        elif arg == "virtual-objref" or arg == "virtual_objref":
            config.state['Virtual Objref Methods'] = 1

        elif arg == "impl-mapping" or arg == "impl_mapping":
            config.state['Impl Mapping'] = 1

        elif arg == "debug":
            config.state['Debug']             = 1

        elif arg[:2] == "h=":
            config.state['HH Suffix']         = arg[2:]

        elif arg[:2] == "s=":
            config.state['SK Suffix']         = arg[2:]

        elif arg[:2] == "d=":
            config.state['DYNSK Suffix']      = arg[2:]

        elif arg[:2] == "e=":
            config.state['IMPL Suffix']       = arg[2:]

        elif arg == "inline":
            config.state['Inline Includes']   = 1

        elif arg == "shortcut":
            config.state['Shortcut']          = 1

        elif arg[:9] == "shortcut=":
            if arg[9:] == "refcount":
                config.state['Shortcut']      = 2
            elif arg[9:] == "simple":
                config.state['Shortcut']      = 1
            else:
                util.fatalError('Unknown shortcut option "%s"' % arg[9:])

        elif arg == "dll-includes" or arg == "dll_includes":
            config.state['DLLIncludes']       = 1

        elif arg[:13] == "guard-prefix=" or arg[:13] == "guard_prefix=":
            config.state['GuardPrefix']       = arg[14:]

        elif arg == "ami":
            config.state['AMI']               = 1

        else:
            util.fatalError('Argument "%s" is unknown' % arg)
Ejemplo n.º 31
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)