Update of /cvsroot/pymerase/smw/smw/mmgen
In directory sc8-pr-cvs1:/tmp/cvs-serv32238/smw/mmgen
Added Files:
__init__.py basicmm.py makefile mmdiff.py mmgen.py mmgencpp.py
mmprint.py
Log Message:
Imported version of SMW downloaded on 2003 Apr 14
--- NEW FILE: __init__.py ---
--- NEW FILE: basicmm.py ---
Element("Core","Element",[],[])
Element("Core","PresentationElement",[],[])
Aggregation("Element","presentation","*",
"PresentationElement","subject","*")
--- NEW FILE: makefile ---
all:
(cd dlg; make)
--- NEW FILE: mmdiff.py ---
import sys
from smw.metamodel import MetaMM
import types
class Diff:
def formatAttribute(self,name,t):
(kind,mmtype,multiplicity,otherRole,otherMultiplicity,ordering)=t
if kind==MetaMM.MMClass.kind__Attribute:
s="attribute "
elif kind==MetaMM.MMClass.kind__Association:
s="association "
else:
s="composition "
s=s+name+" : "
if kind!=MetaMM.MMClass.kind__Attribute:
if otherMultiplicity==1:
m="1 to "
else:
m="* to "
if multiplicity==1:
s=s+m+"1 "
else:
s=s+m+"* "
s=s+mmtype.__name__
return s
def compareElements(self,e1,e2):
s=""
definedInE1=[]
for a in e1.__mm__.keys():
found=0
for b in e1.__bases__:
if hasattr(b,"__mm__") and b.__mm__.has_key(a):
found=1
break
if not found:
definedInE1.append(a)
definedInE2=[]
for a in e2.__mm__.keys():
found=0
for b in e2.__bases__:
if hasattr(b,"__mm__") and b.__mm__.has_key(a):
found=1
break
if not found:
definedInE2.append(a)
for a in definedInE1:
if not e2.__mm__.has_key(a):
s=s+" -"+self.formatAttribute(a,e1.__mm__[a])+"\n"
for a in definedInE2:
if not e1.__mm__.has_key(a):
s=s+" +"+self.formatAttribute(a,e2.__mm__[a])+"\n"
for a in definedInE2:
if e1.__mm__.has_key(a):
if (e1.__mm__[a][0]!= e2.__mm__[a][0]) or (
e1.__mm__[a][1].__name__!= e2.__mm__[a][1].__name__) or (
e1.__mm__[a][2]!= e2.__mm__[a][2]):
#s=s+"<"+str(e1.__mm__[a])+"\n"
#s=s+">"+str(e2.__mm__[a])+"\n"
s=s+" <"+self.formatAttribute(a,e1.__mm__[a])+"\n"
s=s+" >"+self.formatAttribute(a,e2.__mm__[a])+"\n"
return s
def compare(self,n1,n2):
try:
self.metamodel1=MetaMM.getMetamodelByName(n1)
except Exception,e:
print "An error ocurred while loading",n1,":",e
sys.exit(-1)
try:
self.metamodel2=MetaMM.getMetamodelByName(n2)
except Exception,e:
print "An error ocurred while loading",n2,":",e
sys.exit(-1)
self.mm1name=self.metamodel1.MMName+' '+self.metamodel1.MMVersion
self.mm2name=self.metamodel2.MMName+' '+self.metamodel2.MMVersion
print "Comparing",self.mm1name,"and",self.mm2name
if self.metamodel1==self.metamodel2:
print "It is the same metamodel."
return
self.elements1={}
self.elements2={}
for e in self.metamodel1.__dict__.values():
if e!=MetaMM.MMClass and type(e)==types.ClassType and issubclass(e,MetaMM.MMClass):
self.elements1[e.__name__]=e
for e in self.metamodel2.__dict__.values():
if e!=MetaMM.MMClass and type(e)==types.ClassType and issubclass(e,MetaMM.MMClass):
self.elements2[e.__name__]=e
removed=0
print "Elements removed from ", self.mm2name
for n in self.elements1.keys():
if not self.elements2.has_key(n):
print "-",n
removed=removed+1
added=0
print "New elements in",self.mm2name
for n in self.elements2.keys():
if not self.elements1.has_key(n):
print "+",n
added=added+1
changed=0
print "Elements that have changed"
for n in self.elements1.keys():
if self.elements2.has_key(n):
s=self.compareElements(self.elements1[n],
self.elements2[n])
if s:
print n
print s
changed=changed+1
print removed," elements removed"
print added," elements added"
print changed," elements changed"
if __name__=='__main__':
if len(sys.argv)!=3:
print "mmdiff compares two diffrent versions of a metamodel."
print "Usage : mmdiff old new"
print " Where old is the name of the old verion and new of the new version of the metamodel to compare."
print "Example: mmdiff UML13 UML14"
else:
d=Diff()
d.compare(sys.argv[1],sys.argv[2])
--- NEW FILE: mmgen.py ---
#
# mmgen.py Ivan Porres ip...@ab...
#
#
# TO-DO:
#
# !!!!! Think and FIX data types
#
# Implement org.omg.xmi.enumerationUnprefix 3-23
# Check for name clashes with MMClass
# Some datatypes (like Geometry) should not be enumerations but Classes
import os
import copy
import string
import sys
import xml.dom
from xml.dom import minidom
from smw import io
from smw.metamodel import UML0
from smw.metamodel import UMLDatatypes
import qt
from smw.smwQtApplication import *
from smw.mmgen.dlg import GeneratorDlg
from smw import Configuration
def nameCase(s):
return string.upper(s[0])+s[1:]
class MetaElement:
pass
class MetaClass(MetaElement):
def __init__(self,pak,name,sup,attr,ops):
self.name=name
self.pak=pak
self.sup=sup
self.attr=attr
self.processed=0
self.ops=ops
self.subclasses=[]
def addSubClass(self,melements):
for c in melements.values():
if self.name in c.sup:
if c not in self.subclasses:
self.subclasses.append(c)
for c in self.subclasses:
c.addSubClass(melements)
for c in copy.copy(self.subclasses):
for c1 in c.subclasses:
if c1 not in self.subclasses:
self.subclasses.append(c1)
def generate1(self,melements,code,template):
if self.processed:
return 0
self.addSubClass(melements)
for s in self.sup:
if (melements[s]).processed==0:
return 0
#print self.name,
sys.stdout.flush()
if self.name in ["Element","PresentationElement"]:
self.processed=1
return 1
if self.sup!=[]:
super=""
for s in self.sup:
for p in melements[s].attr:
e=0
for n in self.attr:
if p[0]==n[0]:
e=1
if not e:
self.attr.append(p)
if super!="":
super=super+" ,"
super=super+s
code.add("\nclass "+self.name+"("+super+"):")
else:
self.params=self.attr
code.add("\nclass "+self.name+"(MMClass):")
code.add(" __name__='"+self.name+"'")
code.add(" __userWellFormedRule__=MMSet()")
if template.has_key(self.name):
code.addpl(string.join(
string.split(template[self.name],'\n')[1:],'\n' ))
del template[self.name]
as=""
for a in self.attr:
if len(a)!=3:
if not (
a[1].lower==0 and a[1].upper==1 or (
a[1].lower==0 and a[1].upper==-1)):
name=a[0]
if name[0]=="+":
name=name[1:]
if as!="":
as=as+" and \\\n "
if a[1].lower==1 and a[1].upper==1:
as=as+"self."+name+"!=None"
else:
if a[1].lower>0:
as=as+"self."+name+".size()>="+str(a[1].lower)
if a[1].upper!=-1:
as=as+" and "
if a[1].upper!=-1:
as=as+"self."+name+".size()<="+str(a[1].upper)
if as:
code.add("\n def wfrMetaModelMultiplicity(self):")
code.add(" return "+as)
self.processed=1
return 1
def generate2(self,melements,code,template):
s=''
for c in self.subclasses:
if s:
s=s+', '
s=s+c.name
code.add(self.name+".__subclasses__=["+s+"]")
if self.name in ["Element","PresentationElement"]:
return 1
code.add(self.name+".__mm__={")
count=0
for a in self.attr:
count+=1
if count<len(self.attr):
comma=','
else:
comma=''
if len(a)==3:
m=1
atype=a[2]
assert(atype)
code.add(" '"+a[0]+"': (MMClass.kind__Attribute,"+atype+","+str(m)+",None,None,0)"+comma)
else:
ordered=0
if a[0][0]=="+":
a[0]=a[0][1:]
ordered=1
otherName=a[5]
if otherName[0]=="+":
otherName=otherName[1:]
if a[1].upper==1:
m1=1
else:
m1=0
if a[6].upper==1:
m2=1
else:
m2=0
if a[3]=='composite':
kind="MMClass.kind__Composition"
else:
kind="MMClass.kind__Association"
code.add(" '"+a[0]+"': ("+kind+","+a[2]+","+str(m1)+
",'"+otherName+"',"+str(m2)+","+str(ordered)+")"+comma)
code.add("}")
code.add("")
# create multiplicty assertion
as=""
class CodeArtifact:
def __init__(self):
self.tabs=0
self.text=''
def indent(self,i):
self.tabs=self.tabs+i
def addpl(self,s):
for i in range(self.tabs):
self.text=self.text+' '
self.text=self.text+s
def prepend(self,s):
self.text=s+'\n'+self.text
def add(self,s):
self.addpl(s+'\n')
def dump(self,file):
f=open(file,'w')
f.write(self.text)
f.close()
class MOF2SimpleMetamodelLanguage:
def __init__(self,doc):
self.elementById={}
self.findIds(doc)
self.referenceTable={}
def findIds(self,node):
self.elementById[node.getAttribute('xmi.id')]=node
for c in node.childNodes:
if c.nodeType!= xml.dom.Node.TEXT_NODE:
self.findIds(c)
def extractMOFClass(self,node,code):
mmclass=node.nodeName
name=node.getAttribute('name')
supertypes=[]
for s in string.split(node.getAttribute('supertypes')):
supertypes.append(self.elementById[s].getAttribute('name'))
attrs=[]
for c in node.childNodes:
if c.nodeName=='Model:Namespace.contents':
for a in c.childNodes:
if a.nodeName in ['Model:Attribute','Model:StructuredField']:
atype= self.elementById[a.getAttribute('type')].getAttribute('name')
for aem in a.childNodes:
if aem.nodeName=="Model:TypedElement.type":
for item in aem.childNodes:
if item.nodeName=='Model:Classifier':
atype=self.elementById[item.getAttribute('xmi.idref')].getAttribute('name')
attrs.append([a.getAttribute('name'),"1",atype])
elif a.nodeName=='Model:EnumerationType':
self.extractMOFDataType(a,code)
elif a.nodeName=='Model:Reference':
self.extractMOFReference(a)
else:
self.cannotHandle(a,"extractMOFClass")
elif c.nodeName=='Model:GeneralizableElement.supertypes':
for a in c.childNodes:
if a.nodeName=="Model:GeneralizableElement":
id=a.getAttribute("xmi.idref")
supertypes.append(self.elementById[id].getAttribute('name'))
else:
self.cannotHandle(c,"extractMOFClass")
Element("?",name,supertypes,attrs)
def extractMOFReference(self,node):
id=node.getAttribute("xmi.id")
for c in node.childNodes:
if c.nodeName=="Model:Reference.referencedEnd":
for a in c.childNodes:
if a.nodeName=="Model:AssociationEnd":
self.referenceTable[a.getAttribute("xmi.idref")]=id
print "reference table ",self.referenceTable
def extractMOFDataType(self,dt,code):
name=dt.getAttribute('name')
if name in ['Name','Integer','Boolean','String','UnlimitedInteger']:
# we implement the basic dataypes in Python
return
code.add("class "+name+"(MMEnumeration):")
code.indent(+1)
e=0
descriptions=[]
for tc in dt.childNodes:
if tc.nodeName=='Model:DataType.typeCode':
for ctc in tc.childNodes:
if ctc.nodeName=='XMI.CorbaTypeCode':
for enum in ctc.childNodes:
if enum.nodeName=='XMI.CorbaTcEnum':
for enuml in enum.childNodes:
if enuml.nodeName=='XMI.CorbaTcEnumLabel':
label=enuml.getAttribute('xmi.tcName')
descriptions.append(label)
code.add(label+'='+str(e))
e=e+1
code.add("description="+str(descriptions))
code=code.indent(-1)
def extractMOFAssociation(self,node):
#agregation=node.getAttribute('agregation')
ends=[]
for c in node.childNodes:
if c.nodeName=='Model:Namespace.contents':
for e in c.childNodes:
if e.nodeName in ['Model:AssociationEnd','Model:Reference']:
if self.referenceTable.has_key(e.getAttribute("xmi.id")):
print "CAMBIAZO!"
e=self.elementById[self.referenceTable[e.getAttribute("xmi.id")]]
aType=self.elementById[e.getAttribute('type')].getAttribute('name')
multiplicity=[]
for aem in e.childNodes:
if aem.nodeName=="Model:TypedElement.type":
for item in aem.childNodes:
if item.nodeName=='Model:Classifier':
aType=self.elementById[item.getAttribute('xmi.idref')].getAttribute('name')
elif aem.nodeName in ['Model:AssociationEnd.multiplicity', 'Model:StructuralFeature.multiplicity']:
for item in aem.childNodes:
if item.nodeName=='XMI.field':
multiplicity.append(item.childNodes[0].data)
else:
self.cannotHandle(aem,"extractMOFAssociation2")
m=''
if multiplicity[1]=='-1':
m=multiplicity[0]+'..*'
elif multiplicity[0]==multiplicity[1]:
m=multiplicity[0]
else:
m=multiplicity[0]+'..'+multiplicity[1]
aE=[aType,
e.getAttribute('name'),
e.getAttribute('aggregation')
]
if multiplicity[2]=='true':
aE[1]="+"+aE[1]
print ">>>> Ordered ",aE
aE.append(m)
ends.append(aE)
else:
self.cannotHandle(e,"extractMOFAssociation1")
temp=ends[0][0]
ends[0][0]=ends[1][0]
ends[1][0]=temp
if ends[0][2]=='composite':
ends=[ends[1],ends[0]]
if ends[1][2]=='composite':
Composition(ends[0][0],ends[0][1],ends[0][3],
ends[1][0],ends[1][1],ends[1][3])
else:
Association(ends[0][0],ends[0][1],ends[0][3],
ends[1][0],ends[1][1],ends[1][3])
def extractMOFPackage(self,node,code):
for c in node.childNodes:
if c.nodeName=='Model:Namespace.contents':
for a in c.childNodes:
if a.nodeName in ['Model:DataType','Model:EnumerationType']:
self.extractMOFDataType(a,code)
elif a.nodeName in ['Model:Class','Model:StructureType']:
self.extractMOFClass(a,code)
elif a.nodeName=='Model:Association':
self.extractMOFAssociation(a)
else:
self.cannotHandle(a,"processPackage")
else:
self.cannotHandle(c)
def cannotHandle(self,node,context=''):
if node.nodeName!='#text' and node.nodeName not in \
['Model.Tag','Model:Tag','Model:Import'] :
print "Warning:I cannot handle element "+node.nodeName,
if context:
print "Context:"+context
else:
print
def extractMOF(self,node,code):
if node.nodeName=='Model:Package':
self.extractMOFPackage(node,code)
else:
for c in node.childNodes:
if c.nodeType!= xml.dom.Node.TEXT_NODE:
self.extractMOF(c,code)
class UML2SimpleMetamodelLanguage:
def __init__(self,metamodel):
self.metamodel=metamodel
def extractUMLClass(self,m,path):
m.name=str(m.name)
parents=[]
for p in m.generalization:
if p.parent:
pname=str(p.parent.name)
if pname!=m.name and pname not in parents:
parents.append(pname)
attrs=[]
for a in m.feature:
if isinstance(a,self.metamodel.Attribute) and a.type:
attrs.append(Attribute(str(a.name),str(a.type.name)))
if str(m.name) in UMLDatatypes.standardDataTypes:
print "skiping ",m.name," since is a basic data type"
else:
Element(path,m.name,parents,attrs)
def extractUML13Association(self,m):
if m.connection[1].aggregation==2:
c0=m.connection[1]
c1=m.connection[0]
else:
c0=m.connection[0]
c1=m.connection[1]
for c in [c0,c1]:
if not str(c.name):
c.name=string.lower(c.type.name[0])+c.type.name[1:]
c.multiplicityAsString=str(c.multiplicity.range[0].lower)
if c.multiplicity.range[0].upper!=-1:
c.multiplicityAsString+=".."+str(c.multiplicity.range[0].upper)
else:
c.multiplicityAsString+="..*"
if c0.aggregation==2:
Composition(
str(c0.type.name),str(c1.name),c1.multiplicityAsString,
str(c1.type.name),str(c0.name),c0.multiplicityAsString)
else:
Association(
str(c1.type.name),str(c0.name),c0.multiplicityAsString,
str(c0.type.name),str(c1.name),c1.multiplicityAsString)
def extractUML14Association(self,m):
if m.connection[1].aggregation==2:
c0=m.connection[1]
c1=m.connection[0]
else:
c0=m.connection[0]
c1=m.connection[1]
for c in [c0,c1]:
if not str(c.name):
c.name=string.lower(c.participant.name[0])+c.participant.name[1:]
c.multiplicityAsString=str(c.multiplicity.range[0].lower)
if c.multiplicity.range[0].upper!=-1:
c.multiplicityAsString+=".."+str(c.multiplicity.range[0].upper)
else:
c.multiplicityAsString+="..*"
if c0.aggregation==2:
Composition(
str(c0.participant.name),str(c1.name),c1.multiplicityAsString,
str(c1.participant.name),str(c0.name),c0.multiplicityAsString)
else:
Association(
str(c1.participant.name),str(c0.name),c0.multiplicityAsString,
str(c0.participant.name),str(c1.name),c1.multiplicityAsString)
def extractUML(self,package,path=''):
for m in package.ownedElement:
if isinstance(m,self.metamodel.Class) and str(m.name)!="<DummyClass>":
self.extractUMLClass(m,path)
if isinstance(m,self.metamodel.Association) and m.connection.size()==2:
if self.metamodel.MMVersion=="14":
self.extractUML14Association(m)
else:
self.extractUML13Association(m)
if isinstance(m,self.metamodel.Package):
if path:
newpath=path+"."+m.name
else:
newpath=m.name
self.extractUML(m,newpath)
class SimpleMetamodelLanguageGenerator:
def __init__(self,name,version):
global theGenerator
theGenerator=self
self.associations={}
self.melements={}
self.name=name
self.version=version
self.conflicts={}
self.conflictsCounter={}
def registerPackage(self,name):
# We ignore packages so far
pass
def registerClass(self,package,name,supertypes,attr):
self.melements[name]=MetaClass(package,name,supertypes,attr,[])
def checkAConflicts(self,c,r,c2,r2):
if self.conflicts.has_key(c):
if self.conflicts[c].has_key(r):
print "Warning: association end conflict in:",
print c+"."+r,"-",c2+"."+r2
print " Conflicting association is:",
print c+"."+r,"-",self.conflicts[c][r][0]+"."+self.conflicts[c][r][1]
finalRole=r+string.capitalize(r2[0])+r2[1:]
if self.conflicts[c].has_key(finalRole):
print " I cannot find an alternative name. Please fix the metamodel."
assert(0)
print " The association has been renamed to:",
print c+"."+finalRole,"-",c2+"."+r2
return (c,finalRole)
else:
self.conflicts[c][r]=(c2,r2)
else:
self.conflicts[c]={r: (c2,r2)}
return (c,r)
def registerAssociation(self,atype,c1,r1,n1,c2,r2,n2):
c1,r1=self.checkAConflicts(c1,r1,c2,r2)
c2,r2=self.checkAConflicts(c2,r2,c1,r1)
self.associations["A_"+c1+"."+r1+"_"+c2+"."+r2]=[atype,c1,r1,n1,c2,r2,n2]
def generate(self,code,template):
for k in self.associations.keys():
a=self.associations[k]
if a[2]=="presentation":
a[0]="composite"
if self.melements.has_key(a[4]) and self.melements.has_key(a[1]):
self.melements[a[1]].attr.append([a[2],a[3],a[4],a[0],1,a[5],a[6],a[1]])
self.melements[a[4]].attr.append([a[5],a[6],a[1],'none',2,a[2],a[3],a[1]])
else:
if not self.melements.has_key(a[4]) and UMLDatatypes.__dict__.has_key(a[4]):
self.melements[a[1]].attr.append([a[2],Multiplicity(1,1),a[4]])
if not self.melements.has_key(a[1]) and UMLDatatypes.__dict__.has_key(a[1]):
self.melements[a[4]].attr.append([a[5],Multiplicity(1,1),a[1]])
toprocess=len(self.melements)
while(toprocess>0):
for k in self.melements.keys():
e=self.melements[k]
if e.generate1(self.melements,code,template):
toprocess=toprocess-1
for k in self.melements.keys():
e=self.melements[k]
e.generate2(self.melements,code,template)
print len(self.melements),"elements generated."
s=''
for c in template.values():
s=s+c+'\n'
code.prepend(s)
code.prepend("MMName='"+str(self.name)+"'")
code.prepend("MMVersion='"+str(self.version)+"'")
code.prepend("MMFullName='"+str(self.name)+' '+str(self.version)+"'")
code.prepend('from smw.metamodel.MetaMM import *')
code.prepend('import copy')
code.prepend('from __future__ import nested_scopes')
#
#
def Package(name):
global theGenerator
assert(len(name))
theGenerator.registerPackage(name)
def Element(package,name,parent=[],attribute=[]):
global theGenerator
assert(len(name))
for p in parent:
if type(p)!=type("") and type(p)!=type(u""):
raise "Invalid parent specification",parent
theGenerator.registerClass(package,name,parent,attribute)
def Attribute(name,type):
assert(name and type)
return [name,Multiplicity(1,1),type]
def Association(participant1,role1,multiplicity1,participant2,role2,multiplicity2,kind="none"):
global theGenerator
print participant1,role1,role2
role1=fixName(role1,context=participant1+"."+role1)
role2=fixName(role2,context=participant2+"."+role2)
m1=fromStringToMultiplicity(multiplicity1)
if not m1:
raise "Invalid multiplicity "+multiplicity1+ "in ", participant1+"."+role1
m2=fromStringToMultiplicity(multiplicity2)
if not m2:
raise "Invalid multiplicity "+multiplicity2+ "in ", participant2+"."+role2
assert(participant1 and role1 and m1 and \
participant2 and role2 and m2)
theGenerator.registerAssociation(kind,participant1,role1,m1
,participant2,role2,m2)
def Composition(participant1,role1,multiplicity1,participant2,role2,multiplicity2):
Association(participant1,role1,multiplicity1,
participant2,role2,multiplicity2,
kind="composite")
def DataType():
pass
def Enumeration():
pass
###
class Multiplicity:
def __init__(self,lower=0,upper=0):
self.lower=lower
self.upper=upper
def fromStringToMultiplicity(s):
s=string.replace(s," ","")
list=string.split(s,",")
if len(list)==0:
return None
m=Multiplicity()
for temp in list:
r=string.split(temp,"..")
#If only element x in list, lower=x and upper=x
if len(r)==1:
r.append(r[0])
# r[0]=string.strip(r[0])
if r[0]=='*':
r[0]=0
r.append(-1)
else:
try:
r[0]=int(r[0])
except ValueError:
return None
if r[1]=='*':
r[1]=-1
else:
try:
r[1]=int(r[1])
except ValueError:
return None
if r[1] != -1 and r[0] > r[1] or r[0]==-1:
r[0],r[1]=r[1],r[0] #Swap
if len(r)==3 and r[1]!=-1: #if input is i.e(*..5) swap to (5..*)
r[0]=r[1]
r[1]=r[2]
m.lower=r[0]
m.upper=r[1]
return m
def removecolon(s):
if s and s[-1]==':':
return s[:-1]
else:
return s
def fixName(s,context=""):
if s:
if s[0]=="/":
print "Warning: malformed name",s,
if context:
print "in",context
else:
print
print "I will use",s[1:],"instead"
return s[1:]
return s
class MMGen:
def __init__(self,source,format,target,name,version,templateFile,baseModel=None):
self.source=source
self.format=format
self.target=target
self.version=version
self.name=name
self.templateFile=templateFile
self.baseModel=baseModel
assert(not self.baseModel) # base model not supported yet
def generateModule(self):
if len(self.target)<3 or self.target[-3:] not in ['.py','.PY'] :
self.target_noextension=self.target
self.target=self.target+".py"
else:
self.target_noextension=self.target[:-3]
if self.templateFile:
print "Reading template file "+self.templateFile
self.parseTemplateFile(self.templateFile)
else:
self.template={}
code=CodeArtifact()
generator=SimpleMetamodelLanguageGenerator(self.name,self.version)
if self.format=="mofformat":
print "Reading MOF definition "+self.source+"..."
fd=open(self.source,'r')
doc=minidom.parse(fd).documentElement
fd.close()
extractor=MOF2SimpleMetamodelLanguage(doc)
extractor.extractMOF(doc,code)
elif self.format=="umlformat":
if type(self.source)==type(""):
print "Reading UML definition "+self.source+".."
doc=io.loadModel(self.source,UML0)
else:
doc=self.source
print "USING LOADED MODEL",doc
code.add(UMLDatatypes.standardDataTypesCode)
extractor=UML2SimpleMetamodelLanguage(metamodel=doc.getMetamodel())
extractor.extractUML(doc)
else:
print "Reading python definition "+self.source+"..."
fd=open(self.source,'r')
doc= fd.read()
fd.close()
exec(doc)
print "Generating python module "+self.target+" ..."
generator.generate(code,self.template)
print "Saving python module "+self.target
code.dump(self.target)
self.checkModule(self.target_noextension)
def checkModule(self,m):
print "Trying to import module "+m+" ..."
ok=0
#sys.path.append(os.getcwd())
try:
ok=not(os.system("python2 "+m+".py"))
except Exception,e:
print e
if not ok:
try:
test=__import__(m)
ok=1
except Exception,e:
print e
if ok:
print "The module "+m+" loads correctly. Happy scripting!"
else:
print "Problems loading module"
return ok
def parseTemplateFile(self,templateFile):
self.template={}
fd=open(templateFile,'r')
inclass=0
for l in fd.readlines():
w=string.split(l)
if not inclass:
if w and w[0]=="class":
inclass=1
className=removecolon(w[1])
text=l
else:
if w and w[0]=="class":
self.template[className]=text
className=removecolon(w[1])
text=l
else:
text=text+l
if inclass:
self.template[className]=text
fd.close()
profileCode="""
from smw.metamodel.Profiles import *
from smw.Configuration import Configuration
class <<NAME>>Profile(Profile):
def createModel(self,name):
from <<MODULE>> import *
return <<ROOT>>(name=name)
blurb='<<NAME>> Profile.'
def register(modelerApp):
p= <<NAME>>Profile('<<NAME>>',
'<<MODULE>>',
[],
blurb)
modelerApp.registerProfile(p)
"""
class GeneratorGUI(GeneratorDlg.GeneratorDlg):
def __init__(self):
GeneratorDlg.GeneratorDlg.__init__(self)
self.model=None
def chooseInputFile(self):
name=qt.QFileDialog.getOpenFileName(
'','Metamodels (*.*)',self)
if str(name):
self.SourceFile.setText(name)
def chooseAditionalPythonModule(self):
name=qt.QFileDialog.getOpenFileName(
'','Python Modules (*.py)',self)
if str(name):
self.TemplateFile.setText(name)
def chooseTargetDir(self):
name=qt.QFileDialog.getExistingDirectory()
if str(name):
self.TargetDir.setText(name)
def convert(self):
if not self.model:
source=str(self.SourceFile.text())
if not input:
qt.QMessageBox.critical(self,"No source file",
"Please enter the source file containing the metamodel to generate")
return
else:
source=self.model
name=str(self.Name.text())
version=str(self.Version.text())
if not name or not version:
qt.QMessageBox.critical(self,"Target",
"Please enter the name and version of the metamodel to generate, for example: UML 14")
return
config=Configuration.Configuration()
if self.HOME.isChecked():
path=config.getParameter("user_home").get()+"/.smw/profiles/"+name
try:
os.makedirs(path+"/metamodel")
except:
pass
target=path+"/metamodel/"
else:
target=str(self.TargetDir.text())
if target[-1] not in ["/","\\"]:
target=target+"/"
target=target+name+version+".py"
templateFile=str(self.TemplateFile.text())
if self.MOFFormat.isChecked():
format="mofformat"
if self.UMLFormat.isChecked():
format="umlformat"
if self.SimpleFormat.isChecked():
format="simpleformat"
mmgen=MMGen(source=source,
target=target,
name=name,
version=version,
format=format,
templateFile=templateFile)
mmgen.generateModule()
if self.HOME.isChecked() and self.GenerateProfile.isChecked():
self.createInitFile(config.getParameter("user_home").get()+"/.smw/profiles/"+name)
self.createInitFile(config.getParameter("user_home").get()+"/.smw/profiles/"+name+"/metamodel")
fd=open(path+"/"+name+"profile.py","w")
c=profileCode
c=string.replace(c,"<<NAME>>",name)
c=string.replace(c,"<<MODULE>>",name+".metamodel."+name+version)
c=string.replace(c,"<<ROOT>>","Model")
fd.write(c)
fd.close()
self.close()
def createInitFile(self,s):
fd=open(s+"/__init__.py","w")
fd.close()
def cli():
format="mofformat"
baseModel=None
baseFlag=0
args=[]
for a in sys.argv[1:]:
if baseFlag:
baseModel=a
baseFlag=0
continue
if a=='--simple':
format="simpleformat"
continue
if a=='--uml':
format="umlformat"
continue
if a=='--mof':
format="mofformat"
continue
if a=="--base":
baseFlag=1
continue
args.append(a)
if len(args)>=5:
templateFile=args[4]
else:
templateFile=None
if baseModel:
print "Using "+baseModel+" as base metamodel"
mmgen=MMGen(source=args[0],
target=args[1],
name=args[2],
version=args[3],
format=format,
templateFile=templateFile,
baseModel=baseModel)
mmgen.generateModule()
if __name__=='__main__':
if len(sys.argv)>=5:
cli()
else:
app=qt.QApplication(sys.argv)
dlg=GeneratorGUI()
dlg.exec_loop()
--- NEW FILE: mmgencpp.py ---
#
# mmgen.py Ivan Porres ip...@ab...
#
# c++ modifications/hacks Marcus Alanen maa...@ab...
#
# TO-DO:
#
# !!!!! Think and FIX data types
#
# Implement org.omg.xmi.enumerationUnprefix 3-23
# Check for name clashes with MMClass
# Some datatypes (like Geometry) should not be enumerations but Classes
import os
import copy
import string
import sys
import xml.dom
[...1031 lines suppressed...]
version=args[3],
format=format,
templateFile=templateFile,
baseModel=baseModel)
mmgen.generateModule()
if __name__=='__main__':
if len(sys.argv)>=5:
cli()
else:
app=qt.QApplication(sys.argv)
dlg=GeneratorGUI()
dlg.exec_loop()
--- NEW FILE: mmprint.py ---
import sys
from smw.metamodel import MetaMM
import copy
import string
def mmprint(mname,ename):
try:
mm=MetaMM.getMetamodelByName(mname)
except Exception,e:
print "An error ocurred while loading",mname,":",e
sys.exit(-1)
if not mm.__dict__.has_key(ename):
print "Metamodel",mname,"does not contain an element called ",ename
sys.exit(-1)
element=mm.__dict__[ename]
for c in [element]:
print "Element",c.__name__,":"
if c.__bases__:
bases=list(c.__bases__)
bases.sort(lambda s1,s2: cmp(s1.__name__,s2.__name__))
print " Subclass of",
for sc in bases:
print sc.__name__,
print
if c.__subclasses__:
c.__subclasses__.sort(lambda s1,s2: cmp(s1.__name__,s2.__name__))
print " Inherinted by",
for sc in c.__subclasses__:
print sc.__name__,
print
print
l=copy.copy(c.__mm__.keys())
l.sort()
for name in l:
(kind,mmtype,multiplicity,otherRole,otherMultiplicity)=c.__mm__[name]
if kind==MetaMM.MMClass.kind__Attribute:
print " Attribute ",
elif kind==MetaMM.MMClass.kind__Association:
print " Association",
else:
print " Composition",
print name,
if kind!=MetaMM.MMClass.kind__Attribute:
print ":",
if otherMultiplicity==1:
m="1 to"
else:
m="* to"
if multiplicity==1:
print m+" 1",
else:
print m+" *",
print mmtype.__name__
else:
print ":",mmtype.__name__
print
if __name__=="__main__":
if len(sys.argv)!=3:
print "mmprint prints a description of a model element"
print "Usage : mmprint metamodel element"
print "Example: mmprint UML14 ModelElement"
sys.exit(0)
else:
mmprint(sys.argv[1],sys.argv[2])
|