1 # Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 # See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
25 import string, sys, fpformat, re, os
29 from xml.sax.handler import *
30 from omniidl import idlast, idltype, idlvisitor, idlutil, output
32 # parameters not found in IDL file, user's specified in optional parameters
33 common_data={"AUTHOR" : "",
45 #--------------------------------------------------
46 # extract value of <param_name> from <args> list
47 # it's proposed that the matching <args> item
48 # looks like <param_name>=<value>, for example,
49 # catalog=/tmp/myxml.xml
50 #--------------------------------------------------
51 def getParamValue( param_name, default_value, args ):
52 pattern=param_name+"="
54 res = default_value #initial value
56 s = re.compile(pattern).search(opt)
64 #--------------------------------------------------
66 #--------------------------------------------------
68 print "ERROR : ", message
71 #--------------------------------------------------
72 # base class implementing tree
73 #--------------------------------------------------
76 def __init__(self, name = '', content = '', key = None):
78 self.content = content
84 def addChild(self, tree):
86 self.childs.append(tree)
90 def addNamedChild(self, name, content = ''):
91 return self.addChild(Tree(name, content))
93 def replaceChild(self, tree):
97 if (i.name == tree.name) & ((i.key is None) | (i.key == tree.key)):
99 self.childs.insert(pos, tree)
103 return self.addChild(tree)
105 def insertFirstChild(self, tree):
107 self.childs.insert(0, tree)
110 def insertFirstNamedChild(self, name, content = ''):
111 return self.insertFirstChild(Tree(name, content))
113 def output_xml(self, f, depth=0):
116 s = string.ljust('', 4*depth)
117 s += '<' + self.name + '>'
118 if self.content != '':
121 if len(self.childs) > 0:
126 for i in self.childs:
130 s = '</' + self.name + '>\n'
131 if len(self.childs) > 0 :
132 s = string.ljust('', 4*depth) + s
135 def Dump(self, levels=-1, depth=0):
136 #Dumps the tree contents
138 if levels == 0: return
140 s = string.ljust('', 4*depth)
141 print s, self, self.content
142 for i in self.childs:
143 i.Dump(levels-1, depth+1)
146 #Returns list of the parents
155 def getChild(self, name, content=None):
156 # return child node with a given name
157 # if content == None, don't compare contents
158 for i in self.childs:
160 if (content is None) | (i.content == content):
164 def getNode(self, name, content='', depth=-1):
165 # recursive search of a node with a given name
166 # content == None, don't compare content
167 if (self.name == name):
168 if (content is None) | (self.content == content):
172 for i in self.childs:
173 n = i.getNode(name, content, depth-1)
190 def mergeChilds(self, t, list):
191 L_ext = t.getChild(list)
192 L_int = self.getChild(list)
196 for i_ext in L_ext.childs:
198 if k_ext is None: continue
201 for i_int in L_int.childs:
203 if k_int is None: continue
211 L_merge.addChild(i_int)
213 L_merge.addChild(i_ext)
215 self.replaceChild(L_merge)
219 #--------------------------------------------------
220 # implements parameter tree
221 #--------------------------------------------------
222 class parameter(Tree):
224 def __init__(self, name=None, mode = 'in', type='', comment='unknown'):
225 Tree.__init__(self, mode + 'Parameter', key=name)
227 if name is None: return
229 self.addNamedChild(mode + 'Parameter-name', name)
230 self.addNamedChild(mode + 'Parameter-type', type)
231 self.addNamedChild(mode + 'Parameter-comment', comment)
236 self.replaceChild(P.getChild(P.mode + 'Parameter-name'))
237 self.replaceChild(P.getChild(P.mode + 'Parameter-type'))
238 C = P.getChild(P.mode + 'Parameter-comment')
239 if C.content != 'unkonwn':
242 #--------------------------------------------------
243 # implements dataStreamParameter tree
244 #--------------------------------------------------
245 class dataStreamParameter(parameter):
247 def __init__(self, name=None, mode='in', type='', dependency='', comment='unknown'):
248 parameter.__init__(self, name, mode, type, comment)
249 if name is None: return
251 self.addNamedChild(mode + 'Parameter-dependency', dependency)
256 parameter.merge(self, P)
257 self.replaceChild(P.getChild(mode + 'Parameter-dependency'))
260 def parseComment(comment):
263 word = spaces + '([a-zA-Z][a-zA-Z0-9_]*)' + spaces
269 ## match : // followed by a 'DataStreamPorts' string,
270 ## the service name, and a list of ports
271 pattern = '// *DataStreamPorts{,1}' + word
272 m = re.match(pattern, comment)
274 ## if there is a match, parse remaining part of comment
277 type = 'DataStreamPorts'
280 sPorts = comment[m.end():]
281 pattern = word + '\('+word+','+word +','+word+'\)' \
282 + spaces + ',{,1}' + spaces
283 while len(sPorts) > 0:
284 ## process next DataStreamPort
285 ## match a definition like xx(a,b,c) with a possible trailing ,
286 ## returns a tuple (xx, a, b, c) and
287 ## the remaining part of input string
288 m = re.match(pattern, sPorts)
291 'format error in DataStreamPort definition : '+sPorts
292 sPorts = sPorts[m.end():]
293 result.append(m.groups())
295 return type, key, result;
297 #--------------------------------------------------
298 # implements service tree
299 #--------------------------------------------------
302 def __init__(self, name=None, comment = 'unknown'):
304 Tree.__init__(self, 'component-service', key=name)
305 if name is None: return
307 self.addNamedChild('service-name', name)
308 self.addNamedChild('service-author',common_data["AUTHOR"])
309 self.addNamedChild('service-version',common_data["VERSION"])
310 self.addNamedChild('service-comment', comment)
311 self.addNamedChild('service-by-default', "0")
312 self.addNamedChild('inParameter-list')
313 self.addNamedChild('outParameter-list')
314 self.addNamedChild('DataStream-list')
316 def createInParameter(self, name, type):
317 L = self.getChild('inParameter-list')
318 p = parameter(name, 'in', type)
322 def createOutParameter(self, name, type):
323 L = self.getChild('outParameter-list')
324 p = parameter(name, 'out', type)
328 def createDataStreamParameter(self, p):
329 L = self.getChild('DataStream-list')
330 p = dataStreamParameter(p[0], p[2], p[1], p[3])
336 self.replaceChild(S.getChild('service-author'))
337 self.replaceChild(S.getChild('service-version'))
338 self.replaceChild(S.getChild('service-by-default'))
339 C = S.getChild('service-comment')
340 if C.content != 'unkonwn':
343 for L in ['inParameter-list', 'outParameter-list', 'DataStream-list']:
344 self.mergeChilds(S, L)
348 #--------------------------------------------------
349 # implements interface tree
350 #--------------------------------------------------
351 class Interface(Tree):
353 def __init__(self, name=None, comment='unknown'):
355 Tree.__init__(self, key=name)
357 if name is None: return
359 self.addNamedChild('component-interface-name', name)
360 self.addNamedChild('component-interface-comment', comment);
361 self.addNamedChild('component-service-list')
363 def createService(self, name):
364 L = self.getChild('component-service-list')
367 error ("Interface.createService() : 'component-service-list' is not found")
374 def findService(self, key):
375 L = self.getChild('component-service-list')
383 C = S.getChild('component-interface-comment')
384 if C.content != 'unkonwn':
387 self.mergeChilds(I, 'component-service-list')
389 def processDataStreams(self):
390 for sComment in self.comments:
392 type, key, result = parseComment(sComment)
394 if type == 'DataStreamPorts':
395 Service = self.findService(key)
399 ' not found in interface : ' + self.key
401 ## process next DataStreamPort
402 Service.createDataStreamParameter(p)
405 #--------------------------------------------------
406 # implements Component tree
407 #--------------------------------------------------
408 class Component(Tree):
409 def __init__(self, name=None):
410 Tree.__init__(self, 'component', key=name)
411 if name is None: return
413 self.addNamedChild('component-name', name)
415 if common_data["COMP_UNAME"] != '':
416 self.addNamedChild('component-username', common_data["COMP_UNAME"])
418 self.addNamedChild('component-username', name)
420 self.addNamedChild('component-type', common_data["COMP_TYPE"])
421 self.addNamedChild('component-author', common_data["AUTHOR"])
422 self.addNamedChild('component-version', common_data["VERSION"])
423 self.addNamedChild('component-comment', 'unknown')
424 self.addNamedChild('component-multistudy', common_data["COMP_MULT"])
425 self.addNamedChild('component-icone', common_data["ICON"])
426 self.addNamedChild('constraint')
427 self.addNamedChild('component-interface-list')
429 def createInterface(self, name):
430 L = self.getChild('component-interface-list')
432 error("createInterface: No component-interface-list is found")
440 for i in ['component-username', 'component-author',
441 'component-type', 'component-icone', 'component-version',
442 'component-multistudy', 'constraint']:
444 int = self.getChild(i)
447 elif ext is not None and len(ext.content):
448 int.content = ext.content
450 Cc = C.getChild('component-comment')
451 if Cc.content != 'unkonwn':
452 self.replaceChild(Cc)
454 self.mergeChilds(C, 'component-interface-list')
456 #--------------------------------------------------
457 # implements document tree
458 #--------------------------------------------------
459 class Catalog(ContentHandler, Tree):
460 def __init__(self, filename = None):
465 parser = xml.sax.make_parser()
466 parser.setContentHandler(self)
467 parser.parse(filename)
469 t = self.addNamedChild('begin-catalog')
470 t.addNamedChild('component-list')
472 n = self.getChild('begin-catalog')
474 error("Catalog.__init__ : No 'begin-catalog' is found!")
476 if n.getChild('path-prefix-list') is None:
477 n.insertFirstNamedChild('path-prefix-list')
478 if n.getChild('component-list') is None:
479 n.addNamedChild('component-list')
481 def removeComponent(self, name):
482 complist = self.getNode('component-list')
485 print "Catalog.removeComponent() : 'component-list' is not found"
487 for comp in complist.childs:
488 cname = comp.getChild('component-name')
489 if cname is not None:
490 if cname.content == name:
491 complist.childs.pop(idx)
492 print "Component " + name + " is removed"
495 def startDocument(self):
496 self.list.append(self)
498 def startElement(self, name, attrs):
499 p = self.list[len(self.list)-1]
500 if name == 'component':
501 e = p.addChild(Component())
502 elif name == 'component-interface-name':
503 e = p.addNamedChild(name)
504 elif name == 'component-service':
505 e = p.addChild(Service())
506 elif name == 'inParameter':
507 e = p.addChild(parameter(mode='in'))
508 elif name == 'outParameter':
509 e = p.addChild(parameter(mode='out'))
511 e = p.addNamedChild(name)
515 def endElement(self, name):
516 self.buffer = string.join(string.split(self.buffer), ' ')
517 p = self.list[len(self.list)-1]
518 p.content = self.buffer
519 if name == 'component':
520 p.key = p.getChild('component-name').content
524 def characters(self, ch):
527 def mergeComponent(self, comp):
529 L_int = self.getNode('component-list')
531 error("Catalog.mergeComponent : 'component-list' is not found")
537 for i_int in L_int.childs:
538 if (i_int.key == n_ext):
543 print ' add component', i_ext.getChild('component-name').content
544 L_int.addChild(i_ext)
546 print ' replace component', i_ext.getChild('component-name').content
555 idltype.tk_void: "void",
556 idltype.tk_short: "short",
557 idltype.tk_long: "long",
558 idltype.tk_ushort: "unsigned short",
559 idltype.tk_ulong: "unsigned long",
560 idltype.tk_float: "float",
561 idltype.tk_double: "double",
562 idltype.tk_boolean: "boolean",
563 idltype.tk_char: "char",
564 idltype.tk_octet: "octet",
565 idltype.tk_any: "any",
566 idltype.tk_TypeCode: "CORBA::TypeCode",
567 idltype.tk_Principal: "CORBA::Principal",
568 idltype.tk_longlong: "long long",
569 idltype.tk_ulonglong: "unsigned long long",
570 idltype.tk_longdouble: "long double",
571 idltype.tk_wchar: "wchar"
575 #--------------------------------------------------
576 # class ModuleCatalogVisitor
577 #--------------------------------------------------
578 class ModuleCatalogVisitor (idlvisitor.AstVisitor):
580 def __init__(self, catalog):
581 self.catalog = catalog
584 def visitAST(self, node):
585 for n in node.declarations():
588 def visitModule(self, node):
589 for n in node.definitions():
592 def visitInterface(self, node):
598 for i in node.inherits():
600 if ((s[0] == "Engines") & (s[1] == "Component")):
601 self.EngineType = 1; break
603 Comp = Component(node.identifier())
605 self.currentInterface = Comp.createInterface(node.identifier())
607 for c in node.callables():
608 if isinstance(c, idlast.Operation):
611 for c in node.declarations():
612 if isinstance(c, idlast.Struct):
615 for i in node.comments():
616 self.currentInterface.comments.append(str(i))
618 self.currentInterface.processDataStreams()
620 if (self.EngineType):
622 nb_components = nb_components + 1
623 self.catalog.mergeComponent(Comp)
628 def visitOperation(self, node):
630 self.currentService = self.currentInterface.createService \
633 for c in node.parameters():
636 node.returnType().accept(self)
637 if (self.currentType != "void"):
638 self.currentService.createOutParameter \
639 ("return", self.currentType)
641 for i in node.comments():
642 self.currentInterface.comments.append(str(i))
645 def visitDeclaredType(self, type):
646 self.currentType = type.name()
648 def visitBaseType(self, type):
649 self.currentType = ttsMap[type.kind()]
651 def visitStringType(self, type):
652 self.currentType = "string"
654 def visitParameter(self, node):
655 node.paramType().accept(self)
657 self.currentService.createInParameter \
658 (node.identifier(), self.currentType)
660 self.currentService.createOutParameter \
661 (node.identifier(), self.currentType)
663 #--------------------------------------------------
664 # parse idl and store xml file
665 #--------------------------------------------------
668 CatalogFileName=getParamValue("catalog", "CatalogModulePersonnel.xml", args)
669 if re.compile(".*?.xml$").match(CatalogFileName, 1) is None:
670 CatalogFileName = CatalogFileName + '.xml'
672 #========= Read parameters ======================
673 common_data["ICON"] = getParamValue("icon", "", args)
674 common_data["AUTHOR"] = getParamValue("author", os.getenv("USER"), args)
675 common_data["VERSION"] = getParamValue("version", "1", args)
676 common_data["COMP_NAME"] = getParamValue("name", "", args)
677 common_data["COMP_UNAME"] = getParamValue("username", "", args)
678 common_data["COMP_TYPE"] = getParamValue("type", "OTHER", args)
679 common_data["COMP_MULT"] = getParamValue("multistudy", "1", args)
680 common_data["COMP_IMPL"] = getParamValue("impltype", "1", args)
684 remove_comp = getParamValue("remove", "", args)
686 #==================================================
688 if (os.path.exists(CatalogFileName)):
689 print "Importing", CatalogFileName
690 C = Catalog(CatalogFileName)
692 print "Creating ",CatalogFileName
695 print "Reading idl file"
697 visitor = ModuleCatalogVisitor(C)
703 C.removeComponent(remove_comp)
705 if (os.path.exists(CatalogFileName)):
706 print "Updating", CatalogFileName
707 CatalogFileName_old = CatalogFileName + '_old'
708 os.rename(CatalogFileName, CatalogFileName_old)
710 CatalogFileName_old = ""
711 print "Writing", CatalogFileName
713 CatalogFileName_new = CatalogFileName + '_new'
714 f=open(CatalogFileName_new, 'w')
715 f.write("<?xml version='1.0' encoding='us-ascii' ?>\n\n")
719 os.rename(CatalogFileName_new, CatalogFileName)
720 if ((CatalogFileName_old != "") & os.path.exists(CatalogFileName_old)):
721 os.unlink(CatalogFileName_old)
726 if __name__ == "__main__":
728 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>] <file.idl>"