def visitValueAbs(self, node): if node.inherits(): inheritl = [] for i in node.inherits(): inheritl.append("::" + idlutil.ccolonName(i.scopedName())) inherits = ": " + string.join(inheritl, ", ") + " " else: inherits = "" if node.supports(): inheritl = [] for i in node.supports(): inheritl.append("::" + idlutil.ccolonName(i.scopedName())) inherits = (inherits + "supports " + string.join(inheritl, ", ") + " ") self.st.out("""\ abstract valuetype @id@ @inherits@{""", id=node.identifier(), inherits=inherits) self.st.inc_indent() for n in node.contents(): n.accept(self) self.st.dec_indent() self.st.out("""\ };""")
def visitValueAbs(self, node): if node.inherits(): inheritl = [] for i in node.inherits(): inheritl.append("::" + idlutil.ccolonName(i.scopedName())) inherits = ": " + string.join(inheritl, ", ") + " " else: inherits = "" if node.supports(): inheritl = [] for i in node.supports(): inheritl.append("::" + idlutil.ccolonName(i.scopedName())) inherits = (inherits + "supports " + string.join(inheritl, ", ") + " ") self.st.out("""\ abstract valuetype @id@ @inherits@{""", id = node.identifier(), inherits=inherits) self.st.inc_indent() for n in node.contents(): n.accept(self) self.st.dec_indent() self.st.out("""\ };""")
def visitInterface(self, node): name = idlutil.ccolonName(node.scopedName()) if node.mainFile(): for c in node.callables(): if isinstance(c, idlast.Operation): print(name + "::" + c.identifier() + "()")
def outputTypedef(self, node, name): attr = "" ma = "" node.aliasType().accept(self) type = self.getResultType() type = type.replace("<","_"); type = type.replace(">","_"); type = type.replace(":","_"); for d in node.declarators(): n = 0 idx = "" typename = idlutil.ccolonName(d.scopedName()) self.st.out("uint32_t @tn@_@name@(@ma@MessageBuffer_t buffer, uint32_t offset, @attr@@tn@ *value)", tn=string.replace(typename, ":", "_"), name=name, attr=attr, ma=ma) self.st.out("{") self.st.inc_indent() self.st.out("uint32_t typeOffset = 0;") self.st.out("uint32_t idx;") for s in d.sizes(): self.st.out("for (idx=0; idx<@s@; idx++)", n=n, s=s) self.st.out("{") self.st.inc_indent() idx = idx + "[idx]" n=n+1 self.st.out("typeOffset += @type@_@name@(buffer, offset + typeOffset, value@idx@);", type=type, name=name, idx=idx) for s in d.sizes(): self.st.dec_indent() self.st.out("}") self.st.out("return typeOffset;") self.st.dec_indent() self.st.out("}\n")
def visitInterface(self, node): if len(node.inherits()) != 0: inheritl = [] for i in node.inherits(): inheritl.append("public " + idlutil.ccolonName(i.scopedName())) inherits = ": " + string.join(inheritl, ", ") + " " else: inherits = "" self.st.out("""\ class @id@ @inherits@ { public: virtual ~@id@() {};""", id=node.identifier(), inherits=inherits) self.st.inc_indent() for n in node.contents(): n.accept(self) self.st.dec_indent() self.st.out("""\ }; """)
def visitOperation(self, node): if node.oneway(): oneway = "oneway " else: oneway = "" node.returnType().accept(self) rtype = self.__result_type paraml = [] for p in node.parameters(): if p.is_in() and p.is_out(): inout = "inout" elif p.is_in(): inout = "in" else: inout = "out" p.paramType().accept(self) type = self.__result_type paraml.append(inout + " " + type + " " + p.identifier()) params = string.join(paraml, ", ") if len(node.raises()) > 0: raisel = [] for r in node.raises(): ename = idlutil.ccolonName(r.scopedName()) raisel.append(ename) raises = " raises (" + string.join(raisel, ", ") + ")" else: raises = "" self.st.out("""\ @oneway@@rtype@ @id@(@params@)@raises@;""", oneway=oneway, rtype=rtype, id=node.identifier(), params=params, raises=raises)
def visitInterface(self, node): if len(node.inherits()) != 0: inheritl = [] for i in node.inherits(): inheritl.append("::" + idlutil.ccolonName(i.scopedName())) inherits = ": " + string.join(inheritl, ", ") + " " else: inherits = "" if node.abstract(): qual = "abstract " elif node.local(): qual = "local " else: qual = "" self.st.out("""\ @qual@interface @id@ @inherits@{""", id = node.identifier(), inherits=inherits, qual=qual) self.st.inc_indent() for n in node.contents(): n.accept(self) self.st.dec_indent() self.st.out("""\ };""")
def visitInterface(self, node): name = idlutil.ccolonName(node.scopedName()) if node.mainFile(): for c in node.callables(): if isinstance(c, idlast.Operation): print name + "::" + c.identifier() + "()"
def visitOperation(self, node): node.returnType().accept(self) rtype = self.__result_type paraml = [] for p in node.parameters(): if p.is_in() and p.is_out(): inout = "" elif p.is_in(): inout = "const" else: inout = "" p.paramType().accept(self) type = self.__result_type if type != 'void': if type in tools.ttsMap.values(): paraml.append(inout + ' ' + type + ' ' + p.identifier()) else: paraml.append(inout + ' ' + type + '& ' + p.identifier()) else: paraml.append(inout + ' ' + type + ' ' + p.identifier()) params = string.join(paraml, ", ") if len(node.raises()) > 0: raisel = [] for r in node.raises(): ename = idlutil.ccolonName(r.scopedName()) raisel.append(ename) raises = " throw (" + string.join(raisel, ", ") + ")" else: raises = "" self.st.out(self.templates[self.__class__.__name__]['operation'], rtype=rtype, id=node.identifier(), params=params, raises=raises)
def visitInterface(self, node): if len(node.inherits()) != 0: inheritl = [] for i in node.inherits(): inheritl.append("public " + idlutil.ccolonName(i.scopedName())) inherits = ": " + string.join(inheritl, ", ") + " " else: inherits = "" self.st.out("""\ class @id@ @inherits@ { public: virtual ~@id@() {}""", id=node.identifier(), inherits=inherits) self.st.inc_indent() for n in node.contents(): n.accept(self) self.st.dec_indent() self.st.out("""\ }; """)
def visitInterface(self, node): if len(node.inherits()) != 0: inheritl = [] for i in node.inherits(): inheritl.append("::" + idlutil.ccolonName(i.scopedName())) inherits = ": " + string.join(inheritl, ", ") + " " else: inherits = "" if node.abstract(): qual = "abstract " elif node.local(): qual = "local " else: qual = "" self.st.out("""\ @qual@interface @id@ @inherits@{""", id=node.identifier(), inherits=inherits, qual=qual) self.st.inc_indent() for n in node.contents(): n.accept(self) self.st.dec_indent() self.st.out("""\ };""")
def outputStruct(self, node, name): attr = "" ma = "" ref = "&" typename = idlutil.ccolonName(node.scopedName()) self.st.out("uint32_t @sn@_@name@(@ma@MessageBuffer_t buffer, uint32_t offset, @attr@@sn@ *value)", sn=string.replace(typename, ":", "_"), name=name, attr=attr, ma=ma) self.st.out("{") self.st.inc_indent() self.st.out("uint32_t structOffset = 4;") self.st.out("uint32_t idx;") for m in node.members(): m.memberType().accept(self) type = self.getResultType() type = type.replace("<","_"); type = type.replace(">","_"); type = type.replace(":","_"); for d in m.declarators(): n = 0 idx = "" for s in d.sizes(): self.st.out("for (idx=0; idx<@s@; idx++)", n=n, s=s) self.st.out("{") self.st.inc_indent() idx = idx + "[idx]" n=n+1 self.st.out("structOffset += @type@_@name@(buffer, offset+structOffset, @ref@(value->@id@@idx@));", type=type, id=d.identifier(), name=name, idx=idx, ref=ref) for s in d.sizes(): self.st.dec_indent() self.st.out("}") if (name == "marshal"): self.st.out("(void) uint32_t_marshal(buffer, offset, &structOffset); // struct length") self.st.out("return structOffset;") self.st.dec_indent() self.st.out("}\n")
def outputEnum(self, node, name): attr = "" ma = "" ref = "*" typename = idlutil.ccolonName(node.scopedName()) self.st.out("extern uint32_t @tn@_@name@(@ma@MessageBuffer_t buffer, uint32_t offset, @attr@@tn@ @ref@value);", tn = string.replace(typename, ":", "_"), name=name, attr=attr, ma=ma,ref=ref)
def visitConst(self, node): node.constType().accept(self) type = self.__result_type if node.constKind() == idltype.tk_enum: value = "::" + idlutil.ccolonName(node.value().scopedName()) elif node.constKind() == idltype.tk_string: value = '"' + idlutil.escapifyString(node.value()) + '"' elif node.constKind() == idltype.tk_wstring: value = 'L"' + idlutil.escapifyWString(node.value()) + '"' elif node.constKind() == idltype.tk_wchar: value = "L'" + idlutil.escapifyWString([node.value()]) + "'" elif node.constKind() in [ idltype.tk_float, idltype.tk_double, idltype.tk_longdouble ]: value = idlutil.reprFloat(node.value()) elif node.constKind() == idltype.tk_fixed: value = node.value() + "d" else: value = str(node.value()) self.st.out("""\ const @type@ @id@ = @value@;""", type=type, id=node.identifier(), value=value)
def visitInterface(self, node): name = idlutil.ccolonName(node.scopedName()) if "Attributes" == node.identifier(): processor = CxxAttributeCodeSetCaseInterfaceVisitor(self.st, self.func) for n in node.contents(): n.accept(processor)
def visitConst(self, node): node.constType().accept(self) type = self.__result_type if node.constKind() == idltype.tk_enum: value = "::" + idlutil.ccolonName(node.value().scopedName()) elif node.constKind() == idltype.tk_string: value = '"' + idlutil.escapifyString(node.value()) + '"' elif node.constKind() == idltype.tk_wstring: value = 'L"' + idlutil.escapifyWString(node.value()) + '"' elif node.constKind() == idltype.tk_wchar: value = "L'" + idlutil.escapifyWString([node.value()]) + "'" elif node.constKind() in [idltype.tk_float, idltype.tk_double, idltype.tk_longdouble]: value = idlutil.reprFloat(node.value()) elif node.constKind() == idltype.tk_fixed: value = node.value() + "d" else: value = str(node.value()) self.st.out("""\ const @type@ @id@ = @value@;""", type=type, id=node.identifier(), value=value)
def visitOperation(self, node): self.operations.append(node.identifier()) node.returnType().accept(self) rtype = self.__result_type paraml = [] i = 0 for p in node.parameters(): p.paramType().accept(self) ptype = self.__result_type paraml.append((ptype, 'param' + str(i), p.is_out())) i += 1 params_def = '\n'.join( map(lambda (ptype, name, is_out): ptype + ' ' + name + ';', paraml)) params_serialize = 'dboost::iserializer is(m);\nis ' if len( paraml) > 0 else '' params_serialize += ' '.join( map(lambda (ptype, name, is_out): '& ' + name, paraml)) if params_serialize != '': params_serialize += ';' params_out = filter(lambda (ptype, name, is_out): is_out, paraml) params_out_serialize = 'dboost::oserializer os(result.get());\nos ' if rtype != 'void' or len( params_out) > 0 else '' params_out_serialize += '& r ' if rtype != 'void' else '' params_out_serialize += ' '.join( map(lambda (ptype, name, is_out): '& ' + name, params_out)) if params_out_serialize != '': params_out_serialize += ';' call = '' if rtype != 'void': call += rtype + ' r = ' call += 't->' + node.identifier() + '(' call += ', '.join(map(lambda (type, name, is_out): name, paraml)) call += ')' raisel = [] if len(node.raises()) > 0: for r in node.raises(): ename = idlutil.ccolonName(r.scopedName()) raisel.append(ename) raises = '\n'.join(map(self.__exceptionCatch, raisel)) self.st.out(self.templates[self.__class__.__name__]['operation'], operation=node.identifier(), interface=self.interface, params_def=params_def, params_serialize=params_serialize, params_out_serialize=params_out_serialize, call=call, module_name=self.module_name, class_name=self.class_name, exception_catch=raises) self.st.out("""\ } """)
def visitInterface(self, node): name = idlutil.ccolonName(node.scopedName()) if "Attributes" == node.identifier(): processor = CxxAttributesStaticVisitor(self.st) else: processor = CxxStaticVisitor(self.st) for n in node.contents(): n.accept(processor)
def visitValue(self, node): if node.inherits(): inheritl = [] for i in node.inherits(): inheritl.append("::" + idlutil.ccolonName(i.scopedName())) if node.truncatable(): truncatable = "truncatable " else: truncatable = "" inherits = ": " + truncatable + string.join(inheritl, ", ") + " " else: inherits = "" if node.supports(): inheritl = [] for i in node.supports(): inheritl.append("::" + idlutil.ccolonName(i.scopedName())) inherits = inherits + "supports " + string.join(inheritl, ", ") + " " if node.custom(): custom = "custom " else: custom = "" self.st.out( """\ @custom@valuetype @id@ @inherits@{""", id=node.identifier(), inherits=inherits, custom=custom, ) self.st.inc_indent() for n in node.contents(): n.accept(self) self.st.dec_indent() self.st.out( """\ };""" )
def getCppTypeText(self, typ, out=False, full=NOT_FULL): if isinstance(typ, idltype.Base): return cxx.types.basic_map[typ.kind()] if isinstance(typ, idltype.String): return ('char*' if out else 'const char*') # ?? if isinstance(typ, idltype.Declared): postfix = ('*' if out and cxx.types.variableDecl(typ.decl()) else '') return self.getCppTypeText(typ.decl(), False, full) + postfix if isinstance(typ, idlast.Struct): if full == CPP_FULL: name = idlutil.ccolonName(typ.scopedName()) elif full == ROS_FULL: return '_'.join(typ.scopedName()) # return else: name = typ.identifier() return name + ('*' if out and cxx.types.variableDecl(typ) else '') if isinstance(typ, idlast.Enum) or \ isinstance(typ, idlast.Interface) or \ isinstance(typ, idlast.Operation): if full == CPP_FULL: if (idlutil.ccolonName( typ.scopedName()) == "RTC::LightweightRTObject"): return idlutil.ccolonName(typ.scopedName()) + "_var" else: return idlutil.ccolonName(typ.scopedName()) elif full == ROS_FULL: return '_'.join(typ.scopedName()) else: return typ.identifier() if isinstance(typ, idlast.Typedef): if full == CPP_FULL: return idlutil.ccolonName(typ.declarators()[0].scopedName()) elif full == ROS_FULL: return '_'.join(typ.declarators()[0].scopedName()) else: return typ.declarators()[0].identifier() if isinstance(typ, idlast.Declarator): return self.getCppTypeText(typ.alias(), out, full) return 'undefined'
def outputTypedef(self, node, name): attr = "" ma = "" node.aliasType().accept(self) type = self.getResultType() for d in node.declarators(): n = 0 idx = "" typename = idlutil.ccolonName(d.scopedName()) self.st.out("extern uint32_t @tn@_@name@(@ma@MessageBuffer_t buffer, uint32_t offset, @attr@@tn@ *value);", tn=string.replace(typename, ":", "_"), name=name, attr=attr, ma=ma)
def visitEnum(self, node): typename = idlutil.ccolonName(node.scopedName()) self.st.out("typedef enum") self.st.out("{") self.st.inc_indent() enuml = [] for e in node.enumerators(): enuml.append(e.identifier()) self.st.out(string.join(enuml, ", ")) self.st.dec_indent() self.st.out("} @en@;\n", en=string.replace(typename, ":", "_"))
def visitTypedef(self, node): if node.constrType(): node.aliasType().decl().accept(self) node.aliasType().accept(self) type = self.getResultType() for d in node.declarators(): d.accept(self) arr = self.getResultArray() typename = idlutil.ccolonName(d.scopedName()) self.st.out("typedef @type@ @id@@arr@;\n", type=type, id=string.replace(typename, ":", "_"), arr=arr);
def visitValue(self, node): if node.inherits(): inheritl = [] for i in node.inherits(): inheritl.append("::" + idlutil.ccolonName(i.scopedName())) if node.truncatable(): truncatable = "truncatable " else: truncatable = "" inherits = ": " + truncatable + string.join(inheritl, ", ") + " " else: inherits = "" if node.supports(): inheritl = [] for i in node.supports(): inheritl.append("::" + idlutil.ccolonName(i.scopedName())) inherits = (inherits + "supports " + string.join(inheritl, ", ") + " ") if node.custom(): custom = "custom " else: custom = "" self.st.out("""\ @custom@valuetype @id@ @inherits@{""", id=node.identifier(), inherits=inherits, custom=custom) self.st.inc_indent() for n in node.contents(): n.accept(self) self.st.dec_indent() self.st.out("""\ };""")
def visitDeclaredType(self, type): self.__result_type = idlutil.ccolonName(type.decl().scopedName()) if type.unalias().kind() in [idltype.tk_null, idltype.tk_void, idltype.tk_short, idltype.tk_long, idltype.tk_ushort, idltype.tk_ulong, idltype.tk_float, idltype.tk_double, idltype.tk_boolean, idltype.tk_char, idltype.tk_octet, idltype.tk_any, idltype.tk_TypeCode, idltype.tk_Principal, idltype.tk_longlong, idltype.tk_ulonglong, idltype.tk_longdouble, idltype.tk_wchar, idltype.tk_enum]: self.basetype = 1 else: self.basetype = 0 self.__result_array = ""
def visitUnion(self, node): if node.constrType(): self.st.out("""\ union @id@ switch (""", id = node.identifier()) self.st.inc_indent() node.switchType().decl().accept(self) self.st.out(""") {""") self.st.dec_indent else: node.switchType().accept(self) stype = self.__result_type self.st.out("""\ union @id@ switch (@stype@) {""", id=node.identifier(), stype=stype) for c in node.cases(): if c.constrType(): self.st.inc_indent() c.caseType().decl().accept(self) self.st.dec_indent() for l in c.labels(): if l.default(): self.st.out("""\ default:""") else: if l.labelKind() == idltype.tk_enum: lv = "::" + idlutil.ccolonName(l.value().scopedName()) elif l.labelKind() == idltype.tk_char: lv = "'" + repr(l.value())[1:-1] + "'" else: lv = str(l.value()) self.st.out("""\ case @lv@:""", lv=lv) c.caseType().accept(self) type = self.__result_type c.declarator().accept(self) decl = self.__result_declarator self.st.out("""\ @type@ @decl@;""", type=type, decl=decl) self.st.out("};")
def getCppTypeText(self, typ, out=False, full=NOT_FULL): if isinstance(typ, idltype.Base): return cxx.types.basic_map[typ.kind()] if isinstance(typ, idltype.String): return ('char*' if out else 'const char*') # ?? if isinstance(typ, idltype.Declared): postfix = ('*' if out and cxx.types.variableDecl(typ.decl()) else '') return self.getCppTypeText(typ.decl(), False, full) + postfix if isinstance(typ, idlast.Struct): if full == CPP_FULL: name = idlutil.ccolonName(typ.scopedName()) elif full == ROS_FULL: return '_'.join(typ.scopedName()) # return else: name = typ.identifier() return name + ('*' if out and cxx.types.variableDecl(typ) else '') if isinstance(typ, idlast.Enum) or \ isinstance(typ, idlast.Interface) or \ isinstance(typ, idlast.Operation): if full == CPP_FULL: if ( idlutil.ccolonName(typ.scopedName()) == "RTC::LightweightRTObject") : return idlutil.ccolonName(typ.scopedName())+"_var" else: return idlutil.ccolonName(typ.scopedName()) elif full == ROS_FULL: return '_'.join(typ.scopedName()) else: return typ.identifier() if isinstance(typ, idlast.Typedef): if full == CPP_FULL: return idlutil.ccolonName(typ.declarators()[0].scopedName()) elif full == ROS_FULL: return '_'.join(typ.declarators()[0].scopedName()) else: return typ.declarators()[0].identifier() if isinstance(typ, idlast.Declarator): return self.getCppTypeText(typ.alias(), out, full) return 'undefined'
def visitAttribute(self, node): # create the Attribute object decl = node.declarators()[0] kind = node.attrType().kind() if (kind==idltype.tk_alias): # resolve the 'alias' kind = node.attrType().decl().alias().aliasType().kind() if hasattr(node.attrType(),'scopedName'): dataType = idlutil.ccolonName(node.attrType().scopedName()) else: dataType = baseTypes[kind] new_attr = Attribute(decl.identifier(),node.readonly(),IDLType.instance(node.attrType())) self.interface.attributes.append(new_attr)
def visitOperation(self, node): timeout = 'TIMEOUT_MS' for p in node.comments(): text = p.text()[2:].strip() if not text.startswith('@@'): continue key, value = text.split(' ') if key == '@@operation_timeout': timeout = value break self.operations.append(node.identifier()) node.returnType().accept(self) rtype = self.__result_type paraml = [] i = 0 for p in node.parameters(): p.paramType().accept(self) ptype = self.__result_type paraml.append((ptype, 'param' + str(i), p.is_out())) i += 1 params = ', '.join(map(lambda (ptype, name, is_out): ('const ' if not is_out else '') + ptype + ('& ' if ptype not in tools.ttsMap.values() else '') + ' ' + name, paraml)) params_serialize = 'dboost::oserializer os(msg.get());\nos ' if len(paraml) > 0 else '' params_serialize += ' '.join(map(lambda (ptype, name, is_out): '& ' + name, paraml)) params_out = filter(lambda (type, name, is_out): is_out, paraml) params_out_serialize = 'dboost::iserializer is(reply.get());\n' + rtype + ' r;\nis ' if rtype != 'void' or len(params_out) > 0 else '' if rtype != 'void': params_out_serialize += ' & r' if len(params_out) > 0: params_out_serialize += ' '.join(map(lambda (type, name, is_out): '& ' + name, params_out)) result = '' if rtype == 'void' else 'r' raisel = [] if len(node.raises()) > 0: for r in node.raises(): ename = idlutil.ccolonName(r.scopedName()) raisel.append(ename) raises = " throw (" + string.join(raisel, ", ") + ")" else: raises = "" exceptions_throw = '\n'.join(map(self.__exceptionThrow, raisel)) self.st.out(self.templates[self.__class__.__name__]['operation'], class_name=self.class_name, rtype=rtype, operation=node.identifier(), params=params, params_serialize=params_serialize, params_out_serialize=params_out_serialize, result=result, raises=raises, exceptions_throw=exceptions_throw, timeout=timeout)
def visitUnion(self, node): if node.constrType(): self.st.out("""\ union @id@ switch (""", id=node.identifier()) self.st.inc_indent() node.switchType().decl().accept(self) self.st.out(""") {""") self.st.dec_indent else: node.switchType().accept(self) stype = self.__result_type self.st.out("""\ union @id@ switch (@stype@) {""", id=node.identifier(), stype=stype) for c in node.cases(): if c.constrType(): self.st.inc_indent() c.caseType().decl().accept(self) self.st.dec_indent() for l in c.labels(): if l.default(): self.st.out("""\ default:""") else: if l.labelKind() == idltype.tk_enum: lv = "::" + idlutil.ccolonName(l.value().scopedName()) elif l.labelKind() == idltype.tk_char: lv = "'" + repr(l.value())[1:-1] + "'" else: lv = str(l.value()) self.st.out("""\ case @lv@:""", lv=lv) c.caseType().accept(self) type = self.__result_type c.declarator().accept(self) decl = self.__result_declarator self.st.out("""\ @type@ @decl@;""", type=type, decl=decl) self.st.out("};")
def visitStruct(self, node): typename = idlutil.ccolonName(node.scopedName()) self.st.out("typedef struct") self.st.out("{") self.st.inc_indent() for m in node.members(): if m.constrType(): m.memberType().decl().accept(self) m.memberType().accept(self) type = self.getResultType() for d in m.declarators(): d.accept(self) arr = self.getResultArray() self.st.out("@type@ @id@@arr@;", type=type, id=d.identifier(), arr=arr) self.st.dec_indent() self.st.out("} @sn@;\n", sn=string.replace(typename, ":", "_"))
def visitOperation(self, node): self.operations.append(node.identifier()) node.returnType().accept(self) rtype = self.__result_type paraml = [] i = 0 for p in node.parameters(): p.paramType().accept(self) ptype = self.__result_type paraml.append((ptype, 'param' + str(i), p.is_out())) i += 1 params_def = '\n'.join(map(lambda (ptype, name, is_out): ptype + ' ' + name + ';', paraml)) params_serialize = 'dboost::iserializer is(m);\nis ' if len(paraml) > 0 else '' params_serialize += ' '.join(map(lambda (ptype, name, is_out): '& ' + name, paraml)) if params_serialize != '': params_serialize += ';' params_out = filter(lambda (ptype, name, is_out): is_out, paraml) params_out_serialize = 'dboost::oserializer os(result.get());\nos ' if rtype != 'void' or len(params_out) > 0 else '' params_out_serialize += '& r ' if rtype != 'void' else '' params_out_serialize += ' '.join(map(lambda (ptype, name, is_out): '& ' + name, params_out)) if params_out_serialize != '': params_out_serialize += ';' call = '' if rtype != 'void': call += rtype + ' r = ' call += 't->' + node.identifier() + '(' call += ', '.join(map(lambda (type, name, is_out): name, paraml)) call += ')' raisel = [] if len(node.raises()) > 0: for r in node.raises(): ename = idlutil.ccolonName(r.scopedName()) raisel.append(ename) raises = '\n'.join(map(self.__exceptionCatch, raisel)) self.st.out(self.templates[self.__class__.__name__]['operation'], operation=node.identifier(), interface=self.interface, params_def=params_def, params_serialize=params_serialize, params_out_serialize=params_out_serialize, call=call, module_name=self.module_name, class_name=self.class_name, exception_catch=raises) self.st.out("""\ } """)
def outputEnum(self, node, name): attr = "" ma = "" ref = "*" typename = idlutil.ccolonName(node.scopedName()) self.st.out("uint32_t @tn@_@name@(@ma@MessageBuffer_t buffer, uint32_t offset, @attr@@tn@ @ref@value)", tn = string.replace(typename, ":", "_"), name=name, attr=attr, ma=ma,ref=ref) self.st.out("{") self.st.inc_indent() if name == "marshal": self.st.out("uint32_t valueInt = (uint32_t) *value;") self.st.out("return uint32_t_@name@(buffer, offset, &valueInt);", name=name) else: self.st.out("uint32_t valueInt;") self.st.out("uint32_t size = uint32_t_@name@(buffer, offset, &valueInt);", name=name) self.st.out("*value = (@tn@)valueInt;",tn=string.replace(typename, ":", "_")) self.st.out("return size;") self.st.dec_indent() self.st.out("}\n")
def visitOperation(self, node): comments = '\n'.join(map(lambda c: c.text(), node.comments())) node.returnType().accept(self) rtype = self.__result_type paraml = [] for p in node.parameters(): if p.is_in() and p.is_out(): inout = "" elif p.is_in(): inout = "const" else: inout = "" p.paramType().accept(self) ptype = self.__result_type if ptype != 'void': if ptype in tools.ttsMap.values(): paraml.append(inout + ' ' + ptype + ' ' + p.identifier()) else: paraml.append(inout + ' ' + ptype + '& ' + p.identifier()) else: paraml.append(inout + ' ' + ptype + ' ' + p.identifier()) params = string.join(paraml, ", ") if len(node.raises()) > 0: raisel = [] for r in node.raises(): ename = idlutil.ccolonName(r.scopedName()) raisel.append(ename) raises = " throw (" + string.join(raisel, ", ") + ")" else: raises = "" self.st.out("""\ @comments@\ virtual @rtype@ @id@(@params@)@raises@ = 0;""", rtype=rtype, id=node.identifier(), params=params, raises=raises, comments=comments)
def addOps(self,node,ops): for i in node.inherits(): self.addOps(i,ops) for d in node.contents(): if isinstance(d, idlast.Operation): new_op = CC.Operation(d.identifier(),baseTypes[d.returnType().kind()]) # Get the c++ mappping of the return type cxxRT = types.Type(d.returnType()) new_op.cxxReturnType = cxxRT.base() # if new_op.returnType == 'string': # print foo2.base() #print new_op.name + "::" + d.identifier() + "()" #tmpstr = node.identifier() + "::" + d.identifier() + "(" #tmpstr2 = " " + node.identifier() + "::" + d.identifier() + "(" if hasattr(d,'parameters'): for p in d.parameters(): new_param = CC.Param(p.identifier()) t = p.paramType() # Get the c++ mapping of the type cxxT = types.Type(t) new_param.cxxType = cxxT.op(types.direction(p)) if hasattr(t,'scopedName'): #print ' '*8 + str(t.scopedName()), new_param.dataType = idlutil.ccolonName(t.scopedName()) else: if isinstance(t,idltype.Type): #print ' '*8 + baseTypes[t.kind()], new_param.dataType = baseTypes[t.kind()] if p.is_in() and p.is_out(): new_param.direction = 'inout' elif p.is_out(): new_param.direction = 'out' else: new_param.direction = 'in' new_op.params.append(new_param) #tmpstr += new_param.direction + " " + new_param.dataType + "," #tmpstr2 += new_param.direction + " " + new_param.cxxType + "," ops.append(new_op)
def visitOperation(self, node): node.returnType().accept(self) self.rtype = self.getResultType() params = self.getAllParametersString(node) if len(node.raises()) > 0: raisel = [] for r in node.raises(): ename = idlutil.ccolonName(r.scopedName()) raisel.append(ename) raises = " raises (" + string.join(raisel, ", ") + ")" else: raises = "" self.st.out("""\ @preattr@@rtype@ @id@(@params@)@postattr@@raises@@term@""", preattr=self.getOperationPreAttributes(node), postattr=self.getOperationPostAttributes(node), rtype=self.rtype, id=self.getOperationName(node), params=params, raises=raises, term=self.getOperationTerminator(node))
def addOps(self, node, ops, attrs): # add inherited operations for i in node.inherits(): self.addOps(i, ops, attrs) for d in node.contents(): if isinstance(d, idlast.Operation): # create the Operation object #new_op = base.Operation(d.identifier(),baseTypes[d.returnType().kind()]) kind = d.returnType().kind() if (kind == idltype.tk_alias): # resolve the 'alias' kind = d.returnType().decl().alias().aliasType().kind() new_op = Operation(d.identifier(), baseTypes[kind]) # Get the c++ mapping of the return type cxxRT = types.Type(d.returnType()) #if not new_op.cxxReturnType == 'void': new_op.cxxReturnType = (cxxRT.base(), cxxRT.variable()) #print new_op.name + "::" + d.identifier() + "()" #tmpstr = node.identifier() + "::" + d.identifier() + "(" #tmpstr2 = " " + node.identifier() + "::" + d.identifier() + "(" # find and process the parameters of the operation if hasattr(d, 'parameters'): for p in d.parameters(): #new_param = base.Param(p.identifier()) new_param = Param(p.identifier()) t = p.paramType() # Get the c++ mapping of the type cxxT = types.Type(t) new_param.cxxType = cxxT.op(types.direction(p)) if hasattr(t, 'scopedName'): new_param.dataType = idlutil.ccolonName( t.scopedName()) else: if isinstance(t, idltype.Type): new_param.dataType = baseTypes[t.kind()] if p.is_in() and p.is_out(): new_param.direction = 'inout' elif p.is_out(): new_param.direction = 'out' else: new_param.direction = 'in' new_op.params.append(new_param) if hasattr(d, 'raises'): for r in d.raises(): #print r.identifier() new_raises = Raises(r.identifier()) new_op.raises.append(new_raises) ops.append(new_op) if isinstance(d, idlast.Attribute): # create the Attribute object decl = d.declarators()[0] kind = d.attrType().kind() if (kind == idltype.tk_alias): # resolve the 'alias' kind = d.attrType().decl().alias().aliasType().kind() if hasattr(d.attrType(), 'scopedName'): dataType = idlutil.ccolonName(d.attrType().scopedName()) else: dataType = baseTypes[kind] new_attr = Attribute(decl.identifier(), d.readonly(), dataType, baseTypes[kind]) # Get the c++ mapping of the return type cxxRT = types.Type(d.attrType()) new_attr.cxxReturnType = (cxxRT.base(), cxxRT.variable()) new_attr.cxxType = cxxRT.op(0) attrs.append(new_attr)
def visitDeclaredType(self, type): self.__result_type = idlutil.ccolonName(type.decl().scopedName())
def visitModule(self, node): self.namespace = idlutil.ccolonName(node.scopedName()) for n in node.definitions(): n.accept(self)
def addOps(self,node,ops,attrs): # add inherited operations for i in node.inherits(): self.addOps(i,ops,attrs) for d in node.contents(): if isinstance(d, idlast.Operation): # create the Operation object #new_op = base.Operation(d.identifier(),baseTypes[d.returnType().kind()]) kind = d.returnType().kind() if (kind==idltype.tk_alias): # resolve the 'alias' kind = d.returnType().decl().alias().aliasType().kind() new_op = Operation(d.identifier(),baseTypes[kind]) # Get the c++ mapping of the return type cxxRT = types.Type(d.returnType()) new_op.cxxReturnType = cxxRT.base() #print new_op.name + "::" + d.identifier() + "()" #tmpstr = node.identifier() + "::" + d.identifier() + "(" #tmpstr2 = " " + node.identifier() + "::" + d.identifier() + "(" # find and process the parameters of the operation if hasattr(d,'parameters'): for p in d.parameters(): #new_param = base.Param(p.identifier()) new_param = Param(p.identifier()) t = p.paramType() # Get the c++ mapping of the type cxxT = types.Type(t) new_param.cxxType = cxxT.op(types.direction(p)) if hasattr(t,'scopedName'): new_param.dataType = idlutil.ccolonName(t.scopedName()) else: if isinstance(t,idltype.Type): new_param.dataType = baseTypes[t.kind()] if p.is_in() and p.is_out(): new_param.direction = 'inout' elif p.is_out(): new_param.direction = 'out' else: new_param.direction = 'in' new_op.params.append(new_param) if hasattr(d, 'raises'): for r in d.raises(): #print r.identifier() new_raises = Raises(r.identifier()) new_op.raises.append(new_raises) ops.append(new_op) if isinstance(d, idlast.Attribute): # create the Attribute object decl = d.declarators()[0] kind = d.attrType().kind() if (kind==idltype.tk_alias): # resolve the 'alias' kind = d.attrType().decl().alias().aliasType().kind() if hasattr(d.attrType(),'scopedName'): dataType = idlutil.ccolonName(d.attrType().scopedName()) else: dataType = baseTypes[kind] new_attr = Attribute(decl.identifier(),d.readonly(),dataType,baseTypes[kind]) # Get the c++ mapping of the return type cxxRT = types.Type(d.attrType()) new_attr.cxxReturnType = cxxRT.base() new_attr.cxxType = cxxRT.op(0) attrs.append(new_attr)
def genBridgeComponent(self, interface): idlfile = interface.file() module_name = '%sROSBridge' % interface.identifier() #service_name = idlutil.ccolonName(interface.scopedName()) service_name = interface.identifier() idl_name = os.path.split(idlfile)[1] wd = basedir + '/src_gen' Comp_cpp = wd + '/' + module_name + 'Comp.cpp' mod_cpp = wd + '/' + module_name + '.cpp' mod_h = wd + '/' + module_name + '.h' print Comp_cpp print mod_cpp print mod_h if options.filenames: return if all([ os.path.exists(x) and os.stat(x).st_mtime > os.stat(idlfile).st_mtime for x in [Comp_cpp, mod_cpp, mod_h] ]) and not options.overwrite: return # do not overwrite # check if rtc-template exists under `rospack find openrtm_aist`/bin, otherwise use openrtm_aist_PREFIX/lib/openrtm_aist/bin from subprocess import check_output, Popen, PIPE openrtm_path = Popen([ 'rospack', 'find', 'openrtm_aist' ], stdout=PIPE).communicate()[0].rstrip( ) # use Popen, not check_output, since catkin_make can not found rospack find if not os.path.exists(os.path.join(openrtm_path, "bin")): openrtm_path = os.path.join( check_output( ['pkg-config', 'openrtm-aist', '--variable=prefix']).rstrip(), "lib/openrtm_aist") command = "PATH=%s/bin:$PATH rtc-template -bcxx --module-name=%s --consumer=%s:service0:'%s' --consumer-idl=%s --idl-include=%s" % ( openrtm_path, module_name, service_name, service_name, idlfile, idldir) #command = "rosrun openrtm_aist rtc-template -bcxx --module-name=%s --consumer=%s:service0:'%s' --consumer-idl=%s --idl-include=%s" % (module_name, service_name, service_name, idlfile, idldir) os.system("mkdir -p %s" % tmpdir) os.system("mkdir -p %s" % wd) os.system("cd %s; yes 2> /dev/null | %s > /dev/null" % (tmpdir, command)) # TODO: ignore attribute read/write operators operations = [ o for o in interface.callables() if isinstance(o, idlast.Operation) ] def addline(src, dest, ref): idx = dest.find(ref) idx = dest.find('\n', idx) return dest[0:idx] + '\n' + src + dest[idx:] def replaceline(src, dest, ref): idx1 = dest.find(ref) idx2 = dest.find('\n', idx1) return dest[0:idx1] + src + dest[idx2:] # Comp.cpp # use ros node name as rtm component name # call ros::init in Comp.cpp compsrc = open(tmpdir + '/' + module_name + 'Comp.cpp').read() compsrc = addline( ' ros::init(argc, argv, "' + module_name + '", ros::init_options::NoSigintHandler);', compsrc, 'RTC::Manager::init(argc, argv);') compsrc = replaceline( ' comp = manager->createComponent(std::string("' + module_name + '?instance_name="+ros::this_node::getName().substr(1)).c_str()); // skip root name space for OpenRTM instance name', compsrc, ' comp = manager->createComponent("' + module_name + '");') open(wd + '/' + module_name + 'Comp.cpp', 'w').write(compsrc) #.cpp # make ROS service in onInitialize # make ROS bridge functions in .cpp compsrc = open(tmpdir + '/' + module_name + '.cpp').read() port_name_src = """ nh = ros::NodeHandle("~"); std::string port_name = "service0"; nh.getParam("service_port", port_name);""" compsrc = addline(port_name_src, compsrc, 'Set service consumers to Ports') compsrc = compsrc.replace('registerConsumer("service0"', 'registerConsumer(port_name.c_str()') compsrc += """ RTC::ReturnCode_t %s::onExecute(RTC::UniqueId ec_id) { ros::spinOnce(); return RTC::RTC_OK; }\n\n""" % module_name compsrc += "RTC::ReturnCode_t %s::onActivated(RTC::UniqueId ec_id) {\n" % module_name for i in range(len(operations)): name = operations[i].identifier() compsrc += ' _srv%d = nh.advertiseService("%s", &%s::%s, this);\n' % ( i, name, module_name, name) compsrc += " return RTC::RTC_OK;\n}\n\n" "" compsrc += "RTC::ReturnCode_t %s::onDeactivated(RTC::UniqueId ec_id) {\n" % module_name for i in range(len(operations)): name = operations[i].identifier() srvinst = ' _srv%d.shutdown();' % i compsrc = addline(srvinst, compsrc, 'Unadvertise service') compsrc += " return RTC::RTC_OK;\n}\n\n" "" compsrc += convert_functions + self.convertFunctionCode(interface) for op in operations: compsrc += self.ServiceBridgeFunction(op, module_name, pkgname) open(wd + '/' + module_name + '.cpp', 'w').write(compsrc) #.h # add ros headers, service server functions, uncomment onExecute compsrc = open(tmpdir + '/' + module_name + '.h').read() compsrc = re.sub(basedir + "/idl/(.+).h", pkgname + r'/idl/\1.h', compsrc) compsrc = compsrc.replace( '<%s>' % service_name, '<%s>' % idlutil.ccolonName(interface.scopedName())) incs = ['', '// ROS', '#include <ros/ros.h>'] incs += [ '#include <%s/%s.h>' % (pkgname, self.getCppTypeText(op, full=ROS_FULL)) for op in operations ] incs = '\n'.join(incs) compsrc = addline(incs, compsrc, '#define') compsrc = '\n'.join([(a.replace('//', '') if ('RTC::ReturnCode_t onExecute' in a) else a) for a in compsrc.split('\n')]) compsrc = '\n'.join([(a.replace('//', '') if ('RTC::ReturnCode_t onActivated' in a) else a) for a in compsrc.split('\n')]) compsrc = '\n'.join([(a.replace('//', '') if ('RTC::ReturnCode_t onDeactivated' in a) else a) for a in compsrc.split('\n')]) srvfunc = [ ' bool %s(%s::%s::Request &req, %s::%s::Response &res);' % (op.identifier(), pkgname, self.getCppTypeText(op, full=ROS_FULL), pkgname, self.getCppTypeText(op, full=ROS_FULL)) for op in operations ] srvfunc = '\n'.join(srvfunc) compsrc = addline(srvfunc, compsrc, 'public:') defsrv = " ros::NodeHandle nh;\n" defsrv += " ros::ServiceServer " + ', '.join( ['_srv%d' % i for i in range(len(operations))]) + ';' compsrc = addline(defsrv, compsrc, 'private:') open(wd + '/' + module_name + '.h', 'w').write(compsrc) # finialize ## os.system("rm -f %s" % tmpdir) remove tmpdir in rtmbuild.cmake return