<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.0.11" -->
<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/"
	>

<channel>
	<title>AdaCore - The GNAT Pro Company</title>
	<link>http://www2.adacore.com</link>
	<description>AdaCore technology and news</description>
	<pubDate>Tue, 13 May 2008 10:36:24 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.0.11</generator>
	<language>en</language>
			<item>
		<title>Gem #35: bounded buffer package in GNAT hierarchy (Part 1)</title>
		<link>http://www2.adacore.com/2008/05/12/gem-35/</link>
		<comments>http://www2.adacore.com/2008/05/12/gem-35/#comments</comments>
		<pubDate>Mon, 12 May 2008 10:00:57 +0000</pubDate>
		<dc:creator>AdaCore</dc:creator>
		
		<category>Development Log</category>

		<category>Ada / Ada 2005</category>

		<category>Devt log - Gem of the Week</category>

		<guid isPermaLink="false">http://www2.adacore.com/2008/05/12/gem-35/</guid>
		<description><![CDATA[Ada Gem #35 &#8212;  Ada 95 introduced “protected types” as
a fundamental building block for efficient concurrent programming
and interrupt handling.  In this Gem we examine the use of
protected types in the implementation of the classic asynchronous
bounded buffer abstraction provided by the GNAT hierarchy of library units.  This
Gem assumes the reader is somewhat familiar with protected types
and will, therefore, explain some, but by no means all, of their
semantics.]]></description>
			<content:encoded><![CDATA[<h3>Let&#8217;s get started&#8230;</h3>


<p>The bounded buffer is a classic concurrent programming component
exhibiting asynchronous task interactions.  The concept is that
of a buffer of a fixed size that is accessed by multiple tasks, some inserting items and some removing them, concurrently and
asynchronously.  Hence the buffer implementation must be
protected against race conditions in which the tasks access the
implementation in an interleaved manner and thereby corrupt the
representation.  In addition to this “mutually exclusive access”,
the buffer also requires “condition synchronization”, in which
callers are kept waiting until the requested buffer has the
necessary state.  For example, a task cannot remove an item from
a buffer when the buffer is empty.  Likewise, an item cannot be
put into a buffer when the buffer is full.</p>



<p>Prior to Ada 95, programmers wanting to write portable code had
to use the rendezvous to achieve mutual exclusion, with guards to
implement the condition synchronization, because no other
synchronization mechanism was provided by the language.  Although
the extended rendezvous has a number of advantages and was a step
forward in language design, it has significant overhead when
compared to lower-level mechanisms such as semaphores, and is a
synchronous mechanism as well.  (Ada 80 had a built-in
“Semaphore” task type, intended to be implemented efficiently and
used as the name suggests, but mixing the higher-level rendezvous
with the much lower-level semaphore abstraction was considered
poor language design.) In addition, the rendezvous is only
available between tasks, meaning that the buffer would have to be
implemented as a task too, like the accessing threads.  As a
result, inserting and removing items would involve expensive task
switching, which is the primary source of the comparative
inefficiency.</p>



<p>The protected type construct added in Ada 95 addresses this issue
directly.  Protected types provide efficient mutually exclusive
access to encapsulated data, with direct expression of condition
synchronization when required.  Protected types do not define
threads of control, so their use does not involve task switching,
and although they do more than simple semaphores, their overhead
is comparable.</p>


The GNAT hierarchy of packages includes the generic package
GNAT.Bounded_Buffers, providing just the sort of abstraction we
have in mind, parameterized for general use.  The implementation
of the bounded buffer will be that of an array, and we will do
assignments of the values held within any given buffer, so the
generic formal type representing the values is declared as
private, but not limited private or indefinite:</p>


<pre>

<b>generic</b>
   <b>type</b> Element <b>is</b> <b>private</b>;
<b>package</b> GNAT.Bounded_Buffers <b>is</b>
</pre>


<p>Given this generic formal profile, users can instantiate the
generic as required.  For example, given an appropriate generic
actual parameter type named “Job”, we could instantiate it as
follows:</p>

<pre>

   <b>package</b> Jobs <b>is</b> <b>new</b> GNAT.Bounded_Buffers (Element =&gt; Job);
</pre>


<p>The package declaration contains a pragma Pure so
that the generic can be used during library unit elaboration
without a potential access-before-elaboration problem.  That
effect is achieved because Pure units are preelaborated, in
addition to other semantics.</p>



<p>Next the package declares the array type used internally in the
representation of the bounded buffer type:</p>

<pre>

   <b>type</b> Content <b>is</b> <b>array</b> (Positive <b>range</b> &lt;&gt;) <b>of</b> Element;
</pre>


<p>The array type must be declared outside the protected type,
rather than inside in the private part as a hidden implementation
artifact.  This is an unfortunate holdover from the fact that
protected types were originally named “protected records”, with
record type semantics: record types cannot declare such things as
other types!  This limitation was known during the Ada 2005 revision
but other revision aspects were more important, so this
undesirable restriction remains.</p>



<p>The next declaration in the package is a constant value of type
System.Priority:</p>

<pre>

   Default_Ceiling : <b>constant</b> System.Priority := System.Default_Priority;
</pre>


<p>In a real-time application using the Real-Time Systems Annex,
protected types are given a “ceiling” priority.  The constant
declared here is a default for that purpose so that applications
not using that Annex can ignore this aspect.</p>



<p>Finally the package declares the protected type itself, with two
discriminants:</p>

<pre>

   <b>protected</b> <b>type</b> Bounded_Buffer
      (Capacity : Positive;
       Ceiling  : System.Priority)
   <b>is</b>
      <b>pragma</b> Priority (Ceiling);
</pre>


<p>The first discriminant is the capacity of the instance object,
that is, the maximum number of values it can contain.  This value
will be used in the declaration of a hidden array object of type
Content.  With this approach, different objects of the one buffer
type can have different capacities.  The second discriminant
represents the ceiling priority value, used in the pragma
Priority.  This is where the Default_Ceiling constant would be
used in non-real-time applications.  Note that we cannot use the
Default_Ceiling constant as a default discriminant value because
the language does not allow some discriminants to have defaults
unless all have defaults.</p>



<p>Continuing with our “Jobs” example instantiation, declaration of
a bounded buffer specifies these discriminant values:</p>

<pre>

   Buffer : Jobs.Bounded_Buffer (Capacity =&gt; 20,
                                 Ceiling =&gt; Jobs.Default_Ceiling);
</pre>


<p>In this example we have arbitrarily set the capacity of Buffer to
20.  Note that the Bounded_Buffer type is provided directly as a
protected type, rather than as a limited private type completed
with a protected type.  With this approach, clients have full
flexibility to do all that protected types allow, such as timed
and conditional calls.
</p>


<p>Next the protected type declares the visible operations.  The two
primary operations are Insert and Remove, defined as entries for
the sake of the barriers that specify the required condition
synchronization.  (Only protected entries can have barriers,
unlike protected procedures and functions.) The barriers express the “not full”
and “not empty” conditions and keep their callers waiting until
those conditions hold.</p>

<pre>

      <b>entry</b> Insert (Item : Element);
      <b>entry</b> Remove (Item : <b>out</b> Element);
</pre>


<p>Then three functions are declared.  The names “Empty” and “Full”
describe the purpose of the first two functions.  The third,
“Extent”, returns the number of elements currently held in the
buffer.  It is worth noting that the state of a buffer to which
these functions may be applied can change immediately after the
call returns.</p>

<pre>

      <b>function</b> Empty <b>return</b> Boolean;
      <b>function</b> Full <b>return</b> Boolean;
      <b>function</b> Extent <b>return</b> Natural;
</pre>


<p>In part two of this Gem we will explore the private part of the
protected type, the package body, and the body of the protected
type. </p>

<h3>Related Source Code</h3>

<p>Ada Gems example files are distributed by AdaCore and may be used or modified for any purpose without restrictions.</p>]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2008/05/12/gem-35/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Gem #34: Safe and Secure Software : Chapter 2, Safe Typing</title>
		<link>http://www2.adacore.com/2008/05/05/gem-34/</link>
		<comments>http://www2.adacore.com/2008/05/05/gem-34/#comments</comments>
		<pubDate>Mon, 05 May 2008 10:00:22 +0000</pubDate>
		<dc:creator>AdaCore</dc:creator>
		
		<category>Development Log</category>

		<category>Ada / Ada 2005</category>

		<category>Devt log - Gem of the Week</category>

		<guid isPermaLink="false">http://www2.adacore.com/2008/05/05/gem-34/</guid>
		<description><![CDATA[This week's gem is the second chapter of John Barnes' new booklet:</p> 

<p>Safe and Secure Software: An Introduction to Ada 2005.</p>

<p>
Over the coming months, we will be publishing all thirteen chapters of the booklet. In the attachment at the bottom of Gem #30 you can access the contents and bibliography for the entire booklet.

We hope you will enjoy the read!</p>]]></description>
			<content:encoded><![CDATA[<h3>Let&#8217;s get started&#8230;</h3>


<p>Safe typing is not about preventing heavy-handed use of the keyboard, although it can detect errors made by typos!</p>


<p>Safe typing is about designing the type structure of the language in order to prevent many common semantic errors. It is often known as strong typing.</p>


<p>Early languages such as Fortran and Algol treated all data as numeric types. Of course, at the end of the day, everything is indeed held in the computer as a numeric of some form, usually as an integer or floating point value and usually encoded using a binary representation. Later languages, starting with Pascal, began to recognize that there was merit in taking a more abstract view of the objects being manipulated. Even if they were ultimately integers, there was much benefit to be gained by treating colors as colors and not as integers by using enumeration types (just called scalar types in Pascal).</p>


<p>Ada take this idea much further as we shall see, but other languages still treat scalar types as just raw numeric types, and miss the critical idea of abstraction, which is to distinguish semantic intent from machine representation. The Ada approach provides more opportunities for detecting programming errors.
</p>

<h3>Read Chapter 2 in full</h3>


<p>Note: All chapters of this booklet will, in time, be available on the <a href="/home/ada_answers/ada_2005">Ada 2005 home page</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2008/05/05/gem-34/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Gem #33: Accessibility Checks (Part I: Ada95)</title>
		<link>http://www2.adacore.com/2008/04/28/gem-33/</link>
		<comments>http://www2.adacore.com/2008/04/28/gem-33/#comments</comments>
		<pubDate>Mon, 28 Apr 2008 10:00:15 +0000</pubDate>
		<dc:creator>AdaCore</dc:creator>
		
		<category>Development Log</category>

		<category>Ada / Ada 2005</category>

		<category>Devt log - Gem of the Week</category>

		<guid isPermaLink="false">http://www2.adacore.com/2008/04/28/gem-33/</guid>
		<description><![CDATA[Ada Gem #33 &#8212; The existence of dangling references (pointers to objects that no longer
  exist) in a program can have catastrophic results. Ada incorporates a
  set of "accessibility rules" that help the programmer prevent dangling
  references, making programs more secure.]]></description>
			<content:encoded><![CDATA[<h3>Let&#8217;s get started&#8230;</h3>


<p>  Ada is a block-structured language, which means the programmer can nest blocks of
  code inside other blocks. At the end of a block, all objects declared
  inside of it go out of scope, meaning they no longer exist, so the
  language disallows pointers to objects in blocks with a deeper nesting
  level.</p>

  
  
<p>In order to prevent dangling references, every entity is associated with a number,
  called its &#8220;accessibility level&#8221;, according to a Ada&#8217;s accessibility rules.
  When certain references are made to an entity of an access type (Ada&#8217;s
  parlance for pointer), the accessibility level of the entity is checked
  against the level allowed by the context so that no dangling pointers can occur.</p>


  
<p>Consider the following example:</p>

<pre>

     <b>procedure</b> Static_Check <b>is</b>
        <b>type</b> Global <b>is</b> <b>access</b> <b>all</b> Integer;
        X : Global;

        <b>procedure</b> Init <b>is</b>
           Y : <b>aliased</b> Integer := 0;
        <b>begin</b>
           X := Y&apos;Access; <EM>&#45;&#45; Illegal!</EM>
        <b>end</b> Init;
   
     <b>begin</b>
        Init;
        &#8230;
     <b>end</b> Static_Check;
</pre>

  
<p>The assignment is illegal because when the procedure <tt>Init</tt> finishes, the
  object <tt>Y</tt> no longer exists, thus making <tt>X</tt> a danging pointer. The compiler
  will detect this situation and flag the error.</p>


  
<p>The beauty of the accessibility rules is that most of them can be
  checked and enforced at compile time, just by using statically known accessibility
  levels.
</p>

  
<p>However, there are cases when it is not possible to statically determine the
  accessibility level that an entity will have during program execution. In
  these cases, the compiler will insert a run-time check to raise an
  exception if a dangling pointer can be created:</p>

<pre>

     <b>procedure</b> Access_Params <b>is</b>
        <b>type</b> Integer_Access <b>is</b> <b>access</b> <b>all</b> Integer;
        Data : Integer_Access;

        <b>procedure</b> Init_Data (Value : <b>access</b> Integer) <b>is</b>
        <b>begin</b>
           Data := Integer_Access (Value);
           <EM>&#45;&#45; this conversion performs a dynamic accessibility check</EM>
        <b>end</b>;

        X : <b>aliased</b> Integer := 1;

     <b>begin</b>
        Init_Data (X&apos;Access); <EM>&#45;&#45; This is OK</EM> 

        <b>declare</b>  
           Y : <b>aliased</b> Integer := 2;
        <b>begin</b>
           Init_Data (Y&apos;Access); <EM>&#45;&#45;  Trouble!</EM>
        <b>end</b>;
	<EM>&#45;&#45;  Y no longer exists!</EM>

	Process (Data);
     <b>end</b>;
</pre>

  
<p>In the example above, we cannot know at compile time the accessibility
  level of the object that will be passed to <tt>Init_Data</tt>, so the compiler
  inserts a run-time check to make sure that the assignment &#8216;<tt>Data :=</tt> &#8230;&#8217;
  does not cause a dangling reference &#8212; and to raise an exception if it
  would.</p>


  
<p>In summary, when it comes to dangling references, Ada makes it very
  hard for you to shoot yourself in the foot!</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2008/04/28/gem-33/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Gem #32: Safe and Secure Software : Chapter 1, Safe Syntax</title>
		<link>http://www2.adacore.com/2008/04/21/gem-32/</link>
		<comments>http://www2.adacore.com/2008/04/21/gem-32/#comments</comments>
		<pubDate>Mon, 21 Apr 2008 10:00:54 +0000</pubDate>
		<dc:creator>AdaCore</dc:creator>
		
		<category>Development Log</category>

		<category>Ada / Ada 2005</category>

		<category>Devt log - Gem of the Week</category>

		<guid isPermaLink="false">http://www2.adacore.com/2008/04/21/gem-32/</guid>
		<description><![CDATA[This week's gem is the first chapter of John Barnes' new booklet:</p> 

<p>Safe and Secure Software: An Introduction to Ada 2005.</p>

<p>
Over the coming months, we will be publishing all thirteen chapters of the booklet. In the attachment at the bottom of Gem #30 you can access the contents and bibliography for the entire booklet.

We hope you will enjoy the read!</p>]]></description>
			<content:encoded><![CDATA[<h3>Let&#8217;s get started&#8230;</h3>


<p>Syntax is often considered to be a rather boring mechanical detail. The argument being that it is what you say that matters but not so much how it is said. That of course is not true. Being clear and unambiguous are important aids to any communication in a civilized world. </p>


<p>Similarly, a computer program is a communication between the writer and the reader, whether the reader be that awkward thing: the compiler, another team member, a reviewer or other human soul. Indeed, most communication regarding a program is between two people. Clear and unambiguous syntax is a great help in aiding communication and, as we shall see, avoids a number of common errors. </p>


<p>An important aspect of good syntax design is that it is a worthwhile goal to try to ensure that typical simple typing errors cause the program to become illegal and thus fail to compile, rather than having an unintended meaning. Of course it is hard to prevent the accidental typing of X rather than Y or + rather than * but many structural risks can be prevented. Note incidentally that it is best to avoid short identifiers for just this reason. If we have a financial program about rates and times then using identifiers R and T is risky since we could easily type the wrong identifier by mistake (the letters are next to each other on the keyboard). But if the identifiers are Rate and Time then inadvertently typing Tate or Rime will be caught by the compiler. This applies to any language of course.</p>

<h3>Read Chapter 1 in full</h3>

<p>Note: All chapters of this booklet will, in time, be available on the <a href="/home/ada_answers/ada_2005">Ada 2005 home page</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2008/04/21/gem-32/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Gem #31: preconditions/postconditions</title>
		<link>http://www2.adacore.com/2008/04/14/gem-31/</link>
		<comments>http://www2.adacore.com/2008/04/14/gem-31/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 10:00:11 +0000</pubDate>
		<dc:creator>AdaCore</dc:creator>
		
		<category>Development Log</category>

		<category>Ada / Ada 2005</category>

		<category>Devt log - Gem of the Week</category>

		<guid isPermaLink="false">http://www2.adacore.com/2008/04/14/gem-31/</guid>
		<description><![CDATA[Ada Gem #31 &#8212; The notion of preconditions and postconditions is an old one.
A precondition is a condition that must be true before a
section of code is executed, and a postcondition is a
condition that must be true after the section of code
is executed.]]></description>
			<content:encoded><![CDATA[<h3>Let&#8217;s get started&#8230;</h3>


<p>The notion of preconditions and postconditions is an old one.
A precondition is a condition that must be true before a
section of code is executed, and a postcondition is a
condition that must be true after the section of code
is executed.</p>


<p>In the context we are talking about here, the section
of code will always be a subprogram. Preconditions
are conditions that must be guaranteed by the caller
before the call, and postconditions are results
guaranteed by the subprogram code itself.</p>



<p>It is possible, using pragma Assert (as defined in
Ada 2005, and as implemented in all versions of
GNAT), to approximate run-time checks corresponding
to preconditions and postconditions by placing
assertion pragmas in the body of the subprogram,
but there are several problems with that approach:
</p>


<p>1. The assertions are not visible in the spec, and
preconditions and postconditions are logically a
part of (in fact, an important part of) the spec.</p>



<p>2. Postconditions have to be repeated at every
exit point.
</p>


<p>3. Postconditions often refer to the original value
of a parameter on entry or the result of a function,
and there is no easy way to do that in an assertion.</p>



<p>The latest versions of GNAT implement two pragmas,
Precondition and Postcondition, that deal with all
three problems in a convenient way. The easiest way
to describe these is to use an example:</p>

<pre>

    <b>package</b> Arith <b>is</b>
       <b>function</b> Sqrt (Arg : Integer) <b>return</b> Integer;
       <b>pragma</b> Precondition (Arg &gt;= 0);
       <b>pragma</b> Postcondition
        (Sqrt&apos;Result &gt;= 0
           <b>and</b> <b>then</b>
        (Sqrt&apos;Result ** 2) &lt;= Arg
           <b>and</b> <b>then</b>
        (Sqrt&apos;Result + 1) ** 2 &gt; Arg);
    <b>end</b> Arith;

    <b>with</b> Arith; <b>use</b> Arith;
    <b>with</b> Text_IO; <b>use</b> Text_IO;
    <b>procedure</b> Main <b>is</b>
    <b>begin</b>
       Put_Line (Sqrt (9)&apos;Img);
       Put_Line (Sqrt (10)&apos;Img);
       Put_Line (Sqrt (-3)&apos;Img);
    <b>end</b>;
</pre>


<p>Now if we compile with -gnata (which enables preconditions
and postconditions), and we have a correct body for Sqrt,
then when we run Main we will get:</p>

<pre>

     3
     3

    raised SYSTEM.ASSERTIONS.ASSERT_FAILURE :
       Precondition failed at arith.ads:3
</pre>


<p>Now if there was something wrong with the body of Sqrt
that gave the wrong answer, we might get:</p>

<pre>

    raised SYSTEM.ASSERTIONS.ASSERT_FAILURE :
      postcondition failed at arith.ads:4
</pre>


<p>Indicating that we have a bug in the body of Sqrt
that we must investigate.</p>



<p>There is one more thing to mention, which is the promised
ability to refer to the old value of parameters. A new
attribute &#8216;Old allows this as shown in this example:</p>

<pre>

    <b>procedure</b> Write_Data (Total_Writes : <b>in</b> <b>out</b> Natural);
    <EM>&#45;&#45;  Write out the data incrementing Total_Writes to</EM>
    <EM>&#45;&#45;  show number of write operations performed.</EM>
    <b>pragma</b> Postcondition (Total_Writes &gt; Total_Writes&apos;Old);
</pre>

The introduction of preconditions and postconditions into
GNAT provides a powerful tool for design and documentation
(Eiffel has referred to this approach as &#8220;design by contract&#8221;).</p>




<p>The preconditions and postconditions serve three functions<br/>



1. They provide valuable formal documentation in the spec<br/>


2. They provide input to proof tools<br/>


3. They help find bugs in the course of normal debugging
as shown by the example above.</p>



<p>Support for preconditions and postconditions will be
available in GNAT Pro 6.2.1 and forthcoming versions
of GNAT GPL. If you are a GNAT Pro user and you want
to try this feature out today, request a wavefront
by using GNAT Tracker.</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2008/04/14/gem-31/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Gem #30: Safe and Secure Software : Introduction</title>
		<link>http://www2.adacore.com/2008/04/08/gem-30/</link>
		<comments>http://www2.adacore.com/2008/04/08/gem-30/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 06:00:06 +0000</pubDate>
		<dc:creator>AdaCore</dc:creator>
		
		<category>Development Log</category>

		<category>Ada / Ada 2005</category>

		<category>Devt log - Gem of the Week</category>

		<guid isPermaLink="false">http://www2.adacore.com/2008/04/07/gem-30/</guid>
		<description><![CDATA[This week's gem is the introduction to John Barnes' new booklet:</p> 

<p>Safe and Secure Software: An Introduction to Ada 2005.</p>

<p>
Over the coming months, we will be publishing all thirteen chapters of the booklet. In the attachment at the bottom of this page you can access the contents and bibliography for the entire booklet.

We hope you will enjoy the read!</p>]]></description>
			<content:encoded><![CDATA[<h3>Let&#8217;s get started&#8230;</h3>


<p>The aim of this booklet is to show how Ada 2005 addresses the needs of designers and implementers of safe and secure software. The discussion will also show that those aspects of Ada that make it ideal for safety-critical and security-critical application areas will also simplify the development of robust and reliable software in many other areas.</p>


<p>The world is becoming more and more concerned about both safety and security. Moreover, software now pervades all aspects of the workings of society. Accordingly, it is important that software which is concerned with systems for which safety or security are a major concern should be safe and secure.</p>


<p>There has been a long tradition of concern for safety going back to the development of railroad signaling and more recently with aviation. Vital software systems such as those that control aircraft navigation and landing have to meet well established certification and validation criteria.</p>



<p>More recently there has been growing concern with security in systems such as banking and communications generally. This has been heightened with concern for the activities of terrorists.</p>


<p>Safety and security are intertwined through communication. An interesting characterization of the difference is<br/>

▪	safety – the software must not harm the world,<br/>

▪	security – the world must not harm the software.</p>


<p>So a safety-critical system is one in which the program must be correct, otherwise it might wrongly change some external device such as an aircraft flap or a railroad signal, with serious real-world consequences.</p>

<p>
And a security-critical system is one in which it must not be possible for some incorrect or malicious input from the outside to violate the integrity of the system, for example by corrupting a password checking mechanism and stealing social security information.</p>


<p>The key to guarding against both problems is that the software must be correct in the aspects affecting the system&#8217;s integrity. And by correct we mean that it meets its specification. Of course if the specification is incomplete or itself incorrect then the system will be vulnerable. Capturing requirements correctly is a hard problem and is the focus of much attention from the lean software development community.</p>


<p>One of the trends of the second half of the twentieth century was a universal concern with freedom. But there are two aspects of freedom. The ability of the individual to do whatever they want conflicts with the right to be protected from the actions of others. Maybe A would like the freedom to smoke in a pub whereas B wants freedom from smoke in a pub. Concern with health in this example is changing the balance between these freedoms. Maybe the twenty-first century will see further shifts from &#8220;freedom to&#8221; to &#8220;freedom from&#8221;.</p>

<p>
In terms of software, the languages Ada and C have very different attitudes to freedom. Ada introduces restrictions and checks, with the goal of providing freedom from errors. On the other hand C gives the programmer more freedom, making it easier to make errors. </p>


<p>One of the historical guidelines in C was &#8220;trust the programmer&#8221;. This would be fine were it not for the fact that programmers, like all humans, are frail and fallible beings. Experience shows that whatever techniques are used it is hard to write &#8220;correct&#8221; software. It is good advice therefore to use tools that can help by finding bugs and preventing bugs. Ada was specifically designed to help in this respect. There have been three versions of Ada – Ada 83, Ada 95 and now Ada 2005.</p>


<p>The purpose of this booklet is to illustrate the ways in which Ada 2005 can help in the construction of reliable software, by illustrating some aspects of its features. It is hoped that it will be of interest to programmers and managers at all levels.</p>


<p>It must be stressed that the discussion is not complete. Each chapter selects a particular topic under the banner of Safe X where Safe is just a brief token to designate both safety and security. For the most critical software, use of the related SPARK language appears to be very beneficial, and this is outlined in Chapter 11.</p>


<p>A topic with which Ada has much synergy is lean software development – there is not enough space in this booklet to expand on this concept but the reader is encouraged to explore its good ideas elsewhere.</p>


<p>As the twenty-first century progresses we will see software becoming even more pervasive. It would be nice to think that software in automobiles for example was developed with the same care as that in airplanes. But that is not so. My wife recently had an experience where her car displayed two warning icons. One said &#8220;stop at once&#8221;, the other said &#8220;drive immediately to your dealer&#8221;. Another anecdotal motor story is that of a driver attempting to select channel 5 on the radio, only to see the car change into 5th gear! Luckily he did not try Replay.</p>


<p>For a fuller description of Ada 2005, SPARK, and lean software development and papers on related topics please consult the bibliography.</p>

<h3>Read on&#8230;</h3>

<p>Note: All chapters will also be available on the <a href="/home/ada_answers/ada_2005">Ada 2005 home page</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2008/04/08/gem-30/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Gem #29: Introduction to the Ada Web Server (AWS)</title>
		<link>http://www2.adacore.com/2008/03/31/gem-29/</link>
		<comments>http://www2.adacore.com/2008/03/31/gem-29/#comments</comments>
		<pubDate>Mon, 31 Mar 2008 09:00:54 +0000</pubDate>
		<dc:creator>AdaCore</dc:creator>
		
		<category>Development Log</category>

		<category>Ada / Ada 2005</category>

		<category>Devt log - Gem of the Week</category>

		<guid isPermaLink="false">http://www2.adacore.com/2008/03/31/gem-29/</guid>
		<description><![CDATA[Ada Gem #29 &#8212; Introduction to Ada Web Server (AWS)  ]]></description>
			<content:encoded><![CDATA[<h3>Let&#8217;s get started&#8230;</h3>


<p>This Gem presents a basic introduction the Ada Web Server (AWS). The core components
of AWS comprise a Web server which supports the HTTP protocol. This Web server
can be embedded into any application. Common usages are:
</p>
   
<p>- To develop a full Web application.<br/>


   - Adding a GUI to a mostly batch-oriented application like a long-running
     simulation that we want to get control of from time to time.<br/>


   - To develop a distributed application exchanging messages using the
     HTTP or SOAP protocols.<br/>
</p>



<p>The AWS HTTP module handles the decoding of the HTTP request and encoding
of the user&#8217;s response. It uses a callback mechanism to interact with the user&#8217;s application. Let&#8217;s take the famous Hello World example and see how it could be translated into the AWS framework.</p>



<p>First the user&#8217;s hello_world callback, which is a function with a single
parameter of type Status.Data and returning a Response.Data object:</p>

<pre>

   <b>with</b> AWS.MIME;
   <b>with</b> AWS.Response;
   <b>with</b> AWS.Status;

   <b>package</b> <b>body</b> CB <b>is</b>
      <b>use</b> AWS;
      <b>function</b> Hello_World (Request : <b>in</b> Status.Data) <b>return</b> Response.Data <b>is</b>
      <b>begin</b>
         <b>return</b> Response.Build (MIME.Text_HTML, &quot;&lt;p&gt;Hello World!&lt;/p&gt;&quot;);
      <b>end</b> Hello_World;
   <b>end</b> CB;
</pre>


<p>The AWS.Response unit contains many constructors. Response.Build is one.
Another is Response.File, for returning a file. Various high-level constructors are
provided, such as for streaming data.</p>



<p>Now here&#8217;s the main subprogram with the server:</p>

<pre>

   <b>with</b> AWS.Server;
   <b>with</b> CB;
   <b>procedure</b> Hello_World <b>is</b>
      <b>use</b> AWS;
      HTTP : Server.HTTP;
   <b>begin</b>
      Server.Start (HTTP, &quot;Hello_World&quot;, Callback =&gt; CB.Hello_World&apos;<b>Access</b>);
      <b>delay</b> 60.0;
      Server.Shutdown (HTTP);
   <b>end</b> Hello_World;
</pre>


<p>That&#8217;s it. The start routine registers the CB.Hello_World procedure as the user&#8217;s
callback and starts the server using the default port, which
is 8080. After running the hello_world executable, by entering the URL
http://localhost:8080/ into your web browser you&#8217;ll receive the message
&#8220;Hello World&#8221;, and this will occur for any URI. So entering http://localhost:8080/whatever
will also return &#8220;Hello World&#8221;. After 60 seconds the server will shut down
and the program will exit.</p>



<p>All HTTP parameters are available from the Request parameter of the Hello_World callback.
So let&#8217;s add a local constant to get the actual URI received:</p>

<pre>

   URI : <b>constant</b> String := Status.URI (Request);
</pre>


<p>Then we change the Response.Build call to:</p>

<pre>

   <b>return</b> Response.Build
      (MIME.Text_HTML, &quot;&lt;p&gt;Hello World! URI=&quot; &amp; URI &amp; &quot;&lt;/p&gt;&quot;);
</pre>


<p>After restarting the server, entering http://localhost:8080/home into the
web browser will display &#8220;Hello World! URI=/home&#8221;.
</p>


<p>An if/elsif construction can be used to test for each URI that must be handled by the server:</p>

<pre>

   <b>if</b> URI = &quot;&#8230;&quot; <b>then</b>
      &#8230;
   <b>elsif</b> URI = &quot;&#8230;&quot; <b>then</b>
      &#8230;
   <b>else</b>
      <b>return</b> Response.Build
         (MIME.Text_HTML,
          &quot;&lt;p&gt;Not found : URI=&quot; &amp; URI &amp; &quot;&lt;/p&gt;&quot;,
          Status_Code =&gt; Messages.S404);
   <b>end</b> <b>if</b>;
</pre>


<p>Using callbacks is simple, but when the application becomes larger
it&#8217;s easier to use dispatchers. So let&#8217;s change the Hello World program
to use dispatchers:</p>

<pre>

   <b>with</b> AWS.Response;
   <b>with</b> AWS.Status;
   <b>with</b> AWS.Dispatchers;
   <b>package</b> CB <b>is</b>
      <b>use</b> AWS;

      <b>type</b> Hello_World <b>is</b> <b>new</b> Dispatchers.Handler <b>with</b> <b>null</b> <b>record</b>;

      <b>overriding</b> <b>function</b> Dispatch
        (Handler : <b>in</b> Hello_World;
         Request : <b>in</b> Status.Data) <b>return</b> Response.Data;
   <b>private</b>
      <b>overriding</b> <b>function</b> Clone (Element : <b>in</b> Hello_World) <b>return</b> Hello_World;
   <b>end</b> CB;
</pre>


<p>The body of Dispatch is identical to the Hello_World callback above.
The Dispatchers.Handler type has a clonable interface, and Clone in this case is
trivial:</p>

<pre>

   <b>overriding</b> <b>function</b> Clone (Element : <b>in</b> Hello_World) <b>return</b> Hello_World <b>is</b>
   <b>begin</b>
      <b>return</b> Element;
   <b>end</b> Clone;
</pre>


<p>In this case the main subprogram is slightly larger:</p>

<pre>

   <b>with</b> AWS.Config;
   <b>with</b> AWS.Server;
   <b>with</b> AWS.Services.Dispatchers.URI;
   <b>with</b> CB;

   <b>procedure</b> Hello_World <b>is</b>
      <b>use</b> AWS;
      HTTP : Server.HTTP;
      Conf : Config.Object;
      HW   : CB.Hello_World;
      Root : Services.Dispatchers.URI.Handler;
   <b>begin</b>
      Services.Dispatchers.URI.Register (Root, &quot;/hello&quot;, HW);
      Server.Start (HTTP, Root, Conf);
      <b>delay</b> 60.0;
      Server.Shutdown (HTTP);
  <b>end</b> Hello_World;
</pre>


<p>The main difference is that we have registered the HW dispatcher to be used
only for URI &#8220;/hello&#8221; (http://localhost:8080/hello). For any other URL, a
404 error message will be sent by the dispatcher module. It&#8217;s also possible to
use a regular expression or a prefix if needed. The configuration object
can be set to change any server settings, such as the port, the number of
simultaneous connections, timeouts, etc.</p>



<p>Many kinds of dispatchers exist, not only for supporting URIs (as in this example),
but also for handling virtual hosts, request methods (POST/GET) and services for
linking dispatchers, as well as dispatching based on timers (see child units of
AWS.Services.Dispatchers). For an example of a simple API for converting a
callback to a dispatcher see AWS.Dispatchers.Callback.</p>



<p>Various other services are offered directly by AWS, including HTTP/SOAP, WSDL,
Ajax, SMTP, and a templates engine. But covering all of those is beyond the scope
of this introduction.</p>

<h3>Related Source Code</h3>

<p>Ada Gems example files are distributed by AdaCore and may be used or modified for any purpose without restrictions.</p>]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2008/03/31/gem-29/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Gem #28: Changing Data Representation (Part 2)</title>
		<link>http://www2.adacore.com/2008/03/17/gem-28/</link>
		<comments>http://www2.adacore.com/2008/03/17/gem-28/#comments</comments>
		<pubDate>Mon, 17 Mar 2008 10:00:49 +0000</pubDate>
		<dc:creator>AdaCore</dc:creator>
		
		<category>Development Log</category>

		<category>Ada / Ada 2005</category>

		<category>Devt log - Gem of the Week</category>

		<guid isPermaLink="false">http://www2.adacore.com/2008/03/17/gem-28/</guid>
		<description><![CDATA[Ada Gem #28 &#8212; Part 2, Efficiency Considerations]]></description>
			<content:encoded><![CDATA[<p>Last week, we discussed the use of derived types and
representation clauses to achieve automatic change of
representation. More accurately, this feature is not
completely automatic, since it requires you to write
an explicit conversion. In fact there is a principle
behind the design here which says that a change of
representation should never occur implicitly behind
the back of the programmer without such an explicit
request by means of a type conversion.</p>



<p>The reason for that is that the change of representation
operation can be very expensive, since in general it can
require component by component copying, changing the
representation on each comoponent.</p>



<p>Let&#8217;s have a look at the -gnatG expanded code to see what
is hidden under thecovers here. For example, the conversion
Arr (Input_Data) from last week&#8217;s example generates the
following expanded code:</p>

<pre>

   B26b : <b>declare</b>
      [<b>subtype</b> p__TarrD1 <b>is</b> integer <b>range</b> 1 .. 16]
      R25b : p__TarrD1 := 1;
   <b>begin</b>
      <b>for</b> L24b <b>in</b> 1 .. 16 <b>loop</b>
         [<b>subtype</b> p__arr___XP3 <b>is</b>
           system__unsigned_types__long_long_unsigned <b>range</b> 0 ..
           16#FFFF_FFFF_FFFF#]
         work_data := p__arr___XP3!((work_data <b>and</b> <b>not</b> shift_left!(
           16#7#, 3 * (integer(L24b - 1)))) <b>or</b> shift_left!(p__arr___XP3!
           (input_data (R25b)), 3 * (integer(L24b - 1))));
         R25b := p__TarrD1&apos;succ(R25b);
      <b>end</b> <b>loop</b>;
   <b>end</b> B26b;
</pre>


<p>That&#8217;s pretty horrible! In fact one of the Ada experts
here thought that it was too gruesome and suggested
simplifying it for this gem, but we have left it in
its original form, so that you can see why it is nice
to let the compiler generate all this stuff so you don&#8217;t
have to worry about it yourself.</p>



<p>Given that the conversion can be pretty inefficient, you
don&#8217;t want to convert backwards and forwards more than you
have to, and the whole approach is only worth while if
will be doing extensive computations involving the value.</p>



<p>The expense of the conversion explains two aspects
of this feature that are not obvious. First, why do
we require derived types instead of just allowing
subtypes to have different representations, avoiding
the need for an explicit conversion?</p>



<p>The answer is precisely that the conversions are
expensive, and you don&#8217;t want them happening behind
your back. So if you write the explicit conversion,
you get all the gobbledygook listed above, but you
can be sure that this never happens unless you
explicitly ask for it.</p>



<p>This also explains the restriction we mentioned in
last week&#8217;s gem from RM 13.1(10):</p>


  
<p><blockquote>10    For an untagged derived type, no type-related
  representation items are allowed if the parent type
  is a by-reference type, or has any user-defined
  primitive subprograms.</blockquote></p>



<p>It turns out this restriction is all about avoiding
implicit changes of representation. Let&#8217;s have a look
at how type derivation works when there are primitive
subprograms defined at the point of derivation. Connsider
this example:</p>

<pre>

  <b>type</b> My_Int_1 <b>is</b> <b>range</b> 1 .. 10;

  <b>function</b> Odd (Arg : My_Int_1) <b>return</b> Boolean;

  <b>type</b> My_Int_2 <b>is</b> <b>new</b> My_Int_1;
</pre>


<p>Now when we do the type derivation, we inherit the function
Odd for My_Int_2. But where does this function come from?
We haven&#8217;t written it explicitly, so the compiler somehow
materializes this new implicit function. How does it do that?</p>



<p>We might think that a complete new function is created
including a body in which My_Int_2 replaces My_Int_1, but
that would be impractical and expensive. The actual mechanism
avoids the need to do this by use of implicit type conversions.
Suppose after the above declarations, we write:</p>

<pre>

  Var : My_Int_2;
  ...
  <b>if</b> Odd (Var) <b>then</b>
     &#8230;
</pre>


<p>The compiler translates this as:</p>

<pre>

  Var : My_Int_2;
  ...
  <b>if</b> Odd (My_Int_1 (Var)) <b>then</b>
     &#8230;
</pre>


<p>This implicit conversion is a nice trick, it means that we
can get the effect of inheriting a new operation without
actually having to create it. Furthermore, in a case like
this, the type conversion generates no code, since My_Int_1
and My_Int_2 have the same representation.</p>



<p>But the whole point is that they might not have the same
representation if one of them had a rep clause that made
the representations different, and in this case the implicit
conversion inserted by the compiler could be expensive,
perhaps generating the junk we quoted above for the Arr
case. Since we never want that to happen implicitly, there
is a rule to prevent it.</p>



<p>The business of forbidding by-reference types (which
includes all tagged types) is also driven by this
consideration. If the representations are the same,
it is fine to pass by reference, even in the presence
of the conversion, but if there was a change of
representation, it would force a copy, which would
violate the by-reference requirement.</p>



<p>So to summarize these two gems, on the one hand Ada
gives you a very convenient way to trigger these
complex conversions between different representations.
On the other hand, Ada guarantees that you never get
these potentially expensive conversions happening unless
you explicitly ask for them.</p>]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2008/03/17/gem-28/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Gem #27: Changing Data Representation (Part 1)</title>
		<link>http://www2.adacore.com/2008/03/03/gem-27/</link>
		<comments>http://www2.adacore.com/2008/03/03/gem-27/#comments</comments>
		<pubDate>Mon, 03 Mar 2008 10:00:16 +0000</pubDate>
		<dc:creator>AdaCore</dc:creator>
		
		<category>Development Log</category>

		<category>Ada / Ada 2005</category>

		<category>Devt log - Gem of the Week</category>

		<guid isPermaLink="false">http://www2.adacore.com/2008/03/03/gem-27/</guid>
		<description><![CDATA[Ada Gem #27 &#8212; Part 1, Automatic Representation Changes  ]]></description>
			<content:encoded><![CDATA[<h3>Let&#8217;s get started&#8230;</h3>


<ind><p>A powerful feature of Ada is the ability to specify the
exact data layout. This is particularly important when
you have an external device or program that requires a
very specific format. Some examples are:</p>

<pre>

   <b>type</b> Com_Packet <b>is</b> <b>record</b>
      Key : Boolean;
      Id  : Character;
      Val : Integer <b>range</b> 100 .. 227;
   <b>end</b> <b>record</b>;

   <b>for</b> Com_Packet <b>use</b> <b>record</b>
      Key <b>at</b> 0 <b>range</b> 0 .. 0;
      Id  <b>at</b> 0 <b>range</b> 1 .. 8;
      Val <b>at</b> 0 <b>range</b> 9 .. 15;
   <b>end</b> <b>record</b>;
</pre>


<p>which lays out the fields of a record, and in the case of
Val, forces a biased representation in which all zero bits
represents 100. Another example is:</p>

<pre>

   <b>type</b> Val <b>is</b> (A,B,C,D,E,F,G,H);
   <b>type</b> Arr <b>is</b> <b>array</b> (1 .. 16) <b>of</b> Val;
   <b>for</b> Arr&apos;Component_Size <b>use</b> 3;
</pre>

which forces the components to take only 3 bits, crossing
byte boundaries as needed. A final example is:
<pre>

   <b>type</b> Status <b>is</b> (Off, On, Unknown);
   <b>for</b> Status <b>use</b> (Off =&gt; 2#001#, On =&gt; 2#010#, Unknown =&gt; 2#100#);
</pre>


<p>which allows specified values for an enumeration type, instead
of the efficient default values of 0,1,2.
</p>


<p>In all these cases, we might use these representation clauses
to match external specifications, which can be very useful. The
disadvantage of such layouts is that they are inefficient, and
accessing individual components, or in the case of the enumeration
type, looping through the values, can increase space and time
requirements for the program code.</p>



<p>One approach that is often effective is to read or write the data
in question in this specified form, but internally in the program
represent the data in the normal default layout, allowing efficient
access, and do all internal computations with this more efficient
form.</p>



<p>To follow this approach, you will need to convert between the
efficient format and the specified format. Ada provides a very
convenient method for doing this, as described in RM 13.6
&#8220;Change of Representation&#8221;.</p>



<p>The idea is to use type derivation, where one type has the specified
format and the other has the normal default format. For instance
for the array case above, we would write:</p>

<pre>

   <b>type</b> Val <b>is</b> (A,B,C,D,E,F,G,H);
   <b>type</b> Arr <b>is</b> <b>array</b> (1 .. 16) <b>of</b> Val;

   <b>type</b> External_Arr <b>is</b> <b>new</b> Arr;
   <b>for</b> External_Arr&apos;Component_Size <b>use</b> 3;
</pre>


<p>Now we read and write the data using the External_Arr
type. When we want to convert to the efficient form,
Arr, we simply use a type conversion.</p>

<pre>

    Input_Data  : External_Arr;
    Work_Data   : Arr;
    Output_Data : External_Arr;

    (read data into Input_Data)

    <EM>&#45;&#45;  Now convert to internal form
    Work_Data := Arr (Input_Data);

    (computations using efficient Work_Data form)

    &#8212;  Convert back to external form
    Output_Data := External_Arr (Work_Data);</EM>
</pre>


<p>Using this approach, the quite complex task of copying all
the data of the array from one form to another, with all the
necessary masking and shift operations, is completely automatic.</p>



<p>Similar code can be used in the record and enumeration type
cases. It is even possible to specify two different
representations for the two types, and convert from one
form to the other, as in:</p>

<pre>

   <b>type</b> Status_In <b>is</b> (Off, On, Unknown);
   <b>type</b> Status_Out <b>is</b> <b>new</b> Status_In;

   <b>for</b> Status_In <b>use</b> (Off =&gt; 2#001#, On =&gt; 2#010#, Unknown =&gt; 2#100#);
   <b>for</b> Status_Out <b>use</b> (Off =&gt; 103, On =&gt; 1045, Unknown =&gt; 7700);
</pre>


<p>There are two restrictions that must be kept in mind when
using this feature. First, you have to use a derived type.
You can&#8217;t put representation clauses on subtypes, which
means that the conversion must always be explicit. Second,
there is a rule RM 13.1(10) that restricts the placement
of interesting representation clauses:</p>
  
<p><blockquote>10    For an untagged derived type, no type-related
  representation items are allowed if the parent type
  is a by-reference type, or has any user-defined
  primitive subprograms.</blockquote></p>


<p>All the representation clauses that are interesting from the
point of view of change of representation are &#8220;type related&#8221;,
so for example, the following sequence would be illegal:</p>

<pre>

   <b>type</b> Val <b>is</b> (A,B,C,D,E,F,G,H);
   <b>type</b> Arr <b>is</b> <b>array</b> (1 .. 16) <b>of</b> Val;

   <b>procedure</b> Rearrange (Arg : in out Arr);

   <b>type</b> External_Arr <b>is</b> <b>new</b> Arr;
   <b>for</b> External_Arr&apos;Component_Size <b>use</b> 3;
</pre>


<p>Why these restrictions? Well the answer is a little
complex, and has to do with efficiency considerations,
which we will address in next week&#8217;s GEM.
</p>
]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2008/03/03/gem-27/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Gem #26: The Mod Attribute</title>
		<link>http://www2.adacore.com/2008/02/25/gem-26/</link>
		<comments>http://www2.adacore.com/2008/02/25/gem-26/#comments</comments>
		<pubDate>Mon, 25 Feb 2008 10:00:14 +0000</pubDate>
		<dc:creator>AdaCore</dc:creator>
		
		<category>Development Log</category>

		<category>Ada / Ada 2005</category>

		<category>Devt log - Gem of the Week</category>

		<guid isPermaLink="false">http://www2.adacore.com/2008/02/25/gem-26/</guid>
		<description><![CDATA[Ada Gem #26 &#8212; T'Mod can be used to convert signed integers to modular integers using modular (wraparound) arithmetic.
]]></description>
			<content:encoded><![CDATA[<h3>Let&#8217;s get started&#8230;</h3>

<p>Ada has two kinds of integer type: signed and modular:</p>

<pre>
    <b>type</b> Signed_Integer <b>is</b> <b>range</b> 1..1_000_000;
    <b>type</b> Modular <b>is</b> <b>mod</b> 2**32;
</pre>

<p>Operations on signed integers can overflow: if the result is outside the base range, <code>Constraint_Error</code> will be raised.  The base range of <code>Signed_Integer</code> is the range of <code>Signed_Integer'Base</code>, which is chosen by the compiler, but is likely to be something like <code>-2**31..2**31-1</code>.</p>

<p>Operations on modular integers use modular (wraparound) arithmetic.</p>

<p>For example:</p>

<pre>
      X : Modular := 1;
      X := - X;
</pre>

<p>Negating X gives -1, which wraps around to <code>2**32-1</code>, i.e. all-one-bits.</p>

<p>But what about a type conversion from signed to modular?  Is that a signed operation (so it should overflow) or is it a modular operation (so it should wrap around)?  The answer in Ada is the former &#8212; that is, if you try to convert, say, <code>Integer'(-1)</code> to Modular, you will get <code>Constraint_Error</code>:</p>

<pre>
      I : Integer := -1;
      X := Modular (I);  <i>&#8211;  raises Constraint_Error</i>
</pre>

<p>In Ada 95, the only way to do that conversion is to use <code>Unchecked_Conversion</code>, which is somewhat uncomfortable.  Furthermore, if you&#8217;re trying to convert to a generic formal modular type, how do you know what size of signed integer type to use?  Note that <code>Unchecked_Conversion</code> might malfunction if the source and target types are of different sizes.</p>

<p>A small feature added to Ada 2005 solves the problem: the <code>Mod</code> attribute:</p>

<pre>
    <b>generic</b>
       <b>type</b> Formal_Modular <b>is</b> <b>mod</b> &lt;&gt;;
    <b>package</b> Mod_Attribute <b>is</b>
       <b>function</b> F <b>return</b> Formal_Modular;
    <b>end</b> Mod_Attribute;

    <b>package</b> <b>body</b> Mod_Attribute <b>is</b>

       A_Signed_Integer : Integer := -1;

       <b>function</b> F <b>return</b> Formal_Modular <b>is</b>
       <b>begin</b>
          <b>return</b> Formal_Modular&#8217;Mod (A_Signed_Integer);
       <b>end</b> F;

    <b>end</b> Mod_Attribute;</pre>

<p>The <code>Mod</code> attribute will correctly convert from any integer type to a given modular type, using wraparound semantics.  Thus, F will return the all-ones bit pattern, for whatever modular type is passed to <code>Formal_Modular</code>.</p>

<h3>Related Source Code</h3>

<p>Ada Gems example files are distributed by AdaCore and may be used or modified for any purpose without restrictions.</p>]]></content:encoded>
			<wfw:commentRss>http://www2.adacore.com/2008/02/25/gem-26/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
