<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AdaCore - The GNAT Pro Company &#187; Devt log &#8211; Gem of the Week</title>
	<atom:link href="http://www2.adacore.com/category/developers-center/gems/feed/" rel="self" type="application/rss+xml" />
	<link>http://www2.adacore.com</link>
	<description>AdaCore technology and news</description>
	<lastBuildDate>Tue, 07 Feb 2012 12:00:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Gem #117: Design Pattern: Overridable Class Attributes in Ada 2012</title>
		<link>http://www2.adacore.com/2012/01/30/gem-117-design-pattern-overridable-class-attributes-in-ada-2012/</link>
		<comments>http://www2.adacore.com/2012/01/30/gem-117-design-pattern-overridable-class-attributes-in-ada-2012/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 13:32:46 +0000</pubDate>
		<dc:creator>Emmanuel Briot, of AdaCore</dc:creator>
				<category><![CDATA[Ada / Ada 2005 / Ada 2012]]></category>
		<category><![CDATA[Development Log]]></category>
		<category><![CDATA[Devt log - Gem of the Week]]></category>

		<guid isPermaLink="false">http://www2.adacore.com/?p=13448</guid>
		<description><![CDATA[<p>In this Gem we consider how to realize the capability of "class attributes" (such as supported
in Python) using Ada.</p>]]></description>
			<content:encoded><![CDATA[<strong>Let&#8217;s get started&#8230;</strong>

<p>Most  object-oriented programming  languages provide  a facility for declaring
variables that are  shared by all objects of a given class. In C++, these are
called &#8220;static members&#8221; (and use  the &#8220;static&#8221; keyword), and similarly Python has the notion
of &#8220;class attributes&#8221;.</p>

<p>Let&#8217;s consider an example where this is useful. For instance, let&#8217;s say we want to
define the notion of a block of text that is generated by expanding a template
(perhaps after we replace some parameters in that template, as can be done with
AWS&#8217;s templates parser, for instance). Once we have computed those parameters,
we might want to generate multiple outputs (for instance HTML and CSV). Only
the template needs to change, not the computation of the parameters.</p>

<p>Typically, such as in Python, the template could  be implemented as a class
attribute of the Text_Block class. We can then create templates that need the
same information but have a different output simply by extending that class:</p>

<pre>
   class Text_Block(object):
       template = &quot;somefile.txt&quot;
       def render (self):
           # ... compute some parameters
           # <b>Then</b> <b>do</b> template expansion
           print &quot;processing %s&quot; % self.__class__.template

   class Html_Block(Text_Block):
       template = &quot;otherfile.html&quot;
</pre>

<p>In this example, we chose to use a class attribute rather than the usual
instance attribute (<code>self.template</code>). This example comes from the
implementation of GnatTracker: in the web server we create a new instance of
Text_Block for every request we have to serve. For this, we use a registry that
maps the URL to the class we need to create. It is thus easier to create a new
instance without specifying the template name as a parameter, which would be
required if the template name was stored in the instance. Another reason (though
not really applicable here) is to save memory, which would be important in cases
where there are thousands of instances of the class.</p>

<p>Of course, the approach proposed in this Gem is not the only way to solve the
basic problem, but it serves as a nice example of one of the new Ada 2012
features.</p>

<p>C++, like Ada, does not provide a way to override a static class member, so it
would use a similar solution as described below.</p>

<p>Since Ada has no notion of an overridable class attribute, we&#8217;ll model
it using a subprogram instead (the only way to get dispatching in Ada). The important
point here is that we want to be able to override the template name in child classes,
so we cannot use a simple constant in the package spec or body.</p>

<pre>
   <b>type</b> Text_Block <b>is</b> <b>tagged</b> <b>null</b> <b>record</b>;
   <b>function</b> Template (Self : Text_Block) <b>return</b> String;
   <b>function</b> Render (Self : Text_Block) <b>return</b> String;

   <b>function</b> Template (Self : Text_Block) <b>return</b> String <b>is</b>
      <b>pragma</b> Unreferenced (Self);
   <b>begin</b>
      <b>return</b> &quot;file_name.txt&quot;;
   <b>end</b> Template;
</pre>

<p>The parameter Self is only used for dispatching (so that children
of Text_Block can override this function). Since we prefer to compile
with &#8220;-gnatwu&#8221; to get a warning on unused entities, we indicate to the
compiler that it is expected that Self is unreferenced.</p>

<p>We could make the function Template inlinable, which might be useful
in a few cases (for instance if called from Render in a nondispatching
call), but in general there will be no benefit because Template will be
a dispatching call, which requires an indirect call and thus
wouldn&#8217;t benefit from inlining.</p>

<p>And that&#8217;s it. We have the Ada equivalent of a Python class member.</p>

<p>But so far there is nothing new here, and this approach is rather heavy to write.
For instance, the body of Render could contain code like:</p>

<pre>
   <b>pragma</b> Ada95;

   <b>function</b> Render (Self : Text_Block) <b>return</b> String <b>is</b>
      T : <b>constant</b> String := Template (Text_Block'Class (Self));
   <b>begin</b>
      ..  prepare the parameters <b>for</b> template expansion
      ..  substitute <b>in</b> the template <b>and</b> <b>return</b> it
   <b>end</b> Render;
</pre>

<p>Fortunately, Ada 2012 provides an easier way to write this, using the new
feature of <i>expression functions</i>. Since Template is a function that returns a
constant, we can declare that directly in the spec, and remove the body
altogether. The spec will thus look like:</p>

<pre>
   <b>pragma</b> Ada_2012;

   <b>type</b> Text_Block <b>is</b> <b>tagged</b> <b>null</b> <b>record</b>;
   <b>function</b> Template (Self : Text_Block) <b>return</b> String
      <b>is</b> (&quot;filename.txt&quot;);
   <b>function</b> Render (Self : Text_Block) <b>return</b> String;
</pre>

<p>This is a much lighter syntax, and much closer to how one would do
it in Python (except we use a function instead of a variable to represent
a class member). A child of Text_Block would override Template using
the same notation:</p>

<pre>
   <b>type</b> Html_Block <b>is</b> <b>new</b> Text_Block <b>with</b> <b>null</b> <b>record</b>;
   <b>overriding</b> <b>function</b> Template (Self : Text_Block) <b>return</b> String
      <b>is</b> (&quot;otherfile.html&quot;);
</pre>

<p>Compared to Python, this is in fact more powerful, because some of the children
could provide a more complex body for Template, so we are not limited to using the
value of a simple variable as in Python. In fact, we can do this in the spec itself,
by using a <i>conditional expression</i> (another new feature of Ada 2012):</p>

<pre>
   <b>pragma</b> Ada_2012;

   <b>type</b> Text_Block <b>is</b> <b>tagged</b> <b>null</b> <b>record</b>;
   <b>function</b> Template (Self : Text_Block) <b>return</b> String
       <b>is</b> (<b>if</b> Self.Blah <b>then</b> &quot;filename.html&quot; <b>else</b> &quot;file2.json&quot;);
   <b>function</b> Render (Self : Text_Block) <b>return</b> String;
</pre>

<p>Finally, we can also make the body of Render slightly more familiar (in terms of
object-oriented notation) using the dotted notation introduced in Ada 2005:</p>

<pre>
   <b>function</b> Render (Self : Text_Block) <b>return</b> String <b>is</b>
      T : <b>constant</b> String := Text_Block'Class (Self).Template;
   <b>begin</b>
      ..  prepare the parameters <b>for</b> template expansion
      ..  substitute <b>in</b> the template <b>and</b> <b>return</b> it
   <b>end</b> Render;
</pre>

<p>Now the call to Template looks closer to how it would appear in those languages
that provide overridable class members. Some will argue that this doesn&#8217;t look like
a function call and thus is less readable, since we don&#8217;t know that we are
calling a function. This is a matter of taste, but at least we have the
choice.</p>

<p>There is one thing we have lost, temporarily, in the declaration of
Template. If we compile with -gnatwu, the compiler will complain that
Self is unreferenced. There is currently no way to add a pragma Unreferenced
within an expression function. This has generated a discussion here
at AdaCore and the issue is not resolved yet. The current two proposals are
either to always omit the unused parameter warning when a function has a single
parameter and it controls dispatching (precisely to facilitate this class member
pattern), or else to use an Ada 2012 aspect for this, as in the following:</p>

<pre>
   <b>function</b> Template (Self : Text_Block) <b>return</b> String
      <b>is</b> (&quot;filename.html&quot;)
   <b>with</b> Unreferenced =&gt; Self;
</pre>

<p>Note also that the use of expression functions in this Gem requires
a very recent version of GNAT: the expression function feature
wasn&#8217;t available in older versions, and the initial implementation had
some limitations.
</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2012/01/30/gem-117-design-pattern-overridable-class-attributes-in-ada-2012/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Gem #116: Ada and C++ Exceptions</title>
		<link>http://www2.adacore.com/2012/01/16/gem-114-ada-and-c-exceptions/</link>
		<comments>http://www2.adacore.com/2012/01/16/gem-114-ada-and-c-exceptions/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 11:42:36 +0000</pubDate>
		<dc:creator>Quentin Ochem, AdaCore</dc:creator>
				<category><![CDATA[Ada / Ada 2005 / Ada 2012]]></category>
		<category><![CDATA[Development Log]]></category>
		<category><![CDATA[Devt log - Gem of the Week]]></category>

		<guid isPermaLink="false">http://www2.adacore.com/?p=13409</guid>
		<description><![CDATA[One of the main issues raised by interfacing Ada and C++ is propagation of exceptions from one environment to the other. In this Gem, we’ll demonstrate how the new exception mechanism implemented in GNAT allows catching Ada exceptions in C++, and vice versa. Note that the following code will work starting with GNAT Pro 7.]]></description>
			<content:encoded><![CDATA[<h3>Let’s get started&#8230;</h3>

<p>So we’ve decided to have some fun and are building an application that combines
Ada and C++. So far, so good. We used the C++ to Ada binding generator to bind
the C++ classes directly to Ada, and extend them. However, there’s something
that needs to be considered carefully –- what would happen if an
exception were thrown/raised by C++ vs. Ada code? Let’s try it out:</p>

<h3>Step 1 &#8212; The C++ code</h3>

<p>We’re going to write some very simple C++ code, just two classes, one inheriting
from the other, and overriding a &#8220;compute&#8221; primitive:</p>

<pre>
<b>class</b> COperation {
  <b>public</b>:
  <b>virtual int</b> compute (<b>int</b> a, <b>int</b> b);
  COperation ();
};

<b>class</b> CDivision : <b>public</b> COperation {
  <b>public</b>:
  <b>virtual int</b> compute (<b>int</b> a, <b>int</b> b);
  CDivision ();
};

<b>int</b> CDivision::compute (<b>int</b> a, <b>int</b> b) {
  <b>if</b> (b == 0) {
    <b>throw new</b> Problem (&quot;Division by 0 in C++!&quot;);
  } <b>else</b> {
    <b>return</b> a / b;
  }
}
</pre>

<p>In the computation of CDivision, we’ll raise a C++ exception if a divide-by-zero
occurs. Let’s add a second subprogram doing a dynamic dispatch:</p>

<pre>
<b>void</b> cpp_main (COperation &amp; op) {
  <b>try</b> {
     cout &lt;&lt; op.compute (1, 0);
  } <b>catch</b> (...) {
    cout &lt;&lt; &quot;Unknown exception caught, rethrowing...&quot; &lt;&lt; &quot;\n&quot;;
    <b>throw</b>;
  }
}
</pre>

<p>This function calls the compute operation, catches the exception to display a message, and
then rethrows it.</p>

<p>We’re now going to bind this to Ada. Assuming all specifications are in a 
file base.hh, a simple call to gcc will do it:</p>

<pre>
g++ -fdump-ada-spec base.hh
</pre>

<h3>Step 2 &#8212; Extending the C++ code in Ada</h3>

<p>There is an implementation of CDivision in C++. After the binding phase, let’s 
implement the same code in Ada:</p>

<pre><b>type</b> Ada_Division <b>is</b> <b>new</b> base_hh.Class_COperation.COperation <b>with</b>
     <b>null</b> <b>record</b>;

<b>function</b> Compute
  (this : <b>access</b> Ada_Division;
   a : int;
   b : int) <b>return</b> int <b>is</b>
<b>begin</b>
   <b>if</b> b = 0 <b>then</b>
      <b>raise</b> Constraint_Error <b>with</b> &quot;Division by 0 in Ada!&quot;;
   <b>end</b> <b>if</b>;
   <b>return</b> a / b;
<b>end</b> Compute;
</pre>

<p>We now have three classes in the application. One root C++ class, one pure C++
child, and one mixed Ada/C++ child. Let’s see how things how things work
from there.</p>

<h3>Step 3 &#8212; Catching a C++ exception in Ada</h3>

<p>C++ exceptions do not have a known name once they reach the Ada world.
They act just as if they were declared in the body of a package, so the only
way to catch them is to use a general exception handler. Consider the following
code:</p>

<pre>
   T_Cpp : <b>aliased</b> base_hh.Class_CDivision.CDivision;
   X : Interfaces.C.Int;
<b>begin</b> 
   X :=  T_Cpp.compute (1, 0);
<b>exception</b>
   <b>when</b> <b>others</b> =&gt;
      Put_Line (&quot;[1] Exception caught...&quot;);
<b>end</b>;

</pre>

<p>This will print &#8220;[1] Exception caught&#8230;&#8221; on the screen.</p>

<h3>Step 4 &#8212; Handling exceptions across languages</h3>

<p>Now let’s be a little bit more ambitious. We’re going to call the cpp_main
function with an object coming from Ada:</p>

<pre>
   T_Ada : <b>aliased</b> Base_Ada.Ada_Division;
<b>begin</b>
   base_hh.cpp_main (T_Ada'<b>Access</b>);
<b>exception</b>
   <b>when</b> Constraint_Error =&gt;
      Put_Line (&quot;[2] Constraint_Error caught...&quot;);
   <b>when</b> <b>others</b> =&gt;
      Put_Line (&quot;[2] Exception caught...&quot;);
<b>end</b>;
</pre>

<p>Now, looking back at the cpp_main implementation, we call compute with (1, 0)
as the arguments. This will trigger an exception from the Ada implementation, 
which is going to be caught first by the C++ code, printing &#8220;Unknown
exception caught, rethrowing&#8230;&#8221; on the screen. The same exception is then
rethrown by the C++ side, ending up back in the Ada code above,
printing &#8220;[2] Constraint_Error caught&#8230;&#8221;.</p>

<p></p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2012/01/16/gem-114-ada-and-c-exceptions/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Gem #115: Lego Mindstorms Ada Environment &#8212; Part 2</title>
		<link>http://www2.adacore.com/2011/12/05/gem-115-lego-mindstorms-ada-environment-part-2/</link>
		<comments>http://www2.adacore.com/2011/12/05/gem-115-lego-mindstorms-ada-environment-part-2/#comments</comments>
		<pubDate>Mon, 05 Dec 2011 14:47:20 +0000</pubDate>
		<dc:creator>Pat Rogers, AdaCore</dc:creator>
				<category><![CDATA[Ada / Ada 2005 / Ada 2012]]></category>
		<category><![CDATA[Development Log]]></category>
		<category><![CDATA[Devt log - Gem of the Week]]></category>

		<guid isPermaLink="false">http://www2.adacore.com/?p=13550</guid>
		<description><![CDATA[This series of Gems explores the GNAT Ada programming environment for the Lego Mindstorms robotics kit. The series examines the high- and low-level interfaces to the hardware, the language subset supported by the underlying run-time library, and how to use the environment effectively.  We’ll examine other topics as well.  This Gem introduces the basic steps of the Mindstorms hardware initialization and shutdown.</p>]]></description>
			<content:encoded><![CDATA[<b>Let’s get started&#8230;</b>

<p>The Mindstorms NXT “brick” contains both a 32-bit ARM processor and an 8-bit AVR processor.  The ARM executes the application code, while the AVR is responsible for the lower-level device functionality, including controlling outputs, gathering sensor inputs, and even shutting down the brick itself.</p>

<p>The two processors coordinate by sending an unending stream of messages to each other. Upon initialization, the AVR begins sending messages containing information such as the current buttons pressed, if any, and the battery status, among other data.  The ARM sends messages back to the AVR, for example to set power levels on outputs for motors or to command an analog-to-digital conversion to take place.  The messages go back and forth continually at a fixed rate.  In other words, they are not event-driven, although their content certainly reflects external events and internally generated commands.  Look in the “drivers” directory for the package body of NXT.AVR if you want to see how these messages are sent and received.  The one task declared in the entire API is located in that package body for that purpose.</p>

<p>The timing constraints on message handling are fixed by the hardware and are very strict.  It is therefore possible for messages to be lost or garbled occasionally.  A checksum is calculated to detect these errors, resulting in the problematic message being discarded.</p>

<p>The Ada API hides all these details behind high-level abstract data types for the sensors and motors, and procedural interfaces for the other lower-level facilities such as the A/D converter and discrete I/O capabilities of the ports.   Nonetheless, application code must be written with some of the above architecture in mind.  Specifically, incoming data are not available until the AVR has been initialized and has sent at least one message to the ARM.  Although the AVR is initialized automatically by the Ada drivers, the application programmer must still await receipt of that message.  For example, the current voltage of the battery is stored in a variable declared in the NXT.AVR package.  The value of that variable is dependent upon arrival of a message from the AVR and is undefined beforehand.  The accessor functions that decode the voltage representation simply process the variable as if the value is already defined. (There are ways to mitigate use of the undefined value, of course, but none are ideal.) Other values, such as the raw button readings, are also stored as variables that are set by the decoded AVR messages.</p>

<p>Therefore, the NXT.AVR package provides a procedure that awaits AVR initialization and initial message receipt.  That procedure is named Await_Data_Available. A call to this procedure should typically be the first thing done by the application.</p>

<p>Another procedure is provided to power down the brick for those applications that are intended to complete (unlike, say, embedded control systems that only stop when external power is removed).  This is procedure Power_Down, also found in the NXT.AVR package declaration. The AVR is responsible for actually shutting down the power, so the procedure injects an appropriate message to the AVR into the message stream.  However, as mentioned, messages can be lost or garbled, so the power-down request can be lost.  As a result, it is best to use an infinite loop that calls Power_Down repeatedly.  In effect, the loop “exits” when the AVR disconnects power to the brick.  For example:</p>

<pre>
   <b>loop</b>
      NXT.AVR.Power_Down;
      <b>delay</b> <b>until</b> Clock + Seconds (1);
   <b>end</b> <b>loop</b>;
</pre>

<p>The absolute delay statement emulates a relative delay (as the Ravenscar subset doesn&#8217;t include relative delays) by calling the Ada.Real_Time.Clock function and adding an interval to it.  The duration of the interval is arbitrary and need not be one second.</p>

<p>Note that the NXT.AVR package also detects the situation in which the Power button on the brick is held down for an interval, and will shut down the brick automatically in response.</p>

<p>In summary, although the API goes to some lengths to hide the gory details of the ARM/AVR interactions, ramifications
of the message-based architecture remain visible.</p>

<p>In the next Gem in this series we will explore the high-level abstract data types representing the sensors and motors.</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2011/12/05/gem-115-lego-mindstorms-ada-environment-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gem #114: Logging with GNATCOLL.Traces</title>
		<link>http://www2.adacore.com/2011/11/22/gem-114-logging-with-gnatcoll-traces/</link>
		<comments>http://www2.adacore.com/2011/11/22/gem-114-logging-with-gnatcoll-traces/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 11:23:32 +0000</pubDate>
		<dc:creator>Emmanuel Briot, AdaCore</dc:creator>
				<category><![CDATA[Ada / Ada 2005 / Ada 2012]]></category>
		<category><![CDATA[Development Log]]></category>
		<category><![CDATA[Devt log - Gem of the Week]]></category>

		<guid isPermaLink="false">http://www2.adacore.com/?p=13451</guid>
		<description><![CDATA[The GNAT Components Collection provides a package with facilities for logging
information to various text files. Extra information can be output for each
log, providing convenient ways to understand the behavior of an application
when a debugger is not available.</p>]]></description>
			<content:encoded><![CDATA[<b>Let&#8217;s get started &#8230;</b>

<p>When we write applications, we often add Put_Line statements to help debug the
initial version of the code. Once that code works, we remove the Put_Line and
move on to some other feature of the code. The problem is that when a bug
occurs again in that part of the code (and especially when this is reported by a
user and you can&#8217;t debug on his machine), the output would still be useful, but
it&#8217;s no longer present in the executable.</p>

<p>The solution, of course, is to output the traces to some &#8220;log&#8221; file, and keep
the traces forever in the code. The log file will eventually become very large
if you have lots of traces, and finding information there might not be so
easy. So, a better solution is to split the traces into various groups, and have
a capability to display only some of the groups, so as to limit the amount of
information to look at.</p>

<p>The GNAT Components Collection includes a package GNATCOLL.Traces that
provides support for this. This package is used in various AdaCore products, in
particular GPS.</p>

<p>The first thing to do is to initialize the module. The traces are configured
via an external file, which by default is called &#8220;.gnatdebug&#8221;, and is searched
for in the current directory.</p>

<pre>
   <b>with</b> GNATCOLL.Traces;   <b>use</b> GNATCOLL.Traces;
   <b>with</b> User;
   <b>procedure</b> Main <b>is</b>
   <b>begin</b>
      Parse_Config_File;   <EM>&#45;&#45;  parses default ./.gnatdebug</EM>
      User.Proc;
   <b>end</b> Main;
</pre>

<p>The simplest way to compile this code is to use a project file. For instance:</p>

<pre>
<b>with</b> &quot;gnatcoll&quot;;
<b>project</b> Default <b>is</b>
    <b>for</b> Main <b>use</b> (&quot;main.adb&quot;);
<b>end</b> Default;

gprbuild -Pdefault.gpr
</pre>

<p>In the rest of the code we can create a stream. All log messages are sent to a
stream, and you are free to create as many as you want. A log message will
always be prefixed by the name of its stream, as a way to organize traces in
the log file. Here is what the Ada code would look like:</p>

<pre>
<b>package</b> User <b>is</b>
   Stream1 : <b>constant</b> Trace_Handle := Create (&quot;Stream1&quot;);

   <b>procedure</b> Proc <b>is</b>
   <b>begin</b>
      Trace (Stream1, &quot;Some trace&quot;);
   <b>end</b> Proc;
<b>end</b> User;
</pre>

<p>If you compile this code and run it, there will in fact be nothing
logged. That&#8217;s because the trace streams are disabled by default. We thus need
to create a configuration file. Its format is very simple. The following
example demonstrates a number of its features:</p>

<pre>
+
&gt; log
TRACE1=yes
TRACE2=no
TRACE3=yes &gt; log2
DEBUG.COLORS=yes
</pre>

<p>The first line (&#8220;+&#8221;) indicates that we would like to activate all the streams
by default. So a file with only that line would already show the output in our
Ada example.</p>

<p>The second line (&#8220;>log&#8221;) indicates where the output of the streams should go by
default. If this isn&#8217;t specified, the output goes to stdout. Otherwise, you can
specify a file name. Advanced usage allow you to define other types of
redirection. For instance, GNATCOLL comes by default with support for
redirecting to syslog on Unix systems. It would be relatively simple to add
support for custom outputs, like a socket, a database, etc.</p>

<p>The next three lines configure specific streams and show how to activate or
disable them. The fifth line, in particular, redirects one of the streams to
another log file.</p>

<p>The last line in the example activates one of the extra features of
GNATCOLL.Traces. Activating &#8220;DEBUG.COLORS&#8221; will output the stream using
different colors for the various information that is output on each line.</p>

<p>Other facilities are available. For instance, if you activate
&#8220;DEBUG.ABSOLUTE_TIME&#8221;, each line in the log file will include the time
of the message. More powerfully, you can activate &#8220;DEBUG.STACK_TRACE&#8221; to get a
stack trace for each message (note that the trace needs to be converted via addr2line).
Another useful one is &#8220;DEBUG.COUNT&#8221;, which will add the number of messages
output so far in total and for the specific stream.</p>

<p>Here is what the log file will look like:</p>

<pre>
[STREAM1] 1/1 Some Trace (09:05:32.323)
[STREAM4] 1/2 Some Other Trace (09:05:33.125)
</pre>

<p>As we have seen in the example, text is output using the Trace function. There
are two versions of it: the one we saw that is used to output a simple
message, and another version that takes an exception occurrence as a parameter
and outputs information about that exception. There is also a procedure called
Assert that will output an error message if a Condition is False. The error
will be displayed in red if the colors were activated, thus making it easy to
locate in the log file.</p>

<p>Preparing the text for a message might be expensive (for instance, if the text
should contain the result of a function call, or requires a lot of string
concatenation). For this, the recommended coding pattern is:</p>

<pre>
   <b>if</b> Active (Stream1) <b>then</b>
      Trace (Stream1, &quot;Function result was &quot; &amp; Func(...));
   <b>end</b> <b>if</b>;
</pre>

<p>The log file might still be hard to read when it gets big. GNATCOLL.Traces
provides a facility for indenting the traces. Here is a full example of code
computing Fibonacci numbers recursively:</p>

<pre>
<b>pragma</b> Ada_05;
<b>with</b> Ada.Text_IO;       <b>use</b> Ada.Text_IO;
<b>with</b> GNATCOLL.Traces;   <b>use</b> GNATCOLL.Traces;

<b>procedure</b> Fibo <b>is</b>
   Me : <b>constant</b> Trace_Handle := Create (&quot;FIBO&quot;);

   <b>function</b> Recurse (Num : Positive) <b>return</b> Positive <b>is</b>
      Result : Integer;
   <b>begin</b>
      <b>if</b> Num = 1 <b>or</b> <b>else</b> Num = 2 <b>then</b>
         <b>return</b> 1;
      <b>end</b> <b>if</b>;

      Increase_Indent (Me, &quot;Computing&quot; &amp; Num'Img);
      Result := Recurse (Num - 1) + Recurse (Num - 2);
      Decrease_Indent (Me, &quot;Done =&gt;&quot; &amp; Result'Img);
      <b>return</b> Result;
   <b>end</b> Recurse;

<b>begin</b>
   Parse_Config_File;
   Put_Line (Recurse (5)'Img);
<b>end</b> Fibo;
</pre>

<p>The code should be compiled with a project file, as shown earlier. The current
directory should also contain a file called &#8220;.gnatdebug&#8221; with a single line
that contains &#8220;+&#8221;. The output on stdout is:</p>

<pre>
[FIBO] 1/1 Computing 5
   [FIBO] 2/2 Computing 4
      [FIBO] 3/3 Computing 3
      [FIBO] 4/4 Done =&gt; 2
   [FIBO] 5/5 Done =&gt; 3
   [FIBO] 6/6 Computing 3
   [FIBO] 7/7 Done =&gt; 2
[FIBO] 8/8 Done =&gt; 5
 5
</pre>

<p>which shows the indentation that is increased for each recursive call.</p>

<p>GNATCOLL.Traces uses object-oriented code. It provides a number of hooks
through which you can add your own extra data each time some line is output to
the log file. For this, you should override the Pre_Decorator or Post_Decorator
primitive operations.
</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2011/11/22/gem-114-logging-with-gnatcoll-traces/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gem #113: Visitor Pattern in Ada</title>
		<link>http://www2.adacore.com/2011/11/07/gem-113-visitor-pattern-in-ada/</link>
		<comments>http://www2.adacore.com/2011/11/07/gem-113-visitor-pattern-in-ada/#comments</comments>
		<pubDate>Mon, 07 Nov 2011 11:01:19 +0000</pubDate>
		<dc:creator>Emmanuel Briot, AdaCore</dc:creator>
				<category><![CDATA[Ada / Ada 2005 / Ada 2012]]></category>
		<category><![CDATA[Development Log]]></category>
		<category><![CDATA[Devt log - Gem of the Week]]></category>

		<guid isPermaLink="false">http://www2.adacore.com/?p=12662</guid>
		<description><![CDATA[The visitor pattern is a design pattern that provides a way to execute specific methods on
an object (the visitor) depending on the type of another object.
Since the exact subprogram called depends on both types of the objects,
this pattern is often called double dispatching.]]></description>
			<content:encoded><![CDATA[<b>Let&#8217;s get started&#8230;</b>

<p>Imagine that you have a UML model and you want to generate
code from it. A convenient approach is to have a &#8220;code generator&#8221;
object, which has a set of subprograms to handle each kind of
UML element (one that generates code
for a class, one that generates code for an operation, etc.).</p>

<p>One way to implement this is by using a big series of <b>if</b> statements,
of the form <b>if</b> Obj <b>in</b> CClass&#8217;Class <b>then</b>,
which is rather inelegant and inefficient.</p>

<p>Another approach is to use discriminated
types. A case statement on the discriminant is then efficient,
and Ada will check that all discriminant values are covered. The problem is
that then you would need to use case statements for all clients of the types
in your application. Here, we prefer to use tagged types, to take advantage
of Ada&#8217;s OOP capabilities, so the case statement cannot be
used.</p>

<p>Let&#8217;s consider a specific example. Again, taking the UML example,
assume we have the following types. These are only very roughly similar to
the actual UML metamodel, but will be sufficient for our purposes. In
practice, these types would be automatically generated from the description
of the UML metamodel.</p>

<pre>
   <b>type</b> NamedElement <b>is</b> <b>tagged</b> <b>private</b>;
   <b>type</b> CClass <b>is</b> <b>new</b> NamedElement <b>with</b> <b>private</b>;
   <b>type</b> PPackage <b>is</b> <b>new</b> NamedElement <b>with</b> <b>private</b>;
</pre>

<p>In addition, a visitor class is declared, which will be overridden by the user
code, for instance, to provide a code generator, a model checker, and so on:</p>

<pre>
   <b>type</b> Visitor <b>is</b> <b>abstract</b> <b>tagged</b> <b>null</b> <b>record</b>;

   <b>procedure</b> Visit_NamedElement
      (Self : <b>in</b> <b>out</b> Visitor; Obj : NamedElement'Class) <b>is</b> <b>null</b>;
   <EM>&#45;&#45;  No parent type, do nothing</EM>

   <b>procedure</b> Visit_CClass (Self : <b>in</b> <b>out</b> Visitor; Obj : CClass'Class) <b>is</b>
   <b>begin</b>
      <EM>&#45;&#45;  In UML, a &quot;Class&quot; inherits from a &quot;NamedElement&quot;.</EM>
      <EM>&#45;&#45;  Concrete implementations of the visitor might want to work at the</EM>
      <EM>&#45;&#45;  &quot;NamedElement&quot; level (so that their code applies to both a Class</EM>
      <EM>&#45;&#45;  and a Package, for instance), rather than duplicate the work for each</EM>
      <EM>&#45;&#45;  child of NamedElement. The default implementation here is to call the</EM>
      <EM>&#45;&#45;  parent type's operation.</EM>
   
      Self.Visit_NamedElement (Obj);
   <b>end</b> Visit_Class;

   <b>procedure</b> Visit_PPackage (Self : <b>in</b> <b>out</b> Visitor; Obj : PPackage'Class) <b>is</b>
   <b>begin</b>
      Self.Visit_NamedElement (Obj);
   <b>end</b> Visit_PPackage;
</pre>

<p>We then need to add one primitive Visit operation to each of the types created from
the UML metamodel:</p>

<pre>
   <b>procedure</b> Visit (Self : NamedElement; V : <b>in</b> <b>out</b> Visitor'Class) <b>is</b>
   <b>begin</b>
      <EM>&#45;&#45;  First dispatching was on &quot;Self&quot; (done by the compiler).</EM>
      <EM>&#45;&#45;  Second dispatching is simulated here by calling the right</EM>
      <EM>&#45;&#45;  primitive operation of V.</EM>

      V.Visit_NamedElement (Self);
   <b>end</b> Visit;

   <b>overriding</b> <b>procedure</b> Visit (Self : CClass; V : <b>in</b> <b>out</b> Visitor'Class) <b>is</b>
   <b>begin</b>
      V.Visit_CClass (Self);
   <b>end</b> Visit;

   <b>overriding</b> <b>procedure</b> Visit (Self : PPackage; V : <b>in</b> <b>out</b> Visitor'Class) <b>is</b>
   <b>begin</b>
      V.Visit_PPackage (Self);
   <b>end</b> Visit;
</pre>

<p>All of the code described above is completely systematic, and as such could
and should be generated automatically as much as possible. The &#8220;Visit&#8221; primitive
operations should never be overridden in user code in the usual case. On the
other hand, the &#8220;Visit_&#8230;&#8221; primitives of the visitor itself should be overridden when
it makes sense. The default implementation is provided just so the user has
the choice at which level do to the overriding.</p>

<p>Now let&#8217;s see what a code generator would look like. We&#8217;ll assume
that we are only interested, initially, in doing code generation for classes.
Other types of elements (such as operations) will call the
default implementation for their visitor (Visit_Operation, for instance),
which then calls the visitor for its parent (Visit_NamedElement) and so on,
until we end up calling a Visit operation with a null body. So nothing happens
for those, and we don&#8217;t need to deal with them explicitly.</p>

<p>The code would be something like the following:</p>

<pre>
   <b>type</b> CodeGen <b>is</b> <b>new</b> Visitor <b>with</b> <b>private</b>;

   <b>overriding</b> <b>procedure</b> Visit_CClass
      (Self : <b>in</b> <b>out</b> Codegen; Obj : CClass'Class) <b>is</b>
   <b>begin</b>
       ...;  <EM>&#45;&#45;  Do some code generation</EM>
   <b>end</b> Visit_CClass;

   <b>procedure</b> Main <b>is</b>
      Gen : CodeGen;
   <b>begin</b>
      <b>for</b> Element <b>in</b> All_Model_Elements <b>loop</b>  <EM>&#45;&#45;  Pseudo code</EM>
          Element.Visit (Gen);   <EM>&#45;&#45;  Double dispatching</EM>
      <b>end</b> <b>loop</b>;
   <b>end</b> Main;
</pre>

<p>If we wanted to do model checking, we would create a type Model_Checker,
derived from Visitor, that overrides some of the Visit_* operations. The
body of Main would not change, except for the type of Gen.</p>

<p>When using this in practice, there are a few issues to resolve. For
instance, the UML types need access to the Visitor type (because it
appears as a parameter in their operations). But a visitor also needs to
see the UML types for the same reason. One possibility is to put all the
types in the same package. Another is to use &#8220;limited with&#8221; to give
visibility on access types, and then pass an access to Visitor&#8217;Class
as a parameter to Visit.</p>

<p>Here is a full example. This example must be compiled
with the &#8220;-gnat05&#8243; switch since it uses Ada 2005 features such as the limited
with clause and prefixed call notation.</p>

<pre>
<b>with</b> UML;         <b>use</b> UML;
<b>with</b> Visitors;    <b>use</b> Visitors;
<b>with</b> Ada.Text_IO; <b>use</b> Ada.Text_IO;

<b>procedure</b> Main <b>is</b>
   <b>type</b> Code_Generator <b>is</b> <b>new</b> Visitor <b>with</b> <b>null</b> <b>record</b>;

   <b>overriding</b> <b>procedure</b> Visit_CClass
      (Self : <b>in</b> <b>out</b> Code_Generator; Obj : <b>in</b> <b>out</b> CClass'Class) <b>is</b>
   <b>begin</b>
      Put_Line (&quot;Visiting CClass&quot;);
   <b>end</b> Visit_CClass;

   Tmp1 : NamedElement;
   Tmp2 : CClass;
   Tmp3 : PPackage;

   Gen  : <b>aliased</b> Code_Generator;

<b>begin</b>
   Tmp1.Visit (Gen'<b>Access</b>);  <EM>&#45;&#45;  No output</EM>
   Tmp2.Visit (Gen'<b>Access</b>);  <EM>&#45;&#45;  Outputs &quot;Visiting CClass&quot;</EM>
   Tmp3.Visit (Gen'<b>Access</b>);  <EM>&#45;&#45;  No output</EM>
<b>end</b> Main;


<b>limited</b> <b>with</b> Visitors;
<b>package</b> UML <b>is</b>
   <b>type</b> NamedElement <b>is</b> <b>tagged</b> <b>null</b> <b>record</b>;
   <b>procedure</b> Visit
      (Self        : <b>in</b> <b>out</b> NamedElement;
       The_Visitor : <b>access</b> Visitors.Visitor'Class);

   <b>type</b> CClass <b>is</b> <b>new</b> NamedElement <b>with</b> <b>null</b> <b>record</b>;
   <b>overriding</b> <b>procedure</b> Visit
      (Self        : <b>in</b> <b>out</b> CClass;
       The_Visitor : <b>access</b> Visitors.Visitor'Class);

   <b>type</b> PPackage <b>is</b> <b>new</b> NamedElement <b>with</b> <b>null</b> <b>record</b>;
   <b>overriding</b> <b>procedure</b> Visit
      (Self        : <b>in</b> <b>out</b> PPackage;
       The_Visitor : <b>access</b> Visitors.Visitor'Class);
<b>end</b> UML;


<b>with</b> Visitors;  <b>use</b> Visitors;
<b>package</b> <b>body</b> UML <b>is</b>

   <b>procedure</b> Visit
      (Self        : <b>in</b> <b>out</b> NamedElement;
       The_Visitor : <b>access</b> Visitors.Visitor'Class) <b>is</b>
   <b>begin</b>
      The_Visitor.Visit_NamedElement (Self);
   <b>end</b> Visit;

   <b>overriding</b> <b>procedure</b> Visit
      (Self        : <b>in</b> <b>out</b> CClass;
       The_Visitor : <b>access</b> Visitors.Visitor'Class) <b>is</b>
   <b>begin</b>
      The_Visitor.Visit_CClass (Self);
   <b>end</b> Visit;

   <b>overriding</b> <b>procedure</b> Visit
      (Self        : <b>in</b> <b>out</b> PPackage;
       The_Visitor : <b>access</b> Visitors.Visitor'Class) <b>is</b>
   <b>begin</b>
      The_Visitor.Visit_PPackage (Self);
   <b>end</b> Visit;

<b>end</b> UML;


<b>with</b> UML;  <b>use</b> UML;

<b>package</b> Visitors <b>is</b>
   <b>type</b> Visitor <b>is</b> <b>abstract</b> <b>tagged</b> <b>null</b> <b>record</b>;

   <b>procedure</b> Visit_NamedElement
      (Self : <b>in</b> <b>out</b> Visitor; Obj : <b>in</b> <b>out</b> NamedElement'Class);
   <b>procedure</b> Visit_CClass
      (Self : <b>in</b> <b>out</b> Visitor; Obj : <b>in</b> <b>out</b> CClass'Class);
   <b>procedure</b> Visit_PPackage
      (Self : <b>in</b> <b>out</b> Visitor; Obj : <b>in</b> <b>out</b> PPackage'Class);

<b>end</b> Visitors;


<b>package</b> <b>body</b> Visitors <b>is</b>

   <b>procedure</b> Visit_NamedElement
      (Self : <b>in</b> <b>out</b> Visitor; Obj : <b>in</b> <b>out</b> NamedElement'Class) <b>is</b>
   <b>begin</b>
      <b>null</b>;
   <b>end</b> Visit_NamedElement;

   <b>procedure</b> Visit_CClass
      (Self : <b>in</b> <b>out</b> Visitor; Obj : <b>in</b> <b>out</b> CClass'Class) <b>is</b>
   <b>begin</b>
      Self.Visit_NamedElement (Obj);
   <b>end</b> Visit_CClass;

   <b>procedure</b> Visit_PPackage
      (Self : <b>in</b> <b>out</b> Visitor; Obj : <b>in</b> <b>out</b> PPackage'Class) <b>is</b>
   <b>begin</b>
      Self.Visit_NamedElement (Obj);
   <b>end</b> Visit_PPackage;

<b>end</b> Visitors;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2011/11/07/gem-113-visitor-pattern-in-ada/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gem #112: Lego Mindstorms Ada Environment &#8212; Part 1</title>
		<link>http://www2.adacore.com/2011/10/17/gem-112-lego-mindstorms-ada-environment-part-1/</link>
		<comments>http://www2.adacore.com/2011/10/17/gem-112-lego-mindstorms-ada-environment-part-1/#comments</comments>
		<pubDate>Mon, 17 Oct 2011 11:00:26 +0000</pubDate>
		<dc:creator>Pat Rogers, AdaCore</dc:creator>
				<category><![CDATA[Ada / Ada 2005 / Ada 2012]]></category>
		<category><![CDATA[Development Log]]></category>
		<category><![CDATA[Devt log - Gem of the Week]]></category>

		<guid isPermaLink="false">http://www2.adacore.com/?p=13060</guid>
		<description><![CDATA[This series of Gems explores the GNAT Ada programming environment for the Lego Mindstorms robotics kit. The series will examine the high- and low-level interfaces to the hardware, the language subset supported by the underlying run-time library, and how to use the environment effectively.  We’ll examine other topics as well.  This first Gem introduces the general issue of the Ada language subset available to programmers and shows how the Ada interfaces address one specific aspect of that subset.]]></description>
			<content:encoded><![CDATA[<b>Let’s get started&#8230;</b>

<p>The Lego Mindstorms processor has limited storage available, certainly not enough for a nontrivial application and a complete run-time library. Therefore, the GNAT tool-chain does not implement the full Ada language for this platform.  A considerable number of language capabilities are still  included, especially the Ravenscar tasking profile, but the entire language is not available.</p> 
<p>For example, full exception semantics are not implemented.  Programmers may raise user-defined and language-defined exceptions, and may handle them locally, but unhandled (and reraised) exceptions do not propagate dynamically up the call chain as they do in full Ada.
Instead, an unhandled exception results in a call to a single global routine referred to as the “last chance handler,” so called because it does not return to the application.  Developers may define application-specific last chance handler replacements for the default implementation.</p>
<p>The default implementation shipped with this compiler simply shuts down the Mindstorms processor.  However, the Ada interfaces define an alternative that displays the file name and line number corresponding to the location of the exception, using the LCD on the Mindstorms “brick.”  The routine also briefly buzzes the speaker to get the user’s attention.  It then goes into an infinite loop so that the user can note the location of the exception. This implementation is declared in the NXT.Last_Chance package, shown below.</p>

<pre>
<b>with</b> System;
<b>package</b> NXT.Last_Chance <b>is</b>

   <b>procedure</b> Last_Chance_Handler
     (Source_Location : System.Address;
      Line            : Integer);
   <b>pragma</b> Export (C, Last_Chance_Handler, &quot;__gnat_last_chance_handler&quot;);

<b>end</b> NXT.Last_Chance;
</pre>

<p>Note the pragma exporting the name as &#8220;__gnat_last_chance_handler&#8221;, the routine name invoked by the run-time library when an unhandled exception is raised.  Applications do not call this routine themselves, since it does not return to the caller and shuts down the system.  Instead, they override the symbol and have the linker include their version of the routine in the executable so that the run-time library can call it if necessary.  In the case of the Mindstorms interfaces, the user specifies the package NXT.Last_Chance in a with-clause, typically in the main program.</p>

<pre>
<b>with</b> NXT.Last_Chance;
...
<b>procedure</b> ...
</pre>

<p>You can see the source for the body of the procedure, indeed the sources for all the interfaces, in the “drivers” directory under your installation root.  By default this would be:</p>

<p>C:\GNAT\2011\lib\mindstorms-nxt\drivers</p>

<p>Although not a very large or complicated procedure, in such a memory-constrained environment every byte may be precious, so you should take the size of the code into account.  The procedure uses the audio interface to buzz the speaker, for example, and the LCD display package is also pulled in.  If you were not otherwise using those packages (and their dependents), this could make a difference.  However, there is no requirement for you to use this version of the last chance handler, so you can simply comment out or remove the with-clause if you don’t want the fancier handler and associated code included.
</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2011/10/17/gem-112-lego-mindstorms-ada-environment-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gem #111: The Distributed Systems Annex, Part 5 &#8212; Embedded Name Server</title>
		<link>http://www2.adacore.com/2011/10/03/gem-111-the-distributed-systems-annex-part-5-embedded-name-server/</link>
		<comments>http://www2.adacore.com/2011/10/03/gem-111-the-distributed-systems-annex-part-5-embedded-name-server/#comments</comments>
		<pubDate>Mon, 03 Oct 2011 11:00:45 +0000</pubDate>
		<dc:creator>Thomas Quinot, AdaCore</dc:creator>
				<category><![CDATA[Ada / Ada 2005 / Ada 2012]]></category>
		<category><![CDATA[Development Log]]></category>
		<category><![CDATA[Devt log - Gem of the Week]]></category>

		<guid isPermaLink="false">http://www2.adacore.com/?p=13155</guid>
		<description><![CDATA[This is the fifth in a series of Gems introducing the
facilities defined by the optional annex for Distributed Systems of the Ada Reference Manual (Annex E).
In the
<a href="/2010/09/14/gem-90-the-distributed-systems-annex-part-4-dsa-and-c/">
previous installment</a>, we showed how to integrate DSA code as a
stand-alone Ada library in a C/C++ application.</p>

<p>In this installment, we show how the DSA name server can be embedded in the
main partition, rather than started as a stand-alone process.</p>]]></description>
			<content:encoded><![CDATA[<p><b>Let&#8217;s get started&#8230;</b></p>

<p>In the first installment in this series of DSA Gems, we used an application
managing a public bulletin board as a good example of a client-server
design. We used the following configuration:</p>

<pre>
<b>configuration</b> Dist_App <b>is</b>
   <b>pragma</b> Starter (None);
   -- User starts each partition manually

   ServerP : Partition := (Bulletin_Board);
   --  RCI package Bulletin_Board is on partition ServerP

   ClientP : Partition := ();
   --  Partition ClientP has no RCI packages

   <b>for</b> ClientP'Termination <b>use</b> Local_Termination;
   --  No global termination

   <b>procedure</b> Display_Messages <b>is</b> <b>in</b> ServerP;
   --  Main subprogram of master partition

   <b>procedure</b> Post_Message;
   <b>for</b> ClientP'Main <b>use</b> Post_Message;
   --  Main subprogram of slave partition
<b>end</b> Dist_App;
</pre>

<p>and we obtained two executables, one for each partition (serverp and clientp),
by issuing the following command:</p>

<p>po_gnatdist dist_app</p>

<p>With the above po_gnatdist configuration, running the application requires
three steps:
<ul>
<li><b>Start po_cos_naming</b>, the PolyORB name server. On startup, an
    object reference is displayed, which must be passed to all partitions
    in the environment variable POLYORB_DSA_NAME_SERVICE or through a PolyORB
    configuration file.
<li><b>Start serverp</b>, the server partition, which will register its RCI
    package (Bulletin_Board) with the name server.
<li><b>Start clientp</b>, the client partition, which will query the name
    server for the location of the RCI.
</ul></p>

<p><b>Simplifying the process</b></p>

<p>To make this whole process easier, you can instead direct po_gnatdist to
embed the name server within the main partition (serverp). This is achieved
by saying:</p>

<pre>
   <b>pragma</b> Name_Server (Embedded);
</pre>

<p>in the configuration file.</p>

<p>You can then start serverp without an external name server: it is now included
within the partition. You still need to convey the location of the name server
to clients. From within the server partition, this information can be
retrieved by querying the PolyORB run-time parameters:</p>

<pre>
   Put_Line ("ServerP started, embedded name server is at:");
   Put_Line (PolyORB.Parameters.Get_Conf ("dsa", "name_service", ""));
</pre>

<p>This outputs a string of the form:</p>

<p>IOR:&lt;&#8230;long series of hex digits&gt;</p>

<p>which encodes all required information. You can then start the client
partition by specifying this value in the POLYORB_DSA_NAME_SERVICE environment
variable. In Bourne shell syntax, this translates to:</p>

<p>POLYORB_DSA_NAME_SERVICE=IOR:&lt;&#8230;&gt; ./clientp</p>

<p>Using the Windows cmd shell, this would be:</p>

<p>set POLYORB_DSA_NAME_SERVICE=IOR:&lt;&#8230;&gt;<br/>
client</p>

<p><b>Passing the name server information in a file</b></p>

<p>POLYORB_DSA_NAME_SERVICE can also indicate a file name, prefixed with the
string &#8220;file:&#8221;. So, if you modify serverp to output the name service
reference to a file &#8220;ns.txt&#8221;, you can start the client using</p>

<p>POLYORB_NAME_SERVICE=file:ns.txt ./clientp</p>

<p><b>Using a well-known port</b></p>

<p><em>Note: this requires the latest development version of PolyORB.</em></p>

<p>It is sometimes inconvenient to have to transport a string value or a
file from the server to the client, and to have to update it each time
the server is restarted. Using appropriate PolyORB run-time configuration
directives, you can force the server to listen for network connections
at a fixed location.</p>

<p>The following configuration forces the server to listen on port 8889:</p>

<pre>[iiop]
polyorb.protocols.iiop.default_port=8889</pre>

<p>Once this is set for the server, you can direct the client to that location
by setting POLYORB_DSA_NAME_SERVICE to:</p>

<p>corbaloc:iiop:1.2@&lt;hostname&gt;:8889/_NameService</p>

<p>The included start_server and start_client scripts provide a demonstration
of this facility.
</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2011/10/03/gem-111-the-distributed-systems-annex-part-5-embedded-name-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gem #110: Ada Plug-ins and Shared Libraries &#8212; Part 2</title>
		<link>http://www2.adacore.com/2011/09/21/gem-110-ada-plug-ins-and-shared-libraries-part-2/</link>
		<comments>http://www2.adacore.com/2011/09/21/gem-110-ada-plug-ins-and-shared-libraries-part-2/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 08:04:07 +0000</pubDate>
		<dc:creator>Pascal Obry of EDF R&#038;D</dc:creator>
				<category><![CDATA[Ada / Ada 2005 / Ada 2012]]></category>
		<category><![CDATA[Development Log]]></category>
		<category><![CDATA[Devt log - Gem of the Week]]></category>

		<guid isPermaLink="false">http://www2.adacore.com/?p=13063</guid>
		<description><![CDATA[In this Gem, we continue the discussion of GNAT's support for shared libraries and explain how to build Ada plug-ins.]]></description>
			<content:encoded><![CDATA[<h3>Let&#8217;s get started&#8230;</h3>

<p>In the first part of this two-part series we saw that stand-alone shared libraries have
the required properties to be used as dynamic plug-ins. In this Gem we
explore how to load and unload code dynamically within an Ada
application. In essence, the dynamically loaded code is compiled into a shared
library, and when this shared library is modified it is reloaded
automatically.</p>

<p>To accomplish this we need three modules:</p>

<ul>
<li>Registry &#8212; A module handles plug-in loading, unloading, and
              service registration</li>

<li>Computer &#8212; A plug-in doing a simple computation using two integers
              and returning the result</li>

<li>Main &#8212; The main application that uses the computer plug-in</li>
</ul>

<h3>Registry</h3>

<p>Each plug-in will inherit from a common type named Any. The
associated access type Ref is used to record all loaded plug-ins
in a hashed map:</p>

<pre>
<b>package</b> Plugins <b>is</b>   
   <b>type</b> Any <b>is</b> <b>abstract</b> <b>tagged</b> <b>null</b> <b>record</b>;
   <b>type</b> Ref <b>is</b> <b>access</b> <b>all</b> Any'Class;
   <EM>&#45;&#45;  A reference to any loaded plug-in</EM>
<b>end</b> Plugins;
</pre>

<p>Our Computer plug-in is described by:</p>

<pre>
<b>package</b> Plugins.Computer <b>is</b>
   
   Service_Name : <b>constant</b> String := &quot;COMPUTER&quot;;
   <EM>&#45;&#45;  Name of the service provided by this plug-in</EM>

   <b>type</b> Handle <b>is</b> <b>abstract</b> <b>new</b> Any <b>with</b> <b>null</b> <b>record</b>;
   <b>type</b> Ref <b>is</b> <b>access</b> <b>all</b> Handle'Class;
   
   <b>function</b> Call
     (H : <b>not</b> <b>null</b> <b>access</b> Handle; A, B : Integer) <b>return</b> Integer <b>is</b> <b>abstract</b>;   

<b>end</b> Plugins.Computer;
</pre>

<p>Note that this is only an abstract view that is shared by all the
modules. This view describes all the routines supported by the
plug-in. A concrete implementation of the computer plug-in will be
given in the computer module.</p>

<p>The Registry spec is:</p>

<pre>
<b>with</b> Plugins;
<b>package</b> Registry <b>is</b>
   
   <b>procedure</b> Discover_Plugins;
   
   <b>procedure</b> Register
     (Service_Name : String; Handle : <b>not</b> <b>null</b> <b>access</b> Plugins.Any'Class);
   
   <b>procedure</b> Unregister (Service_Name : String);
   
   <b>function</b> Get (Service_Name : String) <b>return</b> <b>access</b> Plugins.Any'Class;
   
<b>end</b> Registry;
</pre>

<p>The Register, Unregister, and Get routines are trivial. The
reference to the plug-in service is recorded in a hashed map by
Register, removed by Unregister, and retrieved by Get. This part
does not need further discussion.</p>

<p>The Discover_Plugins routine is the tricky one. Here is how it
works. This routine scans the plug-ins directory for shared libraries
prefixed by &#8220;libplugin_&#8221;. If such a name is found, it is renamed by
removing the &#8220;plugin&#8221; substring and loaded by the dynamic linker (see
Shared_Lib.Load routine in the registry sources of the Gem&#8217;s zip file).
When the shared library is loaded, the
elaboration code is used to register itself (that is, register the
service name associated with the object reference) in the registry.</p>

<p>At this point the service is available and can be used by the main
application.</p>

<p>Note that a map with all loaded shared libraries is kept. If a shared
library is found to be loaded already, it is unloaded first. This
calls the finalization code, which is used by the plug-in to
unregister itself.</p>

<pre>
   <b>procedure</b> Discover_Plugins <b>is</b>
      
      <b>function</b> Plugin_Name (Name : String) <b>return</b> String <b>is</b>
         K : Integer := Strings.Fixed.Index (Name, &quot;plugin_&quot;);
      <b>begin</b>
         <b>return</b> Name (Name'First .. K - 1) &amp; Name (K + 7 .. Name'Last);
      <b>end</b> Plugin_Name;
      
      <b>use</b> Directories;
      <b>use</b> <b>type</b> Calendar.Time;
      
      S          : Search_Type;
      D          : Directory_Entry_Type;
      Only_Files : <b>constant</b> Filter_Type :=
                     (Ordinary_File =&gt; True, <b>others</b> =&gt; False);
      Any_Plugin : <b>constant</b> String :=
                     &quot;libplugin_*.&quot; &amp; Shared_Lib.File_Extension;
   <b>begin</b>
      Start_Search (S, &quot;plugins/&quot;, Any_Plugin, Only_Files);

      <b>while</b> More_Entries (S) <b>loop</b>
         Get_Next_Entry (S, D);
         
         <b>declare</b>
            P     : Shared_Lib.Handle;
            Name  : <b>constant</b> String := Simple_Name (D);
            Fname : <b>constant</b> String := Full_Name (D);
            Pname : <b>constant</b> String := Plugin_Name (Fname);
         <b>begin</b>
            <EM>&#45;&#45;  Proceed if plug-in file is older than 5 seconds (we do not want to try</EM>
            <EM>&#45;&#45;  loading a plug-in not yet fully compiled/linked).</EM>

            <b>if</b> Modification_Time (D) &lt; Calendar.Clock - 5.0 <b>then</b>
               Text_IO.Put_Line (&quot;Plug-in &quot; &amp; Name);

               <b>if</b> Loaded_Plugins.Contains (Pname) <b>then</b>
                  Text_IO.Put_Line (&quot;... already loaded, unload now&quot;);
                  P := Loaded_Plugins.Element (Pname);
                  Shared_Lib.Unload (P);
               <b>end</b> <b>if</b>;

               <EM>&#45;&#45;  Rename plug-in (first removing any existing plug-in)</EM>

               <b>if</b> Exists (Pname) <b>then</b>
                  Delete_File (Pname);
               <b>end</b> <b>if</b>;

               Rename (Fname, Pname);

               <EM>&#45;&#45;  Load it</EM>

               P := Shared_Lib.Load (Pname);
               Loaded_Plugins.Include (Pname, P);
            <b>end</b> <b>if</b>;
         <b>end</b>;
      <b>end</b> <b>loop</b>;
   <b>end</b> Discover_Plugins;
</pre>

<p>The Shared_Lib spec comes with two bodies, one for Windows and one for
GNU/Linux. The proper body is selected automatically.</p>

<p>Note that the renaming of the plug-in is required on Windows, as it is
not possible to write to a shared library which is in use.</p>

<h3>Computer</h3>

<p>Here is the specification of the Computer module that is an implementation of the abstract
type described above:</p>

<pre>
<b>with</b> Plugins.Computer;
<b>package</b> Computer <b>is</b>

   <b>type</b> Handle <b>is</b> <b>new</b> Plugins.Computer.Handle <b>with</b> <b>null</b> <b>record</b>;

   <b>overriding</b> <b>function</b> Call 
     (H : <b>not</b> <b>null</b> <b>access</b> Handle; A, B : Integer) <b>return</b> Integer;

<b>end</b> Computer;
</pre>

<p>The body is straightforward. The Life_Controller is used to control
the Computer object&#8217;s life. The Initialize procedure (called when the
plug-in is loaded) registers the service name and the Finalize
procedure (called when the plug-in is unloaded) unregisters the service
name.
 </p>

<pre>
<b>with</b> Ada.Finalization;
<b>with</b> Registry;
<b>package</b> <b>body</b> Computer <b>is</b>
   
   <b>use</b> Ada;
   
   <b>type</b> Life_Controller <b>is</b> <b>new</b> Finalization.Limited_Controlled <b>with</b> <b>null</b> <b>record</b>;
   <b>overriding</b> <b>procedure</b> Initialize (LC : <b>in</b> <b>out</b> Life_Controller);
   <b>overriding</b> <b>procedure</b> Finalize (LC : <b>in</b> <b>out</b> Life_Controller);
   
   H : <b>aliased</b> Handle;
   
   <b>overriding</b> <b>function</b> Call 
     (H : <b>not</b> <b>null</b> <b>access</b> Handle; A, B : Integer) <b>return</b> Integer <b>is</b>
   <b>begin</b>
      <b>return</b> A + B;
   <b>end</b> Call;
   
   <b>overriding</b> <b>procedure</b> Finalize (LC : <b>in</b> <b>out</b> Life_Controller) <b>is</b>
   <b>begin</b>
      Registry.Unregister (Plugins.Computer.Service_Name);
   <b>end</b> Finalize;
   
   <b>overriding</b> <b>procedure</b> Initialize (LC : <b>in</b> <b>out</b> Life_Controller) <b>is</b>
   <b>begin</b>
      Registry.Register (Plugins.Computer.Service_Name, H'<b>Access</b>);
   <b>end</b> Initialize;

   LC : Life_Controller;
   
<b>end</b> Computer;
</pre>

<h3>Main</h3>

<p>The main is the easy part. We just loop and once every second we
discover plug-ins and call the Computer service if found.</p>

<pre>
<b>with</b> Ada.Text_IO;
<b>with</b> Plugins.Computer;
<b>with</b> Registry;
<b>procedure</b> Run <b>is</b>

   <b>use</b> Ada;
   <b>use</b> <b>type</b> Plugins.Ref;
   
   H      : Plugins.Ref;
   Result : Integer;
   
<b>begin</b>
   <b>loop</b>
      Text_IO.Put_Line (&quot;loop...&quot;);
      Registry.Discover_Plugins;
      H := Plugins.Ref (Registry.Get (Plugins.Computer.Service_Name));
      <b>if</b> H /= <b>null</b> <b>then</b>
         Result := Plugins.Computer.Ref (H).Call (5, 7);
         Text_IO.Put_Line (&quot;Result : &quot; &amp; Integer'Image (Result));
      <b>end</b> <b>if</b>;
      <b>delay</b> 1.0;
   <b>end</b> <b>loop</b>;
<b>end</b> Run;
</pre>

<p>To build and run the program, unpack the zip file attached to this Gem and
execute the following commands:</p>

<p>   $ gnat make -p -Pmain</p>
<p>   $ gnat make -p -Pcomputer</p>
<p>   $ ./run</p>

<p>Now, while the application is running, edit computer.adb and replace the
addition in Call by a multiplication. Then recompile the computer plug-in:</p>

<p>   $ gnat make -p -Pcomputer</p>

<p>After some time you&#8217;ll see that the new plug-in code has been loaded
automatically.</p>

<p>Note that an extended example illustrating dynamic loading and unloading is included
as part of the GNAT examples.
</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2011/09/21/gem-110-ada-plug-ins-and-shared-libraries-part-2/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Gem #109: Ada Plug-ins and Shared Libraries &#8212; Part 1</title>
		<link>http://www2.adacore.com/2011/09/05/gem-109-ada-plug-ins-and-shared-libraries-part-1/</link>
		<comments>http://www2.adacore.com/2011/09/05/gem-109-ada-plug-ins-and-shared-libraries-part-1/#comments</comments>
		<pubDate>Mon, 05 Sep 2011 14:48:23 +0000</pubDate>
		<dc:creator>Pascal Obry of EDF R&#038;D</dc:creator>
				<category><![CDATA[Ada / Ada 2005 / Ada 2012]]></category>
		<category><![CDATA[Development Log]]></category>
		<category><![CDATA[Devt log - Gem of the Week]]></category>

		<guid isPermaLink="false">http://www2.adacore.com/?p=12596</guid>
		<description><![CDATA[In this Gem, we discuss GNAT's support for shared libraries as a prelude to understanding how to build Ada plug-ins.]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s get started&#8230;</p>

<p>This is the first part of a two-part Gem about Ada plug-ins. In this
Gem, we discuss the way shared libraries are supported by GNAT
and the interactions between shared libraries and the Ada
run-time system. This is essential to fully understanding how to build Ada
plug-ins, which are discussed in the second part.</p>

<p>In modern operating systems it is rare to have fully self-contained
applications, that is, executables that require no external support
from the operating system. Such applications occur mostly in
the embedded world. In other domains, an application is built on top of
other services that are accessible from libraries.</p>

<p>There are two basic kinds of libraries: static and dynamic. A static library
is a simple container for object code that will be included in the
final application&#8217;s executable. This is done by the linker as the last
step of creating an executable. That&#8217;s why such libraries are called
static (statically linked, with the library code embedded in the
executable). Without static libraries we would need to link against
many object files, so this simplifies linking. The other benefit of
static libraries organized as archives of object files is to allow
selective linking, so that only the necessary objects from the library
are linked into the final executable.</p>

<p>A static library can be built with GNAT by using project files.
For example:</p>

<pre>
<b>library</b> <b>project</b> MyLib <b>is</b>
    <b>for</b> Source_Dirs <b>use</b> (&quot;src&quot;);
    <b>for</b> Object_Dir <b>use</b> &quot;obj&quot;;
    <b>for</b> Library_Dir <b>use</b> &quot;lib&quot;;
    <b>for</b> Library_Name <b>use</b> &quot;mylib&quot;;
    <b>for</b> Library_Kind <b>use</b> &quot;static&quot;;
<b>end</b> MyLib;
</pre>

<p>Dynamic libraries are quite a different story: they allow splitting
the image of an executable into several pieces, some of which can be
shared among different executables. Dynamic libraries offer two main
advantages: 1) sharing code among executables, thus diminishing global
memory usage, and 2) allowing modular maintainance of an application by
having the capability of replacing a chunk of an application without
having to regenerate or even interrupt the complete application. It is
also important to note that dynamic libraries require direct
support from the operating system.</p>

<p>Linking with a shared library is done in two steps.
The first step occurs at link time, when the linker generates
a table in the executable that contains the name of the shared library and all
of the symbols that must be imported from the shared library.
The second step occurs at load time using the dynamic linker.</p>

<p>The dynamic linker is part of the operating system and is in charge of
finalizing the linking of the application. This step is quite complex, but let&#8217;s
summarize as follows. The dynamic linker:</p>

<p>    1. Loads all shared libraries referenced by the executable.</p>

<p>    2. Creates the executable-specific shared libraries&#8217; data sections
       (only code is shared between executables, not data).</p>

<p>    3. Fills in the executable&#8217;s corresponding shared library table
       with the actual addresses of the referenced symbols (variables and
       routines).</p>

<p>    4. Calls the initialization routines (if any) defined in the
       just-loaded shared libraries.</p>

<p>At this point the application is ready to be run. Of course, shared
libraries can reference other shared libraries; the dynamic linker
is recursively doing the same job in this case. A very important point
to understand is that whenever we have an Ada shared library used by
an Ada application, both will be referencing the very same
Ada run-time system. What is important in our context is that the
elaboration is controlled by the executable and computed at bind
time. This ensures proper Ada semantics as required by the standard.</p>

<p>A shared library can be built using a project file by setting the
Library_Kind attribute to <i>relocatable</i>.</p>

<p>For plug-in support, the same piece of code may be loaded and unloaded
several times and thus requires initialization to happen at load time
and to be tied to the library itself; it cannot depend on the one-time
global elaboration of the application.</p>

<p>GNAT has support for stand-alone shared libraries, and these are exactly
the right kind of libraries to use in this context. A stand-alone
library is a library that contains the necessary code to elaborate the
Ada units that are included in the library and all the units it depends
upon, recursively. Since many libraries may need to elaborate the same
external units, the initialization code must be protected against
multiple initializations of the same data objects.</p>

<p>Note that these libraries do not exactly conform to Ada semantics,
since elaboration is supposed to happen only at program start and not
in the middle when a plug-in is loaded. But such libraries are
suitable for use with executables that are written in other
languages or as plug-in libraries.</p>

<p>Declaring a library to be stand-alone is easy using GNAT Project
files: it just requires adding an additional attribute in the library
project file:</p>

<code>
   <b>for</b> Library_Interface
      <b>use</b> ("interface_unit1", "interface_unit2", ...);
</code>

<p>This attribute declares the units that are visible from outside the
library, and thus offers a hiding mechanism (for all units not in the
interface), complementing the one offered by Ada: any unit not in the
interface cannot be called from outside. This means, in particular,
that changing the implementation of such units can be done without
having to recompile, rebind, or relink the rest of the application.</p> 

<p>In the second part of this series we will see how to set up an Ada
plug-in framework based on stand-alone libraries.</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2011/09/05/gem-109-ada-plug-ins-and-shared-libraries-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Ada Gems on summer holiday</title>
		<link>http://www2.adacore.com/2011/07/14/gems-on-holiday-201/</link>
		<comments>http://www2.adacore.com/2011/07/14/gems-on-holiday-201/#comments</comments>
		<pubDate>Thu, 14 Jul 2011 00:40:53 +0000</pubDate>
		<dc:creator>Gems Team</dc:creator>
				<category><![CDATA[Ada / Ada 2005 / Ada 2012]]></category>
		<category><![CDATA[Devt log - Gem of the Week]]></category>

		<guid isPermaLink="false">http://www2.adacore.com/?p=12935</guid>
		<description><![CDATA[Ada Gems are on holiday until September 2011. Have a great summer!
]]></description>
			<content:encoded><![CDATA[<p>Ada Gems are on holiday until September 2011. Have a great summer!</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2011/07/14/gems-on-holiday-201/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

