1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2010 CEA/DEN, EDF R&D, OPEN CASCADE
4 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License.
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # Lesser General Public License for more details.
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
26 import string, sys, fpformat, re, os
30 from xml.sax.handler import *
31 from omniidl import idlast, idltype, idlvisitor, idlutil, output
33 # parameters not found in IDL file, user's specified in optional parameters
34 common_data={"AUTHOR" : "",
46 #--------------------------------------------------
47 # extract value of <param_name> from <args> list
48 # it's proposed that the matching <args> item
49 # looks like <param_name>=<value>, for example,
50 # catalog=/tmp/myxml.xml
51 #--------------------------------------------------
52 def getParamValue( param_name, default_value, args ):
53 pattern="^"+param_name+"="
55 res = default_value #initial value
57 s = re.compile(pattern).search(opt)
65 #--------------------------------------------------
67 #--------------------------------------------------
69 print "ERROR : ", message
72 #--------------------------------------------------
73 # base class implementing tree
74 #--------------------------------------------------
77 def __init__(self, name = '', content = '', key = None):
79 self.content = content
86 def addChild(self, tree):
88 self.childs.append(tree)
92 def addNamedChild(self, name, content = ''):
93 return self.addChild(Tree(name, content))
95 def replaceChild(self, tree):
99 if (i.name == tree.name) & ((i.key is None) | (i.key == tree.key)):
101 self.childs.insert(pos, tree)
105 return self.addChild(tree)
107 def insertFirstChild(self, tree):
109 self.childs.insert(0, tree)
112 def insertFirstNamedChild(self, name, content = ''):
113 return self.insertFirstChild(Tree(name, content))
115 def output_xml(self, f, depth=0):
118 s = string.ljust('', 4*depth)
120 for k,v in self.attrs.items():
121 s += ' ' + k + '="' + v + '"'
123 if self.content != '':
126 if len(self.childs) > 0:
131 for i in self.childs:
135 s = '</' + self.name + '>\n'
136 if len(self.childs) > 0 :
137 s = string.ljust('', 4*depth) + s
140 def Dump(self, levels=-1, depth=0):
141 #Dumps the tree contents
143 if levels == 0: return
145 s = string.ljust('', 4*depth)
146 print s, self, self.content
147 for i in self.childs:
148 i.Dump(levels-1, depth+1)
151 #Returns list of the parents
160 def getChild(self, name, content=None):
161 # return child node with a given name
162 # if content == None, don't compare contents
163 for i in self.childs:
165 if (content is None) | (i.content == content):
169 def getNode(self, name, content='', depth=-1):
170 # recursive search of a node with a given name
171 # content == None, don't compare content
172 if (self.name == name):
173 if (content is None) | (self.content == content):
177 for i in self.childs:
178 n = i.getNode(name, content, depth-1)
195 def mergeChilds(self, t, list):
196 L_ext = t.getChild(list)
197 L_int = self.getChild(list)
201 for i_ext in L_ext.childs:
203 if k_ext is None: continue
206 for i_int in L_int.childs:
208 if k_int is None: continue
216 L_merge.addChild(i_int)
218 L_merge.addChild(i_ext)
220 self.replaceChild(L_merge)
222 def setAttrib(self, name,value):
223 self.attrs[name]=value
226 #--------------------------------------------------
227 # implements parameter tree
228 #--------------------------------------------------
229 class parameter(Tree):
231 def __init__(self, name=None, mode = 'in', type='', comment='unknown'):
232 Tree.__init__(self, mode + 'Parameter', key=name)
234 if name is None: return
236 self.addNamedChild(mode + 'Parameter-name', name)
237 self.addNamedChild(mode + 'Parameter-type', type)
238 self.addNamedChild(mode + 'Parameter-comment', comment)
243 self.replaceChild(P.getChild(P.mode + 'Parameter-name'))
244 self.replaceChild(P.getChild(P.mode + 'Parameter-type'))
245 C = P.getChild(P.mode + 'Parameter-comment')
246 if C.content != 'unkonwn':
249 #--------------------------------------------------
250 # implements dataStreamParameter tree
251 #--------------------------------------------------
252 class dataStreamParameter(parameter):
254 def __init__(self, name=None, mode='in', type='', dependency='', comment='unknown'):
255 parameter.__init__(self, name, mode, type, comment)
256 if name is None: return
258 self.addNamedChild(mode + 'Parameter-dependency', dependency)
263 parameter.merge(self, P)
264 self.replaceChild(P.getChild(mode + 'Parameter-dependency'))
267 def parseComment(comment):
270 word = spaces + '([a-zA-Z][a-zA-Z0-9_]*)' + spaces
276 ## match : // followed by a 'DataStreamPorts' string,
277 ## the service name, and a list of ports
278 pattern = '// *DataStreamPorts{,1}' + word
279 m = re.match(pattern, comment)
281 ## if there is a match, parse remaining part of comment
284 type = 'DataStreamPorts'
287 sPorts = comment[m.end():]
288 pattern = word + '\('+word+','+word +','+word+'\)' \
289 + spaces + ',{,1}' + spaces
290 while len(sPorts) > 0:
291 ## process next DataStreamPort
292 ## match a definition like xx(a,b,c) with a possible trailing ,
293 ## returns a tuple (xx, a, b, c) and
294 ## the remaining part of input string
295 m = re.match(pattern, sPorts)
298 'format error in DataStreamPort definition : '+sPorts
299 sPorts = sPorts[m.end():]
300 result.append(m.groups())
302 return type, key, result;
304 #--------------------------------------------------
305 # implements service tree
306 #--------------------------------------------------
309 def __init__(self, name=None, comment = 'unknown'):
311 Tree.__init__(self, 'component-service', key=name)
312 if name is None: return
314 self.addNamedChild('service-name', name)
315 self.addNamedChild('service-author',common_data["AUTHOR"])
316 self.addNamedChild('service-version',common_data["VERSION"])
317 self.addNamedChild('service-comment', comment)
318 self.addNamedChild('service-by-default', "0")
319 self.addNamedChild('inParameter-list')
320 self.addNamedChild('outParameter-list')
321 self.addNamedChild('DataStream-list')
323 def createInParameter(self, name, type):
324 L = self.getChild('inParameter-list')
325 p = parameter(name, 'in', type)
329 def createOutParameter(self, name, type):
330 L = self.getChild('outParameter-list')
331 p = parameter(name, 'out', type)
335 def createDataStreamParameter(self, p):
336 L = self.getChild('DataStream-list')
337 p = dataStreamParameter(p[0], p[2], p[1], p[3])
343 self.replaceChild(S.getChild('service-author'))
344 self.replaceChild(S.getChild('service-version'))
345 self.replaceChild(S.getChild('service-by-default'))
346 C = S.getChild('service-comment')
347 if C.content != 'unkonwn':
350 for L in ['inParameter-list', 'outParameter-list', 'DataStream-list']:
351 self.mergeChilds(S, L)
354 #--------------------------------------------------
355 # implements interface tree
356 #--------------------------------------------------
357 class Interface(Tree):
359 def __init__(self, name=None, comment='unknown'):
361 Tree.__init__(self, key=name)
363 if name is None: return
365 self.addNamedChild('component-interface-name', name)
366 self.addNamedChild('component-interface-comment', comment);
367 self.addNamedChild('component-service-list')
369 def createService(self, name):
370 L = self.getChild('component-service-list')
373 error ("Interface.createService() : 'component-service-list' is not found")
380 def findService(self, key):
381 L = self.getChild('component-service-list')
389 C = S.getChild('component-interface-comment')
390 if C.content != 'unkonwn':
393 self.mergeChilds(I, 'component-service-list')
395 def processDataStreams(self):
396 for sComment in self.comments:
398 type, key, result = parseComment(sComment)
400 if type == 'DataStreamPorts':
401 Service = self.findService(key)
405 ' not found in interface : ' + self.key
407 ## process next DataStreamPort
408 Service.createDataStreamParameter(p)
411 #--------------------------------------------------
412 # implements Component tree
413 #--------------------------------------------------
414 class Component(Tree):
415 def __init__(self, name=None):
416 Tree.__init__(self, 'component', key=name)
417 if name is None: return
419 # ASV : fix for bug PAL8922 (Component name indicated by user in GUI is not taken into account
420 if common_data["COMP_NAME"] != '':
421 self.addNamedChild('component-name', common_data["COMP_NAME"])
423 self.addNamedChild('component-name', name)
425 # ASV : if user name is NOT set, then use component-name instead. Else - default.
426 if common_data["COMP_UNAME"] != '':
427 self.addNamedChild('component-username', common_data["COMP_UNAME"])
429 if common_data["COMP_NAME"] != '':
430 self.addNamedChild('component-username', common_data["COMP_NAME"] )
432 self.addNamedChild('component-username', name)
434 self.addNamedChild('component-type', common_data["COMP_TYPE"])
435 self.addNamedChild('component-author', common_data["AUTHOR"])
436 self.addNamedChild('component-version', common_data["VERSION"])
437 self.addNamedChild('component-comment', 'unknown')
438 self.addNamedChild('component-multistudy', common_data["COMP_MULT"])
439 self.addNamedChild('component-impltype', common_data["COMP_IMPL"])
440 self.addNamedChild('component-icone', common_data["ICON"])
441 self.addNamedChild('constraint')
442 self.addNamedChild('component-interface-list')
444 def createInterface(self, name):
445 L = self.getChild('component-interface-list')
447 error("createInterface: No component-interface-list is found")
455 for i in ['component-username', 'component-author',
456 'component-type', 'component-icone', 'component-version',
457 'component-multistudy', 'component-impltype', 'constraint']:
459 int = self.getChild(i)
462 elif ext is not None and len(ext.content):
463 int.content = ext.content
465 Cc = C.getChild('component-comment')
466 if Cc.content != 'unkonwn':
467 self.replaceChild(Cc)
469 self.mergeChilds(C, 'component-interface-list')
471 #--------------------------------------------------
472 # implements document tree
473 #--------------------------------------------------
474 class Catalog(ContentHandler, Tree):
475 def __init__(self, filename = None):
480 parser = xml.sax.make_parser()
481 parser.setContentHandler(self)
482 parser.parse(filename)
484 t = self.addNamedChild('begin-catalog')
485 t.addNamedChild('type-list')
486 t.addNamedChild('component-list')
488 n = self.getChild('begin-catalog')
490 error("Catalog.__init__ : No 'begin-catalog' is found!")
492 if n.getChild('path-prefix-list') is None:
493 n.insertFirstNamedChild('path-prefix-list')
494 if n.getChild('type-list') is None:
495 p=n.childs.index(n.getChild('path-prefix-list'))
496 n.childs.insert(p+1,Tree('type-list'))
497 if n.getChild('component-list') is None:
498 n.addNamedChild('component-list')
500 def removeComponent(self, name):
501 complist = self.getNode('component-list')
504 print "Catalog.removeComponent() : 'component-list' is not found"
506 for comp in complist.childs:
507 cname = comp.getChild('component-name')
508 if cname is not None:
509 if cname.content == name:
510 complist.childs.pop(idx)
511 print "Component " + name + " is removed"
514 def startDocument(self):
515 self.list.append(self)
517 def startElement(self, name, attrs):
518 p = self.list[len(self.list)-1]
519 if name == 'component':
520 e = p.addChild(Component())
521 elif name == 'component-interface-name':
522 e = p.addNamedChild(name)
523 elif name == 'component-service':
524 e = p.addChild(Service())
525 elif name == 'inParameter':
526 e = p.addChild(parameter(mode='in'))
527 elif name == 'outParameter':
528 e = p.addChild(parameter(mode='out'))
529 elif name == 'sequence':
530 e = p.addChild(SeqType(attrs["name"],attrs["content"]))
531 elif name == 'objref':
532 e = p.addChild(ObjType(attrs["name"]))
533 elif name == 'struct':
534 e = p.addChild(StructType(attrs["name"]))
536 e = p.addChild(Type(attrs["name"],attrs["kind"]))
537 elif name == 'member':
538 e = p.addChild(Member(attrs["name"],attrs["type"]))
540 e = p.addNamedChild(name)
544 def endElement(self, name):
545 self.buffer = string.join(string.split(self.buffer), ' ')
546 p = self.list[len(self.list)-1]
547 p.content = self.buffer
548 if name == 'component':
549 p.key = p.getChild('component-name').content
553 def characters(self, ch):
556 def mergeComponent(self, comp):
558 L_int = self.getNode('component-list')
560 error("Catalog.mergeComponent : 'component-list' is not found")
566 for i_int in L_int.childs:
567 if (i_int.key == n_ext):
572 print ' add component', i_ext.getChild('component-name').content
573 L_int.addChild(i_ext)
575 print ' replace component', i_ext.getChild('component-name').content
578 def mergeType(self, type):
579 L_int = self.getNode('type-list')
581 error("Catalog.mergeType : 'type-list' is not found")
583 for t in L_int.childs:
584 if t.attrs["name"] == type.attrs["name"]:
591 def __init__(self, name,type):
592 Tree.__init__(self, 'member')
593 self.setAttrib("name",name)
594 self.setAttrib("type",type)
597 def __init__(self, name,kind):
598 Tree.__init__(self, 'type')
599 self.setAttrib("name",name)
600 self.setAttrib("kind",kind)
603 self.setAttrib("kind",t.attrs["kind"])
606 def __init__(self, name,content):
607 Tree.__init__(self, 'sequence')
608 self.setAttrib("name",name)
609 self.setAttrib("content",content)
612 self.setAttrib("content",t.attrs["content"])
614 class StructType(Tree):
615 def __init__(self, name):
616 Tree.__init__(self, 'struct')
617 self.setAttrib("name",name)
620 #remove childs and replace by t childs
623 self.childs.append(c)
626 def __init__(self, name):
627 Tree.__init__(self, 'objref')
628 self.setAttrib("name",name)
631 RepoId=t.attrs.get("id")
633 self.setAttrib("id",RepoId)
634 #remove childs and replace by t childs
637 self.childs.append(c)
642 idltype.tk_void: "void",
643 idltype.tk_short: "short",
644 idltype.tk_long: "long",
645 idltype.tk_ushort: "unsigned short",
646 idltype.tk_ulong: "unsigned long",
647 idltype.tk_float: "float",
648 idltype.tk_double: "double",
649 idltype.tk_boolean: "boolean",
650 idltype.tk_char: "char",
651 idltype.tk_octet: "octet",
652 idltype.tk_any: "any",
653 idltype.tk_TypeCode: "CORBA::TypeCode",
654 idltype.tk_Principal: "CORBA::Principal",
655 idltype.tk_longlong: "long long",
656 idltype.tk_ulonglong: "unsigned long long",
657 idltype.tk_longdouble: "long double",
658 idltype.tk_wchar: "wchar"
662 #--------------------------------------------------
663 # class ModuleCatalogVisitor
664 #--------------------------------------------------
665 class ModuleCatalogVisitor (idlvisitor.AstVisitor):
667 def __init__(self, catalog):
668 self.catalog = catalog
670 self.currentScope=None
672 def visitAST(self, node):
673 for n in node.declarations():
677 def visitModule(self, node):
678 self.currentScope=node
679 for n in node.definitions():
682 def visitInterface(self, node):
687 for i in node.inherits():
689 if s[0] == "Engines":
690 if s[1] == "EngineComponent":
691 self.EngineType = 1; break
692 if s[1] == "Superv_Component":
693 self.EngineType = 2; break
696 #This interface is a SALOME component
697 Comp = Component(node.identifier())
699 self.currentInterface = Comp.createInterface(node.identifier())
701 for c in node.callables():
702 if isinstance(c, idlast.Operation):
705 for c in node.declarations():
706 if isinstance(c, idlast.Struct):
709 for i in node.comments():
710 self.currentInterface.comments.append(str(i))
712 if self.EngineType == 2:
713 self.currentInterface.processDataStreams()
716 nb_components = nb_components + 1
717 self.catalog.mergeComponent(Comp)
720 #This interface is not a component : use it as a DataType
721 t=ObjType("/".join(node.scopedName()))
722 for i in node.inherits():
723 t.addNamedChild("base","/".join(i.scopedName()))
724 self.catalog.mergeType(t)
729 def visitOperation(self, node):
731 self.currentService = self.currentInterface.createService \
734 node.returnType().accept(self)
735 if (self.currentType != "void"):
736 self.currentService.createOutParameter \
737 ("return", self.currentType)
739 for c in node.parameters():
742 for i in node.comments():
743 self.currentInterface.comments.append(str(i))
746 def visitDeclaredType(self, type):
748 scoped_name="/".join(type.scopedName())
749 self.currentType = scoped_name
751 def visitBaseType(self, type):
752 self.currentType = ttsMap[type.kind()]
754 def visitStringType(self, type):
755 self.currentType = "string"
757 def visitParameter(self, node):
758 node.paramType().accept(self)
760 self.currentService.createInParameter \
761 (node.identifier(), self.currentType)
763 self.currentService.createOutParameter \
764 (node.identifier(), self.currentType)
766 def visitSequenceType(self,type):
767 type.seqType().accept(self)
768 if type.bound() == 0:
769 self.contentType=self.currentType
770 self.currentType = "sequence"
772 self.currentType = None
774 def visitTypedef(self, node):
775 if node.constrType():
776 node.aliasType().decl().accept(self)
778 node.aliasType().accept(self)
779 type = self.currentType
783 for d in node.declarators():
785 if self.__result_declarator:
786 decll.append(self.__result_declarator)
787 if type == "sequence":
788 #it's a sequence type
790 scoped_name="/".join(self.currentScope.scopedName()+[name])
791 self.catalog.mergeType(SeqType(scoped_name,self.contentType))
795 # scoped_name="/".join(self.currentScope.scopedName()+[name])
796 # self.catalog.mergeType(Type(scoped_name,type))
798 def visitStruct(self, node):
799 t=StructType("/".join(node.scopedName()))
800 for m in node.members():
802 m.memberType().decl().accept(self)
804 m.memberType().accept(self)
805 type = self.currentType
806 for d in m.declarators():
808 t.addChild(Member(self.__result_declarator,type))
810 self.catalog.mergeType(t)
812 def visitDeclarator(self, node):
814 self.__result_declarator =None
816 self.__result_declarator =node.identifier()
818 #--------------------------------------------------
819 # parse idl and store xml file
820 #--------------------------------------------------
823 CatalogFileName=getParamValue("catalog", "CatalogModulePersonnel.xml", args)
824 if re.compile(".*?.xml$").match(CatalogFileName, 1) is None:
825 CatalogFileName = CatalogFileName + '.xml'
827 #========= Read parameters ======================
828 common_data["ICON"] = getParamValue("icon", "", args)
829 common_data["AUTHOR"] = getParamValue("author", os.getenv("USER"), args)
830 common_data["VERSION"] = getParamValue("version", "1", args)
831 common_data["COMP_NAME"] = getParamValue("name", "", args)
832 common_data["COMP_UNAME"] = getParamValue("username", "", args)
833 common_data["COMP_TYPE"] = getParamValue("type", "OTHER", args)
834 common_data["COMP_MULT"] = getParamValue("multistudy", "1", args)
835 common_data["COMP_IMPL"] = getParamValue("impltype", "1", args)
839 remove_comp = getParamValue("remove", "", args)
841 #==================================================
843 if (os.path.exists(CatalogFileName)):
844 print "Importing", CatalogFileName
845 C = Catalog(CatalogFileName)
847 print "Creating ",CatalogFileName
850 print "Reading idl file"
852 visitor = ModuleCatalogVisitor(C)
858 C.removeComponent(remove_comp)
860 if (os.path.exists(CatalogFileName)):
861 print "Updating", CatalogFileName
862 CatalogFileName_old = CatalogFileName + '_old'
863 os.rename(CatalogFileName, CatalogFileName_old)
865 CatalogFileName_old = ""
866 print "Writing", CatalogFileName
868 CatalogFileName_new = CatalogFileName + '_new'
869 f=open(CatalogFileName_new, 'w')
870 f.write("<?xml version='1.0' encoding='us-ascii' ?>\n\n")
874 os.rename(CatalogFileName_new, CatalogFileName)
875 if ((CatalogFileName_old != "") & os.path.exists(CatalogFileName_old)):
876 os.unlink(CatalogFileName_old)
881 if __name__ == "__main__":
883 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>"