Salome HOME
Moved some functionality to VTKViewer_Utilities.h
[modules/kernel.git] / src / ModuleGenerator / IDLparser.py
1 #  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
3
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. 
8
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. 
13
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 
17
18 #  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
19 #
20 #
21 #
22 #  File   : IDLparser.py
23 #  Module : SALOME
24
25 import string, sys, fpformat, re, os
26 import xml.sax
27 import pdb
28
29 from xml.sax.handler import *
30 from omniidl import idlast, idltype, idlvisitor, idlutil, output
31
32 # parameters not found in IDL file, user's specified in optional parameters
33 common_data={"AUTHOR"     : "",
34              "ICON"       : "",
35              "VERSION"    : "",
36              "COMP_TYPE"  : "",
37              "COMP_NAME"  : "",
38              "COMP_UNAME" : "",
39              "COMP_MULT"  : "",
40              "COMP_IMPL"  : ""
41              }
42
43 nb_components = 0
44
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+"="
53
54     res = default_value        #initial value
55     for opt in args:
56         s = re.compile(pattern).search(opt)
57         if s:
58             res = opt[s.end():]
59             break     #found
60
61     return res    
62
63
64 #--------------------------------------------------
65 # print error message
66 #--------------------------------------------------
67 def error (message):
68     print "ERROR : ", message
69
70
71 #--------------------------------------------------
72 # base class implementing tree
73 #--------------------------------------------------
74 class Tree:
75     
76     def __init__(self, name = '', content = '', key = None):
77         self.name = name
78         self.content = content
79         self.key = key
80         self.parent = None
81         self.childs = []
82         self.comments = []
83         
84     def addChild(self, tree):
85         if tree is not None: 
86             self.childs.append(tree)
87             tree.parent = self
88         return tree
89
90     def addNamedChild(self, name, content = ''):
91         return self.addChild(Tree(name, content))
92
93     def replaceChild(self, tree):
94          if tree is not None:
95             pos = 0
96             for i in self.childs:
97                 if (i.name == tree.name) & ((i.key is None) | (i.key == tree.key)):
98                     self.childs.pop(pos)
99                     self.childs.insert(pos, tree)
100                     return tree
101                 pos += 1
102
103          return self.addChild(tree)
104        
105     def insertFirstChild(self, tree):
106         if tree is not None:
107             self.childs.insert(0, tree)
108         return tree
109     
110     def insertFirstNamedChild(self, name, content = ''):
111         return self.insertFirstChild(Tree(name, content))
112
113     def output_xml(self, f, depth=0):
114         d = depth
115         if self.name != '':
116             s = string.ljust('', 4*depth)
117             s += '<' + self.name + '>'
118             if self.content != '':
119                 s +=  self.content
120             else:
121                 if len(self.childs) > 0:
122                     s += '\n'
123             f.write(s)
124             d +=  1
125             
126         for i in self.childs:
127             i.output_xml(f, d)
128             
129         if self.name != '':
130             s = '</' + self.name + '>\n'
131             if len(self.childs) > 0 :
132                 s = string.ljust('', 4*depth) + s
133             f.write(s)
134
135     def Dump(self, levels=-1, depth=0):
136         #Dumps the tree contents
137         
138         if levels == 0: return
139         
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)
144
145     def parents(self):
146         #Returns list of the parents
147         l = []
148         p = self.parent
149         while p:
150             l.append(p)
151             l.append(p.name)
152             p = p.parent
153         return l
154         
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:
159             if (i.name == name):
160                 if (content is None) | (i.content == content):
161                     return i
162         return None
163
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):
169                 return self
170             
171         if (depth != 0):
172             for i in self.childs:
173                 n = i.getNode(name, content, depth-1)
174                 if n:  return n 
175             
176         return None
177
178     def __repr__(self):
179         s = '<'
180         if self.name != '':
181             s += self.name
182         else:
183             s +=  'None'
184         s += '>'
185         return s
186
187     def merge(self, t):
188         pass
189
190     def mergeChilds(self, t, list):
191         L_ext = t.getChild(list)
192         L_int = self.getChild(list)
193
194         L_merge = Tree(list)
195         
196         for i_ext in L_ext.childs:
197             k_ext = i_ext.key
198             if k_ext is None:  continue
199             present = 0
200             
201             for i_int in L_int.childs:
202                 k_int = i_int.key
203                 if k_int is None:  continue
204                 
205                 if (k_int == k_ext):
206                     present = 1
207                     break;
208                 
209             if present :
210                 i_int.merge(i_ext)
211                 L_merge.addChild(i_int)
212             else:
213                 L_merge.addChild(i_ext)
214                 
215         self.replaceChild(L_merge)
216             
217
218     
219 #--------------------------------------------------
220 # implements parameter tree
221 #--------------------------------------------------
222 class parameter(Tree):
223     
224     def __init__(self, name=None, mode = 'in', type='', comment='unknown'):
225         Tree.__init__(self, mode + 'Parameter', key=name)
226         self.mode = mode
227         if name is None:  return
228         
229         self.addNamedChild(mode + 'Parameter-name', name)
230         self.addNamedChild(mode + 'Parameter-type', type)
231         self.addNamedChild(mode + 'Parameter-comment', comment)
232         
233     def merge(self, P):
234
235         self.mode = P.mode
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':
240             self.replaceChild(C)
241     
242 #--------------------------------------------------
243 # implements dataStreamParameter tree
244 #--------------------------------------------------
245 class dataStreamParameter(parameter):
246     
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
250         
251         self.addNamedChild(mode + 'Parameter-dependency', dependency)
252         self.mode = mode
253             
254     def merge(self, P):
255
256         parameter.merge(self, P)
257         self.replaceChild(P.getChild(mode + 'Parameter-dependency'))
258
259
260 def parseComment(comment):
261
262     spaces = '[\t\n ]*'
263     word = spaces + '([a-zA-Z][a-zA-Z0-9_]*)' + spaces
264     
265     result = []
266     type = None
267     key = None
268     
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)
273
274     ## if there is a match, parse remaining part of comment
275     if m:
276         ## service
277         type = 'DataStreamPorts'
278         key = m.group(1)
279         
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)
289             if m is None:
290                 raise LookupError, \
291                       'format error in DataStreamPort definition : '+sPorts
292             sPorts = sPorts[m.end():]
293             result.append(m.groups())
294             
295     return type, key, result;
296
297 #--------------------------------------------------
298 # implements service tree
299 #--------------------------------------------------
300 class Service(Tree):
301     
302     def __init__(self, name=None, comment = 'unknown'):
303         
304         Tree.__init__(self, 'component-service', key=name)
305         if name is None:  return
306         
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')
315             
316     def createInParameter(self, name, type):
317         L = self.getChild('inParameter-list')
318         p = parameter(name, 'in', type)
319         L.replaceChild(p)
320         return p
321     
322     def createOutParameter(self, name, type):
323         L = self.getChild('outParameter-list')
324         p = parameter(name, 'out', type)
325         L.replaceChild(p)
326         return p
327
328     def createDataStreamParameter(self, p):
329         L = self.getChild('DataStream-list')
330         p = dataStreamParameter(p[0], p[2], p[1], p[3])
331         L.replaceChild(p)
332         return p
333             
334     def merge(self, S):
335
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':
341             self.replaceChild(C)
342             
343         for L in ['inParameter-list', 'outParameter-list', 'DataStream-list']:
344            self.mergeChilds(S, L)
345             
346
347
348 #--------------------------------------------------
349 # implements interface tree
350 #--------------------------------------------------
351 class Interface(Tree):
352     
353     def __init__(self, name=None, comment='unknown'):
354                
355         Tree.__init__(self, key=name)
356
357         if name is None:  return
358         
359         self.addNamedChild('component-interface-name', name)
360         self.addNamedChild('component-interface-comment', comment);
361         self.addNamedChild('component-service-list')
362             
363     def createService(self, name):
364         L = self.getChild('component-service-list')
365
366         if L is None:
367             error ("Interface.createService() : 'component-service-list' is not found")
368             return None
369
370         s = Service(name)
371         L.addChild(s)
372         return s
373
374     def findService(self, key):
375         L = self.getChild('component-service-list')
376         for S in L.childs:
377             if S.key == key:
378                 return S
379         return None
380     
381     def merge(self, I):
382
383         C = S.getChild('component-interface-comment')
384         if C.content != 'unkonwn':
385             self.replaceChild(C)
386
387         self.mergeChilds(I, 'component-service-list')
388     
389     def processDataStreams(self):
390         for sComment in self.comments:
391
392             type, key, result = parseComment(sComment)
393
394             if type == 'DataStreamPorts':
395                 Service = self.findService(key)
396                 if Service is None:
397                     raise LookupError, \
398                           'service ' + key + \
399                           ' not found in interface : ' + self.key
400                 for p in result:
401                 ## process next DataStreamPort
402                     Service.createDataStreamParameter(p)
403
404
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
412                  
413         self.addNamedChild('component-name',       name)
414
415         if common_data["COMP_UNAME"] != '':
416             self.addNamedChild('component-username',   common_data["COMP_UNAME"])
417         else:
418             self.addNamedChild('component-username',   name)
419             
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')
428             
429     def createInterface(self, name):
430         L = self.getChild('component-interface-list')
431         if L is None:
432             error("createInterface: No component-interface-list is found")
433             return None
434         i = Interface(name)
435         L.addChild(i)
436         return i
437
438     def merge(self, C):
439
440         for i in ['component-username', 'component-author',
441                   'component-type', 'component-icone', 'component-version',
442                   'component-multistudy', 'constraint']:
443             ext = C.getChild(i)
444             int = self.getChild(i)
445             if int is None:
446                 int = ext
447             elif ext is not None and len(ext.content):
448                 int.content = ext.content
449                 
450         Cc = C.getChild('component-comment')
451         if Cc.content != 'unkonwn':
452             self.replaceChild(Cc)
453                 
454         self.mergeChilds(C, 'component-interface-list')
455     
456 #--------------------------------------------------
457 # implements document tree
458 #--------------------------------------------------
459 class Catalog(ContentHandler, Tree):
460     def __init__(self, filename = None):
461         Tree.__init__(self)
462         self.buffer = ''
463         self.list = []
464         if (filename):
465             parser = xml.sax.make_parser()
466             parser.setContentHandler(self)
467             parser.parse(filename)
468         else:
469             t = self.addNamedChild('begin-catalog')
470             t.addNamedChild('component-list')
471
472         n = self.getChild('begin-catalog')
473         if n is None:
474             error("Catalog.__init__ : No 'begin-catalog' is found!")
475             return
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')
480             
481     def removeComponent(self, name):
482         complist = self.getNode('component-list')
483         idx = 0
484         if complist is None:
485             print "Catalog.removeComponent() : 'component-list' is not found"
486             return
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"
493             idx += 1       
494  
495     def startDocument(self):
496         self.list.append(self)
497     
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'))
510         else:
511             e = p.addNamedChild(name)
512         self.list.append(e)
513         self.buffer = ''
514         
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
521         self.buffer = ''
522         e = self.list.pop()
523         
524     def characters(self, ch):
525         self.buffer += ch
526
527     def mergeComponent(self, comp):
528         
529         L_int = self.getNode('component-list')
530         if   L_int is None:
531             error("Catalog.mergeComponent : 'component-list' is not found")
532             return
533         
534         i_ext = comp
535         present = 0
536         n_ext = i_ext.key
537         for i_int in L_int.childs:
538             if (i_int.key == n_ext):
539                 present = 1
540                 break;
541                 
542         if present == 0:
543             print '   add component', i_ext.getChild('component-name').content
544             L_int.addChild(i_ext)
545         else:
546             print '   replace component', i_ext.getChild('component-name').content
547             i_int.merge(i_ext)
548             
549
550             
551
552 # IDL file reader
553
554 ttsMap = {
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"
572     }
573
574
575 #--------------------------------------------------
576 # class ModuleCatalogVisitor
577 #--------------------------------------------------
578 class ModuleCatalogVisitor (idlvisitor.AstVisitor):
579     
580     def __init__(self, catalog):
581         self.catalog = catalog
582         self.EngineType = 0
583         
584     def visitAST(self, node):
585         for n in node.declarations():
586             n.accept(self)
587             
588     def visitModule(self, node):
589         for n in node.definitions():
590             n.accept(self)
591                 
592     def visitInterface(self, node):
593             
594         if node.mainFile():
595
596             self.EngineType = 0
597             
598             for i in node.inherits():
599                 s = i.scopedName();
600                 if ((s[0] == "Engines") & (s[1] == "Component")):
601                     self.EngineType = 1; break
602                 
603             Comp = Component(node.identifier())
604             
605             self.currentInterface = Comp.createInterface(node.identifier())
606         
607             for c in node.callables():
608                 if isinstance(c, idlast.Operation):
609                     c.accept(self)
610
611             for c in node.declarations():
612                 if isinstance(c, idlast.Struct):
613                     c.accept(self)
614                 
615             for i in node.comments():
616                 self.currentInterface.comments.append(str(i))
617
618             self.currentInterface.processDataStreams()
619             
620             if (self.EngineType):    
621                 global nb_components
622                 nb_components = nb_components + 1
623                 self.catalog.mergeComponent(Comp)
624
625             self.EngineType = 0
626             
627
628     def visitOperation(self, node):
629
630         self.currentService = self.currentInterface.createService \
631                                        (node.identifier())
632
633         for c in node.parameters():
634             c.accept(self)
635             
636         node.returnType().accept(self)
637         if (self.currentType != "void"):
638             self.currentService.createOutParameter \
639                 ("return", self.currentType)
640             
641         for i in node.comments():
642             self.currentInterface.comments.append(str(i))
643         
644
645     def visitDeclaredType(self, type):
646         self.currentType = type.name()
647             
648     def visitBaseType(self, type):
649         self.currentType = ttsMap[type.kind()]
650     
651     def visitStringType(self, type):
652         self.currentType = "string"
653         
654     def visitParameter(self, node):
655         node.paramType().accept(self)
656         if node.is_in():
657             self.currentService.createInParameter \
658                      (node.identifier(), self.currentType)
659         if node.is_out():
660             self.currentService.createOutParameter \
661                      (node.identifier(), self.currentType)
662         
663 #--------------------------------------------------
664 # parse idl and store xml file
665 #--------------------------------------------------
666 def run(tree, args):
667     
668     CatalogFileName=getParamValue("catalog", "CatalogModulePersonnel.xml", args)
669     if re.compile(".*?.xml$").match(CatalogFileName, 1) is None:
670         CatalogFileName = CatalogFileName + '.xml'
671
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)
681
682     print common_data
683     
684     remove_comp = getParamValue("remove", "", args)
685     
686     #==================================================    
687     
688     if (os.path.exists(CatalogFileName)):
689         print "Importing", CatalogFileName
690         C = Catalog(CatalogFileName)
691     else:
692         print "Creating ",CatalogFileName
693         C = Catalog()
694
695     print "Reading idl file"
696     
697     visitor = ModuleCatalogVisitor(C)
698     tree.accept(visitor)
699
700 ##    C.Dump()
701     
702     if remove_comp :
703         C.removeComponent(remove_comp)
704     
705     if (os.path.exists(CatalogFileName)):
706         print "Updating", CatalogFileName
707         CatalogFileName_old = CatalogFileName + '_old'
708         os.rename(CatalogFileName, CatalogFileName_old)
709     else:
710         CatalogFileName_old = ""
711         print "Writing", CatalogFileName
712         
713     CatalogFileName_new = CatalogFileName + '_new'
714     f=open(CatalogFileName_new, 'w')
715     f.write("<?xml version='1.0' encoding='us-ascii' ?>\n\n")
716     C.output_xml(f)
717     f.close()
718
719     os.rename(CatalogFileName_new, CatalogFileName)
720     if ((CatalogFileName_old != "") & os.path.exists(CatalogFileName_old)):
721         os.unlink(CatalogFileName_old)
722         
723     print
724
725
726 if __name__ == "__main__":
727     print
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>"
729     print
730
731