<commit_before>
p(edit-on-github). "Edit on GitHub":https://github.com/Yakindu/statecharts/edit/master/plugins/org.yakindu.sct.doc.user/src/user-guide/generating_code.textile

h1(#generating-state-machine-code). Generating state machine code

For configuring the code generation process, YAKINDU Statechart Tools uses a textual generator model called *SGen*. It can be created either by using the provided wizard *YAKINDU Statechart Generator Model* or by creating a new text file with the file extension @.sgen@.

To create a generator model with the wizard, proceed as follows:

# Select _File → New → YAKINDU SCT → Code Generator Model_.
# Enter a name and click _Next_.
# Choose the desired generator, i.&nbsp;e. _YAKINDU SCT Java Code Generator_.
# Check the model(s) to generate code from and click _Finish_.

!images/docu_genmodelwizardchooselanguage.jpg(Selecting code generator and models)!

The result is an @.sgen@ file of the following format: 
 
bc(prettyprint).. 
GeneratorModel for [GeneratorId] {
	statechart [StatechartReference] {
		feature [Feature] {
			[ParameterName] = [ParameterValue]
		}
	}
}
 
p. The _[GeneratorId]_ represents the unique ID of the generator. Currently, the following generators are supported out of the box:

# @yakindu::java@ – Generator ID for the Java code generator 
# @yakindu::c@ – Generator ID for the C code generator
# @yakindu::generic@ – Generator ID for custom Java-based code generators  

A single generator model can contain several _StatechartReferences_. These are cross references to statechart models for whom code is to be generated. For each reference, the generator process can be configured with _Feature_ zs. Each feature has one or more parameters. These parameters can be configured with _ParameterName_ @=@ _ParameterValue_.
 
The generator model is executed by a so-called Eclipse builder. Thus, the artifacts are generated automatically if _Project → Build Automatically_ is checked. If you want to execute your Generator Model manually, select _Generate Statechart Artifacts_ from the _Package Explorer_'s context menu.

h2(#configuring-a-generator). Configuring a generator

All generators can be customized by a generator model. This is a textual model in a file, specifying generator features, i. e. the outlet path. The following screenshot shows a sample configuration for the Java code generator.

To get started with the generator model, YAKINDU Statechart Tools includes a wizard that creates a basic configuration file with default values.

!(standard-image)images/docu_sGenEditor.png(SGen generator model with default values)!

p=. SGen generator model with default values

###. FIXME: Explain what a "builder" is!

The generator model is associated with a builder. If _Project → Build Automatically_ is checked, the generator automatically creates its output files for each modification the user makes to the statechart model. The sections below explain the specific customizing features of the generator models.

The following section describes the *Core Features* which are available for all code generators.


==<!-- Start sgen_feature_outlet -->==

h3(#outlet). Outlet

The *Outlet* feature specifies target project and target folder for the generated artifacts. It is a _required_ feature and has the following parameters:

# _targetProject_ (String, required): The project to store the generated artifacts to.
# _targetFolder_ (String, required): The folder to store the generated artifacts to. If a library folder is given, only the dynamic (i. e. model-dependent artifacts) are generated into the target folder, if not all generated artifacts will be generated into it. All artifacts in this folder will be overwritten during re-generation.
# _libraryTargetFolder_ (String, optional): The folder to store the static (i. e. model-independent artifacts) to. In case this is not specified, all artifacts will be generated into the target folder. All artifacts in this folder will be preserved during re-generation.
# _apiTargetFolder_ (String, optional): The folder to store API code, e.g. interfaces or header files. In case this is not specified, all artifacts will be generated into the target folder.


bq.. *Example:*

bc. feature Outlet {
    targetProject = "SampleProject"
    targetFolder = "src-gen"
    libraryTargetFolder = "src"
    apiTargetFolder = "api-gen"
}

==<!-- End sgen_feature_outlet -->==
==<!-- Start sgen_feature_licenseheader -->==

h3(#LicenseHeader). LicenseHeader

The *LicenseHeader* feature specifies the license text to be added as a header to the generated artifacts. It is an *optional* feature and has the following parameter:

# _licenseText_ (String, required): License text to be added as a file header

bq.. *Example:*

bc. feature LicenseHeader {
    licenseText = "Copyright (c) 2016 committers of YAKINDU and others."
}

==<!-- End sgen_feature_licenseheader -->==
==<!-- Start sgen_feature_functioninlining -->==

h3(#FunctionInlining). FunctionInlining

The *FunctionInlining* feature enables the inlining of expressions instead of generating separate functions or methods. This might reduce the readability of the generated code, but increases performance, because less operation calls are necessary. This is an *optional* feature and has the following parameters:

# _inlineReactions_ (Boolean, optional): inlines the expression for reactions
# _inlineEntryActions_ (Boolean, optional): inlines the expression for entry actions
# _inlineExitActions_ (Boolean, optional): inlines the expression for exit actions
# _inlineEnterSequences_ (Boolean, optional): inlines the expression for enter sequences
# _inlineExitSequences_ (Boolean, optional): inlines the expression for exit sequences
# _inlineChoices_ (Boolean, optional): inlines the expression for choices
# _inlineEnterRegion_ (Boolean, optional): inlines the expression for enter regions
# _inlineExitRegion_ (Boolean, optional): inlines the expression for exit regions
# _inlineEntries_ (Boolean, optional): inlines the expression for entries

bq.. *Example:*

bc. feature FunctionInlining {
    inlineChoices = false
    inlineEnterRegion = true
    inlineEntries = true
}

==<!-- End sgen_feature_functioninlining -->==
==<!-- Start sgen_feature_debug -->==

h3(#Debug). Debug

The *Debug* feature dumps the execution model to the target folder as an XMI model. It is an *optional* feature and has the following parameter:

# _dumpSexec_ (Boolean, required): dumps the execution model as XMI model

bq.. *Example:*

bc. feature Debug {
    dumpSexec = true
}

==<!-- End sgen_feature_debug -->==


h2(#running-a-generator). Running a generator

Before you can run a generator, you have to establish a generator model first. This is explained in section "Configuring a generator":#configuring-a-generator and in the sections describing specific generators.

Provided you have created the generator model, proceed as follows:
# In the project explorer view, right-click on the @.sgen@ file containing the generator model. The context menu opens.
# In the context menu, select _Generate Code Artifacts_.
# The generator is executed.

Please note that depending on the generator you are using you don't always need to explicitly run the generator manually as described above. Instead an Eclipse builder will do that for you automatically whenever the associated statechart model is changed. However, if that doesn't work for one or the other reason, you can always execute the generator by hand.

h2(#general-concepts-of-the-state-machine-code). General concepts of the state machine code

h3(#oss_responsibilities-of-generated-code). Responsibilities of generated code

The generated source code supports a basic statechart execution model that can be used to implement different variants. It is important to understand the responsibilities of the generated code, i.&nbsp;e. what it cares about and what it doesn't. The remaining issues are out of scope and must be dealt with in the client code the developer has to provide.

The generated code basically takes care about the following:
* It provides the interfaces to access state machine variables and events.
* It initializes the state machine.
* It implements the execution semantics within a run-to-completion (RTC) step. This is everything that is happening within the _runCycle()_ function.

There are some predefined constraints:
* The implementation is not thread-safe. Therefore the _runCycle()_ method must never be called in parallel by different threads.
* All events for a run-to-completion step will be consumed.

Out of scope are:
* *Scheduling:* The code generator cannot make any general assumptions about scheduling mechanisms and constraints.
* *Timers:* The code generator does not know how the system handles times. If any specific time-dependend behavior is required, the client code has to contribute it.
* *Event handling:* The code generator cannot know and does not prescribe how events are entering the system. Therefore deciding when events will be delivered to the state machine is an outside (client code) responsibility.
* *Concurrency:* The client code has to care about any thread synchronization.
* *Memory management:* The generated state machine code will never allocate any memory. Allocating the memory needed for the statechart structure is a responsibility of the client code.

All these things are out of the generated code's scope, since the code generators coming with YAKINDU Statechart Tools cannot provide tailored solutions without knowing any details about a respective specific environment, like runtime system, libraries, etc.

In order to have a better code generator support for specific usage patterns, you would have to implement corresponding code generator extensions.

h3(#oss_cycle-based-execution). Cycle-based execution

The generated state machine code implements a so-called _cycle-based execution scheme_. Each run cycle consists of two different phases:
# In the first phase, incoming events are collected.
# In the second phase, _runCycle()_ is executed.

This approach allows for explicitly processing several events at the same time as well as for checking combinations of events, e.&nbsp;g. something like @[eventA && eventB]@. This is very useful for systems that are close to hardware and input signals. Basically it is the IPO (input processing output) model.

In other cases an event-driven approach might be more suitable. This can be implemented e.&nbsp;g. by directly calling _runCycle()_ as soon as a certain event occurs, like in:

bc. sc_raiseEventA(handle);
sc_runCycle(handle);

More sophisticated approaches could care about buffering of events, managing an event queue, dealing with priority events, and so on. However, since this is out of the the generated code's scope, it is the client code's responsibility.

h3(#oss_thread-safe-execution). Thread-safe execution

In order to circumvent the missing thread-safety of the _runCycle()_ method, the Java code generator has an option for generating a so-called runnable wrapper, providing event queueing and multi-threading support. For details, see section "&quot;RunnableWrapper&quot;":#oss_runnablewrapper. It is easy to implement this as a general solution for Java, since the programming language provides corresponding standard features that by definition are available everywhere by can simply be used.

C, however, does not have any standardized threading features. Therefore a general solution cannot be given. Specific solutions for specific threading libraries would require the implementation of a suitable code generator extension.

h1(#c-code-generator). C code generator

h2(#c-generator-features). C generator features

The C generator features are the same a the "C&#43;&#43; generator features":#cpp-generator-features.

h2(#specifications-of-c-code). Specification of C code

The explanations below are using the _Traffic Light &#40;C)_ sample state machine to describe the API specifications of the code generated by the YAKINDU C code generator. The image below is showing the statechart. It models a pedestrian crossing with push-button operated traffic lights ("pelican crossing").

!(standard-image)images/docu_TrafficLight.png(The traffic light model)!

p=. The traffic light model

You can find the C sample project _"Traffic Light &#40;C)":https://github.com/Yakindu/examples/tree/master/traffic_light_c_ in the "YAKINDU Statechart Tools examples repository":https://github.com/Yakindu/examples. The C example contains statechart, SGen model, graphical widgets, and some glue code to connect the generated code with the widgets. The graphical widgets are based on Qt.

To execute the C example, run the file _org&#95;yakindu&#95;sct&#95;examples&#95;c&#95;trafficlight&#95;_ as _Local C/C&#43;&#43; application_ from the Eclipse _Run As_ context menu.

h3(#c-generated-code). Generated code files

You will find the generated code in the _src-gen_ folder of the traffic light example.

The C code generator generates three header files. The first one is _sc&#95;types.h_:

bc.. 

#ifndef SC_TYPES_H_
#define SC_TYPES_H_

#ifdef __cplusplus
extern "C"
{
#endif 

#include <stdint.h>
#include <stdbool.h>

#define sc_string		char*
 
typedef bool			sc_boolean;
typedef int_fast16_t	sc_short;
typedef uint_fast16_t	sc_ushort;
typedef int32_t			sc_integer;
typedef uint32_t		sc_uinteger;

typedef double			sc_real;

typedef void*			sc_eventid;

typedef intptr_t		sc_intptr_t;

#ifdef __cplusplus
}
#endif

#ifndef null
	#ifdef __cplusplus
		#define null 0
	#else
		#define null ((void *)0)
	#endif
#endif

#define bool_true true
#define bool_false false

#endif /* SC_TYPES_H_ */

p. The header file contains some basic definitions for C&#43;&#43; compiler compatibility and typedefs to map the YAKINDU statechart types to C types. The next header file is named after the statechart. In case of the traffic light example it is called _TrafficLight.h_:

bc.. 

#ifndef TRAFFICLIGHT_H_
#define TRAFFICLIGHT_H_

#include "../src/sc_types.h"
		
#ifdef __cplusplus
extern "C" { 
#endif 

/*! \file Header of the state machine 'TrafficLight'.
*/

/*! Enumeration of all states */ 
typedef enum
{
	TrafficLight_main_region_on,
	TrafficLight_main_region_on_r1_StreetGreen,
	TrafficLight_main_region_on_r1_PedWaiting,
	TrafficLight_main_region_on_r1_PedWaiting_r1_waitOn,
	TrafficLight_main_region_on_r1_PedWaiting_r1_waitOff,
	TrafficLight_main_region_on_r1_StreetAttention,
	TrafficLight_main_region_on_r1_StreetRed,
	TrafficLight_main_region_on_r1_PedestrianGreen,
	TrafficLight_main_region_on_r1_PedestrianRed,
	TrafficLight_main_region_on_r1_StreetPrepare,
	TrafficLight_main_region_on_r1_Safe,
	TrafficLight_main_region_off,
	TrafficLight_main_region_off_r1_YellowOn,
	TrafficLight_main_region_off_r1_YellowOff,
	TrafficLight_last_state
} TrafficLightStates;

/*! Type definition of the data structure for the TrafficLightIfaceTrafficLight interface scope. */
typedef struct
{
	sc_boolean red;
	sc_boolean yellow;
	sc_boolean green;
} TrafficLightIfaceTrafficLight;

/*! Type definition of the data structure for the TrafficLightIfacePedestrian interface scope. */
typedef struct
{
	sc_boolean request;
	sc_boolean red;
	sc_boolean green;
} TrafficLightIfacePedestrian;

/*! Type definition of the data structure for the TrafficLightIface interface scope. */
typedef struct
{
	sc_boolean pedestrianRequest_raised;
	sc_boolean onOff_raised;
} TrafficLightIface;

/*! Type definition of the data structure for the TrafficLightTimeEvents interface scope. */
typedef struct
{
	sc_boolean trafficLight_main_region_on_r1_PedWaiting_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_PedWaiting_r1_waitOn_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_PedWaiting_r1_waitOff_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_StreetAttention_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_StreetRed_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_PedestrianGreen_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_PedestrianRed_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_StreetPrepare_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_Safe_tev0_raised;
	sc_boolean trafficLight_main_region_off_r1_YellowOn_tev0_raised;
	sc_boolean trafficLight_main_region_off_r1_YellowOff_tev0_raised;
	sc_boolean trafficLight_tev0_raised;
} TrafficLightTimeEvents;


/*! Define dimension of the state configuration vector for orthogonal states. */
#define TRAFFICLIGHT_MAX_ORTHOGONAL_STATES 1

/*! 
 * Type definition of the data structure for the TrafficLight state machine.
 * This data structure has to be allocated by the client code. 
 */
typedef struct
{
	TrafficLightStates stateConfVector[TRAFFICLIGHT_MAX_ORTHOGONAL_STATES];
	sc_ushort stateConfVectorPosition; 
	
	TrafficLightIfaceTrafficLight ifaceTrafficLight;
	TrafficLightIfacePedestrian ifacePedestrian;
	TrafficLightIface iface;
	TrafficLightTimeEvents timeEvents;
} TrafficLight;

/*! Initializes the TrafficLight state machine data structures. Must be called before first usage.*/
extern void trafficLight_init(TrafficLight* handle);

/*! Activates the state machine */
extern void trafficLight_enter(TrafficLight* handle);

/*! Deactivates the state machine */
extern void trafficLight_exit(TrafficLight* handle);

/*! Performs a 'run to completion' step. */
extern void trafficLight_runCycle(TrafficLight* handle);

/*! Raises a time event. */
extern void trafficLight_raiseTimeEvent(const TrafficLight* handle, sc_eventid evid);

/*! Gets the value of the variable 'red' that is defined in the interface scope 'TrafficLight'. */ 
extern sc_boolean trafficLightIfaceTrafficLight_get_red(const TrafficLight* handle);
/*! Sets the value of the variable 'red' that is defined in the interface scope 'TrafficLight'. */ 
extern void trafficLightIfaceTrafficLight_set_red(TrafficLight* handle, sc_boolean value);
/*! Gets the value of the variable 'yellow' that is defined in the interface scope 'TrafficLight'. */ 
extern sc_boolean trafficLightIfaceTrafficLight_get_yellow(const TrafficLight* handle);
/*! Sets the value of the variable 'yellow' that is defined in the interface scope 'TrafficLight'. */ 
extern void trafficLightIfaceTrafficLight_set_yellow(TrafficLight* handle, sc_boolean value);
/*! Gets the value of the variable 'green' that is defined in the interface scope 'TrafficLight'. */ 
extern sc_boolean trafficLightIfaceTrafficLight_get_green(const TrafficLight* handle);
/*! Sets the value of the variable 'green' that is defined in the interface scope 'TrafficLight'. */ 
extern void trafficLightIfaceTrafficLight_set_green(TrafficLight* handle, sc_boolean value);
/*! Gets the value of the variable 'request' that is defined in the interface scope 'Pedestrian'. */ 
extern sc_boolean trafficLightIfacePedestrian_get_request(const TrafficLight* handle);
/*! Sets the value of the variable 'request' that is defined in the interface scope 'Pedestrian'. */ 
extern void trafficLightIfacePedestrian_set_request(TrafficLight* handle, sc_boolean value);
/*! Gets the value of the variable 'red' that is defined in the interface scope 'Pedestrian'. */ 
extern sc_boolean trafficLightIfacePedestrian_get_red(const TrafficLight* handle);
/*! Sets the value of the variable 'red' that is defined in the interface scope 'Pedestrian'. */ 
extern void trafficLightIfacePedestrian_set_red(TrafficLight* handle, sc_boolean value);
/*! Gets the value of the variable 'green' that is defined in the interface scope 'Pedestrian'. */ 
extern sc_boolean trafficLightIfacePedestrian_get_green(const TrafficLight* handle);
/*! Sets the value of the variable 'green' that is defined in the interface scope 'Pedestrian'. */ 
extern void trafficLightIfacePedestrian_set_green(TrafficLight* handle, sc_boolean value);
/*! Raises the in event 'pedestrianRequest' that is defined in the default interface scope. */ 
extern void trafficLightIface_raise_pedestrianRequest(TrafficLight* handle);

/*! Raises the in event 'onOff' that is defined in the default interface scope. */ 
extern void trafficLightIface_raise_onOff(TrafficLight* handle);


/*!
 * Checks whether the state machine is active (until 2.4.1 this method was used for states).
 * A state machine is active if it was entered. It is inactive if it has not been entered at all or if it has been exited.
 */
extern sc_boolean trafficLight_isActive(const TrafficLight* handle);

/*!
 * Checks if all active states are final. 
 * If there are no active states then the state machine is considered being inactive. In this case this method returns false.
 */
extern sc_boolean trafficLight_isFinal(const TrafficLight* handle);

/*! Checks if the specified state is active (until 2.4.1 the used method for states was called isActive()). */
extern sc_boolean trafficLight_isStateActive(const TrafficLight* handle, TrafficLightStates state);

#ifdef __cplusplus
}
#endif 

#endif /* TRAFFICLIGHT_H_ */

p. Within this header file an @enum@ containing the state names is defined as well as data structures for each of the statechart's interfaces. Additionally a structure for the statechart's time events is defined. The interfaces' and time events' data structures are nested into the parent structure @TrafficLight@. The client has to allocate this structure. It is a common parameter of most methods the statechart defines. Below this structure is called the _statechart data structure_.

h4(#c-fundamental-statechart-methods). Fundamental statechart methods

The generated code contains fundamental methods to initialize, enter, and exit a state machine, as well as a method to start a run-to-completion step.

In the header file the method names are made up of the statechart name followed by the name of the respective functionality. For example, the methods of the traffic light example are generated as follows:

bc.. 
/*! Initializes the TrafficLight state machine data structures. Must be called before first usage.*/
extern void trafficLight_init(TrafficLight* handle);

/*! Activates the state machine */
extern void trafficLight_enter(TrafficLight* handle);

/*! Deactivates the state machine */
extern void trafficLight_exit(TrafficLight* handle);

/*! Performs a 'run to completion' step. */
extern void trafficLight_runCycle(TrafficLight* handle);

p. 

<ul><li><p>The @init()@ function is used to initialize the internal objects of the state machine right after its instantiation. Variables are initialized to their respective default values. If the statechart defines initialized variables, these initializations are also done in the @init()@ function.</p></li><li><p>The @enter()@ function must be called to enter the state machine. It brings the state machine to a well-defined state.</p></li><li><p>The @exit()@ function is used to leave a state machine statefully. If for example a history state is used in one of the top regions, the last active state is stored and the state machine is left via @exit()@. Re-entering it via @enter()@ continues to work with the saved state.</p></li><li><p>The @runCycle()@ function is used to trigger a run-to-completion step in which the state machine evaluates arising events and computes possible state changes. Somewhat simplified, a run-to-completion cycle consists of the following steps:</p><ol style="list-style-type:  decimal;"><li><p>Clear list of outgoing events.</p></li><li><p>Check whether events have occurred which are leading to a state change.</p></li><li><p>If a state change has to be done:</p><ol style="list-style-type:  decimal;"><li><p>Make the present state inactive.</p></li><li><p>Execute exit actions of the present state.</p></li><li><p>Save history state, if necessary.</p></li><li><p>Execute transition actions, if any.</p></li><li><p>Execute entry actions of the new state.</p></li><li><p>Make the new state active.</p></li></ol></li><li><p>Clear list of incoming events.</p></li></ol></li></ul>

h4(#accessing-variables-and-events). Accessing variables and events
<commit_msg>Added 'state machine' for SEO<commit_after>
p(edit-on-github). "Edit on GitHub":https://github.com/Yakindu/statecharts/edit/master/plugins/org.yakindu.sct.doc.user/src/user-guide/generating_code.textile

h1(#generating-state-machine-code). Generating state machine code

For configuring the code generation process, YAKINDU Statechart Tools uses a textual generator model called *SGen*. It can be created either by using the provided wizard *YAKINDU Statechart Generator Model* or by creating a new text file with the file extension @.sgen@.

To create a generator model with the wizard, proceed as follows:

# Select _File → New → YAKINDU SCT → Code Generator Model_.
# Enter a name and click _Next_.
# Choose the desired generator, i.&nbsp;e. _YAKINDU SCT Java Code Generator_.
# Check the model(s) to generate code from and click _Finish_.

!images/docu_genmodelwizardchooselanguage.jpg(Selecting code generator and models)!

The result is an @.sgen@ file of the following format: 
 
bc(prettyprint).. 
GeneratorModel for [GeneratorId] {
	statechart [StatechartReference] {
		feature [Feature] {
			[ParameterName] = [ParameterValue]
		}
	}
}
 
p. The _[GeneratorId]_ represents the unique ID of the generator. Currently, the following generators are supported out of the box:

# @yakindu::java@ – Generator ID for the Java code generator 
# @yakindu::c@ – Generator ID for the C code generator
# @yakindu::generic@ – Generator ID for custom Java-based code generators  

A single generator model can contain several _StatechartReferences_. These are cross references to statechart models for whom code is to be generated. For each reference, the generator process can be configured with _Feature_ zs. Each feature has one or more parameters. These parameters can be configured with _ParameterName_ @=@ _ParameterValue_.
 
The generator model is executed by a so-called Eclipse builder. Thus, the artifacts are generated automatically if _Project → Build Automatically_ is checked. If you want to execute your Generator Model manually, select _Generate Statechart Artifacts_ from the _Package Explorer_'s context menu.

h2(#configuring-a-generator). Configuring a generator

All generators can be customized by a generator model. This is a textual model in a file, specifying generator features, i. e. the outlet path. The following screenshot shows a sample configuration for the Java code generator.

To get started with the generator model, YAKINDU Statechart Tools includes a wizard that creates a basic configuration file with default values.

!(standard-image)images/docu_sGenEditor.png(SGen generator model with default values)!

p=. SGen generator model with default values

###. FIXME: Explain what a "builder" is!

The generator model is associated with a builder. If _Project → Build Automatically_ is checked, the generator automatically creates its output files for each modification the user makes to the statechart model. The sections below explain the specific customizing features of the generator models.

The following section describes the *Core Features* which are available for all code generators.


==<!-- Start sgen_feature_outlet -->==

h3(#outlet). Outlet

The *Outlet* feature specifies target project and target folder for the generated artifacts. It is a _required_ feature and has the following parameters:

# _targetProject_ (String, required): The project to store the generated artifacts to.
# _targetFolder_ (String, required): The folder to store the generated artifacts to. If a library folder is given, only the dynamic (i. e. model-dependent artifacts) are generated into the target folder, if not all generated artifacts will be generated into it. All artifacts in this folder will be overwritten during re-generation.
# _libraryTargetFolder_ (String, optional): The folder to store the static (i. e. model-independent artifacts) to. In case this is not specified, all artifacts will be generated into the target folder. All artifacts in this folder will be preserved during re-generation.
# _apiTargetFolder_ (String, optional): The folder to store API code, e.g. interfaces or header files. In case this is not specified, all artifacts will be generated into the target folder.


bq.. *Example:*

bc. feature Outlet {
    targetProject = "SampleProject"
    targetFolder = "src-gen"
    libraryTargetFolder = "src"
    apiTargetFolder = "api-gen"
}

==<!-- End sgen_feature_outlet -->==
==<!-- Start sgen_feature_licenseheader -->==

h3(#LicenseHeader). LicenseHeader

The *LicenseHeader* feature specifies the license text to be added as a header to the generated artifacts. It is an *optional* feature and has the following parameter:

# _licenseText_ (String, required): License text to be added as a file header

bq.. *Example:*

bc. feature LicenseHeader {
    licenseText = "Copyright (c) 2016 committers of YAKINDU and others."
}

==<!-- End sgen_feature_licenseheader -->==
==<!-- Start sgen_feature_functioninlining -->==

h3(#FunctionInlining). FunctionInlining

The *FunctionInlining* feature enables the inlining of expressions instead of generating separate functions or methods. This might reduce the readability of the generated code, but increases performance, because less operation calls are necessary. This is an *optional* feature and has the following parameters:

# _inlineReactions_ (Boolean, optional): inlines the expression for reactions
# _inlineEntryActions_ (Boolean, optional): inlines the expression for entry actions
# _inlineExitActions_ (Boolean, optional): inlines the expression for exit actions
# _inlineEnterSequences_ (Boolean, optional): inlines the expression for enter sequences
# _inlineExitSequences_ (Boolean, optional): inlines the expression for exit sequences
# _inlineChoices_ (Boolean, optional): inlines the expression for choices
# _inlineEnterRegion_ (Boolean, optional): inlines the expression for enter regions
# _inlineExitRegion_ (Boolean, optional): inlines the expression for exit regions
# _inlineEntries_ (Boolean, optional): inlines the expression for entries

bq.. *Example:*

bc. feature FunctionInlining {
    inlineChoices = false
    inlineEnterRegion = true
    inlineEntries = true
}

==<!-- End sgen_feature_functioninlining -->==
==<!-- Start sgen_feature_debug -->==

h3(#Debug). Debug

The *Debug* feature dumps the execution model to the target folder as an XMI model. It is an *optional* feature and has the following parameter:

# _dumpSexec_ (Boolean, required): dumps the execution model as XMI model

bq.. *Example:*

bc. feature Debug {
    dumpSexec = true
}

==<!-- End sgen_feature_debug -->==


h2(#running-a-generator). Running a generator

Before you can run a generator, you have to establish a generator model first. This is explained in section "Configuring a generator":#configuring-a-generator and in the sections describing specific generators.

Provided you have created the generator model, proceed as follows:
# In the project explorer view, right-click on the @.sgen@ file containing the generator model. The context menu opens.
# In the context menu, select _Generate Code Artifacts_.
# The generator is executed.

Please note that depending on the generator you are using you don't always need to explicitly run the generator manually as described above. Instead an Eclipse builder will do that for you automatically whenever the associated statechart model is changed. However, if that doesn't work for one or the other reason, you can always execute the generator by hand.

h2(#general-concepts-of-the-state-machine-code). General concepts of the state machine code

h3(#oss_responsibilities-of-generated-code). Responsibilities of generated code

The generated source code supports a basic statechart execution model that can be used to implement different variants. It is important to understand the responsibilities of the generated code, i.&nbsp;e. what it cares about and what it doesn't. The remaining issues are out of scope and must be dealt with in the client code the developer has to provide.

The generated code basically takes care about the following:
* It provides the interfaces to access state machine variables and events.
* It initializes the state machine.
* It implements the execution semantics within a run-to-completion (RTC) step. This is everything that is happening within the _runCycle()_ function.

There are some predefined constraints:
* The implementation is not thread-safe. Therefore the _runCycle()_ method must never be called in parallel by different threads.
* All events for a run-to-completion step will be consumed.

Out of scope are:
* *Scheduling:* The code generator cannot make any general assumptions about scheduling mechanisms and constraints.
* *Timers:* The code generator does not know how the system handles times. If any specific time-dependend behavior is required, the client code has to contribute it.
* *Event handling:* The code generator cannot know and does not prescribe how events are entering the system. Therefore deciding when events will be delivered to the state machine is an outside (client code) responsibility.
* *Concurrency:* The client code has to care about any thread synchronization.
* *Memory management:* The generated state machine code will never allocate any memory. Allocating the memory needed for the statechart structure is a responsibility of the client code.

All these things are out of the generated code's scope, since the code generators coming with YAKINDU Statechart Tools cannot provide tailored solutions without knowing any details about a respective specific environment, like runtime system, libraries, etc.

In order to have a better code generator support for specific usage patterns, you would have to implement corresponding code generator extensions.

h3(#oss_cycle-based-execution). Cycle-based execution

The generated state machine code implements a so-called _cycle-based execution scheme_. Each run cycle consists of two different phases:
# In the first phase, incoming events are collected.
# In the second phase, _runCycle()_ is executed.

This approach allows for explicitly processing several events at the same time as well as for checking combinations of events, e.&nbsp;g. something like @[eventA && eventB]@. This is very useful for systems that are close to hardware and input signals. Basically it is the IPO (input processing output) model.

In other cases an event-driven approach might be more suitable. This can be implemented e.&nbsp;g. by directly calling _runCycle()_ as soon as a certain event occurs, like in:

bc. sc_raiseEventA(handle);
sc_runCycle(handle);

More sophisticated approaches could care about buffering of events, managing an event queue, dealing with priority events, and so on. However, since this is out of the the generated code's scope, it is the client code's responsibility.

h3(#oss_thread-safe-execution). Thread-safe execution

In order to circumvent the missing thread-safety of the _runCycle()_ method, the Java code generator has an option for generating a so-called runnable wrapper, providing event queueing and multi-threading support. For details, see section "&quot;RunnableWrapper&quot;":#oss_runnablewrapper. It is easy to implement this as a general solution for Java, since the programming language provides corresponding standard features that by definition are available everywhere by can simply be used.

C, however, does not have any standardized threading features. Therefore a general solution cannot be given. Specific solutions for specific threading libraries would require the implementation of a suitable code generator extension.

h1(#c-code-generator). C code generator

h2(#c-generator-features). C generator features

The C generator features are the same a the "C&#43;&#43; generator features":#cpp-generator-features.

h2(#specifications-of-c-code). Specification of C code

The explanations below are using the _Traffic Light &#40;C)_ sample state machine to describe the API specifications of the code generated by the YAKINDU C code generator. The image below is showing the statechart. It models a pedestrian crossing with push-button operated traffic lights ("pelican crossing").

!(standard-image)images/docu_TrafficLight.png(The traffic light model)!

p=. The traffic light model

You can find the C sample project _"Traffic Light &#40;C)":https://github.com/Yakindu/examples/tree/master/traffic_light_c_ in the "YAKINDU Statechart Tools examples repository":https://github.com/Yakindu/examples. The C example contains statechart, SGen model, graphical widgets, and some glue code to connect the generated code with the widgets. The graphical widgets are based on Qt.

To execute the C example, run the file _org&#95;yakindu&#95;sct&#95;examples&#95;c&#95;trafficlight&#95;_ as _Local C/C&#43;&#43; application_ from the Eclipse _Run As_ context menu.

h3(#c-generated-code). Generated code files

You will find the generated code in the _src-gen_ folder of the traffic light example.

The C code generator generates three header files. The first one is _sc&#95;types.h_:

bc.. 

#ifndef SC_TYPES_H_
#define SC_TYPES_H_

#ifdef __cplusplus
extern "C"
{
#endif 

#include <stdint.h>
#include <stdbool.h>

#define sc_string		char*
 
typedef bool			sc_boolean;
typedef int_fast16_t	sc_short;
typedef uint_fast16_t	sc_ushort;
typedef int32_t			sc_integer;
typedef uint32_t		sc_uinteger;

typedef double			sc_real;

typedef void*			sc_eventid;

typedef intptr_t		sc_intptr_t;

#ifdef __cplusplus
}
#endif

#ifndef null
	#ifdef __cplusplus
		#define null 0
	#else
		#define null ((void *)0)
	#endif
#endif

#define bool_true true
#define bool_false false

#endif /* SC_TYPES_H_ */

p. The header file contains some basic definitions for C&#43;&#43; compiler compatibility and typedefs to map the YAKINDU statechart types to C types. The next header file is named after the statechart. In case of the traffic light example it is called _TrafficLight.h_:

bc.. 

#ifndef TRAFFICLIGHT_H_
#define TRAFFICLIGHT_H_

#include "../src/sc_types.h"
		
#ifdef __cplusplus
extern "C" { 
#endif 

/*! \file Header of the state machine 'TrafficLight'.
*/

/*! Enumeration of all states */ 
typedef enum
{
	TrafficLight_main_region_on,
	TrafficLight_main_region_on_r1_StreetGreen,
	TrafficLight_main_region_on_r1_PedWaiting,
	TrafficLight_main_region_on_r1_PedWaiting_r1_waitOn,
	TrafficLight_main_region_on_r1_PedWaiting_r1_waitOff,
	TrafficLight_main_region_on_r1_StreetAttention,
	TrafficLight_main_region_on_r1_StreetRed,
	TrafficLight_main_region_on_r1_PedestrianGreen,
	TrafficLight_main_region_on_r1_PedestrianRed,
	TrafficLight_main_region_on_r1_StreetPrepare,
	TrafficLight_main_region_on_r1_Safe,
	TrafficLight_main_region_off,
	TrafficLight_main_region_off_r1_YellowOn,
	TrafficLight_main_region_off_r1_YellowOff,
	TrafficLight_last_state
} TrafficLightStates;

/*! Type definition of the data structure for the TrafficLightIfaceTrafficLight interface scope. */
typedef struct
{
	sc_boolean red;
	sc_boolean yellow;
	sc_boolean green;
} TrafficLightIfaceTrafficLight;

/*! Type definition of the data structure for the TrafficLightIfacePedestrian interface scope. */
typedef struct
{
	sc_boolean request;
	sc_boolean red;
	sc_boolean green;
} TrafficLightIfacePedestrian;

/*! Type definition of the data structure for the TrafficLightIface interface scope. */
typedef struct
{
	sc_boolean pedestrianRequest_raised;
	sc_boolean onOff_raised;
} TrafficLightIface;

/*! Type definition of the data structure for the TrafficLightTimeEvents interface scope. */
typedef struct
{
	sc_boolean trafficLight_main_region_on_r1_PedWaiting_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_PedWaiting_r1_waitOn_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_PedWaiting_r1_waitOff_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_StreetAttention_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_StreetRed_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_PedestrianGreen_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_PedestrianRed_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_StreetPrepare_tev0_raised;
	sc_boolean trafficLight_main_region_on_r1_Safe_tev0_raised;
	sc_boolean trafficLight_main_region_off_r1_YellowOn_tev0_raised;
	sc_boolean trafficLight_main_region_off_r1_YellowOff_tev0_raised;
	sc_boolean trafficLight_tev0_raised;
} TrafficLightTimeEvents;


/*! Define dimension of the state configuration vector for orthogonal states. */
#define TRAFFICLIGHT_MAX_ORTHOGONAL_STATES 1

/*! 
 * Type definition of the data structure for the TrafficLight state machine.
 * This data structure has to be allocated by the client code. 
 */
typedef struct
{
	TrafficLightStates stateConfVector[TRAFFICLIGHT_MAX_ORTHOGONAL_STATES];
	sc_ushort stateConfVectorPosition; 
	
	TrafficLightIfaceTrafficLight ifaceTrafficLight;
	TrafficLightIfacePedestrian ifacePedestrian;
	TrafficLightIface iface;
	TrafficLightTimeEvents timeEvents;
} TrafficLight;

/*! Initializes the TrafficLight state machine data structures. Must be called before first usage.*/
extern void trafficLight_init(TrafficLight* handle);

/*! Activates the state machine */
extern void trafficLight_enter(TrafficLight* handle);

/*! Deactivates the state machine */
extern void trafficLight_exit(TrafficLight* handle);

/*! Performs a 'run to completion' step. */
extern void trafficLight_runCycle(TrafficLight* handle);

/*! Raises a time event. */
extern void trafficLight_raiseTimeEvent(const TrafficLight* handle, sc_eventid evid);

/*! Gets the value of the variable 'red' that is defined in the interface scope 'TrafficLight'. */ 
extern sc_boolean trafficLightIfaceTrafficLight_get_red(const TrafficLight* handle);
/*! Sets the value of the variable 'red' that is defined in the interface scope 'TrafficLight'. */ 
extern void trafficLightIfaceTrafficLight_set_red(TrafficLight* handle, sc_boolean value);
/*! Gets the value of the variable 'yellow' that is defined in the interface scope 'TrafficLight'. */ 
extern sc_boolean trafficLightIfaceTrafficLight_get_yellow(const TrafficLight* handle);
/*! Sets the value of the variable 'yellow' that is defined in the interface scope 'TrafficLight'. */ 
extern void trafficLightIfaceTrafficLight_set_yellow(TrafficLight* handle, sc_boolean value);
/*! Gets the value of the variable 'green' that is defined in the interface scope 'TrafficLight'. */ 
extern sc_boolean trafficLightIfaceTrafficLight_get_green(const TrafficLight* handle);
/*! Sets the value of the variable 'green' that is defined in the interface scope 'TrafficLight'. */ 
extern void trafficLightIfaceTrafficLight_set_green(TrafficLight* handle, sc_boolean value);
/*! Gets the value of the variable 'request' that is defined in the interface scope 'Pedestrian'. */ 
extern sc_boolean trafficLightIfacePedestrian_get_request(const TrafficLight* handle);
/*! Sets the value of the variable 'request' that is defined in the interface scope 'Pedestrian'. */ 
extern void trafficLightIfacePedestrian_set_request(TrafficLight* handle, sc_boolean value);
/*! Gets the value of the variable 'red' that is defined in the interface scope 'Pedestrian'. */ 
extern sc_boolean trafficLightIfacePedestrian_get_red(const TrafficLight* handle);
/*! Sets the value of the variable 'red' that is defined in the interface scope 'Pedestrian'. */ 
extern void trafficLightIfacePedestrian_set_red(TrafficLight* handle, sc_boolean value);
/*! Gets the value of the variable 'green' that is defined in the interface scope 'Pedestrian'. */ 
extern sc_boolean trafficLightIfacePedestrian_get_green(const TrafficLight* handle);
/*! Sets the value of the variable 'green' that is defined in the interface scope 'Pedestrian'. */ 
extern void trafficLightIfacePedestrian_set_green(TrafficLight* handle, sc_boolean value);
/*! Raises the in event 'pedestrianRequest' that is defined in the default interface scope. */ 
extern void trafficLightIface_raise_pedestrianRequest(TrafficLight* handle);

/*! Raises the in event 'onOff' that is defined in the default interface scope. */ 
extern void trafficLightIface_raise_onOff(TrafficLight* handle);


/*!
 * Checks whether the state machine is active (until 2.4.1 this method was used for states).
 * A state machine is active if it was entered. It is inactive if it has not been entered at all or if it has been exited.
 */
extern sc_boolean trafficLight_isActive(const TrafficLight* handle);

/*!
 * Checks if all active states are final. 
 * If there are no active states then the state machine is considered being inactive. In this case this method returns false.
 */
extern sc_boolean trafficLight_isFinal(const TrafficLight* handle);

/*! Checks if the specified state is active (until 2.4.1 the used method for states was called isActive()). */
extern sc_boolean trafficLight_isStateActive(const TrafficLight* handle, TrafficLightStates state);

#ifdef __cplusplus
}
#endif 

#endif /* TRAFFICLIGHT_H_ */

p. Within this header file an @enum@ containing the state names is defined as well as data structures for each of the statechart's interfaces. Additionally a structure for the statechart's time events is defined. The interfaces' and time events' data structures are nested into the parent structure @TrafficLight@. The client has to allocate this structure. It is a common parameter of most methods the statechart defines. Below this structure is called the _statechart data structure_.

h4(#c-fundamental-statechart-methods). Fundamental statechart methods

The generated code contains fundamental methods to initialize, enter, and exit a state machine, as well as a method to start a run-to-completion step.

In the header file the method names are made up of the state machine name followed by the name of the respective functionality. For example, the methods of the traffic light example are generated as follows:

bc.. 
/*! Initializes the TrafficLight state machine data structures. Must be called before first usage.*/
extern void trafficLight_init(TrafficLight* handle);

/*! Activates the state machine */
extern void trafficLight_enter(TrafficLight* handle);

/*! Deactivates the state machine */
extern void trafficLight_exit(TrafficLight* handle);

/*! Performs a 'run to completion' step. */
extern void trafficLight_runCycle(TrafficLight* handle);

p. 

<ul><li><p>The @init()@ function is used to initialize the internal objects of the state machine right after its instantiation. Variables are initialized to their respective default values. If the statechart defines initialized variables, these initializations are also done in the @init()@ function.</p></li><li><p>The @enter()@ function must be called to enter the state machine. It brings the state machine to a well-defined state.</p></li><li><p>The @exit()@ function is used to leave a state machine statefully. If for example a history state is used in one of the top regions, the last active state is stored and the state machine is left via @exit()@. Re-entering it via @enter()@ continues to work with the saved state.</p></li><li><p>The @runCycle()@ function is used to trigger a run-to-completion step in which the state machine evaluates arising events and computes possible state changes. Somewhat simplified, a run-to-completion cycle consists of the following steps:</p><ol style="list-style-type:  decimal;"><li><p>Clear list of outgoing events.</p></li><li><p>Check whether events have occurred which are leading to a state change.</p></li><li><p>If a state change has to be done:</p><ol style="list-style-type:  decimal;"><li><p>Make the present state inactive.</p></li><li><p>Execute exit actions of the present state.</p></li><li><p>Save history state, if necessary.</p></li><li><p>Execute transition actions, if any.</p></li><li><p>Execute entry actions of the new state.</p></li><li><p>Make the new state active.</p></li></ol></li><li><p>Clear list of incoming events.</p></li></ol></li></ul>

h4(#accessing-variables-and-events). Accessing variables and events

{'fraction_non_alphanumeric': 0.06781707291688349, 'fraction_numerical': 0.004454528423638142, 'mean_word_length': 5.354761904761904, 'pattern_counts': {'":': 12, '<': 147, '<?xml version=': 0, '>': 147, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5404885', 'n_tokens_mistral': 13379, 'n_tokens_neox': 12680, 'n_words': 5675}