Salome HOME
Updated copyright comment
[modules/kernel.git] / src / ModuleGenerator / IDLparser.py
index e22678cd53dbde83da46c20b44d87004b73f1d8b..d0ed9d72d721293fdf664762976bbaddfee9d780 100644 (file)
@@ -1,33 +1,34 @@
-#  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+#  -*- coding: iso-8859-1 -*-
+# Copyright (C) 2007-2024  CEA, EDF, OPEN CASCADE
 #
-#  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-#  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+# Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
 #
-#  This library is free software; you can redistribute it and/or
-#  modify it under the terms of the GNU Lesser General Public
-#  License as published by the Free Software Foundation; either
-#  version 2.1 of the License.
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
 #
-#  This library is distributed in the hope that it will be useful,
-#  but WITHOUT ANY WARRANTY; without even the implied warranty of
-#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-#  Lesser General Public License for more details.
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
 #
-#  You should have received a copy of the GNU Lesser General Public
-#  License along with this library; if not, write to the Free Software
-#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 #
-#  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
-#  File   : IDLparser.py
-#  Module : SALOME
-#
-import string, sys, fpformat, re, os
+
+import os
+import os.path as osp
+import re
 import xml.sax
-import pdb
 
 from xml.sax.handler import *
 from omniidl import idlast, idltype, idlvisitor, idlutil, output
+from salome_utils import getUserName
 
 # parameters not found in IDL file, user's specified in optional parameters
 common_data={"AUTHOR"     : "",
@@ -36,7 +37,6 @@ common_data={"AUTHOR"     : "",
              "COMP_TYPE"  : "",
              "COMP_NAME"  : "",
              "COMP_UNAME" : "",
-             "COMP_MULT"  : "",
              "COMP_IMPL"  : ""
              }
 
@@ -58,21 +58,21 @@ def getParamValue( param_name, default_value, args ):
             res = opt[s.end():]
             break     #found
 
-    return res    
+    return res
 
 
 #--------------------------------------------------
 # print error message
 #--------------------------------------------------
 def error (message):
-    print "ERROR : ", message
+    print("ERROR : ", message)
 
 
 #--------------------------------------------------
 # base class implementing tree
 #--------------------------------------------------
 class Tree:
-    
+
     def __init__(self, name = '', content = '', key = None):
         self.name = name
         self.content = content
@@ -81,9 +81,9 @@ class Tree:
         self.childs = []
         self.comments = []
         self.attrs={}
-        
+
     def addChild(self, tree):
-        if tree is not None: 
+        if tree is not None:
             self.childs.append(tree)
             tree.parent = self
         return tree
@@ -102,21 +102,21 @@ class Tree:
                 pos += 1
 
          return self.addChild(tree)
-       
+
     def insertFirstChild(self, tree):
         if tree is not None:
             self.childs.insert(0, tree)
         return tree
-    
+
     def insertFirstNamedChild(self, name, content = ''):
         return self.insertFirstChild(Tree(name, content))
 
     def output_xml(self, f, depth=0):
         d = depth
         if self.name != '':
-            s = string.ljust('', 4*depth)
-            s += '<' + self.name 
-            for k,v in self.attrs.items():
+            s = ''.ljust(4*depth)
+            s += '<' + self.name
+            for k,v in list(self.attrs.items()):
               s += ' ' + k + '="' + v + '"'
             s += '>'
             if self.content != '':
@@ -126,23 +126,23 @@ class Tree:
                     s += '\n'
             f.write(s)
             d +=  1
-            
+
         for i in self.childs:
             i.output_xml(f, d)
-            
+
         if self.name != '':
             s = '</' + self.name + '>\n'
             if len(self.childs) > 0 :
-                s = string.ljust('', 4*depth) + s
+                s = ''.ljust(4*depth) + s
             f.write(s)
 
     def Dump(self, levels=-1, depth=0):
         #Dumps the tree contents
-        
+
         if levels == 0: return
-        
-        s = string.ljust('', 4*depth)
-        print s, self, self.content
+
+        s = ''.ljust(4*depth)
+        print(s, self, self.content)
         for i in self.childs:
             i.Dump(levels-1, depth+1)
 
@@ -155,7 +155,7 @@ class Tree:
             l.append(p.name)
             p = p.parent
         return l
-        
+
     def getChild(self, name, content=None):
         # return child node with a given name
         # if content == None, don't compare contents
@@ -171,12 +171,12 @@ class Tree:
         if (self.name == name):
             if (content is None) | (self.content == content):
                 return self
-            
+
         if (depth != 0):
             for i in self.childs:
                 n = i.getNode(name, content, depth-1)
-                if n:  return n 
-            
+                if n:  return n
+
         return None
 
     def __repr__(self):
@@ -196,47 +196,46 @@ class Tree:
         L_int = self.getChild(list)
 
         L_merge = Tree(list)
-        
+
         for i_ext in L_ext.childs:
             k_ext = i_ext.key
             if k_ext is None:  continue
             present = 0
-            
+
             for i_int in L_int.childs:
                 k_int = i_int.key
                 if k_int is None:  continue
-                
+
                 if (k_int == k_ext):
                     present = 1
                     break;
-                
+
             if present :
                 i_int.merge(i_ext)
                 L_merge.addChild(i_int)
             else:
                 L_merge.addChild(i_ext)
-                
+
         self.replaceChild(L_merge)
 
     def setAttrib(self, name,value):
       self.attrs[name]=value
-            
 
-    
+
 #--------------------------------------------------
 # implements parameter tree
 #--------------------------------------------------
 class parameter(Tree):
-    
+
     def __init__(self, name=None, mode = 'in', type='', comment='unknown'):
         Tree.__init__(self, mode + 'Parameter', key=name)
         self.mode = mode
         if name is None:  return
-        
+
         self.addNamedChild(mode + 'Parameter-name', name)
         self.addNamedChild(mode + 'Parameter-type', type)
         self.addNamedChild(mode + 'Parameter-comment', comment)
-        
+
     def merge(self, P):
 
         self.mode = P.mode
@@ -245,19 +244,19 @@ class parameter(Tree):
         C = P.getChild(P.mode + 'Parameter-comment')
         if C.content != 'unkonwn':
             self.replaceChild(C)
-    
+
 #--------------------------------------------------
 # implements dataStreamParameter tree
 #--------------------------------------------------
 class dataStreamParameter(parameter):
-    
+
     def __init__(self, name=None, mode='in', type='', dependency='', comment='unknown'):
         parameter.__init__(self, name, mode, type, comment)
         if name is None:  return
-        
+
         self.addNamedChild(mode + 'Parameter-dependency', dependency)
         self.mode = mode
-            
+
     def merge(self, P):
 
         parameter.merge(self, P)
@@ -268,11 +267,11 @@ def parseComment(comment):
 
     spaces = '[\t\n ]*'
     word = spaces + '([a-zA-Z][a-zA-Z0-9_]*)' + spaces
-    
+
     result = []
     type = None
     key = None
-    
+
     ## match :  // followed by a 'DataStreamPorts' string,
     ## the service name, and a list of ports
     pattern = '// *DataStreamPorts{,1}' + word
@@ -283,7 +282,7 @@ def parseComment(comment):
         ## service
         type = 'DataStreamPorts'
         key = m.group(1)
-        
+
         sPorts = comment[m.end():]
         pattern = word + '\('+word+','+word +','+word+'\)' \
                   + spaces + ',{,1}' + spaces
@@ -294,23 +293,22 @@ def parseComment(comment):
             ## the remaining part of input string
             m = re.match(pattern, sPorts)
             if m is None:
-                raise LookupError, \
-                      'format error in DataStreamPort definition : '+sPorts
+                raise LookupError('format error in DataStreamPort definition : '+sPorts)
             sPorts = sPorts[m.end():]
             result.append(m.groups())
-            
+
     return type, key, result;
 
 #--------------------------------------------------
 # implements service tree
 #--------------------------------------------------
 class Service(Tree):
-    
+
     def __init__(self, name=None, comment = 'unknown'):
-        
+
         Tree.__init__(self, 'component-service', key=name)
         if name is None:  return
-        
+
         self.addNamedChild('service-name', name)
         self.addNamedChild('service-author',common_data["AUTHOR"])
         self.addNamedChild('service-version',common_data["VERSION"])
@@ -319,13 +317,13 @@ class Service(Tree):
         self.addNamedChild('inParameter-list')
         self.addNamedChild('outParameter-list')
         self.addNamedChild('DataStream-list')
-            
+
     def createInParameter(self, name, type):
         L = self.getChild('inParameter-list')
         p = parameter(name, 'in', type)
         L.replaceChild(p)
         return p
-    
+
     def createOutParameter(self, name, type):
         L = self.getChild('outParameter-list')
         p = parameter(name, 'out', type)
@@ -337,7 +335,7 @@ class Service(Tree):
         p = dataStreamParameter(p[0], p[2], p[1], p[3])
         L.replaceChild(p)
         return p
-            
+
     def merge(self, S):
 
         self.replaceChild(S.getChild('service-author'))
@@ -346,27 +344,26 @@ class Service(Tree):
         C = S.getChild('service-comment')
         if C.content != 'unkonwn':
             self.replaceChild(C)
-            
+
         for L in ['inParameter-list', 'outParameter-list', 'DataStream-list']:
            self.mergeChilds(S, L)
-            
 
 
 #--------------------------------------------------
 # implements interface tree
 #--------------------------------------------------
 class Interface(Tree):
-    
+
     def __init__(self, name=None, comment='unknown'):
-               
+
         Tree.__init__(self, key=name)
 
         if name is None:  return
-        
+
         self.addNamedChild('component-interface-name', name)
         self.addNamedChild('component-interface-comment', comment);
         self.addNamedChild('component-service-list')
-            
+
     def createService(self, name):
         L = self.getChild('component-service-list')
 
@@ -384,7 +381,7 @@ class Interface(Tree):
             if S.key == key:
                 return S
         return None
-    
+
     def merge(self, I):
 
         C = S.getChild('component-interface-comment')
@@ -392,7 +389,7 @@ class Interface(Tree):
             self.replaceChild(C)
 
         self.mergeChilds(I, 'component-service-list')
-    
+
     def processDataStreams(self):
         for sComment in self.comments:
 
@@ -401,9 +398,8 @@ class Interface(Tree):
             if type == 'DataStreamPorts':
                 Service = self.findService(key)
                 if Service is None:
-                    raise LookupError, \
-                          'service ' + key + \
-                          ' not found in interface : ' + self.key
+                    raise LookupError('service ' + key + \
+                          ' not found in interface : ' + self.key)
                 for p in result:
                 ## process next DataStreamPort
                     Service.createDataStreamParameter(p)
@@ -416,12 +412,12 @@ class Component(Tree):
     def __init__(self, name=None):
         Tree.__init__(self, 'component', key=name)
         if name is None:  return
-                 
+
 # ASV : fix for bug PAL8922 (Component name indicated by user in GUI is not taken into account
-       if common_data["COMP_NAME"] != '':
-           self.addNamedChild('component-name', common_data["COMP_NAME"])
-       else:
-           self.addNamedChild('component-name', name)
+        if common_data["COMP_NAME"] != '':
+            self.addNamedChild('component-name', common_data["COMP_NAME"])
+        else:
+            self.addNamedChild('component-name', name)
 
 # ASV : if user name is NOT set, then use component-name instead.  Else - default.
         if common_data["COMP_UNAME"] != '':
@@ -431,17 +427,16 @@ class Component(Tree):
                 self.addNamedChild('component-username', common_data["COMP_NAME"] )
             else:
                 self.addNamedChild('component-username',   name)
-            
+
         self.addNamedChild('component-type',       common_data["COMP_TYPE"])
         self.addNamedChild('component-author',     common_data["AUTHOR"])
         self.addNamedChild('component-version',    common_data["VERSION"])
         self.addNamedChild('component-comment',    'unknown')
-        self.addNamedChild('component-multistudy', common_data["COMP_MULT"])
         self.addNamedChild('component-impltype',   common_data["COMP_IMPL"])
         self.addNamedChild('component-icone',      common_data["ICON"])
         self.addNamedChild('constraint')
         self.addNamedChild('component-interface-list')
-            
+
     def createInterface(self, name):
         L = self.getChild('component-interface-list')
         if L is None:
@@ -455,20 +450,20 @@ class Component(Tree):
 
         for i in ['component-username', 'component-author',
                   'component-type', 'component-icone', 'component-version',
-                  'component-multistudy', 'component-impltype', 'constraint']:
+                  'component-impltype', 'constraint']:
             ext = C.getChild(i)
             int = self.getChild(i)
             if int is None:
                 int = ext
             elif ext is not None and len(ext.content):
                 int.content = ext.content
-                
+
         Cc = C.getChild('component-comment')
         if Cc.content != 'unkonwn':
             self.replaceChild(Cc)
-                
+
         self.mergeChilds(C, 'component-interface-list')
-    
+
 #--------------------------------------------------
 # implements document tree
 #--------------------------------------------------
@@ -497,24 +492,24 @@ class Catalog(ContentHandler, Tree):
             n.childs.insert(p+1,Tree('type-list'))
         if n.getChild('component-list') is None:
             n.addNamedChild('component-list')
-            
+
     def removeComponent(self, name):
         complist = self.getNode('component-list')
         idx = 0
         if complist is None:
-            print "Catalog.removeComponent() : 'component-list' is not found"
+            print("Catalog.removeComponent() : 'component-list' is not found")
             return
         for comp in complist.childs:
             cname = comp.getChild('component-name')
             if cname is not None:
                 if cname.content == name:
                     complist.childs.pop(idx)
-                    print "Component " + name + " is removed"
-            idx += 1       
+                    print("Component " + name + " is removed")
+            idx += 1
+
     def startDocument(self):
         self.list.append(self)
-    
+
     def startElement(self, name, attrs):
         p = self.list[len(self.list)-1]
         if name == 'component':
@@ -541,26 +536,26 @@ class Catalog(ContentHandler, Tree):
             e = p.addNamedChild(name)
         self.list.append(e)
         self.buffer = ''
-        
+
     def endElement(self, name):
-        self.buffer = string.join(string.split(self.buffer), ' ')
+        self.buffer = ' '.join(self.buffer.split())
         p = self.list[len(self.list)-1]
         p.content = self.buffer
         if name == 'component':
             p.key = p.getChild('component-name').content
         self.buffer = ''
         e = self.list.pop()
-        
+
     def characters(self, ch):
         self.buffer += ch
 
     def mergeComponent(self, comp):
-        
+
         L_int = self.getNode('component-list')
         if   L_int is None:
             error("Catalog.mergeComponent : 'component-list' is not found")
             return
-        
+
         i_ext = comp
         present = 0
         n_ext = i_ext.key
@@ -568,14 +563,14 @@ class Catalog(ContentHandler, Tree):
             if (i_int.key == n_ext):
                 present = 1
                 break;
-                
+
         if present == 0:
-            print '   add component', i_ext.getChild('component-name').content
+            print('   add component', i_ext.getChild('component-name').content)
             L_int.addChild(i_ext)
         else:
-            print '   replace component', i_ext.getChild('component-name').content
+            print('   replace component', i_ext.getChild('component-name').content)
             i_int.merge(i_ext)
-            
+
     def mergeType(self, type):
       L_int = self.getNode('type-list')
       if L_int is None:
@@ -664,41 +659,41 @@ ttsMap = {
 # class ModuleCatalogVisitor
 #--------------------------------------------------
 class ModuleCatalogVisitor (idlvisitor.AstVisitor):
-    
+
     def __init__(self, catalog):
         self.catalog = catalog
         self.EngineType = 0
         self.currentScope=None
-        
+
     def visitAST(self, node):
         for n in node.declarations():
             if n.mainFile():
               n.accept(self)
-            
+
     def visitModule(self, node):
         self.currentScope=node
         for n in node.definitions():
             n.accept(self)
-                
+
     def visitInterface(self, node):
         if node.mainFile():
 
             self.EngineType = 0
-            
+
             for i in node.inherits():
                 s = i.scopedName();
                 if s[0] == "Engines":
-                  if s[1] == "Component":
+                  if s[1] == "EngineComponent":
                     self.EngineType = 1; break
                   if s[1] == "Superv_Component":
                     self.EngineType = 2; break
-                
+
             if self.EngineType:
               #This interface is a SALOME component
               Comp = Component(node.identifier())
-            
+
               self.currentInterface = Comp.createInterface(node.identifier())
-        
+
               for c in node.callables():
                 if isinstance(c, idlast.Operation):
                     c.accept(self)
@@ -706,13 +701,13 @@ class ModuleCatalogVisitor (idlvisitor.AstVisitor):
               for c in node.declarations():
                 if isinstance(c, idlast.Struct):
                     c.accept(self)
-                
+
               for i in node.comments():
                 self.currentInterface.comments.append(str(i))
 
               if self.EngineType == 2:
                 self.currentInterface.processDataStreams()
-            
+
               global nb_components
               nb_components = nb_components + 1
               self.catalog.mergeComponent(Comp)
@@ -725,36 +720,39 @@ class ModuleCatalogVisitor (idlvisitor.AstVisitor):
               self.catalog.mergeType(t)
 
             self.EngineType = 0
-            
+
 
     def visitOperation(self, node):
 
         self.currentService = self.currentInterface.createService \
                                        (node.identifier())
-            
+
         node.returnType().accept(self)
         if (self.currentType != "void"):
             self.currentService.createOutParameter \
                 ("return", self.currentType)
-            
+
         for c in node.parameters():
             c.accept(self)
 
         for i in node.comments():
             self.currentInterface.comments.append(str(i))
-        
+
 
     def visitDeclaredType(self, type):
         name=type.name()
         scoped_name="/".join(type.scopedName())
         self.currentType = scoped_name
-            
+
     def visitBaseType(self, type):
         self.currentType = ttsMap[type.kind()]
-    
+
     def visitStringType(self, type):
         self.currentType = "string"
-        
+
+    def visitWStringType(self, type):
+        self.currentType = "wstring"
+
     def visitParameter(self, node):
         node.paramType().accept(self)
         if node.is_in():
@@ -763,7 +761,7 @@ class ModuleCatalogVisitor (idlvisitor.AstVisitor):
         if node.is_out():
             self.currentService.createOutParameter \
                      (node.identifier(), self.currentType)
-        
+
     def visitSequenceType(self,type):
       type.seqType().accept(self)
       if type.bound() == 0:
@@ -820,52 +818,51 @@ class ModuleCatalogVisitor (idlvisitor.AstVisitor):
 # parse idl and store xml file
 #--------------------------------------------------
 def run(tree, args):
-    
+
     CatalogFileName=getParamValue("catalog", "CatalogModulePersonnel.xml", args)
     if re.compile(".*?.xml$").match(CatalogFileName, 1) is None:
         CatalogFileName = CatalogFileName + '.xml'
 
-    #=========  Read parameters  ======================    
+    #=========  Read parameters  ======================
     common_data["ICON"]       = getParamValue("icon",       "",                args)
-    common_data["AUTHOR"]     = getParamValue("author",     os.getenv("USER"), args)
+    common_data["AUTHOR"]     = getParamValue("author",     getUserName(),     args)
     common_data["VERSION"]    = getParamValue("version",    "1",               args)
-    common_data["COMP_NAME"]  = getParamValue("name",       "",                args) 
+    common_data["COMP_NAME"]  = getParamValue("name",       "",                args)
     common_data["COMP_UNAME"] = getParamValue("username",   "",                args)
     common_data["COMP_TYPE"]  = getParamValue("type",       "OTHER",           args)
-    common_data["COMP_MULT"]  = getParamValue("multistudy", "1",               args)
     common_data["COMP_IMPL"]  = getParamValue("impltype",   "1",               args)
 
-    print common_data
-    
+    print(common_data)
+
     remove_comp = getParamValue("remove", "", args)
-    
-    #==================================================    
-    
-    if (os.path.exists(CatalogFileName)):
-        print "Importing", CatalogFileName
+
+    #==================================================
+
+    if (osp.exists(CatalogFileName)):
+        print("Importing", CatalogFileName)
         C = Catalog(CatalogFileName)
     else:
-        print "Creating ",CatalogFileName
+        print("Creating ",CatalogFileName)
         C = Catalog()
 
-    print "Reading idl file"
-    
+    print("Reading idl file")
+
     visitor = ModuleCatalogVisitor(C)
     tree.accept(visitor)
 
 ##    C.Dump()
-    
+
     if remove_comp :
         C.removeComponent(remove_comp)
-    
-    if (os.path.exists(CatalogFileName)):
-        print "Updating", CatalogFileName
+
+    if (osp.exists(CatalogFileName)):
+        print("Updating", CatalogFileName)
         CatalogFileName_old = CatalogFileName + '_old'
         os.rename(CatalogFileName, CatalogFileName_old)
     else:
         CatalogFileName_old = ""
-        print "Writing", CatalogFileName
-        
+        print("Writing", CatalogFileName)
+
     CatalogFileName_new = CatalogFileName + '_new'
     f=open(CatalogFileName_new, 'w')
     f.write("<?xml version='1.0' encoding='us-ascii' ?>\n\n")
@@ -873,15 +870,13 @@ def run(tree, args):
     f.close()
 
     os.rename(CatalogFileName_new, CatalogFileName)
-    if ((CatalogFileName_old != "") & os.path.exists(CatalogFileName_old)):
+    if ((CatalogFileName_old != "") & osp.exists(CatalogFileName_old)):
         os.unlink(CatalogFileName_old)
-        
-    print
 
-
-if __name__ == "__main__":
-    print
-    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>"
-    print
+    print()
 
 
+if __name__ == "__main__":
+    print()
+    print("Usage : omniidl -bIDLparser [-I<catalog files directory>]* -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,username=<component_username>][,impltype=<implementation type : 0 (python), 1 (C++)>] <file.idl>")
+    print()