Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: c455aa4f2f0ae2f75c26799b20d195837f527e3c (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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
/*******************************************************************************
 * Copyright (c) 2011 protos software gmbh (http://www.protos.de).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 * 
 * CONTRIBUTORS:
 * 		Henrik Rentz-Reichert (initial contribution)
 * 		Thomas Schuetz (changed for C code generator)
 * 
 *******************************************************************************/

package org.eclipse.etrice.generator.c.gen

import com.google.inject.Inject
import com.google.inject.Singleton
import org.eclipse.etrice.core.genmodel.etricegen.Root
import org.eclipse.etrice.core.room.CommunicationType
import org.eclipse.etrice.core.room.Operation
import org.eclipse.etrice.core.room.ProtocolClass
import org.eclipse.etrice.core.room.RoomModel
import org.eclipse.etrice.generator.base.io.IGeneratorFileIO
import org.eclipse.etrice.generator.base.logging.ILogger
import org.eclipse.etrice.generator.base.AbstractGenerator
import org.eclipse.etrice.generator.c.Main
import org.eclipse.etrice.generator.generic.GenericProtocolClassGenerator
import org.eclipse.etrice.generator.generic.ProcedureHelpers
import org.eclipse.etrice.generator.generic.RoomExtensions
import org.eclipse.etrice.generator.generic.TypeHelpers
import org.eclipse.etrice.generator.c.setup.GeneratorOptionsHelper

@Singleton
class ProtocolClassGen extends GenericProtocolClassGenerator {

	@Inject IGeneratorFileIO fileIO
	@Inject extension CExtensions
	@Inject extension RoomExtensions
	@Inject extension ProcedureHelpers
	@Inject extension TypeHelpers
	@Inject protected extension GeneratorOptionsHelper
	@Inject ILogger logger
	
	def doGenerate(Root root) {
		for (pc: root.protocolClasses) {
			val path = pc.generationTargetPath+pc.getPath
			val infopath = pc.generationInfoPath+pc.getPath
			var file = pc.getCHeaderFileName

			// header file
			fileIO.generateFile("generating ProtocolClass header", path, infopath, file, root.generateHeaderFile(pc))
			
			// utils file
			file = pc.getCUtilsFileName
			fileIO.generateFile("generating ProtocolClass utils", path, infopath, file, root.generateUtilsFile(pc))

			// source file
			file = pc.getCSourceFileName
			fileIO.generateFile("generating ProtocolClass source", path, infopath, file, root.generateSourceFile(pc))
		}
	}

	
	def private generateHeaderFile(Root root, ProtocolClass pc) {'''
		/**
		 * @author generated by eTrice
		 *
		 * Header File of ProtocolClass pc.name
		 * 
		 */

		generateIncludeGuardBegin(pc)
		
		#include "etDatatypes.h"
		#include "modelbase/etPort.h"
		
		pc.userCode(1)
		
		/* include all referenced room classes */
		FOR dc : (root.getReferencedProtocolClasses(pc) + root.getReferencedDataClasses(pc) + root.getReferencedEnumClasses(pc)).sortBy[name]
			#include dc.includePath
		ENDFOR
		
		IF pc.commType==CommunicationType::EVENT_DRIVEN
			
			/* message IDs */
			genMessageIDs(pc)
			
			/*--------------------- port structs and methods */
			portClassHeader(pc, false)
			portClassHeader(pc, true)
		ELSEIF pc.commType==CommunicationType::DATA_DRIVEN
			/*--------------------- port structs and methods */
			pc.genDataDrivenPortHeaders
		ELSEIF pc.commType==CommunicationType::SYNCHRONOUS
			#error "synchronoue protocols not implemented yet"
		ENDIF

		IF Main::settings.generateMSCInstrumentation
			/*--------------------- debug helpers */
			
			/* get message string for message id */
			const char* pc.name_getMessageString(int msg_id);
		ENDIF

		pc.userCode(2)
		
		generateIncludeGuardEnd(pc)
		
	'''
	}
	
	def private generateUtilsFile(Root root, ProtocolClass pc) {
		val filename = (pc.eContainer as RoomModel).name.replaceAll("\\.","_")+"_"+pc.name+"_Utils"
	'''
		/**
		 * @author generated by eTrice
		 *
		 * Utils File of ProtocolClass pc.name
		 * 
		 */
		
		generateIncludeGuardBegin(filename)

		IF pc.base!==null
			// include base class utils
			#include pc.base.utilsIncludePath
			
		ENDIF
		#include pc.includePath
		
		/*
		 * access macros for operations and attributes
		*/
		
		pc.generateUtilsFile(false)
		pc.generateUtilsFile(true)
		
		generateIncludeGuardEnd(filename)
		
	'''
	}
	
	def private generateUtilsFile(ProtocolClass pc, boolean conj) {
		val portClass = pc.getPortClass(conj)
		val portClassName = pc.getPortClassName(conj)
	'''
		IF portClass!==null
			/* IF conjconjugateELSEregularENDIF port class */
			
			/* operations */
			FOR op : portClass.operations
				val args = op.argList
				#define op.name(args) portClassName_op.name(selfIF !op.arguments.empty, argsENDIF)
			ENDFOR
			
			/* attributes */
			FOR a : portClass.attributes
				#define a.name (((portClassName_var*)(self->varData))->a.name)
			ENDFOR
		ENDIF
	'''
	}
	
	private def argList(Operation op) {
		'''FOR a : op.arguments SEPARATOR ", "a.nameENDFOR'''
	}
	
	def private generateSourceFile(Root root, ProtocolClass pc) {'''
		/**
		 * @author generated by eTrice
		 *
		 * Source File of ProtocolClass pc.name
		 * 
		 */

		#include "pc.getCHeaderFileName"
		#include "debugging/etMSCLogger.h"
		#include "pc.getCUtilsFileName"

		pc.userCode(3)
		
		/*--------------------- port methods */
		IF pc.commType==CommunicationType::EVENT_DRIVEN
			portClassSource(pc, false)
			portClassSource(pc, true)
			
			IF Main::settings.generateMSCInstrumentation
				/*--------------------- debug helpers */
				generateDebugHelpersImplementation(root, pc)
			ENDIF
		ELSEIF pc.commType==CommunicationType::DATA_DRIVEN
			pc.genDataDrivenPortSources
		ELSEIF pc.commType==CommunicationType::SYNCHRONOUS
			#error "synchronous protocols not implemented yet"
		ENDIF
	'''
	}
	
	def private portClassHeader(ProtocolClass pc, Boolean conj){
		var portClassName = pc.getPortClassName(conj)
		var replPortClassName = pc.getPortClassName(conj, true)
		var messages = if (conj) pc.allIncomingMessages else pc.allOutgoingMessages
		val allPortClasses = pc.getAllPortClasses(conj)
		val allAttributes = allPortClasses.map[p|p.attributes].flatten.toList
		val allOperations = allPortClasses.map[p|p.operations].flatten.toList
		
		'''
		typedef etPort portClassName;
		typedef etReplPort replPortClassName;
		
		IF !(allAttributes.empty)
			/* variable part of PortClass (RAM) */
			typedef struct portClassName_var portClassName_var; 
			struct portClassName_var {
				allAttributes.attributes
			};
			FOR a:allAttributes
				IF a.defaultValueLiteral!==null
					logger.logInfo(portClassName+" "+a.name+": Attribute initialization not supported in C")
				ENDIF
			ENDFOR
		ENDIF
		
		FOR message : messages
			var hasData = message.data!==null
			var typeName = if (hasData) message.data.refType.type.typeName else ""
			var refp = if (hasData && (!(message.data.refType.type.enumerationOrPrimitive)||(message.data.refType.ref))) "*" else ""
			var data = if (hasData) ", "+typeName+refp+" data" else ""
			messageSignature(portClassName, message.name, "", data);
			messageSignature(replPortClassName, message.name, "_broadcast", data);
			messageSignature(replPortClassName, message.name, "", ", int idx"+data);
		ENDFOR
		
		IF !(allOperations.empty)	
			allOperations.operationsDeclaration(portClassName)
		ENDIF
		
		IF pc.handlesReceiveIncludingSuper(conj)
			FOR h:pc.getReceiveHandlersIncludingSuper(conj)
				void portClassName_h.msg.name_receiveHandler(portClassName* self, const etMessage* msg, void * actor, etActorReceiveMessage receiveMessageFunc);
			ENDFOR
		ENDIF
		etInt32 replPortClassName_getReplication(const replPortClassName* self);
		'''
	}


	
	def private genDataDrivenPortHeaders(ProtocolClass pc) {
		var sentMsgs = pc.allIncomingMessages.filter(m|m.data!==null)
		val enumMsgs = sentMsgs.filter(m|m.data.refType.type.isEnumeration)
		val boolMsgs = sentMsgs.filter(m|m.data.refType.type.isBoolean)
		val usesMSC = Main::settings.generateMSCInstrumentation && !(enumMsgs.empty && boolMsgs.empty)
		/*
		 * MSC code is generated for all enumerations and booleans of the messages of this protocol
		 */
		'''
			/* data driven send port (conjugated) */
			typedef struct pc.getPortClassName(true) {
				FOR msg : sentMsgs
					var typeName = msg.data.refType.type.typeName
					var refp = if (msg.data.refType.ref) "*" else ""
					typeNamerefp msg.name;
				ENDFOR
				IF usesMSC
					#ifdef ET_ASYNC_MSC_LOGGER_ACTIVATE
						const char* instName;
						const char** peerNames;
					#endif
				ENDIF
			}
			pc.getPortClassName(true);
			
			/* data driven receive port (regular) */
			typedef struct pc.getPortClassName(false) {
				const pc.getPortClassName(true)* peer;
				IF usesMSC
					#ifdef ET_ASYNC_MSC_LOGGER_ACTIVATE
						const char* instName;
						FOR msg : enumMsgs
							var typeName = msg.data.refType.type.typeName
							var refp = if (msg.data.refType.ref) "*" else ""
							typeNamerefp msg.name;
						ENDFOR
						FOR msg : boolMsgs
							var typeName = msg.data.refType.type.typeName
							var refp = if (msg.data.refType.ref) "*" else ""
							typeNamerefp msg.name;
						ENDFOR
					#endif
				ENDIF
			}
			pc.getPortClassName(false);
			
			FOR message : sentMsgs
				var hasData = message.data!==null
				var typeName = if (hasData) message.data.refType.type.typeName else ""
				var refp = if (hasData && !(message.data.refType.type.enumerationOrPrimitive)) "*" else ""
				var data = if (hasData) ", "+typeName+refp+" data" else ""
				messageSetterSignature(pc.getPortClassName(true), message.name, data);
				messageGetterSignature(pc.getPortClassName(false), message.name, typeName);
				
			ENDFOR
		'''
	}
	
	def private genDataDrivenPortSources(ProtocolClass pc) {
		var messages = pc.allIncomingMessages.filter(m|m.data!==null)
		val enumMsgs = messages.filter(m|m.data.refType.type.isEnumeration)
		val boolMsgs = messages.filter(m|m.data.refType.type.isBoolean)
		val usesMSC = Main::settings.generateMSCInstrumentation && !(enumMsgs.empty && boolMsgs.empty)
		/*
		 * MSC code is generated for all enumerations and all booleans of the messages of this protocol
		 */
	'''
			FOR message : messages
				var typeName =message.data.refType.type.typeName
				var refp = if (!(message.data.refType.type.enumerationOrPrimitive)) "*" else ""
				var data = ", "+typeName+refp+" data"
				messageSetterSignature(pc.getPortClassName(true), message.name, data) {
					IF usesMSC && enumMsgs.exists(m|m==message)
						#ifdef ET_ASYNC_MSC_LOGGER_ACTIVATE
							{
								const char** peerName;
								for (peerName=self->peerNames; *peerName!=NULL; ++peerName) {
									ET_MSC_LOGGER_ASYNC_OUT(self->instName, message.data.refType.type.name_getLiteralName(data), *peerName)
									ET_MSC_LOGGER_ASYNC_IN(self->instName, message.data.refType.type.name_getLiteralName(data), *peerName)
								}
							}
						#endif
					ENDIF
					IF usesMSC && boolMsgs.exists(m|m==message)
						#ifdef ET_ASYNC_MSC_LOGGER_ACTIVATE
							{
								const char** peerName;
								for (peerName=self->peerNames; *peerName!=NULL; ++peerName) {
									ET_MSC_LOGGER_ASYNC_OUT(self->instName, data?"true":"false", *peerName)
									ET_MSC_LOGGER_ASYNC_IN(self->instName, data?"true":"false", *peerName)
								}
							}
						#endif
					ENDIF
					self->message.name = refpdata;
				}
				messageGetterSignature(pc.getPortClassName(false), message.name, typeName) {
					return self->peer->message.name;
				}
				
			ENDFOR
	'''
	}
	
	def private portClassSource(ProtocolClass pc, Boolean conj) {
		val allPortClasses = pc.getAllPortClasses(conj)
		val portClassName = pc.getPortClassName(conj)
		val replPortClassName = pc.getPortClassName(conj, true)
		val messages = if (conj) pc.allIncomingMessages else pc.allOutgoingMessages
		val dir = if (conj) "IN_" else "OUT_"

		'''
			FOR message : messages
				var hasData = message.data!==null
				var typeName = if (hasData) message.data.refType.type.typeName else ""
				var refp = if (hasData && ((message.data.refType.ref))) "*" else ""
				var refpd = if (hasData && (!(message.data.refType.type.enumerationOrPrimitive)||(message.data.refType.ref))) "*" else ""
				var refa = if (hasData && (!(message.data.refType.type.enumerationOrPrimitive))&&(!(message.data.refType.ref))) "" else "&"
				var data = if (hasData) ", "+typeName+refpd+" data__et" else ""
				var dataCall = if (hasData) ", data__et" else ""
				var hdlr = message.getSendHandler(conj)
				
				messageSignature(portClassName, message.name, "", data) {
					IF hdlr !== null
						AbstractGenerator::getInstance().getTranslatedCode(hdlr.detailCode)
					ELSE
						ET_MSC_LOGGER_SYNC_ENTRY("portClassName", "message.name")
							sendMessageCall(hasData, "self", memberInUse(pc.name, dir+message.name), typeName+refp, refa+"data__et")
							IF Main::settings.generateMSCInstrumentation
								ET_MSC_LOGGER_ASYNC_OUT(self->myInstName, "message.name", self->peerInstName)
							ENDIF
						ET_MSC_LOGGER_SYNC_EXIT
					ENDIF
				}
				
				messageSignature(replPortClassName, message.name, "_broadcast", data) {
					IF hdlr !== null
						int i;
						for (i=0; i<((etReplPort*)self)->size; ++i) {
							portClassName_message.name(&((etReplPort*)self)->ports[i].portdataCall);
						}					
					ELSE
						int i;
						ET_MSC_LOGGER_SYNC_ENTRY("replPortClassName", "message.name")
						for (i=0; i<((etReplPort*)self)->size; ++i) {
							sendMessageCall(hasData, "(&((etReplPort*)self)->ports[i].port)", memberInUse(pc.name, dir+message.name), typeName+refp, refa+"data__et")
							IF Main::settings.generateMSCInstrumentation
								ET_MSC_LOGGER_ASYNC_OUT(((etReplPort*)self)->ports[i].port.myInstName, "message.name", ((etReplPort*)self)->ports[i].port.peerInstName)
							ENDIF
						}
						ET_MSC_LOGGER_SYNC_EXIT
					ENDIF
				}
				
				messageSignature(replPortClassName, message.name, "", ", int idx__et"+data) {
					IF hdlr !== null
						portClassName_message.name(&((etReplPort*)self)->ports[idx__et].portdataCall);
					ELSE					
						ET_MSC_LOGGER_SYNC_ENTRY("replPortClassName", "message.name")
						if (0<=idx__et && idx__et<((etReplPort*)self)->size) {
							sendMessageCall(hasData, "(&((etReplPort*)self)->ports[idx__et].port)", memberInUse(pc.name, dir+message.name), typeName+refp, refa+"data__et")
							IF Main::settings.generateMSCInstrumentation
								ET_MSC_LOGGER_ASYNC_OUT(((etReplPort*)self)->ports[idx__et].port.myInstName, "message.name", ((etReplPort*)self)->ports[idx__et].port.peerInstName)
							ENDIF
						}
						ET_MSC_LOGGER_SYNC_EXIT
					ENDIF
				}
				
			ENDFOR
			IF !allPortClasses.empty
				/* begin portClassName specific (including base classes) */
				FOR p : allPortClasses
					p.userCode.userCode
				ENDFOR
				
				FOR p : allPortClasses
					p.operations.operationsImplementation(portClassName)
				ENDFOR
				/* end portClassName specific (including base classes) */
				
			ENDIF
			etInt32 replPortClassName_getReplication(const replPortClassName* self) {
				return ((etReplPort*)self)->size;
			}
			
			IF pc.handlesReceive(conj)
				genReceiveHandlers(pc,conj)
			ENDIF
			
		'''
	}

	def private sendMessageCall(boolean hasData, String selfPtr, String msg, String typeName, String data) {
		if (hasData)
			"etPort_sendMessage("+selfPtr+", "+msg+", sizeof("+typeName+"), "+data+");"
		else
			"etPort_sendMessage("+selfPtr+", "+msg+", 0, NULL);"
	}
	
	def private messageSignature(String className, String messageName, String methodSuffix, String data) {
		"void "+className+"_"+messageName+methodSuffix+"(const "+className+"* self"+data+")"
	}
	
	def private messageSetterSignature(String className, String messageName, String data) {
		"void "+className+"_"+messageName+"_set("+className+"* self"+data+")"
	}
	
	def private messageGetterSignature(String className, String messageName, String type) {
		type+" "+className+"_"+messageName+"_get(const "+className+"* const self)"
	}

// TODO: can this be deleted?
//	def sendMessage(Message m, boolean conj) {'''
//	var dir = if (conj) "IN" else "OUT"
//	var hdlr = m.getSendHandler(conj)
//	messageSignature(m){
//		if (getPeerAddress()!=null)
//				IF m.data==nullgetPeerMsgReceiver().receive(new EventMessage(getPeerAddress(), dir_m.name));
//				ELSEgetPeerMsgReceiver().receive(new EventWithDataMessage(getPeerAddress(), dir_m.name, m.data.nameIF (!m.data.ref).deepCopy()ENDIF));
//			ENDIF
//	}
//	'''
//	}
	
	def private genReceiveHandlers(ProtocolClass pc, Boolean conj){
	var portClassName = pc.getPortClassName(conj)
	
	'''
	/* receiver handlers */
	FOR h:pc.getReceiveHandlers(conj)
		void portClassName_h.msg.name_receiveHandler(portClassName* self, const etMessage* msg, void * actor, etActorReceiveMessage receiveMessageFunc){
			AbstractGenerator::getInstance().getTranslatedCode(h.detailCode)
			/* hand over the message to the actor:      */
			/* (*receiveMessageFunc)(actor, self, msg); */
		}
	ENDFOR
	'''}	

	
	
	def private generateDebugHelpersImplementation(Root root, ProtocolClass pc){'''
		
		TODO: make this optional or different for smaller footprint
		/* message names as strings for debugging (generate MSC) */
		static const char* const pc.name_messageStrings[] = {"MIN", FOR m : pc.getAllOutgoingMessages()"m.name",ENDFORFOR m : pc.getAllIncomingMessages()"m.name", ENDFOR"MAX"};

		const char* pc.name_getMessageString(int msg_id) {
			if (msg_id<pc.name_MSG_MIN || msg_id>pc.name_MSG_MAX+1){
				/* id out of range */
				return "Message ID out of range";
			}
			else{
				return pc.name_messageStrings[msg_id];
			}
		}
		'''
	}
	
}

Back to the top