\section{The Specification and Design of DSLs in Kermeta}
\label{sec:mahsup}

Kermeta is a language workbench designed for specifying and designing DSLs.
For this, it involves different\\meta-languages depending on the concern: abstract syntax (we will also use the term ``metamodel'' to refer to it\footnote{This is one definition in the community. For some researchers, ``metamodel'' sometimes referred to abstract syntax plus static semantics.}), static semantics, behavioral semantics. 

The workbench integrates the OMG standards EMOF and OCL, respectively for specifying the abstract syntax (cf. Subsection \ref{subsec:mof}) and the static semantics (cf. Subsection \ref{subsec:ocl}). 
The choice of EMOF and OCL has been driven by the fact that they are de facto standards. This allows full interoperability with other tools. Indeed, during the years of development of Kermeta, we have reused EMOF models and OCL constraints from many different sources.
The workbench also provides \emph{Kermeta Language} to address the specification of the operational semantics (cf. Subsection \ref{subsec:kermeta}).

The Kermeta Workbench also provides composition operators responsible for mashing-up these different concerns into a standalone execution engine (interpreter or compiler) of the DSL (cf. Subsection \ref{subsec:aspectoriented}).

In this section we illustrate all these features by presenting the implementation of fUML. Then we evaluate the use of the Kermeta workbench from the end user point of view (here, the DSL engineer) on the basis of this case study (cf. Subsection \ref{subsec:eval-user}).

\subsection{Concern \#1: Abstract Syntax Definition}
\label{subsec:mof}

First of all, to build a DSL in Kermeta, one defines its abstract syntax (i.e., the metamodel), which specifies the domain concepts and their relations.
The abstract syntax is expressed in an object-oriented manner, using the OMG meta-language EMOF (Essential Meta Object Facility) \cite{omgmof2core}.
EMOF provides the following language constructs for specifying a DSL metamodel:
package, classes, properties, multiple inheritance and different kinds of associations between classes.
The semantics of these core object-oriented constructs is close to a standard object model that is shared by various languages (\emph{e.g.,} Java, C\#, Eiffel). 
\emph{We chose EMOF for the abstract syntax because it is a \emph{de facto} standard allowing interoperability with other tools}.

Figure \ref{fig:fumlMetamodel} shows the excerpt of the fUML metamodel explained in the previous section, and depicts those classes as a class diagram. 
In our Kermeta-based fUML design, we reuse the abstract syntax standardized by the OMG. In practice, OMG provides the fUML metamodel in terms of EMOF and we automatically translate it into an Ecore-based metamodel (the format supported by the Kermeta workbench).

Since the abstract syntax is expressed as an object-oriented metamodel, a concrete fUML model (equivalent to a DSL progam) is composed of instances of the metamodel classes.

\begin{comment}
\begin{figure*} [hbt]
\center
\includegraphics[width=0.85\textwidth]{fumlMetamodel}
\caption{Excerpt of the EMOF-based fUML Metamodel}
\label{fig:fumlMetamodel}
\end{figure*}
\end{comment}

\begin{figure*}
  \centering
  \tikzumlset{font=\sffamily,fill class=white}
  \scalebox{0.75}{
	\begin{tikzpicture}[x=2.8cm, y=2.5cm]
	  \umlclass[y=0, x=-0.3]{Activity}{
		name : EString
	  }{}
	  \umlclass[y=-1, x=-1.5,type={\,abstract\,}]{ActivityNode}{
		name : EString
	  }{}
	  \umlclass[y=-1, x=1,type={\,abstract\,}]{ActivityEdge}{}{}
	  
	  \umlclass[y=-2, x=-2.5]{ObjectNode}{}{}
	  \umlinherit[geometry=|-|]{ObjectNode}{ActivityNode}
  
	  \umlclass[y=-2, x=-1.5,type={\,abstract\,}]{ControlNode}{}{}
	  \umlinherit[geometry=|-|]{ControlNode}{ActivityNode}
	  
	  \umlclass[y=-2, x=-0.45,type={\,abstract\,}]{ExecutableNode}{}{}
	  \umlinherit[geometry=|-|]{ExecutableNode}{ActivityNode}
	
	  \umlclass[y=-2, x=0.55]{ControlFlow}{}{}
	  \umlinherit[geometry=|-|]{ControlFlow}{ActivityEdge}
	  \umlclass[y=-2, x=1.45]{ObjectFlow}{}{}
	  \umlinherit[geometry=|-|]{ObjectFlow}{ActivityEdge}
	
	  \umlclass[y=-3, x=-3]{InitialNode}{}{}
	  \umlinherit[geometry=|-|]{InitialNode}{ControlNode}
	  \umlclass[y=-3, x=-2]{ForkNode}{}{}
	  \umlinherit[geometry=|-|]{ForkNode}{ControlNode}
	  
	  \umlclass[y=-2.9, x=-0.45,type={\,abstract\,}]{Action}{}{}
	  \umlinherit{Action}{ExecutableNode}
	
	  \umlclass[y=-3.7, x=-2.5]{FinalNode}{}{}
	  \umlinherit[geometry=|-|,arm1=1.2]{FinalNode}{ControlNode}
	  \umlclass[y=-3.7, x=-1.5]{JoinNode}{}{}
	  \umlinherit{JoinNode}{ControlNode}
	
	  \umlclass[y=-3.7, x=-0.45]{CreateObjectAction}{}{}
	  \umlinherit{CreateObjectAction}{Action}
	  
	  \umlunicompo[mult=node\quad 0..*, pos=0.8]{Activity}{ActivityNode}
	  \umlunicompo[arg=0..*\quad edge, pos=0.8]{Activity}{ActivityEdge}
	  \umlCNrelation[
		anchor1=20, mult1=source,arg1=1,pos1=0,align1=left,
		anchor2=160,mult2=outgoing,arg2=0..*,pos2=2.0,align2=right
	  ]{ActivityNode}{-0.3,-0.75}{ActivityEdge}
	  \umlCNrelation[
		anchor1=-20,mult1=1,arg1=target,align1=left,pos1=0,
		anchor2=-160, mult2=0..*,arg2=incoming,pos2=2.0,align2=right
	  ]{ActivityNode}{-0.3,-1.25}{ActivityEdge}
	\end{tikzpicture}
  }
  \caption{Excerpt of the fUML Metamodel}
  \label{fig:fumlMetamodel}
\end{figure*}

\begin{comment}
Figure \ref{fig:abstract-syntax} shows an excerpt of the abstract syntax of a DSL for Petri nets. 
The classes ``PetriNet'', ``Node'' and ``Arc'' and their relations formally express that a Petri net is composed of nodes and arcs. The figure also uses the UML notation (``/'') to express that an association is derived from others (e.g., \texttt{outgoings}) and that it is a hook for a piece of static semantics. Since the abstract syntax is expressed as an object-oriented metamodel, a concrete Petri net is composed of instances of the metamodel classes.
\begin{figure} 
\vspace{-2ex}
\centering\includegraphics[height=3.5cm]{fig/PetriNet.pdf}
\caption{An EMOF-based Abstract Syntax for Petri Nets}
\vspace{-2ex}
\label{fig:abstract-syntax}
\end{figure}
\end{comment}

\subsection{Concern \#2: Static Semantics Definition}
\label{subsec:ocl}

The static semantics of a DSL is the union of the well-formed rules on top of the abstract syntax (as invariants of domain classes) and the axiomatic semantics (as pre- and post conditions on operations of metamodel classes).
The static semantics is used to statically filter incorrect DSL programs before actually running them.
It is also used to check parts of the correctness of a DSL program's execution either at design-time using model-checking or theorem proving, or at run-time using assertions, depending on the execution domain of the DSL. Kermeta uses the OMG Object Constraint Language (OCL) \cite{omgocl2} to express the static semantics, directly woven into the metamodel using the Kermeta aspect keyword. 


Listing \ref{lst:ocl-fuml} shows the previously introduced fUML invariant (specified with the keyword ``inv'') as expressed in the Kermeta workbench using OCL.

\begin{lstlisting}[language=kermeta,
    caption={Weaving the Static Semantics of fUML into the Standard Metamodel},
    label={lst:ocl-fuml}, 
    basicstyle=\small\ttfamily, backgroundcolor=\color{LGrey}, numbers=left, xleftmargin=20pt]
package fuml;
require "fuml.ecore"
aspect class CreateObjectAction {
// The given classifier must be a class.
inv fUML_is_class :
  self.classifier.oclIsKindOf(Class)
}
\end{lstlisting}


\begin{comment}
Listing \ref{lst:WeavingStaticSemantics} shows two static semantic rules for Petri nets as expressed in the Kermeta workbench using OCL.
The two static semantic rules of Listing \ref{lst:WeavingStaticSemantics} are invariants (specified with the keyword ``inv'') and specify the semantics of \emph{pure ordinary Petri nets}.
A pure Petri net contains no transition coming from and going to the same place.
It is expressed in the first rule using OCL by checking that for all transitions there is no place that is source and a destination place at the same time.
The second rule is an invariant on ``Arc'', stating that for a Petri net to be ``N-ordinary'', the weight of the arcs must be less than a constant N (N=3 in Listing \ref{lst:WeavingStaticSemantics}).
Both rules are essential for this DSL, because a number of verification techniques for Petri nets are usable only if those properties hold.
\begin{lstlisting}[language=ocl,
		caption={Two static semantic rules for Petri nets as expressed in the Kermeta workbench using OCL},
		label={lst:WeavingStaticSemantics}, 
                basicstyle=\small\ttfamily, backgroundcolor=\color{LGrey}, numbers=left, xleftmargin=20pt]
context Transition
  // Pure Petri nets contain no self-loops
  inv PurePetriNet : self.incomings->collect(x | x.source)->intersection(self.outgoings->collect(y | y.target))->isEmpty()
    
context Arc
  // N-Ordinary Petri nets have a weight<N (here N=3)
  inv OrdinaryPetriNet : self.weight < 3
\end{lstlisting}
\end{comment}

In the Kermeta workbench, the abstract syntax and the static semantics are conceptually and physically (at the file level) defined in two different modules.
Consequently, it is possible to define different semantic variants for the same domain, i.e. to have a single EMOF metamodel shared by different static semantics, \emph{e.g.,} to cope with language variants.

\subsection{Concern \#3: Behavioral Semantics Definition}
\label{subsec:kermeta}

EMOF does not include concepts for the definition of the behavioral semantics and OCL is a side-effect free language.
To define the behavioral semantics of a DSL, we have created the Kermeta Language, an action language that is used to express the behavioral semantics of a DSL~\cite{models05pam}.
It can be used to define either a translational semantics or an operational semantics~\cite{jsw09}. A translational semantics would result in a compiler while an operational semantics would result in an interpreter. In this paper, for sake of clarity, we will only present operational semantics. However, the language is exactly the same in both cases.

Using the Kermeta language, an operational semantics is expressed as methods of the classes of the abstract syntax~\cite{models05pam}. Listing~\ref{lst:OpSemantics} is an excerpt of the operational semantics of fUML. Using the \texttt{aspect} keyword, a method ``execute'' is added to the metamodel class ``Activity''. The body of the method imperatively describes what is the effect of executing an activity. In this case, it consists of i) creating an activity node activation group and activating all the activity nodes in the activity, and ii) copying the values on the tokens offered by the output parameter nodes to the corresponding output parameter. 

The Kermeta language is imperative, statically typed, and includes classical control structures such as blocks, conditionals, loops and exceptions. The Kermeta language also implements traditional object-oriented mechanisms for handling multiple inheritance and generics.  The Kermeta language provides an execution semantics to all EMOF constructs that must have a semantics at run-time such as containment and associations. First, if a reference is part of a bidirectional association, the assignment operator semantics handles both ends of the association at the same time.
Second, if a reference is part of a containment association, the assignment operator semantics unbinds existing references if any, so that one object is part of another one. Finally, for multiple inheritance, Kermeta borrows the semantics from the Eiffel programming language~\cite{Meyer:1992:EL:129093}.


\begin{lstlisting}[language=kermeta,
caption={In Kermeta, the DSL operational semantics is expressed as methods of metamodel classes},float,
label={lst:OpSemantics}, 
basicstyle=\small\ttfamily, backgroundcolor=\color{LGrey}, numbers=left, xleftmargin=20pt]
aspect class Activity inherits Executable{
// the semantics of executing an activity
method execute(runnable : Runnable) : Void is do					
	// Creation of an activity node activation group
	runnable.execute()
	var group : ActivityNodeActivationGroup init ActivityNodeActivationGroup
				.new()
	group.execution := runnable
	runnable.group := group

	// Activation of all the activity nodes in the activity
	runnable.group.activate(self.node, 
		self.edge)			
	var outputNodeActivations : 
		OrderedSet<ActivityParameterNode> 
		init runnable.group.
	fumlGetOutputParameterNodeActivations()

	// Copy the values on the tokens offered by output parameter nodes to the corresponding output parameters
	outputNodeActivations.each {outputNodeActivation |
		var parameterValue : ParameterValue init ParameterValue.new()
		parameterValue.parameter := (outputNodeActivation.asType(ActivityParameterNode)).parameter
		var tokens : Set<Token> init outputNodeActivation.
					fumlGetTokens()
		tokens.each { token |
			var val : Value init (token.asType(ObjectToken)).val
			if (val != void) then
				parameterValue.values.add(val)
			end
		}			
		runnable.fumlSetParameterValue(parameterValue)
	}
end
}
\end{lstlisting}

\subsection{Composition Operators for the Mashup of Meta-Languages}
\label{subsec:aspectoriented}

As introduced above, mashing-up all DSL concerns in the Kermeta workbench is achieved through two keywords in the Kermeta language: \texttt{aspect} and \texttt{require}.

In Kermeta, all pieces of static and behavioral semantics are encapsulated in metamodel classes.
For instance, in Listing \ref{lst:OpSemantics}, the behavioral semantics  are expressed in the metamodel classes ``Activity''.
The \texttt{aspect} keyword enables DSL engineers to relate the language concerns (abstract syntax, static semantics, behavioral semantics) together.
It allows DSL engineers to reopen a previously created class to add some new pieces of information such as new methods, new properties or new constraints. It is inspired from open-classes \cite{Clifton00multijava:modular} and will be further discussed in Section \ref{sec:thecompilation}.

The keyword \texttt{require} enables the mashup itself. 
A DSL implementation \emph{requires} an abstract syntax, a static semantics and a behavioral semantics.
Listing \ref{lst:fumlmashup} shows how the final fUML mashup looks like in Kermeta.
Three \texttt{require} are used to specify the three concerns.
The require mechanism also provides some flexibility with respect to static and behavioral semantics. For example, several behavioral semantics could be defined in different modules (all on top on the same metamodel) and then chosen depending on particular needs (e.g., simulation, compilation).
It is also convenient to support semantic variants of a given language. For instance, Kermeta can be used to specify several implementations of UML semantics variation points.


\begin{lstlisting}[language=kermeta,
    caption={Mashup of the fUML Concerns},
    label={lst:fumlmashup}, 
    float,basicstyle=\small\ttfamily, backgroundcolor=\color{LGrey}, numbers=left, xleftmargin=20pt]
package fuml;
require "fuml.ecore" // abstract syntax
require "fuml.ocl"  // static semantics
require "fuml.kmt"  // operational semantics
class Main {
  operation Main(): Void is do
    // Execute a fUML model
  end
}
\end{lstlisting}

\begin{comment}
\begin{lstlisting}[language=kermeta,
		caption={Mashup of Meta-languages to Implement DSLs: the \texttt{require} keyword},
		label={lst:petrinetmashup}, 
		basicstyle=\small\ttfamily, backgroundcolor=\color{LGrey}, numbers=left, xleftmargin=10pt]
package petrinet;
require "petrinet.ecore"// abstract syntax
require "petrinet.ocl"  // static semantics
require "petrinet.kmt"  // behavioral semantics
class Main {
  operation Main(): Void is do
    // Execute a Petri net
  end
}
\end{lstlisting}
\end{comment}





\input{eval-end-user}