XML technologies / XSLT / XSLT Cookbook / Code generation / Generating switch code

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

You want to generate switch code routing received messages to their handlers.

Solution

The message repository records which processes receive which messages. Given a process name, you can therefore generate a message switch routing incoming messages to their handlers:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:param name="process" select=" '*' "/>
  <xsl:variable name="message-dir" select=" 'messages' "/>
  <xsl:variable name="directory-sep" select=" '/' "/>
  <xsl:variable name="include-ext" select=" '.h' "/>
  <xsl:template match="MessageRepository">
    <!-- Generiere vorbereitende Maßnahmen in der Quelldatei -->
    <xsl:call-template name="file-start"/>
    <!-- Generiere Include-Anweisungen für die Nachrichten, die dieser Prozess empfängt. -->
    <xsl:apply-templates select="Messages/Message[Receivers/ProcessRef = $process or $process = '*']" mode="includes"/>
    <!-- Generiere vorbereitende Maßnahmen für den Nachrichten-Switch -->
    <xsl:call-template name="switch-start"/>
    <!-- Generiere Switch-Body -->
    <xsl:apply-templates select="Messages/Message[Receivers/ProcessRef = $process or $process = '*']" mode="switch"/>
    <!-- Generiere Switch-Ende -->
    <xsl:call-template name="switch-end"/>
    <!-- Generiere Dateiende -->
    <xsl:call-template name="file-end"/>
  </xsl:template>
  <!-- Generiere eine Include-Anweisung für jede Nachricht -->
  <xsl:template match="Message" mode="includes">
    <xsl:text>#include &lt;</xsl:text>
    <xsl:value-of select="$message-dir"/>
    <xsl:value-of select="$directory-sep"/>
    <xsl:value-of select="Name"/>
    <xsl:value-of select="$include-ext"/>
    <xsl:text>&gt;&#xa;</xsl:text>
  </xsl:template>
  <!-- Generiere Fallunterscheidung für alle Nachrichtentypen -->
  <xsl:template match="Message" mode="switch">case <xsl:value-of select="Name"/>_ID: <xsl:call-template name="case-action"/></xsl:template>
  <!-- Generiere die Aktion des Nachrichtenbehandlers -->
  <xsl:template name="case-action">return <xsl:value-of select="Name"/>(*static_cast&lt;const <xsl:value-of select="DataTypeName"/>*&gt;(msg.getData( ))).process( ) ;</xsl:template>
  <!-- Macht erst einmal nichts. Wird vom Benutzer überschrieben, wenn nötig. -->
  <xsl:template name="file-start"/>
  <xsl:template name="file-end"/>
  <!-- Generiere Anfang der switch-Anweisung -->
  <xsl:template name="switch-start">
    #include &lt;transport/Message.h&gt;
    #include &lt;transport/MESSAGE_IDS.h&gt;
    <xsl:text>&#xa;&#xa;</xsl:text>
    <xsl:call-template name="process-function"/>
    {
      switch (msg.getId( ))
      {
      </xsl:template>
      <xsl:template name="switch-end">
        return false ;
      }
    }
  </xsl:template>
  <!-- Generiere Signatur des nachrichtenverarbeitenden Einstiegspunkts -->
  <xsl:template name="process-function">bool processMessage(const Message&amp; msg)</xsl:template>
</xsl:stylesheet>

Applied to the test repository, this example produces the following switch code:

#include <messages/ADD_STOCK_ORDER.h>
#include <messages/CANCEL_STOCK_ORDER.h>

#include <transport/Message.h>
#include <transport/MESSAGE_IDS.h>

bool processMessage(const Message& msg)

{
  switch (msg.getId( ))
  {

    case ADD_STOCK_ORDER_ID:

      return ADD_STOCK_ORDER(*static_cast<const
      AddStockOrderData*>(msg.getData( ))).process( ) ;

    case CANCEL_STOCK_ORDER_ID:

      return CANCEL_STOCK_ORDER(*static_cast<const
      CancelStockOrderData*>(msg.getData( ))).process( ) ;

    return false ;
  }
}

Discussion

Message-processing applications always have some form of message switching. Its structure varies, but usually it checks a message identifier and routes the message to a handler. The identifier may be an integer, as here, or a string, or a composite type and subtype. The handler may be a simple function or an object instantiated to process the message. Even simple code generators should be modular for reuse across contexts. At one company I worked for, a group built an impressive tool using Perl that generated C++ from an XSD schema. Other groups wanted it, but its developers had considered only their own needs, preventing reuse. Even simple code generators take considerable effort. Make them as general as practical to spare others the pain you experienced.

This solution has variation points controlling the start of the generated file, the start and end of the switch code and the end of the file. This flexibility allows reuse in recipe Generating a pretty printer. It could still be improved: it assumes message switching uses a C statement switch. Some applications may instead use an if-else variant, especially for string message IDs. Others use a lookup table mapping message IDs to function pointers.

Can one generator cover all these options? Perhaps, but it would probably become extremely complex. A better approach is reusable generator components for more complex scenarios. Here is a possible general generator for a C statement switch:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xslt [
  <!-- Wird für die Steuerung der Code-Einrückung benutzt -->
  <!ENTITY INDENT "    ">
  <!ENTITY INDENT2 "&INDENT;&INDENT;">
]>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template name="gen-C-Switch">
    <xsl:param name="variable"/>
    <xsl:param name="cases" select="/.."/>
    <xsl:param name="actions" select="/.."/>
    <xsl:param name="default"/>
    <xsl:param name="baseIndent" select="'&INDENT;'"/>
    <xsl:param name="genBreak" select="true( )"/>
    <xsl:value-of select="$baseIndent"/>
    <xsl:text>switch (</xsl:text>
    <xsl:value-of select="$variable"/>
    <xsl:text>)&#xa;</xsl:text>
    <xsl:value-of select="$baseIndent"/>
    <xsl:text>{&#xa;</xsl:text>
    <xsl:for-each select="$cases">
      <xsl:variable name="pos" select="position( )"/>
      <xsl:value-of select="$baseIndent"/>
      <xsl:text>&INDENT;case </xsl:text>
      <xsl:value-of select="."/>
      <xsl:text>:&#xa;</xsl:text>
      <xsl:call-template name="gen-C-Switch-caseBody">
        <xsl:with-param name="case" select="."/>
        <xsl:with-param name="action" select="$actions[$pos]"/>
        <xsl:with-param name="baseIndent" select="concat('&INDENT2;',$baseIndent)"/>
      </xsl:call-template>
      <xsl:if test="$genBreak">
        <xsl:value-of select="$baseIndent"/>
        <xsl:text>&INDENT2;break;</xsl:text>
      </xsl:if>
      <xsl:text>&#xa;</xsl:text>
    </xsl:for-each>
    <xsl:if test="$default">
      <xsl:value-of select="$baseIndent"/>
      <xsl:text>&INDENT;default:</xsl:text>
      <xsl:text>:&#xa;</xsl:text>
      <xsl:call-template name="gen-C-Switch-default-caseBody">
        <xsl:with-param name="action" select="$default"/>
        <xsl:with-param name="baseIndent" select="concat('&INDENT2;',$baseIndent)"/>
      </xsl:call-template>
      <xsl:text>&#xa;</xsl:text>
    </xsl:if>
    <xsl:value-of select="$baseIndent"/>
    <xsl:text>}&#xa;</xsl:text>
  </xsl:template>
  <!-- Hiermit wird standardmäßig eine leere Anweisung erzeugt. Überschreiben Sie das, um Code für case zu generieren. -->
  <xsl:template name="gen-C-Switch-caseBody">
    <xsl:param name="case"/>
    <xsl:param name="action"/>
    <xsl:param name="baseIndent"/>
    <xsl:value-of select="$baseIndent"/>
    <xsl:text>;</xsl:text>
  </xsl:template>
  <!-- Hiermit wird der Generator für reguläre case-Coderümpfe aufgerufen. Überschreiben Sie das, um etwas Spezielles für den Default-Fall zu machen. -->
  <xsl:template name="gen-C-Switch-default-caseBody">
    <xsl:param name="action"/>
    <xsl:param name="baseIndent"/>
    <xsl:call-template name="gen-C-Switch-caseBody">
      <xsl:with-param name="action" select="$action"/>
      <xsl:with-param name="baseIndent" select="$baseIndent"/>
    </xsl:call-template>
  </xsl:template>
</xsl:stylesheet>

Extending and embedding XSLT shows techniques for generalizing such generators further.

  

 

 

 

back to top