Ada FAQ: Programming with Ada (part 3 of 3)

4 views
Skip to first unread message

Magnus Kempe

unread,
Oct 26, 1995, 3:00:00 AM10/26/95
to
Archive-name: computer-lang/Ada/programming/part3
Comp-lang-ada-archive-name: programming/part3
Posting-Frequency: monthly
Last-modified: 19 August 1995
Last-posted: 19 August 1995

Ada Programmer's
Frequently Asked Questions (FAQ)

IMPORTANT NOTE: No FAQ can substitute for real teaching and
documentation. There is an annotated list of Ada books in the
companion comp.lang.ada FAQ.

Recent changes to this FAQ are listed in the first section after the table
of contents. This document is under explicit copyright.

This is part 3 of a 3-part posting.
Part 2 begins with question 5.5.
Parts 1 and 2 should be the previous postings in this thread.


8.3: Should I stick to a one package, one type approach while writing Ada
software?

(Robb Nebbe responds)

Offhand I can think of a couple of advantages arising from Ada's
separation of the concepts of type and module.

Separation of visibility and inheritance allows a programmer to
isolate a derived type from the implementation details of its parent.
To put it another way information hiding becomes a design decision
instead of a decision that the programming language has already made
for you.

Another advantage that came "for free" is the distinction between
subtyping and implementation inheritance. Since modules and types are
independent concepts the interaction of the facilities for information
hiding already present in Ada83 with inheritance provide an elegant
solution to separating subtyping from implementation inheritance. (In
my opinion more elegant than providing multiple forms of inheritance
or two distinct language constructs.)


8.4: What is the "Beaujolais Effect"?

The "Beaujolais Effect" is detrimental, and language designers should
try to avoid it. But what is it?

(from Tucker Taft)

The term "Beaujolais Effect" comes from a prize (a bottle of
Beaujolais) offered by Jean Ichbiah during the original Ada design
process to anyone who could find a situation where adding or removing
a single "use" clause could change a program from one legal
interpretation to a different legal interpretation. (Or equivalently,
adding or removing a single declaration from a "use"d package.)

At least one bottle was awarded, and if the offer was still open, a
few more might have been awarded during the Ada 9X process. However,
thanks to some very nice analysis by the Ada 9X Language Precision
Team (based at Odyssey Research Associates) we were able to identify
the remaining cases of this effect in Ada 83, and remove them as part
of the 9X process.

The existing cases in Ada 83 had to do with implicit conversion of
expressions of a universal type to a non-universal type. The rules in
Ada 9X are subtly different, making any case that used to result in a
Beaujolais effect in Ada 83, illegal (due to ambiguity) in Ada 9X.

The Beaujolais effect is considered "harmful" because it is expected
that during maintenance, declarations may be added or removed from
packages without being able to do an exhaustive search for all places
where the package is "use"d. If there were situations in the language
which resulted in Beaujolais effects, then certain kinds of changes in
"use"d packages might have mysterious effects in unexpected places.

(from Jean D. Ichbiah)

It is worth pointing that many popular languages have Beaujolais
effect: e.g. the Borland Pascal "uses" clause, which takes an
additive, layer-after-layer, interpretation of what you see in the
used packages (units) definitely exhibits a Beaujolais effect.

Last time I looked at C++, my impression was that several years of
Beaujolais vintage productions would be required.

For component-based software development, such effects are undesirable
since your application may stop working when you recompile it with the
new -- supposedly improved -- version of a component.


8.5: What about the "Ripple Effect"?

(Tucker Taft explains)

We have eliminated all remnants of the Beaujolais Effect, but we did
debate various instances of the "Ripple" effect during the language
revision process (apologies to Gallo Ripple Wine enthusiasts ;-).

In brief, the (undesirable) Ripple effect was related to whether the
legality of a compilation unit could be affected by adding or removing
an otherwise unneeded "with" clause on some compilation unit on which
the unit depended, directly or indirectly.

This issue came up at least twice. One when we were considering rules
relating to use of attributes like 'Address. In Ada 83 as interpreted
by the ARG, if a compilation unit contains a use of 'Address, then
there must be a "with" of package System somewhere in the set of
library unit specs "with"ed by the compilation unit (directly or
indirectly).

In Ada 9X, we have eliminated this rule, as it was for some compilers
an unnecessary implementation burden, and didn't really provide any
value to the user (if anything, it created some confusion). The rule
now is that the use of an attibute that returns a value of some
particular type makes the compilation unit semantically dependent on
the library unit in which the type is declared (whether or not it is
"with"ed).

The second place the Ripple effect came up was when we were trying to
provide automatic direct visibility to (primitive) operators.
Ultimately we ended up with an explicit "use type" clause for making
operators directly visible. For a while we considered various rules
that would make all primitive operators directly visible; some of the
rules considered created the undesirable "Ripple" effects; others
created annoying incompatibilities; all were quite tricky to implement
correctly and efficiently.


8.6: How to write an Ada program to compute when one has had too much alcohol
to legally drive?

Someone asked if there is an Ada archive of this sort of program. Each
drink has a number of units of alcohol, max legal level, etc.

(from Bob Kitzberger :-)

Oh, this is much to vague. Don't touch that whizzy development
environment until you fully analyze the problem domain (unless that
whizzy development environment includes Rose, in which case, you get
to avoid paper and pencil from the git-go).

Let's see, we have several classes to describe before we get to the
implementation:

Person
subclass Drinker

attributes: weight, age, timeline for amount consumed

Drink
attributes: percentage of alcohol, quantity of drink

Country
attributes: legal age to drink; max legal level of alcohol in
blood


Turn on the stereo, perhaps the Brandenburg Concertos. Then, flesh out
the domain classes. Then, have a Belgian beer and consider what to do
next. You decide on implementing these classes in a simple way,
leading to your first successful prototype. Then, have another beer
and decide what to do next. "Identify risk areas" you mutter to
yourself, and off you go...

If the beer wasn't too strong, you'd probably realize that the only
thing of any difficulty in this is the amount consumed / rate of
decay. Decide on investigating this aspect further. Create
implementation classes for this and include a reference from the
Drinker class to this new timeline/decay Class. Have another beer.
Implement your second prototype. Congratulate yourself for making
progress so quickly.

Have another beer. Wander over to the stereo and change the CD to
something more in the mood, maybe some Hendrix or Stevie Ray Vaughn.
Back in front of the computer; pop another beer. Decide that it would
be very cool if each drink was its own subclass of drink, and start
cataloguing every drink out of your "Pocket Bartender's Guide". Have a
slightly muddled epiphany that you really should create a class for
each kind of alcohol (vodka, tequila, etc.) and the individual drink
classes should each multiply inherit from all relevant Alcohol
classes. Ooh, this is going to be a bit rough, so you have another
beer. Draw a few of the hundreds of new class relationships needed,
put that on the back burner when you think "persistence! that's what's
missing!" Change the CD to Kraftwerk. Start your PPP connection, ask
the people on comp.object for recommendations on a good OODBMS to use
to keep track of all of those persistent objects. Make many many typos
in your posting; everyone ignores it. Fall asleep on the keyboard.


8.7: Does Ada have macros?

No, neither Ada 83 nor Ada 95 do. There was a Steelman requirement
that the language developed NOT have a macro capability. This was a
well thought-out requirement. What you see in a piece of Ada code is
what you get (within a debugger for example). This does not hold true
for macro languages.

General text-substitution macros like those in the C preprocessor are
thought to be too unsafe. For example, a macro can refer to a variable
X and depending where the macro is expanded X may or may not be
visible. Ada programs are supposed to be readable and in many cases C
macros are the main culprits in producing unreadable C programs.

Compile time macro facilities tend to be dreadfully over- and misused,
resulting in horrible maintenance problems. Furthermore, there is a
tendency to use macros to patch up glaring omissions in the language.
For example, C has no named constants, a very bad omission, but
#define is used to patch over this gap.

In C, three "legitimate" uses of macros are for defining compile-time
constants, types, and inline functions. Ada has all three of these
facilities, without macros.

If one wants macros to handle conditional compilation, the better way
to achieve the equivalent is in most instances to isolate the system
dependent parts and then put them in separate units with multiple
system-specific implementations.

_________________________________________________________________


9: Ada and Other Programming Languages


9.1: Where can I find programs that will translate from [some language] to
Ada?

It is generally advisable to simply interface from Ada to the
existing code segments that (should) already work. Note that Ada (95)
now has an annex devoted to specifying how to interface with code
written in other programming languages (C, Fotran, and Cobol), and
there are already interfaces to C++ too.

Another option is to redesign the code, taking of course advantage of
one's knowledge of the current system. For instance, Job Honig
reported that he did this twice, once for Coco, a parser generator for
LALR left attributed grammars, and once for Flex, the well known
scanner generator. Both attempts revealed errors in the original
software; they were uncovered by designing the new system using the
higher abstraction level allowed by Ada...

So there is support for the requirements analysis (transition to Ada),
but it is not obvious that the proposed implementation (using a source
code translator) is a good solution.

Still, you may have compelling reasons to translate your existing
source to Ada. In that case, here is a list of available translators:

* Pascal to Ada:

R.R. Software's Pastran program (Pascal to Ada Translator).

To see the differences in programming style, see "Ada for
Experienced Programmers", by A. Nico Habermann and Dewayne E.
Perry (Addison-Wesley Pub. Co., Reading, Mass., 1983). Covers Ada
and Pascal.

* Fortran to Ada: ???

* COBOL to Ada: ???

* C++ to Ada: ???

* C to Ada: ???

* Modula-2 to Ada:

(from Wayne R. Lawton)
The Idaho National Engineering Laboratory (INEL), a Dept of Energy
Lab has a basic capability for Modula-2 to Ada-83. The tool is
"research grade" quality, but may provide a starting point for
what you need. This is the same group of people who brought you
AdaSAGE. Give them a ring at (208) 526-0656. This is an answer
desk hotline in the section that wrote the tool.

If you are looking for commercial quality, I wish you the best of
luck. If you just need something to perform 80% of the grunt code
translation, I think this might meet your needs. I know of two
systems comprising about 250,000 lines of code that were
originally developed in Modula-2 then translated and cleaned up in
Ada 83 after Alsys 1.0 for the PC came out back around 1987.

* Visual Basic to Ada: NOT! :-)


9.2: How can I convert Ada 83 sources to Ada 9X?

First you should read the following document, which will provide you
with much useful information: "Changes to Ada -- 1987 to 1995", file
ch83.{ps,doc}, in directory
ftp://sw-eng.falls-church.va.us/public/AdaIC/standards/95lrm_rat/v6.0


If you're using GNAT, the tool you are probably looking for is
"gnatchop". In csh you could use something like this to quickly
process existing files:

cd dest_dir # The destination directory
foreach f ( ../src_dir/*.a ) # ../src_dir is the source directory
gnatchop $f
end

gnatchop will show you what sources are causing problems.


9.3: I hear that Ada is slower than Fortran or C, is that true?

First, note that you are comparing compilers, not languages. There is
no such thing as "fast" Ada code any more than there is "fast" C++ or
Fortran code. Now, when comparing execution speeds on similar
platforms, you must keep in mind the optimization levels, OS tuning,
etc. while making the comparisons. The bottom line is that
benchmarking, especially between two different languages, requires
_very_ careful measurement. In general, such results should be viewed
with caution.

(A message from Bevin Brett of DEC)

I have been asked to comment on the relative performance of algorithms
coded in Ada and in Fortran.

This question has come up repeatedly over the years, and deserves a
complete answer, rather than a simplistic one.

There are many factors which influence the size and execution speed of
the running program, and they all play together to get a full answer.
I shall then discuss an exact Ada v. Fortran comparison that Digital
was involved in.

First, a position statement: The variation between Ada and Fortran is
less than the variation within the language caused by the exact
implementation details. A person versed in the Ada issues should do as
well in Ada as a person versed in the Fortran issues will do in
Fortran. The size and execution speed of the result should be within a
few percent of each other.

(a) Differences due to the compiler

In the case of the DEC Ada and Fortran compilers, the optimizer and
code generator are the same. Never-the-less, the exact inputs into
the optimizer and code generator may differ slightly when the same
algorithm is compiled by the Ada and Fortran compilers, and this
can result in major differences in the generated code. In these
cases the compiler front ends can usually be modified to correct
the slower one.

We have not observed any major differences in generated code
quality between the DEC Ada and DEC Fortran compilers caused by
such issues.


(b) Differences due to the language

It is very important that the same algorithm be written in the two
languages. The biggest differences we have observed are
1. Having the wrong dimension varying fastest, since it is
desireable to have the first dimension changing fastest in
Fortran, and the last dimension in Ada. Thus when an
algorithm is transliterated, the array indexes must be
reversed.

2. Using compile-time-known bounds for arrays in Fortran, and
using unconstrained arrays in the Ada code. Knowing the exact
values of the dimensions at compile-time results in much
better code.

3. Not suppressing all the runtime checks in Ada. The Fortran
compiler assumes all array bounds are in range, and all
arithmetic operations do not overflow. You must use a pragma
Suppress to tell this to the Ada compiler as well.

4. Don't use arrays of Ada Booleans to match arrays of Fortran
Integers, because accessing bytes on a RISC system might be
much worse than accessing fullwords.


(c) Differences due to the bindings

The biggest bindings differences are related to Fortran's built-in
support for complex types, and for various math routines such as
SQRT and SIN, compared with Ada code that often uses hand-coded or
ISO standardised versions of these functions with different
requirements than are imposed on the Fortran versions.

DEC Ada has built-in support for complex types, and also has
bindings directly to the same primitives that Fortran uses for its
math routines and so gets the same performance as Fortran does.


(d) Differences due to the author

The use of good Ada and Fortran style can also effect the generated
code. Provided the author writes in good Ada style, and follows
the above guidelines, the generated code should do as well as
Fortran.


The Ada Performance Benchmark

A DEC Ada customer had a Fortran benchmark that had been translated
into Ada without awareness of the above issues, and was running
substantially slower with DEC Ada than the original was with DEC
Fortran.

Bevin Brett, a DEC Ada team member, developed the above guidelines in
the process of retranslating the code into Ada.

Portions of this translation are shown here (a) as an illustration of
the application of the above rules, and (b) as an illustration of the
kind of operations that were present in the benchmark.

The whole benchmark has not been provided to avoid possible issues of
ownership.

The resulting Ada benchmark components each ran within a few percent
of their Fortran counterparts. The Ada code is available by FTP, in
file ftp://lglftp.epfl.ch/pub/Ada/FAQ/ada-vs-fortran.ada


9.4: Isn't Ada less "elegant" than Eiffel?

While it is true that programming-language support for "assertions"
is an important contribution of Eiffel to software construction, this
is not an issue of "elegance", and there are many other important
factors to consider.

Note also that preconditions and postconditions can be fairly easily
and efficiently included in Ada code. Invariants seem difficult to
emulate directly in Ada. If you're really interested in the formal use
of assertions with Ada, maybe Anna is a solution for you.

(Tucker Taft comments)

I guess one thing that bothers me a little is that people are quick to
say that Eiffel is "elegant" without really looking at it. I fear that
such statements will become self-fulfilling prophecies, with those
programmers interested in elegance migrating over to Eiffel rather
than sticking with Ada.

In particular, although I like the assertion stuff in Eiffel, I think
the language has a number of "inelegant" aspects. For example:

1. exception handlers only at the top level of a routine, with the
only way to "handle" an exception being by retrying the whole
routine.

2. No way to return from a routine in the middle. This makes it a
pain in the neck to search through a list for something in a loop,
and then return immediately when you find what you want. (I have
never found the addition of extra boolean control variable a help
to the understanding of an algorithm.)

3. Namespace control handled by a separate sublanguage, and no real
higher level concept of "module" or "subsystem."

4. An obscure notation like "!!" being used for an important and
frequent operation (construction).

5. No way to conveniently "use" another abstraction without
inheriting from it.

6. No strong distinctions between integer types used for array
indexing.

7. Using the same operator ":=" for both (aliasing) pointer
assignment, and for value assignment, depending on whether the
type is "expanded." (Simula's solution was far preferable, IMHO).

And most critically:


8. No separate interface for an abstraction. You can view a interface
by running a tool, but this misses completely the importance of
having a physical module that represents the interface, and acts
as a contract between the specifier or user of an abstraction and
its implementor. In Eiffel, one might not even be truly aware when
one is changing the interface to an abstraction, because there is
no particular physical separation between interface and
implementation.


I consider many of the above problems quite serious, with some of them
being real throwbacks to the old style of programming languages where
there were no well defined interfaces or modules.

Hence, I cringe a bit when people say that Eiffel is the "most
elegant" OOP and that they would use it if only it were practical to
do so. In many ways, I think Ada is much better human-engineered than
Eiffel, with important things like range constraints built into the
language in a way that makes them convenient to use. Although general
assertions are nice, they don't give you the kind of line-by-line
consistency checks that Ada can give you.

To summarize --
Although Eiffel certainly has a number of nice features, I don't
consider it ready for prime time as far as building and maintaining
large systems with large numbers of programmers. And from a human
engineering point of view, I think Ada is significantly better.


9.5: Are there any papers detailing the differences between Ada and C++?

Below are two references. Bear in mind that it is difficult to make
such a comparison without exposing biases. However, the two papers
below are well worth reading.

"A Comparison of the OO features of Ada9x and C++" in Springer Lecture
Notes in CS: "Ada Europe 93" pp.125-141 (short paper, good reading,
enlightens idioms)

ftp ajpo.sei.cmu.edu in directory: /public/ada9x, document:
9x_cplus.hlp


9.6: I keep hearing that Ada is a "strongly typed language", but it seems
different from what's meant in C++. Are they different?

(Tucker Taft responds)

I certainly agree that ANSI C and C++ are statically typed languages,
but I would debate the "strength" of their typing.

Essentially any support for implicit conversion (implicit "casting,"
"promotion", "usual" arithmetic conversions, etc.) "weakens" a type
system (but also makes it "friendlier" in some ways).

C allows implicit conversion between all integer types and all
enumeration types. C++ at least cuts off implicit conversion to
enumeration types, but retains implicit conversion among all integer
(and floating-point) types. Also, in both C and C++, typedefs for
pointer/array types are essentially "macros"; all pointer types with
the same target type are implicitly interconvertible.

Finally C++ allows the user to define a number of their own implicit
conversion operators, which basically allows the user to "weaken" the
type system as they see fit.

Of course, all of this implicit conversion serves a purpose, but it
does tend to move C/C++ toward the "weaker" end of the weak vs. strong
typing spectrum.

Note that the "strong" distinctions between integer types helps
dramatically in catching (at compile-time) array indexing errors in
Ada programs, by making sure that if you have an array indexed by a
count of apples, you don't index into it with a count of oranges
(without an *explicit* conversion). The advantages of "strongly"
distinguishing enumeration types is even more obvious (and the
designers of C++ recognized this).

The strong distinctions between access types (pointer types) in Ada
also has advantages, allowing access types to be represented as
offsets within their storage pool rather than as addresses, and giving
more high-level control over storage management.

Strong typing can be carried too far, and some amount of implicit
conversion is essential to make OOP palatable. But note that in Ada
9X, even with OOP, we don't allow implicit conversions that truncate
the extension part of a record (this is a relatively common mistake in
C++ when passing parameters by value). Instead, in Ada 9X, the
language distinguishes between a specific type T and the class-wide
type T'Class, and allows implicit conversions to T'Class from T or any
of its derivatives, but not to the specific type T. Conversions to the
class-wide type never implicitly truncate the extension part.
Conversions to a specific type can truncate, and hence must be
explicit.

Note also that in Ada there are three distinct kinds of conversions,
implicit ones, explicit ones, and unchecked ones. Only the unchecked
ones are potentially unsafe. The explicit ones are safe, with either
compile-time or run-time checks to ensure that. In C there are only
implicit and explicit/unchecked conversions. C++ has recently added a
checked, explicit "dynamic" cast, but still it will be common to use
"normal" explicit casts for both checked and unchecked conversions,
thereby making it more difficult to identify places where the type
system might be compromised.

Hence, the bottom line is that the type checking is (objectively)
"stronger" in Ada than C/C++, though that doesn't necessarily mean
"better" -- whether one is "better" for a particular style of
programming than the other is a "religious" issue IMHO. I know my
religion currently favors the stronger checking of Ada in most cases
[except perhaps for multiply/divide, where I personally believe the
checking should either be weaker, or directly support the concept of
"units"/"dimensions"].


9.7: I'm told Ada does all sorts of static type checking, but can't you get
the same effect using a tool like "lint" with C?

No, here are a few reasons why (this list is by no means complete):

(Submitted by Norm Cohen)
* Running both Lint and a C compiler requires the program text to be
parsed and semantically analyzed twice. The results of an Ada
compiler's parse and semantic analysis are used directly in
performing consistency checks.

* The rules of Ada provide the opportunity for stronger consistency
checks than are possible with C. For example, an Ada programmer
can declare distinct integer types to represent distinct
abstractions. An Ada compiler will catch an inadvertent
intermixing of these two types, but there is no way a
corresponding distinction can be made in C, so there is no way for
Lint to perform a corresponding check. Similarly, in C, a pointer
to an object of type T is indistinguishable from an array of
objects of type T.

* The rules of the Ada language ensure that the program text
provides information allowing PRECISE consistency checks. For
example, the expression in an Ada case statement can be written to
have a static subtype, allowing the compiler to ascertain that all
possible values have been covered without resorting to a default
(when others) arm.

* With lack of precise information, Lint has no choice but to be
overly pessimistic or, with different settings for a complicated
set of options, overly optimistic. When it is overly pessimistic,
the user sees too many "false alarms" and may end up ignoring
valid warnings. When it is overly optimistic, Lint overlooks
certain errors.

* It is impossible to forget to run consistency checks when using an
Ada compiler. (Of course a C programming environment could be set
up so that the C compiler could only be invoked from a script that
also invokes Lint.)

* A compilation that fails Ada consistency checks is rejected. A
compilation that fails Lint consistency checks may still be
compiled, and its object file used (intentionally or accidently)
in building the system. (One cannot automate the rejection of
programs that fail Lint unless one is certain that there will
never be any false warnings.)

* Ada enforces consistency among separately compiled units.


Of course even stronger arguments can be made about Ada's RUN-TIME
checks (which can be used with little additional overhead because the
information contained in an Ada program and the knowledge that the
program has passed compile-time consistency checks make it possible to
optimize away the majority of the checks). These checks, which are
absent in C, tend to smoke out errors early by detecting internal
inconsistencies that might not otherwise be detected during testing.
This reduces the likelihood of fielding a system that appears to work
well during testing but fails in operational use.


9.8: Does Ada have something like the Standard Template Library (STL) in C++,
or components like you find in Smalltalk environments?

Yes, in various ways.

Few components are part of the ISO standard. Ada 95 has an expanded
set of predefined library units, covering e.g. strings of varying- or
dynamic-length, elementary numerical functions, random number
generators, complex numbers, and more; in addition, the Special Needs
Annexes standardize many advanced services which have commonly been
provided by separate components in the past.

A lot of free Ada software components are available from anonymous FTP
sites. There is also an upcoming release of the Booch Components for
Ada 95 under the GNU Library General Public License (LGPL); this will
give you the ability to freely include the library components in your
application without any cost or obligation. (Contact
dwe...@neosoft.com for more details.)

What about STL and the Smalltalk library?

The C++ STL doesn't contain much. Really. Breaking its source code
down, it contains less than 3000 semicolons (~7000 total lines). The
entire library exists in C++ header files as inlineable code
(supposedly within a few percent of the efficiency of hand-optimized
code).

STL class hierarchy

bool, heap -- of course Ada does not need a bool class!
\ function, pair, stack
\ iterator, tempbuf, projection
\ algobase
\ algorithms, bitvector, deque, list, tree, vector
\ map, multimap, set, multiset


The main author of the library, Alexander Stepanov, created the Ada
Generic Library in the 1980's -- and later borrowed from this to
create STL. (There is an interview with Stepanov in the March 1995
issue of Dr. Dobb's Journal -- in the C Programming column beginning
on page 115. Stepanov explains that these components were first done
in Ada.)

The Smalltalk library is quite eclectic. It covers everything from
Boolean to bitmaps, dictionaries and other collections. Parts of it
have direct equivalents in Ada 95, parts are already available in
components from anonymous FTP sites and/or will be in the Booch Ada 95
components, and other parts are available from commercial Ada
component suppliers.


9.9: Where can I find the equivalent of "printf" in Ada?

While the standard package Text_IO provides many features, the
request for a printf-like function is not unusual.

(solution based on a suggestion by Tucker Taft)

It is possible to produce a printf-like capability by overloading the
"&" operator to take an object of type Format and an object of some
type and return the Format, properly advanced, after having performed
the appropriate output. The remaining format can be converted back to
a string--e.g. to examine what is left at the end of the format
string-- or simply printed to display whatever remains at the end. For
example:

with Text_IO;
package Formatted_Output is
type Format is
limited private;

function Fmt (Str : String)
return Format;

function "&" (Left : Format; Right : Integer)
return Format;
function "&" (Left : Format; Right : Float)
return Format;
function "&" (Left : Format; Right : String)
return Format;
... -- other overloadings of "&"

procedure Print (Fmt : Format);

function To_String (Fmt : Format)
return String;

private
...
end Formatted_Output;

with Formatted_Output; use Formatted_Output;
procedure Test is
X, Y : Float;
begin
Print (Fmt("%d * %d = %d\n") & X & Y & X*Y);
end Test;

The private part and body of Formatted_Output are left as an exercise
for the reader ;-).

A "File : File_Type" parameter could be added to an overloading of Fmt
if desired (to create something analogous to fprintf).

This capability is analogous to that provided by the "<<" stream
operator of C++.

_________________________________________________________________


10: Interfacing with Ada


10.1: I am writing software that used the Distributed Interactive Simulation
(DIS) interface, does an interface exist in Ada?

Yes. DIS is a standard for communications between simulators using an
Internet Protocol network (IP). DIS provides a unified virtual
environment for multiple simulator users on a network. It is used
mostly in the DoD simulations business, but it is applicable to ANY
simulation. It is an industry initiative involving military training
and procurement organisations, simulator vendors and universities
mostly in the US, but the technology is unclassified.

The US Army is funding quite a bit of DIS research and development.
The Institute of Simulation and Training, URL
http://www.tiig.ist.ucf.edu/ is a center at the University of Central
Florida (UCF) which serves as the support contractor for the UCF IST,
as are BBS's for the DIS working groups who are attempting to push
those standards forward. The BBS contains an Ada binding for DIS.

Note that the above provides a thin binding to C code. It may be
worthwhile to take the time to make high level DIS bindings. Someone
reports having done it in over 2 man-months using an experienced Ada
engineer, and that it was well worth it. Many bugs were found in the C
DIS code of the machine they were networked with. "A strongly-typed
interface is the network programmer's best friend."

At TRI-Ada'94 there was a demonstration by Coleman Research
Corporation (CRC); here's their short pitch: "CRC presents Ada
VR-Link, the first commercially available DIS NIV. It provides all of
the facilities necessary to jump start your DIS compliant simulation
development efforts. For more information call (205) 922-6000."

Also, the AJPO sponsored an Ada Technology Insertion Program (ATIP)
relating to this: FY93 ATIP project 17, titled "Ada Distributed
Interactive Simulation (ADIS)". Available from directory
ftp://sw-eng.falls-church.va.us/public/AdaIC/source-code/bindings
/ADIS-bindings
The Ada Distributed Interactive Simulation (ADIS)
provides an Ada interface to the IEEE 1278 Distributed Interactive
Simulation (DIS) protocols. The project was developed in Ada 83
(MIL-STD-1815), on Silicon Graphics Indigo R4000 machines using Verdix
Ada 6.2.1 under the IRIX operating system, version 5.2. The Graphical
User Interfaces (GUIs) were developed for X Window version X11R5 using
Motif 1.2.

There are several sources of information available on DIS itself. The
IEEE version of the DIS standard is available through (and only
through) the IEEE (std IEEE 1278). Draft versions of the standard are
available from the Institute for Simulation and Training at the
University of Central Florida. They take orders at (407) 855-0881, and
questions (about ordering) at (407) 658-5054.


10.2: Is there any support for Common Object Request Broker Architecture
(CORBA) for Ada 9X?

OC Systems sells a CORBA Ada product; it is "Standard equipment" with
their PowerAda compiler. Rational, and OIS are also planning on
selling CORBA products for Ada.

Objective Interface Systems, Inc. (OIS), MITRE, and DISA have been
working on a mapping from CORBA IDL to Ada 95 for about six months.
Bill Beckwith (Bill.B...@ois.com) will send a recent copy of the
mapping document to any interested parties.

Note that CORBA IDL to Ada 95 mapping specifies a mapping, not a
binding. This will put Ada 95 on equal footing with the C++ and
Smalltalk products. (except that, of course, the Ada mapping is
cleaner ;-).

_________________________________________________________________

11: Finding Additional Information

11.1: Where can I find Ada books?

Look at the companion comp.lang.ada FAQ or the HBAP WWW Server, URL
http://lglwww.epfl.ch/Ada/

Michael Feldman maintains the "Annotated Sampling of Ada-Oriented
Textbooks"; if you don't have access to WWW, drop him a note at
mfel...@seas.gwu.edu


11.2: Are there other Ada-related FAQs?

Yes. They all appear in comp.lang.ada at regular intervals:
comp.lang.ada FAQ, public Ada library FAQ, and Ada WWW server FAQ. All
these are permanently available in hypertext format from the HBAP WWW
Server (see below) and in ASCII format from
ftp://lglftp.epfl.ch/Ada/FAQ


11.3: What is the "HBAP WWW Server"?

The Home of the Brave Ada Programmers (HBAP) WWW Server is alive and
heavily used. It is a hypertext, multimedia information server for the
Ada programming language.

The URL of the HBAP WWW Server is

http://lglwww.epfl.ch/Ada/

[don't forget the trailing '/'.]

The HBAP WWW Server provides Ada-related information and hypertext
access in areas including:
* Historical notes on Ada
* References
* Ada FAQs
* State of Ada 9X revision process
* Standards
* Bindings
* Tools and Components
* Intellectual Ammunition
* Introductory Material
* Resources
* CS Technical Reports
* FTP and WWW Sites--including mirror sites
* Calendar of Ada-related events
* Ada Today
* Frequently Asked Questions--with Answers (from comp.lang.ada)


For instance, you will find a list of schools using Ada in CS1 or CS2,
an article on commercial success stories, information about software
components, as well as hypertext versions of the Ada reference manual
(both 83 and draft 9X).

The HBAP WWW Server keeps growing. All comments, ideas, and requests
for additions or corrections, are welcome (e-mail to
Magnus...@di.epfl.ch).

_________________________________________________________________


12: Pretty-printing and Measuring Ada Source Code


12.1: Is there software that generates a pretty PostScript file from Ada
source code?

Pretty Ada code in PostScript means that e.g. reserved words are in
bold and comments are in italics. This is a separate issue from
re-formatting and automatic indenting.

If you use the new Ada Mode for GNU Emacs (available from
ftp://cs.nyu.edu/pub/gnat), go and get the package ps-print.el from
any emacs archive (e.g. in directory
ftp://archive.cis.ohio-state.edu/pub/gnu/emacs/elisp-archive). With
this package you can print your code as you see it on the screen, say
with bold keywords and italic comments.

Another possibility is to feed the source to "vgrind" (see below),
then pipe the result through "pscat" (to get PostScript) or "lpr -t"
(to print), e.g.:

vgrind -d <vgrind_defs_file> -lada -o1- -t -w $* | lpr -t


12.2: I use vgrind to do "pretty printing" of my source. Is there a vgrind
definition for Ada?


# Ada!
ada|Ada:\
:pb=(^\d?(procedure|function|package|package body))\d\p:\
:bb=if|case|begin|loop:be=end:\
:cb=--:ce=$:\
:sb=":se=":\
:lb=':le=':\
:id=_.:\
:oc:\
:kw=abort abs abstract accept access aliased all and array at\
begin body case constant declare delay delta digits do else\
elsif end entry exception exit for function generic goto if in is\
limited loop mod new not null of or others out package pragma\
private procedure protected raise range record rem renames requeue\
return reverse select separate subtype tagged task terminate then\
type until use when while with xor:


Note that the above has a problem with attributes, because the "lb"
and "le" terms make two-attributes-20-lines-apart look like one
"string literal." Ada 95 keywords are recognized.

Here is another definition, which "fixes" this problem (not perfect,
but probably better). Only Ada 83 keywords are recognized.

# In order to get the ticks to work, we are assuming that there will be
# whitespace before a literal (like '"') and *not* when used for an
# attribute (like 'Length).
# For sb/se, we are ALSO assuming that literals have whitespace before/after.
Ada|ada:\
:pb=^\d?(procedure|function|package|package\dbody)\d\p:\
:bb=begin:be=end:\
:cb=--:ce=$:\
:sb=( |\t|\()":se="( |\t|;|,|\)):\
:lb=(>| |\t)':le='(\)| |\t|;):\
:tl:\
:oc:\
:kw=abort abs accept access all and array at begin body case constant\
declare delay delta digits do else elsif end entry exception exit for\
function generic goto if in is limited loop mod new not null of or\
others out package pragma private procedure raise range record rem\
renames return reverse select separate subtype task terminate then\
type use when while with xor:


12.3: How about a source code reformatter?

If you can run a Perl script (Perl is freely available for almost
every OS in the world), you can use the program aimap, written by Tom
Quiggle of SGI. It can be found (where ???).


12.4: How can I count source lines of code (SLOC)?

Under Unix and many operating systems (apparently even MS-DOS), the
following works well:

wc -l file_name


If you only want to count "statement lines" (lines with semicolons),
use

sed 's/--.*$//' file_name | grep ';' | wc -l


Some versions of grep have a '-c' option to print a count of the
matching lines, but this may not be universal. You can fold the
grepping into the sed command but that's not as readable:

sed -n -e 's/--.*$//' -e '/;/p' file_name | wc -l


Please note that measuring SLOC should be used to indicate an
approximate relationship to the size of other projects, and as such,
provided that there is some uniformity in the form and number of
comments, it does not matter whether comments are counted or not. It
has often been observed that there is a very high correlation between
measurements of SLOC, semicolons, and Halstead bits (there is probably
also a high enough correlation with the number of characters).

With VMS, try the following, which will print out the number of lines
("records") and characters (use ";" instead of "~~~~~" to count lines
with semicolons; note that "records" will match even in comments):

$ search/stat file_name.ada "~~~~~"


12.5: Can I measure other things?

There is ASAP, the Ada Static Analyzer Program, written in Ada and
set up to compile under Dec Ada on a Vax running VMS. Gives SLOC,
McCabe's, and more. It is available via anonymous ftp in directory
ftp://ftp.sei.cmu.edu/pub/dd

_________________________________________________________________


13: Common Confusions


13.1: Wasn't Ada designed by some committee? What kind of a language could you
possibly get from that kind of approach?

(Tucker Taft, the principal designer of Ada 95, responds)

I believe most reviewers of Ada 9X (and Ada 83 for that matter) will
assure you that it was most certainly not designed by committee ;-).

In fact, with respect to MI, the situation was just the opposite.
There were several reviewers who pushed hard for building in a
particular approach to MI. The principle designer (;-) was unconvinced
that the benefits of building in a particular MI approach outweighed
the costs as far as complexity. There was no clear winner to use as a
model in the outside world; even Sather and Eiffel couldn't agree
exactly on how to resolve the intricacies of MI, despite their strong
similarities in other areas.


13.2: I've heard the DoD is dropping all Military standards to reduce costs,
doesn't that mean the mandate to use Ada goes away too?

The following memo explains how that decision affects the Ada
mandate:

OFFICE OF THE SECRETARY OF DEFENSE

Washington, DC 20301-1000

August 26, 1994


MEMORANDUM FOR SECRETARIES OF THE MILITARY DEPARTMENTS
CHAIRMAN OF THE JOINT CHIEFS OF STAFF
UNDER SECRETARY OF DEFENSE (PERSONNEL AND
READINESS)
UNDER SECRETARY OF DEFENSE (POLICY)
COMPTROLLER OF THE DEPARTMENT OF DEFENSE
GENERAL COUNSEL OF THE DEPARTMENT OF DEFENSE
INSPECTOR GENERAL OF THE DEPARTMENT OF DEFENSE
DIRECTOR OF OPERATIONAL TEST AND EVALUATION
DIRECTORS OF THE DEFENSE AGENCIES

SUBJECT: Use of Ada

The purpose of this memorandum is to reiterate the Department
of Defense (DoD) commitment to the use of Ada.

It is DoD policy to use commercial off-the-shelf (COTS)
software whenever it meets our requirements. However, when COTS
software is not available to satisfy requirements and the DoD must
develop unique software to meet its needs, that software must be
written in the Ada programming language in accordance with DoD
Directive 3405.1 and DoD Instruction 5000.2.

Secretary Perry's June 29, 1994 memorandum, "Specification &
Standards -- A New Way of Doing Business," states that military
standards will only be used "as a last resort, with an appropriate
waiver." This direction has caused some confusion regarding the
Ada requirement since most references to Ada cite its MIL-STD
nomenclature, MIL-STD-1815A. Ada is also a Federal Information
Processing Standard (FIPS 119), an American National Standards
Institute (ANSI) standard (ANSI-1815A-1983), and an International
Standards Organization (ISO) standard (ISO 8652-1987). Any of
these alternative references may be utilized in place of the MIL-
STD reference in request for proposals, contracts, and other
similar documents. Thus, the Ada requirement does not conflict
with the Secretary's direction, and compliance with both policies
can be achieved simultaneously.

Use of other programming languages can be considered if
proposed by a contractor as part of his best practices since
waivers to the use of Ada can be granted, where cost-effective, in
accordance with procedures established in the policy referenced
above. However, such proposals require strong justification to
prove that the overall life-cycle cost will be less than the use of
Ada will provide.

Secretary Perry's memorandum encourages practices that satisfy
the Department's need to build high quality systems that meet
requirements at affordable costs an in a timely manner. This
includes practices which support the development of Defense
Software. Ada is not only a facilitator of software engineering
best practice, but also has inherent features which uniquely
support both real-time systems and safety-critical systems. Use of
Ada also facilitates software reuse and has demonstrated reduced
support costs. Accordingly, Ada is a foundation for sound software
engineering practice.

/signed/ /signed/

Noel Longuemare Emmett Paige, Jr.
Under Secretary of Defense Assistant Secretary of Defense
(Acquisition and Technology) (Command, Control,
(Acting) Communications, and
Intelligence)

cc:
DDR&E


_________________________________________________________________


14: Credits

The following persons have contributed (directly or indirectly,
intentionally or unintentionally, through e.g. comp.lang.ada) to the
information gathered in this FAQ: Tucker Taft, Dave Weller,
David Arno, Christine Ausnit, Bill Beckwith, Chip Bennett,
Bevin Brett, G. Vincent Castellano, Norm Cohen, Marin David Condic,
John Cosby, Richard Crutchfield, Theodore E. Dennison, Robert Dewar,
Bob Duff, Robert Eachus, Rolf Ebert, Dave Emery, Mitch Gart,
Jeffrey L. Grover, Laurent Guerby, Richard G. Hash, Matthew Heaney,
Fergus Henderson, Niklas Holsti, Job Honig, Jean D. Ichbiah,
Nasser Kettani, Wayne R. Lawton, Robert Martin, Robb Nebbe,
Jonathan Parker, Isaac Pentinmaki, Bruce Petrick, Paul Pukite,
Richard Riehle, Keith Shillington, David Shochat, Keith Thompson,
Joyce Tokar, Kevin Weise, Fraser Wilson, and the maintainer has simply
:-) organized, polished, or added some information for your
satisfaction. The general HTML structure of this FAQ was inspired by
the WWW FAQ.

_________________________________________________________________

15: Copying this FAQ

This FAQ is Copyright 1994, 1995 by Magnus Kempe. It may be freely
redistributed --as posted by the copyright holder in comp.lang.ada--
in other forums than Usenet News as long as it is completely
unmodified and that no attempt is made to restrict any recipient from
redistributing it on the same terms. It may not be sold or
incorporated into commercial documents without the explicit written
permission of the copyright holder.

Permission is granted for this document to be made available under the
same conditions for file transfer from sites offering unrestricted
file transfer on the Internet and from Forums on e.g. Compuserve and
Bix.

This document is provided as is, without any warranty.

_________________________________________________________________

Magnus Kempe -- Magnus...@di.epfl.ch
--
Magnus Kempe "I know not what course others may take, but as for me,
Magnus...@di.epfl.ch Give me Liberty... or give me Death!" -- Patrick Henry

Reply all
Reply to author
Forward
0 new messages