Search the FAQ Archives

3 - A - B - C - D - E - F - G - H - I - J - K - L - M
N - O - P - Q - R - S - T - U - V - W - X - Y - Z
faqs.org - Internet FAQ Archives

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

( Part1 - Part2 - Part3 - Part4 )
[ Usenet FAQs | Web FAQs | Documents | RFC Index | Houses ]
Archive-name: computer-lang/Ada/programming/part4
Comp-lang-ada-archive-name: programming/part4
Posting-Frequency: monthly
Last-modified: 22 May 1996
Last-posted: 23 April 1996

See reader questions & answers on this topic! - Help others by sharing your knowledge
                               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 4 of a 4-part posting; part 1 contains the table of contents.
Part 2 begins with question 5.
Part 3 begins with question 6.
Parts 1, 2, and 3 should be the previous postings in this thread.


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/


   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/


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 dweller@dfw.net
   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. Ted
   Dennison, dennison@escmail.orl.mmc.com reports having done it (while
   working for what is now Lockheed Martin Simulation Systems) 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/
       /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.Beckwith@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
   mfeldman@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/


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.Kempe@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. aimap is not really a pretty printer, since it only
   changes the case of identifiers and reserved words (according to the
   options set). It can be found at
   http://reality.sgi.com/employees/quiggle_engr/aimap


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: Credits

   The first draft was made by Dave Weller. 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,
   Moti Ben-Ari, Chip Bennett, Bevin Brett, David Bulman,
   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, Victor Giddings,
   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, André Spiegel,
   Keith Thompson, Joyce Tokar, Kevin Weise, David A. Wheeler,
   Fraser Wilson, and the maintainer has simply :-) organized, polished,
   or added some information for your satisfaction. The general HTML
   structure of this FAQ was originally inspired by the (now differently
   structured) WWW FAQ.

     _________________________________________________________________

14: Copying this FAQ

   This FAQ is Copyright © 1994-1996 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.Kempe@di.epfl.ch

User Contributions:

Comment about this article, ask questions, or add new information about this topic:




Part1 - Part2 - Part3 - Part4

[ Usenet FAQs | Web FAQs | Documents | RFC Index ]

Send corrections/additions to the FAQ Maintainer:
Magnus.Kempe@di.epfl.ch (Magnus Kempe)





Last Update March 27 2014 @ 02:11 PM