forked from aranega/simple-python-gen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuml2python.mtl
319 lines (273 loc) · 12 KB
/
uml2python.mtl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
[comment encoding = UTF-8 /]
[module uml2python('http://www.eclipse.org/uml2/4.0.0/UML')]
[comment]
Main entry point. This main template MUST be named 'generate' and it must
own the main annotation.
[/comment]
[template public generate(m : Package)]
[comment @main/]
[file (m.qualifiedName.replaceAll('::', '/') + '/__init__.py', false, 'UTF-8')]
[if (not m.ownedComment->isEmpty())]
"""
[m.ownedComment.genComment(' ')/]
"""
[/if]
# [protected ('-> additional imports for ' + m.name + ' package')]
# [/protected]
[let nonPrimitiveClasses : Set(Classifier) = m.packagedElement->union(m.importedMember)->filter(Classifier)->reject(oclIsKindOf(Association) or oclIsKindOf(PrimitiveType))]
[let nonPrimitiveInstances : Set(InstanceSpecification) = m.packagedElement->union(m.importedMember)->filter(InstanceSpecification)]
[for (e : NamedElement | nonPrimitiveClasses->union(nonPrimitiveInstances)->sortedBy(qualifiedName)) before('__all__ = [') separator(', ') after(']')]
"[e.name/]"[/for]
[for (e : Classifier | nonPrimitiveClasses->sortedBy(qualifiedName))]
from [e.qualifiedName.replaceAll('::', '.')/] import [e.name/]
[/for]
[for (instance : InstanceSpecification | nonPrimitiveInstances->sortedBy(qualifiedName))]
import [instance.classifier.qualifiedName.replaceAll('::', '.')/]
[/for]
[for (instance : InstanceSpecification | nonPrimitiveInstances->sortedBy(qualifiedName))]
[instance.name/] = [instance.classifier.qualifiedName.replaceAll('::', '.')/]()
[/for]
[/let]
[/let]
[/file]
[m.genPackageContent()/]
[/template]
[**
* This template generates a package content (one class per file)
*/]
[template public genPackageContent(m : Package)]
[for (e : Classifier | m.ownedElement->filter(Classifier)->reject(oclIsKindOf(Association)))]
[file(e.qualifiedName.replaceAll('::', '/') + '.py', false, 'UTF-8')]
# [protected ('-> additional imports for ' + e.name)]
# [/protected]
[if (not m.packagedElement->select(isAbstract)->isEmpty())]
from abc import ABCMeta, abstractmethod, abstractclassmethod, abstractstaticmethod
[/if]
[for (u : Dependency | m.packagedElement->filter(Dependency)->select(match | match.oclAsType(Dependency).client->includes(e))->sortedBy(qualifiedName))]
from [u.supplier.qualifiedName.replaceAll('::', '.')/] import [u.supplier.name/]
[/for]
[comment Dummy and very simple import management (misses the extern module imports) /]
[if (not m.allOwnedElements()->filter(TypedElement)->select(type <> null and type.name <> null and type.name = 'Date')->isEmpty())]
from datetime import datetime
[/if]
[comment Generate code for classes/interfaces /]
[e.genClassif()/]
[/file]
[/for]
[/template]
[comment]
These templates are used to generate 'Classifier' code, i.e., Class, Interface and Enumeration.
[/comment]
[template public genClassif(e : Classifier)/]
[template public genClassif(d : DataType)]
[let inherited : Set(Classifier) = d.parents()]
[for (inheritedNonPrimitiveClass : Classifier | inherited->reject(oclIsKindOf(PrimitiveType))->sortedBy(qualifiedName))]
from [inheritedNonPrimitiveClass.qualifiedName.replaceAll('::', '.')/] import [inheritedNonPrimitiveClass.name/]
[/for]
[let nonPrimitiveAttributes : OrderedSet(Property) = d.attribute->reject(oclIsKindOf(PrimitiveType))->reject(type.qualifiedName = d.qualifiedName)]
[for (attribute : Property | nonPrimitiveAttributes->sortedBy(qualifiedName))]from [attribute.type.qualifiedName.replaceAll('::', '.')/] import [attribute.type.name/]
[/for][/let]
class [d.name/]([if (not inherited->isEmpty())][for (cl : Classifier | inherited) separator(', ')][cl.name/][/for][else]object[/if]):
[/let]
[if (not d.ownedComment->isEmpty())]
"""
[d.ownedComment.genComment(' ')/]
"""
[/if]
def __init__(self):
super().__init__()
[d.ownedAttribute.gen()/]
# [protected ('-> additional implementation details for ' + d.name + ' datatype constructor')]
# [/protected]
# [protected ('-> properties/constructors for ' + d.name + ' class')]
# [/protected]
[/template]
[template public genClassif(c : Class)]
[let inherited : Bag(Classifier) = c.superClass->union(c.interfaceRealization.contract)]
[for (inheritedNonPrimitiveClass : Classifier | inherited->reject(oclIsKindOf(PrimitiveType))->sortedBy(qualifiedName))]
from [inheritedNonPrimitiveClass.qualifiedName.replaceAll('::', '.')/] import [inheritedNonPrimitiveClass.name/]
[/for]
[let nonPrimitiveAttributes : OrderedSet(Property) = c.attribute->reject(oclIsKindOf(PrimitiveType))->reject(type.qualifiedName = c.qualifiedName)]
[for (attribute : Property | nonPrimitiveAttributes->sortedBy(qualifiedName))]from [attribute.type.qualifiedName.replaceAll('::', '.')/] import [attribute.type.name/]
[/for][/let]
class [c.name/]([if (not inherited->isEmpty())][for (cl : Classifier | inherited->sortedBy(qualifiedName)) separator(', ')][cl.name/][/for][else]object[/if][if (not c.ownedOperation->select(isAbstract)->isEmpty())], metaclass=ABCMeta[/if]):
[if (not c.ownedComment->isEmpty())]
"""
[c.ownedComment.genComment(' ')/]
"""
[/if]
[let navig : Bag(Property) = c.getAssociations().navigableOwnedEnd->select(type <> c)]
[if (not c.ownedOperation->select(m | m.name = c.name)->isEmpty())]
[c.ownedOperation->select(m | m.name = c.name)->first().gen()/]
[else]
def __init__(self):
super().__init__()
[if (not c.ownedAttribute->union(navig)->isEmpty())] [c.ownedAttribute->union(navig).gen()/][/if]
# [protected ('-> additional implementation details for ' + c.name + ' class constructor')]
# [/protected]
[/if][/let]
# [protected ('-> properties for ' + c.name + ' class')]
# [/protected]
[if (not c.nestedClassifier->isEmpty())]
[c.nestedClassifier.genClassif()/]
[/if]
[if (not c.ownedOperation->isEmpty())]
[for (ops : Operation | c.ownedOperation->reject(op | op.name = c.name))]
[ops.gen()/]
[/for]
[/if]
# [protected ('-> methods for ' + c.name + ' class')]
# [/protected]
[/let]
[/template]
[template public genClassif(i : Interface)]
[let inherited : Bag(Classifier) = i.generalization.general]
[for (inheritedNonPrimitiveClass : Classifier | inherited->reject(oclIsKindOf(PrimitiveType))->sortedBy(qualifiedName))]
from [inheritedNonPrimitiveClass.qualifiedName.replaceAll('::', '.')/] import [inheritedNonPrimitiveClass.name/]
[/for]
class [i.name/]([if (not inherited->isEmpty())][for (cl : Classifier | inherited->sortedBy(qualifiedName)) separator(', ')][cl.name/][/for][else]object[/if]):
[if (not i.ownedComment->isEmpty())]
"""
[i.ownedComment.genComment(' ')/]
"""
[/if]
[let navig : Bag(Property) = i.getAssociations().navigableOwnedEnd->select(type <> i)]
def __init__(self):
super().__init__()
[if (not i.ownedAttribute->union(navig)->isEmpty())][i.ownedAttribute->union(navig).gen()/][/if]
# [protected ('-> additional implementation details for ' + i.name + ' interface constructor')]
# [/protected]
[/let]
# [protected ('-> properties for ' + i.name + ' class(interface)')]
# [/protected]
[if (not i.nestedClassifier->isEmpty())]
[i.nestedClassifier.genClassif()/]
[/if]
[if (not i.ownedOperation->isEmpty())]
[for (ops : Operation | i.ownedOperation->reject(op | op.name = i.name))]
[ops.gen()/]
[/for]
[/if]
# [protected ('-> methods for ' + i.name + ' class(interface)')]
# [/protected]
[/let]
[/template]
[comment]
This template represents the choice we made about UML Enumeration
compilation to python code.
[/comment]
[template public genClassif(e : Enumeration)]
class [e.name/]:
[if (not e.ownedComment->isEmpty())]
"""
[e.ownedComment.genComment(' ')/]
"""
[/if]
[if (not e.ownedLiteral->isEmpty())]
[for (lit : EnumerationLiteral | e.ownedLiteral) separator(', ')][lit.name/][/for] = range([e.ownedLiteral->size()/])
[/if]
[/template]
[template public gen(p : Property)]
[if (not p.ownedComment->isEmpty())]
[p.ownedComment.genComment('#')/]
[/if]
self.[if (p.visibility = VisibilityKind::_private)]__[/if][p.name/]: [p.type.name/][if ((not p.defaultValue.oclIsInvalid()) and (not p.defaultValue.oclIsUndefined()))] = [p.defaultValue.translate()/][/if]
[/template]
[template public gen(o : Operation)]
[o.header()/]
[if (not o.ownedComment->isEmpty())]
"""
[o.ownedComment.genComment(' ')/]
"""
[/if]
# [protected ('protected zone for ' + o.name + ' function body')]
# [/protected]
[o.bodyOperation()/]
[/template]
[template public translate(v : ValueSpecification)]
[if (v.oclIsTypeOf(InstanceValue) or v.oclIsTypeOf(LiteralNull) or v.oclIsTypeOf(EnumerationLiteral) or v.oclIsTypeOf(LiteralInteger) or v.oclIsTypeOf(LiteralReal) or v.oclIsTypeOf(LiteralBoolean))]
[v.translate()/]
[else]
[v.stringValue()/]
[/if]
[/template]
[template public translate(v : InstanceValue)]
[if (not v.instance.qualifiedName.oclIsUndefined())][v.instance.classifier.name/].[v.instance.name.replaceAll('::', '.')/]
[elseif (not v.type.qualifiedName.oclIsUndefined())][v.type.name.replaceAll('::', '.')/]()
[/if]
[/template]
[template public translate(ln : LiteralNull)]
None
[/template]
[template public translate(v : EnumerationLiteral)]
[v.name/]
[/template]
[template public translate(v : LiteralInteger)]
[v.value/]
[/template]
[template public translate(v : LiteralReal)]
[v.value/]
[/template]
[template public translate(v : LiteralBoolean)]
[if (not v.value.oclIsUndefined() and v.booleanValue())]True[else]False[/if]
[/template]
[comment]
Generate an operation header. If the operation visibility is set to
private, '__' prefixes the operation name.
[/comment]
[template public header(o : Operation)]
[if (o.isAbstract)]@abstractmethod
[/if][if (o.isStatic)]@staticmethod
[/if]
def [if (o.visibility = VisibilityKind::_private)]__[/if][if (o.class.name = o.name)]__init__[else][o.name/][/if]([if (not o.isStatic)]self[if (not o.ownedParameter->excluding(o.getReturnResult())->isEmpty())], [/if][/if][for (param : Parameter | o.ownedParameter->excluding(o.getReturnResult())) separator(', ')][param.name/][if ((not param.type.oclIsInvalid()) and param.type.oclIsKindOf(PrimitiveType))]: [param.type.name/][/if][if ((not param.defaultValue.oclIsUndefined()) and (not param.defaultValue.oclIsInvalid()))] = [param.defaultValue.translate()/][/if][/for])[if ((not o.getReturnResult().oclIsInvalid()) and (not o.getReturnResult().oclIsUndefined()))] -> [o.getReturnResult().type.name/][/if]:
[/template]
[template public bodyOperation(o : Operation)]
[if (o.isAbstract)]raise NotImplementedError
[elseif (not o.method->isEmpty())]
[let behaviors : Set(FunctionBehavior) = o.method]
[for (behavior : FunctionBehavior | behaviors->select(b | b->one(language->first() = 'Python')))][behavior._body->first()/][/for]
[/let]
[elseif (o.getReturnResult() <> null and o.getReturnResult().type <> null)]
return [o.getReturnResult().genValue()/]
[else]raise NotImplementedError
[/if]
[/template]
[template public genValue(m : MultiplicityElement) post (trim())]
[if (m.isMany())]['['/]]
[elseif (m.oclIsKindOf(TypedElement))][m.oclAsType(TypedElement).type.genSingleValue()/]
[else]None
[/if]
[/template]
[comment]
Generate single values for methods and attributes initialization.
[/comment]
[template public genSingleValue(t : Type) ? (not t.oclIsUndefined()) post (trim())]
[if (t.name = 'str')]""
[elseif (t.name = 'unlimitedNatural')]0L
[elseif (t.name = 'double')]0.
[elseif (t.name = 'real')]0.
[elseif (t.name = 'float')]0.
[elseif (t.name = 'long')]0L
[elseif (t.name = 'int')]0
[elseif (t.name = 'short')]0
[elseif (t.name = 'byte')]0x0
[elseif (t.name = 'array')]['['/]]
[elseif (t.name = 'boolean')]False
[elseif (t.name = 'date')]datetime()
[elseif (t.name = 'char')]''
[elseif (t.name = 'List')]['[]'/]
[elseif (t.oclIsKindOf(Enumeration))][if (not t.oclAsType(Enumeration).ownedLiteral->isEmpty())][t.name/].[t.oclAsType(Enumeration).ownedLiteral->at(1).name/][else]None[/if]
[else]None[/if]
[/template]
[template public genComment(c : Comment, prefix : String)]
[prefix/][c.genBody(prefix).replaceAll('\n','\n' + prefix + ' ')/]
[/template]
[template public genBody(c : Comment, prefix : String)]
[c._body/][if (not c.ownedComment->isEmpty())]['\n'/][prefix/] [c.ownedComment.genBody(prefix)->sep('\n ' + prefix)/][/if]
[/template]
[query public isMany(s : MultiplicityElement) : Boolean =
s.lower > 1 or s.upper = -1 or s.upper > 1
/]
[query public isAssociation(p : Property) : Boolean =
not p.association.oclIsUndefined()
/]