Skip to main content
summaryrefslogtreecommitdiffstats
blob: fbd104e5cb71ce6a8840f81f1fbe066cca409138 (plain) (blame)
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package org.eclipse.qvtd.cs2as.compiler.internal;

import static org.eclipse.qvtd.cs2as.compiler.internal.OCL2QVTpUtil.firstToLowerCase;
import static org.eclipse.qvtd.cs2as.compiler.internal.OCL2QVTpUtil.getAllContainers;
import static org.eclipse.qvtd.cs2as.compiler.internal.OCL2QVTpUtil.getAllContents;
import static org.eclipse.qvtd.cs2as.compiler.internal.OCL2QVTpUtil.getAllContentsIncludingSelf;
import static org.eclipse.qvtd.cs2as.compiler.internal.OCL2QVTpUtil.getCreationMappingName;
import static org.eclipse.qvtd.cs2as.compiler.internal.OCL2QVTpUtil.getExpressionContextType;
import static org.eclipse.qvtd.cs2as.compiler.internal.OCL2QVTpUtil.getSuperClasses;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.ocl.pivot.Class;
import org.eclipse.ocl.pivot.IfExp;
import org.eclipse.ocl.pivot.Import;
import org.eclipse.ocl.pivot.Model;
import org.eclipse.ocl.pivot.Namespace;
import org.eclipse.ocl.pivot.OCLExpression;
import org.eclipse.ocl.pivot.Operation;
import org.eclipse.ocl.pivot.OperationCallExp;
import org.eclipse.ocl.pivot.Package;
import org.eclipse.ocl.pivot.PivotFactory;
import org.eclipse.ocl.pivot.Property;
import org.eclipse.ocl.pivot.PropertyCallExp;
import org.eclipse.ocl.pivot.ShadowExp;
import org.eclipse.ocl.pivot.ShadowPart;
import org.eclipse.ocl.pivot.Type;
import org.eclipse.ocl.pivot.TypeExp;
import org.eclipse.ocl.pivot.Variable;
import org.eclipse.ocl.pivot.VariableExp;
import org.eclipse.ocl.pivot.utilities.EnvironmentFactory;
import org.eclipse.qvtd.pivot.qvtbase.QVTbaseFactory;
import org.eclipse.qvtd.pivot.qvtbase.Transformation;
import org.eclipse.qvtd.pivot.qvtbase.TypedModel;
import org.eclipse.qvtd.pivot.qvtcore.CoreModel;
import org.eclipse.qvtd.pivot.qvtcore.Mapping;
import org.eclipse.qvtd.pivot.qvtcore.QVTcoreFactory;
import org.eclipse.qvtd.pivot.qvtcorebase.BottomPattern;
import org.eclipse.qvtd.pivot.qvtcorebase.CoreDomain;
import org.eclipse.qvtd.pivot.qvtcorebase.GuardPattern;
import org.eclipse.qvtd.pivot.qvtcorebase.PropertyAssignment;
import org.eclipse.qvtd.pivot.qvtcorebase.QVTcoreBaseFactory;
import org.eclipse.qvtd.pivot.qvtcorebase.RealizedVariable;

public class OCL2QVTm {

	private @NonNull Logger logger = Logger.getLogger(getClass().getName());
	private @NonNull EnvironmentFactory envFact;
	private @NonNull String traceabilityPropName;
	private @Nullable Map<?,?> saveOptions;
	
	public static final @NonNull String RIGHT_MODEL_TYPE_NAME = "rightAS";
	public static final @NonNull String LEFT_MODEL_TYPE_NAME = "leftCS";
	
	public OCL2QVTm(@NonNull EnvironmentFactory envFact, @NonNull String traceabilityPropName) {
		this.envFact = envFact;
		this.traceabilityPropName = traceabilityPropName;
	}
	
	public Resource run(ResourceSet resourceSet, URI oclDocURI) {
		
		if (!"oclas".equals(oclDocURI.fileExtension())) {
			throw new IllegalArgumentException(oclDocURI.toString() + " is not an .oclas URI");
		}
		Resource input = resourceSet.getResource(oclDocURI, true);
		EObject rootModel = input.getContents().get(0);
		if (rootModel instanceof Model) {
			Model model = (Model) rootModel;
			CoreModel outputModel = oclModelToImperativeModel().apply(model);
			
			// We create the output resource
			URI outputURI = oclDocURI.trimFileExtension().trimFileExtension().appendFileExtension("qvtm");
			Resource outputResource = resourceSet.createResource(outputURI);
			outputResource.getContents().add(outputModel);
			return outputResource;
		
		} else {
			throw new IllegalArgumentException(oclDocURI.toString() + " doesn't contain an OCL Model");
		}
	}
	
	private TypedModel leftTypedModel = QVTbaseFactory.eINSTANCE.createTypedModel();
	private TypedModel rightTypedModel = QVTbaseFactory.eINSTANCE.createTypedModel();
	
	public Function<Model, CoreModel> oclModelToImperativeModel() {
		return oclModel -> {
		
			CoreModel iModel = QVTcoreFactory.eINSTANCE.createCoreModel();
		
		List<Operation> allAstOps = getAllContents().apply(oclModel)
					.filter(isAstOp())
					.map(Operation.class::cast).collect(Collectors.toList());
		List<ShadowExp> shadowExps = allAstOps.stream()
					.flatMap(getAllContents())
					.filter(ShadowExp.class::isInstance)
					.map(ShadowExp.class::cast).collect(Collectors.toList());
		
		iModel.setExternalURI(oclModel.getExternalURI().replace(".ocl", ".qvtm")); // When the externalURI is set, also is its name
		iModel.getOwnedImports().addAll(oclModel.getOwnedImports().stream()
				.map(importToImport())
				.collect(Collectors.toList()));
		
		Package pPackage = PivotFactory.eINSTANCE.createPackage();
		pPackage.setName("");
		iModel.getOwnedPackages().add(pPackage);
		
		Transformation pTx = QVTbaseFactory.eINSTANCE.createTransformation();
		pTx.setName(iModel.getName().replace('.', '_')); // FIXME . as part of the name is causing issues in the CG);
		pPackage.getOwnedClasses().add(pTx);
		
		List<Package> importedPackges = new ArrayList<Package>();
		for (Namespace ns : iModel.getOwnedImports().stream()
							.map(x -> x.getImportedNamespace())
							.collect(Collectors.toList())) {
			if (ns instanceof Model) {
				importedPackges.addAll(((Model)ns).getOwnedPackages());
			} else if (ns instanceof Package) {
				importedPackges.add((Package) ns);
			} else {
				logger.warning("imported namespace not recognised: " + ns.getName());
			}
		}
		
		leftTypedModel.setName(LEFT_MODEL_TYPE_NAME);
		leftTypedModel.getUsedPackage().add(
				importedPackges.stream()
				.filter(p -> p.getName().equals(getExpressionContextType().apply(shadowExps.get(0)).getOwningPackage().getName()))
				.findFirst().get());
		pTx.getModelParameter().add(leftTypedModel);
		
		rightTypedModel.setName(RIGHT_MODEL_TYPE_NAME);
		rightTypedModel.getUsedPackage().add(
				importedPackges.stream()
				.filter(p -> p.getName().equals(shadowExps.get(0).getType().getOwningPackage().getName()))
				.findFirst().get());
		pTx.getModelParameter().add(rightTypedModel);
		
		pTx.getRule().addAll(shadowExps.stream()
				.filter(shadowExpToCreationMappingGuard())
				.map(shadowExpToCreationMapping())
				.collect(Collectors.toList()));
		return iModel;
		};
	}
	
	public Function<@NonNull Import, @NonNull Import> importToImport(){
		return oclImport -> {
		Import pImport = PivotFactory.eINSTANCE.createImport();
		pImport.setName(oclImport.getName());
		pImport.setImportedNamespace(oclImport.getImportedNamespace());
		return pImport;
		};
	}
	
	private Predicate<@NonNull ShadowExp> shadowExpToCreationMappingGuard() {
		return shadowExp -> {
			return ! getAllContainers().apply(shadowExp)
					.anyMatch(ShadowExp.class::isInstance);	
		};
	}
	
	public Function<@NonNull ShadowExp, @NonNull Mapping>  shadowExpToCreationMapping() {
		return shadowExp -> {
			Mapping mapping = QVTcoreFactory.eINSTANCE.createMapping();
			mapping.setName(getCreationMappingName().apply(shadowExp));
			
			CoreDomain leftDomain = createCreationMapping_LeftDomain(shadowExp);
			CoreDomain rightDomain = createCreationMapping_RightDomain(shadowExp);
			mapping.getDomain().add(leftDomain);
			mapping.getDomain().add(rightDomain);
			
			Variable leftVar = leftDomain.getGuardPattern().getVariable().get(0);
			Variable rightVar = rightDomain.getBottomPattern().getVariable().get(0);
			
			GuardPattern guardPattern = QVTcoreBaseFactory.eINSTANCE.createGuardPattern();
			BottomPattern bottomPattern = QVTcoreBaseFactory.eINSTANCE.createBottomPattern();
			mapping.setGuardPattern(guardPattern);
			mapping.setBottomPattern(bottomPattern);
			
			PropertyAssignment pAssignment = QVTcoreBaseFactory.eINSTANCE.createPropertyAssignment();
			VariableExp value = PivotFactory.eINSTANCE.createVariableExp();
			value.setReferredVariable(rightVar);
			value.setType(value.getReferredVariable().getType());
			
			VariableExp slotExpression = PivotFactory.eINSTANCE.createVariableExp();
			slotExpression.setReferredVariable(leftVar);
			slotExpression.setType(slotExpression.getReferredVariable().getType());
			
			pAssignment.setValue(value);
			pAssignment.setSlotExpression(slotExpression);
			pAssignment.setTargetProperty(getTraceabilityProperty(slotExpression.getType()));
			
			bottomPattern.getAssignment().add(pAssignment);
			updateGuardPattern(shadowExp, guardPattern, leftVar);
			bottomPattern.getAssignment().addAll(shadowExp.getOwnedParts().stream().
					map(shadowPartToPropertyAssignment(leftVar, rightVar)).
					collect(Collectors.toList()));
			
			return mapping;
		};
	}
	
	
	public Function<@NonNull ShadowPart, @NonNull PropertyAssignment>  shadowPartToPropertyAssignment(Variable leftVar, Variable rightVar) {
		return shadowPart -> {
			VariableExp slotExpression = PivotFactory.eINSTANCE.createVariableExp();
			slotExpression.setReferredVariable(rightVar);
			slotExpression.setType(slotExpression.getReferredVariable().getType());
			
			PropertyAssignment pAssignment = QVTcoreBaseFactory.eINSTANCE.createPropertyAssignment();
			pAssignment.setTargetProperty(shadowPart.getReferredProperty());
			pAssignment.setValue(createPropertyAssignmentValue(shadowPart, leftVar));
			pAssignment.setSlotExpression(slotExpression);
			return pAssignment;
		};
	}
	
	
	private CoreDomain createCreationMapping_LeftDomain(ShadowExp shadowExp) {
		
		Class contextType = getExpressionContextType().apply(shadowExp);
		CoreDomain domain = QVTcoreBaseFactory.eINSTANCE.createCoreDomain();
		domain.setTypedModel(leftTypedModel);
		domain.setIsCheckable(true);
		
		GuardPattern guardPattern = QVTcoreBaseFactory.eINSTANCE.createGuardPattern();
		BottomPattern bottomPattern = QVTcoreBaseFactory.eINSTANCE.createBottomPattern();
		domain.setGuardPattern(guardPattern);
		domain.setBottomPattern(bottomPattern);
		
		Variable variable = PivotFactory.eINSTANCE.createVariable();
		variable.setName(firstToLowerCase().apply(contextType.getName()));
		variable.setType(contextType);
		
		guardPattern.getVariable().add(variable);
		
		return domain;
	}
	
	private CoreDomain createCreationMapping_RightDomain(ShadowExp shadowExp) {

		Class constructedType = shadowExp.getType();
		CoreDomain domain = QVTcoreBaseFactory.eINSTANCE.createCoreDomain();
		domain.setTypedModel(rightTypedModel);
		domain.setIsEnforceable(true);
		
		GuardPattern guardPattern = QVTcoreBaseFactory.eINSTANCE.createGuardPattern();
		BottomPattern bottomPattern = QVTcoreBaseFactory.eINSTANCE.createBottomPattern();
		domain.setGuardPattern(guardPattern);
		domain.setBottomPattern(bottomPattern);
		
		RealizedVariable variable = QVTcoreBaseFactory.eINSTANCE.createRealizedVariable();
		variable.setName(firstToLowerCase().apply(constructedType.getName()));
		variable.setType(constructedType);
		
		bottomPattern.getRealizedVariable().add(variable);
		return domain;
	}
	
	private OCLExpression createPropertyAssignmentValue(ShadowPart shadowPart, Variable leftVar) {
		
		// FIXME what happens with synthetised types ????
		OCLExpression initExp = shadowPart.getOwnedInit();
		OCLExpression newInitExp = EcoreUtil.copy(initExp);
		//We need to replace the OCL refered "self" varible by the QVTi domain "leftVar" and ast op calls
		return doReplacements(newInitExp, leftVar);
	}
	
	private OCLExpression doReplacements(OCLExpression oclExp, Variable leftVar) {
		
		List<OCLExpression> result = new ArrayList<OCLExpression>();// Simple work aroound to the forEach constraint ;
		result.add(oclExp);
		getAllContentsIncludingSelf().apply(oclExp).forEach(x -> {
			if (isSelfVarExp().test(x)) {
				((VariableExp)x).setReferredVariable(leftVar);
			} else if(isAstOpCallExp().test(x)) {
				OperationCallExp exp = (OperationCallExp) x;
				PropertyCallExp astPropCallExp = PivotFactory.eINSTANCE.createPropertyCallExp();
				astPropCallExp.setOwnedSource(exp.getOwnedSource());
				astPropCallExp.setReferredProperty(getTraceabilityProperty(astPropCallExp.getOwnedSource().getType()));
				astPropCallExp.setType(astPropCallExp.getReferredProperty().getType());
				// Copying remaining changeable OpCallExp properties (excepting ownedArguments and referredOperation)
				astPropCallExp.setTypeValue(exp.getTypeValue());
				astPropCallExp.getOwnedComments().addAll(exp.getOwnedComments());
				astPropCallExp.getOwnedExtensions().addAll(exp.getOwnedExtensions());
				astPropCallExp.setName(exp.getName());
				astPropCallExp.setIsSafe(exp.isIsSafe());
				astPropCallExp.setIsRequired(exp.isIsRequired());
				astPropCallExp.setIsImplicit(exp.isIsImplicit());
				astPropCallExp.setIsPre(exp.isIsPre());
				// end of copy
				
				Type castType = exp.getType();
				OperationCallExp asTypeOpCallExp = PivotFactory.eINSTANCE.createOperationCallExp();
				asTypeOpCallExp.setOwnedSource(astPropCallExp);
				asTypeOpCallExp.setReferredOperation(getOclAnyOclAsTypeOp());
				asTypeOpCallExp.setType(castType);
				asTypeOpCallExp.setIsSafe(astPropCallExp.isIsSafe());
				
				TypeExp argTypeExp = PivotFactory.eINSTANCE.createTypeExp();
				argTypeExp.setReferredType(castType);
				argTypeExp.setType(getOclMetaClass());
				
				asTypeOpCallExp.getOwnedArguments().add(argTypeExp);
				
				if (result.contains(exp)) { // if exp is the initial oclExp, the new asTypeOpCallExp will be the new result
					result.remove(exp);
					result.add(asTypeOpCallExp);
				} else {
					EcoreUtil.replace(exp,asTypeOpCallExp);
				}
				EcoreUtil.delete(exp);
			}
		});
		return result.get(0);
	}
	
	/**
	 * Function which takes into account that the shadow is embedded inside of an IfExp
	 * so that the guard pattern have the proper guards associated to the the IfExp
	 */ 
	 private void updateGuardPattern(ShadowExp shadowExp, GuardPattern guardPattern, Variable leftVar) {

		EObject container = shadowExp.eContainer();		
		
		if (container instanceof IfExp) {
			IfExp ifExp = (IfExp) container;
			OCLExpression condition = ifExp.getOwnedCondition();
			List<OCLExpression> guardPredicates = new ArrayList<OCLExpression>();
			if (ifExp.getOwnedThen() == shadowExp) {
				guardPredicates.add(EcoreUtil.copy(condition));
			} else { // it's the else
				guardPredicates.add(createNegatedExpression(condition));
			}
			
			container = container.eContainer();
			// FIXME create a cached operation to improve performance
			while (container instanceof IfExp) {
				ifExp = (IfExp) container;
				guardPredicates.add(createNegatedExpression(ifExp.getOwnedCondition()));
				container = container.eContainer();
			}
			
			// We need to replace the OCL refered "self" varible by the QVTi domain "leftVar"
			Collections.reverse(guardPredicates);
			for (OCLExpression guardPredicate : guardPredicates ) {
				org.eclipse.qvtd.pivot.qvtbase.Predicate predicate = QVTbaseFactory.eINSTANCE.createPredicate();
				predicate.setConditionExpression(doReplacements(guardPredicate, leftVar));
				guardPattern.getPredicate().add(predicate);
			}
		}
	}
	 
	private OCLExpression createNegatedExpression(OCLExpression oclExp){
		// We don't want to create a 'not not conditionExp'
		if (isBooleanNotOpCallExp().test(oclExp)) {
			OperationCallExp notOpCallExp = (OperationCallExp) oclExp;
			return EcoreUtil.copy(notOpCallExp.getOwnedSource());
		} else {
			OperationCallExp notOpCallExp = PivotFactory.eINSTANCE.createOperationCallExp();
			notOpCallExp.setName("not");
			notOpCallExp.setReferredOperation(getBooleanNotOp());
			notOpCallExp.setType(getBooleanPrimitiveType());
			notOpCallExp.setOwnedSource(EcoreUtil.copy(oclExp));
			return notOpCallExp;
		}
	}  
	
	private Predicate<EObject> isSelfVarExp() {
		return element -> { 
			return element instanceof VariableExp && 
				"self".equals(((VariableExp)element).getReferredVariable().getName());
		};
	}
	
	private Predicate<EObject> isAstOpCallExp() {
		return element -> { 
			return element instanceof OperationCallExp &&
				isAstOp().test(((OperationCallExp)element).getReferredOperation());
		};
	}
	
	private Predicate<EObject> isAstOp() {
		return element -> {
				return element instanceof Operation &&
				"ast".equals(((Operation)element).getName());
		};
	}
	
	/*private List<OperationCallExp> getAstCalls(ShadowPart shadowPart) {
		return getAllContentsIncludingSelf().apply(shadowPart.getOwnedInit())
			.filter(isAstOpCallExp())
			.map(OperationCallExp.class::cast)
			.collect(Collectors.toList());
	}*/
	
	private @NonNull Property getTraceabilityProperty(Type type) {
		Class aClass = type.isClass();
		assert(aClass != null);
		Set<Class> allClasses = getSuperClasses().apply(aClass);
		allClasses.add(aClass);
		return allClasses.stream()
			.flatMap(x -> x.getOwnedProperties().stream())
			.filter(x -> traceabilityPropName.equals(x.getName()))
			.findFirst().get();
	}
	
	private @NonNull Operation getOclAnyEqualsOp() {
		Class oclAny = envFact.getStandardLibrary().getOclAnyType();
		return envFact.getMetamodelManager().getPrimaryClass(oclAny).getOwnedOperations().stream()
			.filter(x -> "=".equals(x.getName()))
			.findFirst().get();
	}
	
	private @NonNull Class getOclMetaClass() { 
		return envFact.getStandardLibrary().getClassType();
	}
	
	private @NonNull Operation getOclAnyOclAsTypeOp() {
		Class oclAny = envFact.getStandardLibrary().getOclAnyType();
		return envFact.getMetamodelManager().getPrimaryClass(oclAny).getOwnedOperations().stream()
			.filter(x -> "oclAsType".equals(x.getName()))
			.findFirst().get();
	}
	
	private @NonNull Class getBooleanPrimitiveType() {
		return envFact.getStandardLibrary().getBooleanType();
		
	}
	
	private @NonNull Operation getBooleanNotOp() {
		Class boolType = envFact.getStandardLibrary().getBooleanType();
		return envFact.getMetamodelManager().getPrimaryClass(boolType).getOwnedOperations().stream()
				.filter(x -> "not".equals(x.getName()))
				.findFirst().get();
	}
	
	private Predicate<OCLExpression> isBooleanNotOpCallExp() {
		return exp -> {
			return exp instanceof OperationCallExp &&
					((OperationCallExp)exp).getReferredOperation() == getBooleanNotOp();
		};
	}
	
}

Back to the top