2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2008 CEA/DEN, EDF R&D, OPEN CASCADE
5 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License.
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # Lesser General Public License for more details.
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
27 import string, sys, fpformat, re, os
31 from xml.sax.handler import *
32 from omniidl import idlast, idltype, idlvisitor, idlutil, output
34 # parameters not found in IDL file, user's specified in optional parameters
35 common_data={"AUTHOR" : "",
47 #--------------------------------------------------
48 # extract value of <param_name> from <args> list
49 # it's proposed that the matching <args> item
50 # looks like <param_name>=<value>, for example,
51 # catalog=/tmp/myxml.xml
52 #--------------------------------------------------
53 def getParamValue( param_name, default_value, args ):
54 pattern="^"+param_name+"="
56 res = default_value #initial value
58 s = re.compile(pattern).search(opt)
66 #--------------------------------------------------
68 #--------------------------------------------------
70 print "ERROR : ", message
73 #--------------------------------------------------
74 # base class implementing tree
75 #--------------------------------------------------
78 def __init__(self, name = '', content = '', key = None):
80 self.content = content
87 def addChild(self, tree):
89 self.childs.append(tree)
93 def addNamedChild(self, name, content = ''):
94 return self.addChild(Tree(name, content))
96 def replaceChild(self, tree):
100 if (i.name == tree.name) & ((i.key is None) | (i.key == tree.key)):
102 self.childs.insert(pos, tree)
106 return self.addChild(tree)
108 def insertFirstChild(self, tree):
110 self.childs.insert(0, tree)
113 def insertFirstNamedChild(self, name, content = ''):
114 return self.insertFirstChild(Tree(name, content))
116 def output_xml(self, f, depth=0):
119 s = string.ljust('', 4*depth)
121 for k,v in self.attrs.items():
122 s += ' ' + k + '="' + v + '"'
124 if self.content != '':
127 if len(self.childs) > 0:
132 for i in self.childs:
136 s = '</' + self.name + '>\n'
137 if len(self.childs) > 0 :
138 s = string.ljust('', 4*depth) + s
141 def Dump(self, levels=-1, depth=0):
142 #Dumps the tree contents
144 if levels == 0: return
146 s = string.ljust('', 4*depth)
147 print s, self, self.content
148 for i in self.childs:
149 i.Dump(levels-1, depth+1)
152 #Returns list of the parents
161 def getChild(self, name, content=None):
162 # return child node with a given name
163 # if content == None, don't compare contents
164 for i in self.childs:
166 if (content is None) | (i.content == content):
170 def getNode(self, name, content='', depth=-1):
171 # recursive search of a node with a given name
172 # content == None, don't compare content
173 if (self.name == name):
174 if (content is None) | (self.content == content):
178 for i in self.childs:
179 n = i.getNode(name, content, depth-1)
196 def mergeChilds(self, t, list):
197 L_ext = t.getChild(list)
198 L_int = self.getChild(list)
202 for i_ext in L_ext.childs:
204 if k_ext is None: continue
207 for i_int in L_int.childs:
209 if k_int is None: continue
217 L_merge.addChild(i_int)
219 L_merge.addChild(i_ext)
221 self.replaceChild(L_merge)
223 def setAttrib(self, name,value):
224 self.attrs[name]=value
228 #--------------------------------------------------
229 # implements parameter tree
230 #--------------------------------------------------
231 class parameter(Tree):
233 def __init__(self, name=None, mode = 'in', type='', comment='unknown'):
234 Tree.__init__(self, mode + 'Parameter', key=name)
236 if name is None: return
238 self.addNamedChild(mode + 'Parameter-name', name)
239 self.addNamedChild(mode + 'Parameter-type', type)
240 self.addNamedChild(mode + 'Parameter-comment', comment)
245 self.replaceChild(P.getChild(P.mode + 'Parameter-name'))
246 self.replaceChild(P.getChild(P.mode + 'Parameter-type'))
247 C = P.getChild(P.mode + 'Parameter-comment')
248 if C.content != 'unkonwn':
251 #--------------------------------------------------
252 # implements dataStreamParameter tree
253 #--------------------------------------------------
254 class dataStreamParameter(parameter):
256 def __init__(self, name=None, mode='in', type='', dependency='', comment='unknown'):
257 parameter.__init__(self, name, mode, type, comment)
258 if name is None: return
260 self.addNamedChild(mode + 'Parameter-dependency', dependency)
265 parameter.merge(self, P)
266 self.replaceChild(P.getChild(mode + 'Parameter-dependency'))
269 def parseComment(comment):
272 word = spaces + '([a-zA-Z][a-zA-Z0-9_]*)' + spaces
278 ## match : // followed by a 'DataStreamPorts' string,
279 ## the service name, and a list of ports
280 pattern = '// *DataStreamPorts{,1}' + word
281 m = re.match(pattern, comment)
283 ## if there is a match, parse remaining part of comment
286 type = 'DataStreamPorts'
289 sPorts = comment[m.end():]
290 pattern = word + '\('+word+','+word +','+word+'\)' \
291 + spaces + ',{,1}' + spaces
292 while len(sPorts) > 0:
293 ## process next DataStreamPort
294 ## match a definition like xx(a,b,c) with a possible trailing ,
295 ## returns a tuple (xx, a, b, c) and
296 ## the remaining part of input string
297 m = re.match(pattern, sPorts)
300 'format error in DataStreamPort definition : '+sPorts
301 sPorts = sPorts[m.end():]
302 result.append(m.groups())
304 return type, key, result;
306 #--------------------------------------------------
307 # implements service tree
308 #--------------------------------------------------
311 def __init__(self, name=None, comment = 'unknown'):
313 Tree.__init__(self, 'component-service', key=name)
314 if name is None: return
316 self.addNamedChild('service-name', name)
317 self.addNamedChild('service-author',common_data["AUTHOR"])
318 self.addNamedChild('service-version',common_data["VERSION"])
319 self.addNamedChild('service-comment', comment)
320 self.addNamedChild('service-by-default', "0")
321 self.addNamedChild('inParameter-list')
322 self.addNamedChild('outParameter-list')
323 self.addNamedChild('DataStream-list')
325 def createInParameter(self, name, type):
326 L = self.getChild('inParameter-list')
327 p = parameter(name, 'in', type)
331 def createOutParameter(self, name, type):
332 L = self.getChild('outParameter-list')
333 p = parameter(name, 'out', type)
337 def createDataStreamParameter(self, p):
338 L = self.getChild('DataStream-list')
339 p = dataStreamParameter(p[0], p[2], p[1], p[3])
345 self.replaceChild(S.getChild('service-author'))
346 self.replaceChild(S.getChild('service-version'))
347 self.replaceChild(S.getChild('service-by-default'))
348 C = S.getChild('service-comment')
349 if C.content != 'unkonwn':
352 for L in ['inParameter-list', 'outParameter-list', 'DataStream-list']:
353 self.mergeChilds(S, L)
357 #--------------------------------------------------
358 # implements interface tree
359 #--------------------------------------------------
360 class Interface(Tree):
362 def __init__(self, name=None, comment='unknown'):
364 Tree.__init__(self, key=name)
366 if name is None: return
368 self.addNamedChild('component-interface-name', name)
369 self.addNamedChild('component-interface-comment', comment);
370 self.addNamedChild('component-service-list')
372 def createService(self, name):
373 L = self.getChild('component-service-list')
376 error ("Interface.createService() : 'component-service-list' is not found")
383 def findService(self, key):
384 L = self.getChild('component-service-list')
392 C = S.getChild('component-interface-comment')
393 if C.content != 'unkonwn':
396 self.mergeChilds(I, 'component-service-list')
398 def processDataStreams(self):
399 for sComment in self.comments:
401 type, key, result = parseComment(sComment)
403 if type == 'DataStreamPorts':
404 Service = self.findService(key)
408 ' not found in interface : ' + self.key
410 ## process next DataStreamPort
411 Service.createDataStreamParameter(p)
414 #--------------------------------------------------
415 # implements Component tree
416 #--------------------------------------------------
417 class Component(Tree):
418 def __init__(self, name=None):
419 Tree.__init__(self, 'component', key=name)
420 if name is None: return
422 # ASV : fix for bug PAL8922 (Component name indicated by user in GUI is not taken into account
423 if common_data["COMP_NAME"] != '':
424 self.addNamedChild('component-name', common_data["COMP_NAME"])
426 self.addNamedChild('component-name', name)
428 # ASV : if user name is NOT set, then use component-name instead. Else - default.
429 if common_data["COMP_UNAME"] != '':
430 self.addNamedChild('component-username', common_data["COMP_UNAME"])
432 if common_data["COMP_NAME"] != '':
433 self.addNamedChild('component-username', common_data["COMP_NAME"] )
435 self.addNamedChild('component-username', name)
437 self.addNamedChild('component-type', common_data["COMP_TYPE"])
438 self.addNamedChild('component-author', common_data["AUTHOR"])
439 self.addNamedChild('component-version', common_data["VERSION"])
440 self.addNamedChild('component-comment', 'unknown')
441 self.addNamedChild('component-multistudy', common_data["COMP_MULT"])
442 self.addNamedChild('component-impltype', common_data["COMP_IMPL"])
443 self.addNamedChild('component-icone', common_data["ICON"])
444 self.addNamedChild('constraint')
445 self.addNamedChild('component-interface-list')
447 def createInterface(self, name):
448 L = self.getChild('component-interface-list')
450 error("createInterface: No component-interface-list is found")
458 for i in ['component-username', 'component-author',
459 'component-type', 'component-icone', 'component-version',
460 'component-multistudy', 'component-impltype', 'constraint']:
462 int = self.getChild(i)
465 elif ext is not None and len(ext.content):
466 int.content = ext.content
468 Cc = C.getChild('component-comment')
469 if Cc.content != 'unkonwn':
470 self.replaceChild(Cc)
472 self.mergeChilds(C, 'component-interface-list')
474 #--------------------------------------------------
475 # implements document tree
476 #--------------------------------------------------
477 class Catalog(ContentHandler, Tree):
478 def __init__(self, filename = None):
483 parser = xml.sax.make_parser()
484 parser.setContentHandler(self)
485 parser.parse(filename)
487 t = self.addNamedChild('begin-catalog')
488 t.addNamedChild('type-list')
489 t.addNamedChild('component-list')
491 n = self.getChild('begin-catalog')
493 error("Catalog.__init__ : No 'begin-catalog' is found!")
495 if n.getChild('path-prefix-list') is None:
496 n.insertFirstNamedChild('path-prefix-list')
497 if n.getChild('type-list') is None:
498 p=n.childs.index(n.getChild('path-prefix-list'))
499 n.childs.insert(p+1,Tree('type-list'))
500 if n.getChild('component-list') is None:
501 n.addNamedChild('component-list')
503 def removeComponent(self, name):
504 complist = self.getNode('component-list')
507 print "Catalog.removeComponent() : 'component-list' is not found"
509 for comp in complist.childs:
510 cname = comp.getChild('component-name')
511 if cname is not None:
512 if cname.content == name:
513 complist.childs.pop(idx)
514 print "Component " + name + " is removed"
517 def startDocument(self):
518 self.list.append(self)
520 def startElement(self, name, attrs):
521 p = self.list[len(self.list)-1]
522 if name == 'component':
523 e = p.addChild(Component())
524 elif name == 'component-interface-name':
525 e = p.addNamedChild(name)
526 elif name == 'component-service':
527 e = p.addChild(Service())
528 elif name == 'inParameter':
529 e = p.addChild(parameter(mode='in'))
530 elif name == 'outParameter':
531 e = p.addChild(parameter(mode='out'))
532 elif name == 'sequence':
533 e = p.addChild(SeqType(attrs["name"],attrs["content"]))
534 elif name == 'objref':
535 e = p.addChild(ObjType(attrs["name"]))
536 elif name == 'struct':
537 e = p.addChild(StructType(attrs["name"]))
539 e = p.addChild(Type(attrs["name"],attrs["kind"]))
540 elif name == 'member':
541 e = p.addChild(Member(attrs["name"],attrs["type"]))
543 e = p.addNamedChild(name)
547 def endElement(self, name):
548 self.buffer = string.join(string.split(self.buffer), ' ')
549 p = self.list[len(self.list)-1]
550 p.content = self.buffer
551 if name == 'component':
552 p.key = p.getChild('component-name').content
556 def characters(self, ch):
559 def mergeComponent(self, comp):
561 L_int = self.getNode('component-list')
563 error("Catalog.mergeComponent : 'component-list' is not found")
569 for i_int in L_int.childs:
570 if (i_int.key == n_ext):
575 print ' add component', i_ext.getChild('component-name').content
576 L_int.addChild(i_ext)
578 print ' replace component', i_ext.getChild('component-name').content
581 def mergeType(self, type):
582 L_int = self.getNode('type-list')
584 error("Catalog.mergeType : 'type-list' is not found")
586 for t in L_int.childs:
587 if t.attrs["name"] == type.attrs["name"]:
594 def __init__(self, name,type):
595 Tree.__init__(self, 'member')
596 self.setAttrib("name",name)
597 self.setAttrib("type",type)
600 def __init__(self, name,kind):
601 Tree.__init__(self, 'type')
602 self.setAttrib("name",name)
603 self.setAttrib("kind",kind)
606 self.setAttrib("kind",t.attrs["kind"])
609 def __init__(self, name,content):
610 Tree.__init__(self, 'sequence')
611 self.setAttrib("name",name)
612 self.setAttrib("content",content)
615 self.setAttrib("content",t.attrs["content"])
617 class StructType(Tree):
618 def __init__(self, name):
619 Tree.__init__(self, 'struct')
620 self.setAttrib("name",name)
623 #remove childs and replace by t childs
626 self.childs.append(c)
629 def __init__(self, name):
630 Tree.__init__(self, 'objref')
631 self.setAttrib("name",name)
634 RepoId=t.attrs.get("id")
636 self.setAttrib("id",RepoId)
637 #remove childs and replace by t childs
640 self.childs.append(c)
645 idltype.tk_void: "void",
646 idltype.tk_short: "short",
647 idltype.tk_long: "long",
648 idltype.tk_ushort: "unsigned short",
649 idltype.tk_ulong: "unsigned long",
650 idltype.tk_float: "float",
651 idltype.tk_double: "double",
652 idltype.tk_boolean: "boolean",
653 idltype.tk_char: "char",
654 idltype.tk_octet: "octet",
655 idltype.tk_any: "any",
656 idltype.tk_TypeCode: "CORBA::TypeCode",
657 idltype.tk_Principal: "CORBA::Principal",
658 idltype.tk_longlong: "long long",
659 idltype.tk_ulonglong: "unsigned long long",
660 idltype.tk_longdouble: "long double",
661 idltype.tk_wchar: "wchar"
665 #--------------------------------------------------
666 # class ModuleCatalogVisitor
667 #--------------------------------------------------
668 class ModuleCatalogVisitor (idlvisitor.AstVisitor):
670 def __init__(self, catalog):
671 self.catalog = catalog
673 self.currentScope=None
675 def visitAST(self, node):
676 for n in node.declarations():
680 def visitModule(self, node):
681 self.currentScope=node
682 for n in node.definitions():
685 def visitInterface(self, node):
690 for i in node.inherits():
692 if s[0] == "Engines":
693 if s[1] == "Component":
694 self.EngineType = 1; break
695 if s[1] == "Superv_Component":
696 self.EngineType = 2; break
699 #This interface is a SALOME component
700 Comp = Component(node.identifier())
702 self.currentInterface = Comp.createInterface(node.identifier())
704 for c in node.callables():
705 if isinstance(c, idlast.Operation):
708 for c in node.declarations():
709 if isinstance(c, idlast.Struct):
712 for i in node.comments():
713 self.currentInterface.comments.append(str(i))
715 if self.EngineType == 2:
716 self.currentInterface.processDataStreams()
719 nb_components = nb_components + 1
720 self.catalog.mergeComponent(Comp)
723 #This interface is not a component : use it as a DataType
724 t=ObjType("/".join(node.scopedName()))
725 for i in node.inherits():
726 t.addNamedChild("base","/".join(i.scopedName()))
727 self.catalog.mergeType(t)
732 def visitOperation(self, node):
734 self.currentService = self.currentInterface.createService \
737 node.returnType().accept(self)
738 if (self.currentType != "void"):
739 self.currentService.createOutParameter \
740 ("return", self.currentType)
742 for c in node.parameters():
745 for i in node.comments():
746 self.currentInterface.comments.append(str(i))
749 def visitDeclaredType(self, type):
751 scoped_name="/".join(type.scopedName())
752 self.currentType = scoped_name
754 def visitBaseType(self, type):
755 self.currentType = ttsMap[type.kind()]
757 def visitStringType(self, type):
758 self.currentType = "string"
760 def visitParameter(self, node):
761 node.paramType().accept(self)
763 self.currentService.createInParameter \
764 (node.identifier(), self.currentType)
766 self.currentService.createOutParameter \
767 (node.identifier(), self.currentType)
769 def visitSequenceType(self,type):
770 type.seqType().accept(self)
771 if type.bound() == 0:
772 self.contentType=self.currentType
773 self.currentType = "sequence"
775 self.currentType = None
777 def visitTypedef(self, node):
778 if node.constrType():
779 node.aliasType().decl().accept(self)
781 node.aliasType().accept(self)
782 type = self.currentType
786 for d in node.declarators():
788 if self.__result_declarator:
789 decll.append(self.__result_declarator)
790 if type == "sequence":
791 #it's a sequence type
793 scoped_name="/".join(self.currentScope.scopedName()+[name])
794 self.catalog.mergeType(SeqType(scoped_name,self.contentType))
798 # scoped_name="/".join(self.currentScope.scopedName()+[name])
799 # self.catalog.mergeType(Type(scoped_name,type))
801 def visitStruct(self, node):
802 t=StructType("/".join(node.scopedName()))
803 for m in node.members():
805 m.memberType().decl().accept(self)
807 m.memberType().accept(self)
808 type = self.currentType
809 for d in m.declarators():
811 t.addChild(Member(self.__result_declarator,type))
813 self.catalog.mergeType(t)
815 def visitDeclarator(self, node):
817 self.__result_declarator =None
819 self.__result_declarator =node.identifier()
821 #--------------------------------------------------
822 # parse idl and store xml file
823 #--------------------------------------------------
826 CatalogFileName=getParamValue("catalog", "CatalogModulePersonnel.xml", args)
827 if re.compile(".*?.xml$").match(CatalogFileName, 1) is None:
828 CatalogFileName = CatalogFileName + '.xml'
830 #========= Read parameters ======================
831 common_data["ICON"] = getParamValue("icon", "", args)
832 common_data["AUTHOR"] = getParamValue("author", os.getenv("USER"), args)
833 common_data["VERSION"] = getParamValue("version", "1", args)
834 common_data["COMP_NAME"] = getParamValue("name", "", args)
835 common_data["COMP_UNAME"] = getParamValue("username", "", args)
836 common_data["COMP_TYPE"] = getParamValue("type", "OTHER", args)
837 common_data["COMP_MULT"] = getParamValue("multistudy", "1", args)
838 common_data["COMP_IMPL"] = getParamValue("impltype", "1", args)
842 remove_comp = getParamValue("remove", "", args)
844 #==================================================
846 if (os.path.exists(CatalogFileName)):
847 print "Importing", CatalogFileName
848 C = Catalog(CatalogFileName)
850 print "Creating ",CatalogFileName
853 print "Reading idl file"
855 visitor = ModuleCatalogVisitor(C)
861 C.removeComponent(remove_comp)
863 if (os.path.exists(CatalogFileName)):
864 print "Updating", CatalogFileName
865 CatalogFileName_old = CatalogFileName + '_old'
866 os.rename(CatalogFileName, CatalogFileName_old)
868 CatalogFileName_old = ""
869 print "Writing", CatalogFileName
871 CatalogFileName_new = CatalogFileName + '_new'
872 f=open(CatalogFileName_new, 'w')
873 f.write("<?xml version='1.0' encoding='us-ascii' ?>\n\n")
877 os.rename(CatalogFileName_new, CatalogFileName)
878 if ((CatalogFileName_old != "") & os.path.exists(CatalogFileName_old)):
879 os.unlink(CatalogFileName_old)
884 if __name__ == "__main__":
886 print "Usage : omniidl -bIDLparser [-I<catalog files directory>]* -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,username=<component_username>][,multistudy=<component_multistudy>][,impltype=<implementation type : 0 (python), 1 (C++)>] <file.idl>"