aboutsummaryrefslogtreecommitdiffstats
path: root/Solvers/Alloy-Solver/hu.bme.mit.inf.dlsreasoner.alloy.reasoner/src/hu/bme/mit/inf/dlsreasoner/alloy/reasoner/builder/Logic2AlloyLanguageMapper_TypeMapper_Horizontal.xtend_old
blob: 7383904d9e414f492565743c81469a3b85d40a43 (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
package hu.bme.mit.inf.dlsreasoner.alloy.reasoner.builder

import hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSIntersection
import hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSMultiplicity
import hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSSignatureDeclaration
import hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSTerm
import hu.bme.mit.inf.dslreasoner.alloyLanguage.AlloyLanguageFactory
import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference
import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.DefinedElement
import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDeclaration
import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDefinition
import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
import hu.bme.mit.inf.dslreasoner.logic.model.patterns.SupertypeStarMatcher
import java.util.HashMap
import java.util.LinkedHashSet
import java.util.LinkedList
import java.util.List
import java.util.Map
import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine
import org.eclipse.viatra.query.runtime.emf.EMFScope
import org.eclipse.xtend.lib.annotations.Data

import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.*

class Logic2AlloyLanguageMapper_TypeMapperTrace_Horizontal
	implements Logic2AlloyLanguageMapper_TypeMapperTrace {
	public var ALSSignatureDeclaration declaredSupertype
	public var ALSSignatureDeclaration definedSupertype
	public val Map<DefinedElement, ALSSignatureDeclaration> definedElement2Declaration = new HashMap
	
	public val Map<TypeDefinition,  ALSSignatureDeclaration> definition2definition = new HashMap
	public val Map<TypeDeclaration, ALSSignatureDeclaration> declaration2definition = new HashMap
	public val Map<TypeDeclaration, ALSSignatureDeclaration> undefined2definition = new HashMap
	public val Map<TypeDeclaration, ALSSignatureDeclaration> new2declaration = new HashMap
	
	def getAllDefinedTypes() {
		return (definition2definition.values) +
		       (declaration2definition.values) +
		       (undefined2definition.values)
	}
	def getAllDeclaredTypes() {
		return new2declaration.values
	}
	
	public val Map<Type,List<ALSSignatureDeclaration>> type2AllSignatures = new HashMap;
}

@Data
class DynamicTypeConstraints {
	List<List<Type>> positiveCNF
	LinkedHashSet<Type> negative
	public new() {
		this.positiveCNF = new LinkedList
		this.negative = new LinkedHashSet
	}
	def public void addPositiveTypeOptions(List<Type> typeDisjunction) {
		this.positiveCNF.add(typeDisjunction)
	}
	def public void addNegativeTypes(Iterable<Type> negativeTypes) {
		this.negative.addAll(negativeTypes)
	}
}

/**
 * Dynamic types are represented by disjoint sets, and 
 * static types are represented by the union of the dynamic type sets.
 * 
 * Definition                         Declaration
 *     |                              /         \
 *     |                  W/DefinedSuper       Wo/DefinedSuper
 *     |                     |                  /           \
 *     |                     |      undefined2declaration  new2declaration
 * definition2definition  definition2declaration
 * +----------------------------------------------------+  +-------------+
 *        Defined                                              Declared
 */
class Logic2AlloyLanguageMapper_TypeMapper_Horizontal implements Logic2AlloyLanguageMapper_TypeMapper{
	private val Logic2AlloyLanguageMapper_Support support = new Logic2AlloyLanguageMapper_Support;
	private val extension AlloyLanguageFactory factory = AlloyLanguageFactory.eINSTANCE
	
	override transformTypes(LogicProblem problem, Logic2AlloyLanguageMapper mapper, Logic2AlloyLanguageMapperTrace trace) {
		// 0. Creating the traces
		val typeTrace = new Logic2AlloyLanguageMapper_TypeMapperTrace_Horizontal
		trace.typeMapperTrace = typeTrace
		/**
		 * Static type -> list of possible dynamic type map
		 */
		val typeToConcreteSubtypes = problem.typeToConcreteSubtypes(trace)
		
		
		
		// 1. Transforming the types
		
		// There are two kind of types:
		// A: one with defined supertypes (including itself), that only has defined elements
		// Those types can have instances only from the defined elements, ie they are subset of problem.elements
		// B: one without defined supertypes 
		// Those types can have instances from two sources
		// B.1 from elements that dont have definitions
		// B.2 from newly created elements
		val allConcreteTypes = problem.types.filter[!it.isAbstract]
		val definitions = allConcreteTypes.filter(TypeDefinition).toList
		val declarationsWithDefinedSupertype = allConcreteTypes.filter(TypeDeclaration).filter[it.hasDefinedSupertype].toList
		val declarationsWithoutDefinedSupertype = allConcreteTypes.filter(TypeDeclaration).filter[!it.hasDefinedSupertype].toList
		
		// 2. If there are defined elements
		if(trace.typeTrace.definedSupertype != null) {
			// 3 mapping the elements
			problem.elements.transformDefinedSupertype(trace)
			// 4. if there are elements that are added to types, then it have to be mapped to defined parts
			if(problem.elements.exists[!it.definedInType.empty]) {
				definitions.forEach[it.transformDefinition2Definition(trace)]
				declarationsWithDefinedSupertype.forEach[it.transformDeclaration2Definition(trace)]
			}
			// 5. if there are elements that are not added to types, then it have to be mapped to declarations without definitions
			if(problem.elements.exists[it.definedInType.empty]) {
				declarationsWithoutDefinedSupertype.forEach[it.transformUndefined2Definition(trace)]
			}
			
			definedConcreteTypesAreFull(trace)
			definedConcreteTypesAreDisjoint(trace)
			problem.definedConcreteTypesAreSatisfyingDefinitions(typeToConcreteSubtypes,trace)
		}
		
		// Transforming the declared and defined concrete types
		problem.elements.transformDefinedSupertype(trace)
		if(trace.typeTrace.definedSupertype != null) {
			problem.elements.transformDefinedElements(trace)
			declarationsWithoutDefinedSupertype.forEach[it.transformNew2Declaration(trace)]
		}
		
		// 2: Caching the types by filling type2AllSignatures
		for(typeToConcreteSubtypesEntry : typeToConcreteSubtypes.entrySet) {
			val type = typeToConcreteSubtypesEntry.key
			val List<ALSSignatureDeclaration> signatures = new LinkedList
			
		}
	}
	
	def getTypeTrace(Logic2AlloyLanguageMapperTrace trace) {
		val res = trace.typeMapperTrace
		if(res instanceof Logic2AlloyLanguageMapper_TypeMapperTrace_Horizontal) {
			return res
		} else {
			throw new IllegalArgumentException('''
			Expected type mapping trace: «Logic2AlloyLanguageMapper_TypeMapperTrace_Horizontal.name»,
			but found «res.class.name»''')
		}
	}
	
	private def boolean hasDefinedSupertype(Type type) {
		if(type instanceof TypeDefinition) {
			return true
		} else {
			if(type.supertypes.empty) return false
			else return type.supertypes.exists[it.hasDefinedSupertype]
		}
	}
	
	private def transformDefinedSupertype(List<DefinedElement> elements, Logic2AlloyLanguageMapperTrace trace) {
		trace.typeTrace.definedSupertype = createALSSignatureDeclaration => [
			it.name = support.toID(#["util","defined","Object"])
		]
		trace.specification.signatureBodies += createALSSignatureBody => [
			it.abstract = true
			it.declarations += trace.typeTrace.definedSupertype
		]
	}
	
	private def transformDefinedElements(List<DefinedElement> elements,
		Logic2AlloyLanguageMapperTrace trace){
		if(trace.typeTrace.definedSupertype != null) {			
			// 2. Create elements as singleton signatures subtype of definedSupertype
			val elementBodies = createALSSignatureBody => [
				it.multiplicity = ALSMultiplicity::ONE
				it.supertype = trace.typeTrace.definedSupertype
			]
			trace.specification.signatureBodies += elementBodies
			for(element : elements) {
				val elementDeclaration = createALSSignatureDeclaration => [
					it.name = support.toIDMultiple(#["element"],element.name)
				]
				elementBodies.declarations += elementDeclaration
				trace.typeTrace.definedElement2Declaration.put(element,elementDeclaration)
			}
			// 3. Specify that definedSupertype is equal to the union of specified
			/*trace.specification.factDeclarations += createALSFactDeclaration => [
				it.name = support.toID(#["util","typehierarchy","definitionOfElements"])
				it.term = createALSEquals => [
					it.leftOperand = createALSReference => [it.referred = trace.typeTrace.definedSupertype]
					it.rightOperand = support.unfoldPlus(elements.map[element|createALSReference=>[
						it.referred = element.lookup(trace.typeTrace.definedElement2Declaration)
					]])
				]
			]*/
		}
	}
	
	///// Type definitions
	
	protected def void transformDefinition2Definition(TypeDefinition type, Logic2AlloyLanguageMapperTrace trace) {
		val sig = createALSSignatureDeclaration => [it.name = support.toIDMultiple(#["definition2definition"],type.name)]
		val body = createALSSignatureBody => [
			it.declarations += sig
			it.superset += trace.typeTrace.definedSupertype
		]
		trace.specification.signatureBodies += body
		trace.typeTrace.definition2definition.put(type,sig)
	}
	protected def void transformDeclaration2Definition(TypeDeclaration type, Logic2AlloyLanguageMapperTrace trace) {
		val sig = createALSSignatureDeclaration => [it.name = support.toIDMultiple(#["declaration2definition"],type.name)]
		val body = createALSSignatureBody => [
			it.declarations += sig
			it.superset += trace.typeTrace.definedSupertype
		]
		trace.specification.signatureBodies += body
		trace.typeTrace.declaration2definition.put(type,sig)
	}
	protected def void transformUndefined2Definition(TypeDeclaration type, Logic2AlloyLanguageMapperTrace trace) {
		val sig = createALSSignatureDeclaration => [it.name = support.toIDMultiple(#["undefined2definition"],type.name)]
		val body = createALSSignatureBody => [
			it.declarations += sig
			it.supertype = trace.typeTrace.definedSupertype
		]
		trace.specification.signatureBodies += body
		trace.typeTrace.undefined2definition.put(type,sig)
	}
	protected def void transformNew2Declaration(TypeDeclaration type, Logic2AlloyLanguageMapperTrace trace) {
		val sig = createALSSignatureDeclaration => [it.name = support.toIDMultiple(#["declaredPartOfDeclaration"],type.name)]
		val body = createALSSignatureBody => [
			it.declarations += sig
			it.supertype = trace.typeTrace.declaredSupertype
		]
		trace.specification.signatureBodies += body
		trace.typeTrace.new2declaration.put(type,sig)
	}
	
	/**
	 * The dynamic types cover each concrete types
	 */
	protected def definedConcreteTypesAreFull(Logic2AlloyLanguageMapperTrace trace) {
		trace.specification.factDeclarations += createALSFactDeclaration => [
			it.name = support.toID(#["util","typehierarchy","elementFull"])
				it.term = createALSEquals => [
					it.leftOperand = createALSReference => [it.referred = trace.typeTrace.definedSupertype]
					it.rightOperand = support.unfoldPlus(
						trace.typeTrace.allDefinedTypes.map[type|
							createALSReference=>[referred = type]
						].toList
					)
				]
		]
		
	}
	/**
	 * The dynamic types are disjoint
	 */
	protected def definedConcreteTypesAreDisjoint(Logic2AlloyLanguageMapperTrace trace) {
		val types = trace.getTypeTrace.allDefinedTypes.toList
		if (types.size >= 2) {
			trace.specification.factDeclarations += createALSFactDeclaration => [
				it.name = support.toID(#["util", "typehierarchy", "elementFull"])
				it.term = types.disjointSets
			]
		}
	}
	/**
	 * The dynamic types are subtypes of the types where it is defined, but not subtypes where it is not
	 */
	protected def definedConcreteTypesAreSatisfyingDefinitions(LogicProblem problem, Map<Type,List<Type>> typeToConcreteSubtypes, Logic2AlloyLanguageMapperTrace trace) {
		val constraintOnElements = problem.elements.typeConstraints(typeToConcreteSubtypes)
		for(constraintOnElement : constraintOnElements.entrySet) {
			val element = constraintOnElement.key
			val elementSignature = element.lookup(trace.typeTrace.definedElement2Declaration)
			val constraint = constraintOnElement.value
			
			var ALSTerm negativeConstraints;
			if(constraint.negative.isEmpty) {
				negativeConstraints = null
			} else {
				negativeConstraints = support.unfoldAnd(constraint.negative.map[type|
					createALSNot=> [ elementInDefinedType(elementSignature, type, trace) ]
				].toList)
			}
			
			var ALSTerm positiveTypeConstraints
			if(constraint.positiveCNF.isEmpty) {
				positiveTypeConstraints = null
			} else {
				positiveTypeConstraints = support.unfoldAnd(constraint.positiveCNF.map[ typeConstraintFromDefinition |
					support.unfoldOr(typeConstraintFromDefinition.map[type |
						elementInDefinedType(elementSignature,type,trace)
					].toList,trace)
				])
			}
			
			var ALSTerm typeConstraint
			if(negativeConstraints != null && positiveTypeConstraints == null) {
				typeConstraint = negativeConstraints
			} else if (negativeConstraints == null && positiveTypeConstraints != null) {
				typeConstraint = positiveTypeConstraints
			} else if (negativeConstraints != null && positiveTypeConstraints != null) {
				val and = createALSAnd
				and.leftOperand = positiveTypeConstraints
				and.rightOperand = negativeConstraints
				typeConstraint = and
			} else {
				typeConstraint = null
			}
			
			if(typeConstraint != null) {
				val fact =  createALSFactDeclaration => [
					name = support.toIDMultiple(#["util","typehierarchy","definition"],element.name)
				]
				fact.term = typeConstraint
				trace.specification.factDeclarations +=fact
			}
			// otherwise there is no type constraint on element
		}
	}
	
	private def elementInDefinedType(
		ALSSignatureDeclaration elementSignature,
		Type type,
		Logic2AlloyLanguageMapperTrace trace)
	{
		var ALSSignatureDeclaration signature
		if(type instanceof TypeDeclaration) {
			if(trace.typeTrace.declaration2definition.containsKey(type)) {
				signature = type.lookup(trace.typeTrace.declaration2definition)
			} else if(trace.typeTrace.undefined2definition.containsKey(type)) {
				signature = type.lookup(trace.typeTrace.undefined2definition)
			} else {
				return null
			}
		} else if(type instanceof TypeDefinition) {
			if(trace.typeTrace.definition2definition.containsKey(type)) {
				signature = type.lookup(trace.typeTrace.definition2definition)
			} else {
				return null
			}
		} else throw new IllegalArgumentException('''Unknownt type «type.class.name»''')
		
		val finalSignature = signature
		return createALSSubset => [
			leftOperand = createALSReference => [
				referred = elementSignature
			]
			rightOperand = createALSReference => [
				referred = finalSignature
			]
		]
	}
	
	def private typeToConcreteSubtypes(LogicProblem problem, Logic2AlloyLanguageMapperTrace trace) {
		if(trace.incqueryEngine == null) {
			trace.incqueryEngine = ViatraQueryEngine.on(new EMFScope(problem))
		}
		val matcher = SupertypeStarMatcher.on(trace.incqueryEngine)
		val Map<Type,List<Type>> typeToConcreteSubtypes = new HashMap
		for(supertype : problem.types) {
			typeToConcreteSubtypes.put(
				supertype,
				matcher.getAllValuesOfsubtype(supertype)
					.filter[!it.isIsAbstract].toList)
		}
		return typeToConcreteSubtypes
	}
	
	/**
	 * Gives type constraints in a form of CNF 
	 */
	def private Map<DefinedElement,DynamicTypeConstraints> typeConstraints(List<DefinedElement> elements, Map<Type,List<Type>> typeToConcreteSubtypes) {
		val Map<DefinedElement,DynamicTypeConstraints> constraints = new HashMap
		elements.forEach[constraints.put(it,new DynamicTypeConstraints)]
		
		for(type : typeToConcreteSubtypes.keySet.filter(TypeDefinition)) {
			val subtypes = type.lookup(typeToConcreteSubtypes)
			for(elementInType:type.elements) {
				elementInType.lookup(constraints).addPositiveTypeOptions(subtypes)
			}
			for(elementNotInType:elements.filter[!type.elements.contains(it)]) {
				elementNotInType.lookup(constraints).addNegativeTypes(subtypes)
			}
		}
		
		return constraints
	}
	
	private def ALSTerm disjointSets(List<ALSSignatureDeclaration> signatures) {
		if(signatures.size >= 2){
			val top = createALSEquals => [
				it.leftOperand = signatures.intersectionOfTypes
				it.rightOperand = createALSNone
			]
			if(signatures.size > 2) {
				return createALSAnd => [
					it.leftOperand = top
					it.rightOperand = signatures.subList(1,signatures.size).disjointSets
				]
			} else{
				return top
			}
		} else {
			throw new UnsupportedOperationException()
		}
	}
	
	private def ALSIntersection intersectionOfTypes(List<ALSSignatureDeclaration> signatures) {
		if(signatures.size == 2) {
			return createALSIntersection => [
				leftOperand = createALSReference => [it.referred = signatures.get(0)]
				rightOperand = createALSReference => [it.referred = signatures.get(1)]
			]
		} else if(signatures.size > 2) {
			return createALSIntersection => [
				leftOperand = createALSReference => [it.referred = signatures.get(0)]
				rightOperand = signatures.subList(1,signatures.size).intersectionOfTypes
			]
		} else throw new UnsupportedOperationException()
	}
	
	
	override transformTypeReference(ComplexTypeReference complexTypeReference, Logic2AlloyLanguageMapper mapper, Logic2AlloyLanguageMapperTrace trace) {
		//trace.typeTrace.
	}
}