\input texinfo   @c -*-texinfo-*-
@c %**start of header
@setfilename adacontrol_pm.info
@settitle AdaControl Programmer Manual V1.21r6b
@c %**end of header

@titlepage
@title AdaControl Programmer Manual

@c The following two commands start the copyright page.
@page
@vskip 0pt plus 1filll
@end titlepage

@dircategory GNU Ada tools
@direntry
* AdaControl Programmer's Manual: (adacontrol_pm).  Writing new rules.
@end direntry

@ifnottex
@node Top, General, (dir), (dir)
@top AdaControl Programmer Manual
@end ifnottex

Last edited: @today{}

This is the AdaControl Programmer Manual. It is intended for those who
want to add new rules to AdaControl, or more generally modify (and
presumably improve!) AdaControl. Reading this manual is not necessary
to use AdaControl. On the other hand, it is assumed that the reader
is familiar with how to use AdaControl.

@menu
* General::
* The framework and utilities packages::
* Writing a new rule::
* Plugging-in a new rule into the framework::
* Testing and debugging a rule::
@end menu

Commercial support is available for AdaControl. If you plan to use
AdaControl for industrial projects, or if you want it to be customized
or extended to match your own needs, please contact Adalog at
@uref{mailto::info@@adalog.fr,,info@@adalog.fr}.

AdaControl is Copyright @copyright{} 2005-2019 Eurocontrol/Adalog,
except for some specific modules that are @copyright{} 2006
Belgocontrol/Adalog, @copyright{} 2006 CSEE/Adalog, @copyright{}
2006 SAGEM/Adalog, or @copyright{} 2015 Alstom/Adalog. AdaControl is
free software; you can redistribute
it and/or modify it under terms of the GNU General Public License as
published by the Free Software Foundation; either version 2, or (at
your option) any later version. This unit is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more details.  You
should have received a copy of the GNU General Public License
distributed with this program; see file COPYING.  If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.

As a special exception, if other files instantiate generics from this
program, or if you link units from this program with other files to
produce an executable, this does not by itself cause the resulting
executable to be covered by the GNU General Public License. This
exception does not however invalidate any other reasons why the
executable file might be covered by the GNU Public License.

This document is Copyright @copyright{} 2005-2019
Eurocontrol/Adalog. This document may be copied, in whole or in part,
in any form or by any means, as is or with alterations, provided that
(1) alterations are clearly marked as alterations and (2) this
copyright notice is included unmodified in any copy.

@iftex
@contents
@end iftex

@node General, The framework and utilities packages, Top, Top
@chapter General
This programmer manual describes how to add new rules to
AdaControl. Since AdaControl is based on ASIS, this manual assumes
that the reader has some familiarity with ASIS programming.

Modifying AdaControl needs of course a source distribution. It is OK
to work with the regular source distribution, but if you intend to
submit your patches, it is appropriate to get the latest ``bleeding
edge'' version from our GIT repository on SourceForge. Instructions on
how to get AdaControl from GIT are
@uref{http://sourceforge.net/projects/adacontrol/files/download-from-git.txt/download,here}

@section vocabulary
Some terms have a precise definition in AdaControl, and will be used
with that signification in the rest of this manual.

A @i{rule} is an AdaControl package whose purpose is to recognize
occurrences of certain constructs in Ada programs. All rules are
children of  the ``Rules'' package. By extension, the term rule is
also used to designate the check that is performed by the package. A
rule has a name, and may have parameters.

A @i{control} defines a check to be performed on some Ada text. A
control is defined by a rule, and the value of the parameters given to
the rule.

A @i{command} is a statement in the command language interpreted by
AdaControl.

A @i{control command} is a kind of command that describes a check to
be performed. A control commmand includes a @i{kind} (``check'', ``search''
or ``count'', see user's guide), and a control (rule name and parameters).

A @i{context} is a set of values used by a rule to keep the
characteristics associated with a control. Those values can, but need
not necessarily, be the parameters of the control.

@section General organization
The AdaControl tool includes several main components. Those that are
relevant for writing new rules are:
@itemize @bullet
@item
A general @i{framework} that provides services that are necessary to
write rules. This includes a special module, @code{Framework.Plugs},
where rules are plugged-in;
@item
A set of @i{utilities} providing useful functionalities, but not
specific to the writing of rules. Actually, the utilities packages are
shared with other programs from Adalog's ``Semtools'' family of tools.
@item
The @i{rules} themselves.
@end itemize

This clear distinction makes it easy to add new rules. Actually, the
framework relieves the programmer from all the ``dirty work'', and
adding a new rule requires nothing else than caring about the rule
itself.

@node The framework and utilities packages, Writing a new rule, General, Top
@chapter The framework and utilities packages

The framework includes the package @code{Framework} itself and its
public child packages. There are also some private child packages, but
they are of course not relevant to the users of the framework.

In each package, services (declarations, subprograms) that are
relevant for writing rules appear at the beginning of the package
specification. Other services that are used by the rest of the
framework, but not intended to be called from a rule, appear below the
following comment lines:
@example
   --
   --  Declarations below this line are for the use of the framework
   --
@end example

This section provides an overview of the services that are made
available by the framework and other utilities packages. It is not the
purpose of this section to describe the syntax of every service
provided : please refer to the comments in the specification of each
package. Existing rules are also typical examples of how to use these
functionnalities.

@menu
* The package Adactl_Constants::
* The package Framework::
* The package Framework.Rules_Manager::
* The package Framework.Reports::
* The package Framework.Fixes::
* The package Framework.Language::
* The package Framework.Variables::
* The package Framework.Plugs::
* The package Scope_Manager::
* The package Rules::
* The package Utilities::
* The packages Thick_Queries and Framework.Queries::
* The packages Linear_Queue and Binary_Map::
* The package A4G_Bugs::
@end menu

@node  The package Adactl_Constants, The package Framework, The framework and utilities packages, The framework and utilities packages
@section The package Adactl_Constants
AdaControl has some fixed size structures that limit the complexity of
the programs it can handle, like for example the maximum numbers of
parameters that subprograms can have, the maximum nesting of loops,
etc.

These limits are set as constants in the package
@code{Adactl_Constants}. These values are large enough to accomodate
any reasonable program, but should you hit one of these limits, you
can safely change them here. No other change is required.

If a rule needs to set a fixed dimension to some tables for example,
it should use the constants defined in this package. If no existing
constant is appropriate, add a new one to the package, don't define
dimensioning constants in the rule itself.

@node The package Framework, The package Framework.Rules_Manager, The package Adactl_Constants, The framework and utilities packages
@section The package Framework
The package Framework includes general services, needed by most
rules. These include:

@itemize @bullet
@item
The definition of some constants that are used to fix a bound to the
number of allowable constructs. Use these constants to dimension
tables for example.
@item
The notion of @i{location}, with associated subprograms. A location is
a place within a source file where some construct happens.
@item
The notion of @i{rule context}. A rule context is some information
that a rule associates to entities. For example, given the following
rules:
@example
search Entities (Blah);
Strictly_Forbidden: check entities (Ada.Unchecked_Conversion)
@end example
the rule Entities must associate that @code{Blah} is the target of a
search, and that @code{Ada.Unchecked_Deallocation} is the target of a
check with label @code{Strictly_Forbidden}.
@end itemize

@node The package Framework.Rules_Manager, The package Framework.Reports, The package Framework, The framework and utilities packages
@section The package Framework.Rules_Manager
The package @code{Framework.Rules_Manager} is used to register and
manage rules.

The procedure  @code{Register} declares the name of the rule and the
associated @code{Help}, @code{Add_Control}, @code{Command},
@code{Prepare}, and @code{Finalize} procedures.

Note that there is nothing else to do to make a rule known to the
system: once it is registered, it will be recognized on the command
line, help command will work, etc.

The procedure  @code{Enter} is used to let the system know which rule is
currently active.

@node The package Framework.Reports, The package Framework.Fixes, The package Framework.Rules_Manager, The framework and utilities packages
@section The package Framework.Reports
The package @code{Framework.Reports} is used to report error or found
messages when a rule matches. It deals automatically with things like
rules being temporarily disabled, therefore the rule does not have to
care.

The main service provided by this package is the @code{Report} procedure,
which comes in two flavors. This is the only allowed way for a rule to
report its findings, never use @code{Wide_Text_IO} or any other
mean. The specifications of the Report procedures are:

@example
@b{procedure} Report (Rule_Id    : @b{in} Wide_String;
                  Rule_Label : @b{in} Wide_String;
                  Ctl_Type   : @b{in} Control_Kinds;
                  Loc        : @b{in} Location;
                  Msg        : @b{in} Wide_String);

@b{procedure} Report (Rule_Id    : @b{in} Wide_String;
                  Context    : @b{in} Root_Context'class;
                  Loc        : @b{in} Location;
                  Msg        : @b{in} Wide_String);
@end example

The first procedure expects the label and type to be given
explicitely, while the second one gets them from a @code{Context}
object (see comments in the package).

Note that there is only one string for the message. Please do not try
to ``improve'' the presentation by introducing line breaks in the
report message: the output of AdaControl should remain parseable by
rather naive tools, therefore it is necessary to ensure that one
output line = one message.

In addition, there is an @code{Uncheckable} procedure, with the following profile:
@example
   @b{procedure} Uncheckable (Rule_Id : @b{in} Wide_String;
                          Risk    : @b{in} Uncheckable_Consequence;
                          Loc     : @b{in} Location;
                          Msg     : @b{in} Wide_String);
@end example
This procedure is called each time a rule encounters some dynamic
construct that prevents normal checking. The parameter @code{Risk} is
@code{False_Positive} if the consequence of not being able to analyze
the construct would result in wrong error messages, and
@code{False_Negative} if it would result in not detecting something
that could be an error. It is important to call this procedure for any
non-checkable construct, since it is what allows the rule
``Uncheckable'' to work.

@node The package Framework.Fixes, The package Framework.Language, The package Framework.Reports, The framework and utilities packages
@section The package Framework.Reports.Fixes
The package @code{Framework.Reports.Fixes} provides functionalities
for generating fixes to the source code.

The functionalities provided here allow to insert, delete, or replace
elements of the source text. See the specification for details.

If your rule knows how to fix a violation, just call the corresponding
subprograms from this package. Always call the fixes subprograms @i{after} the
corresponding report subprograms, because it's the report subprogram that
determines if the rule is enabled or disabled.

Note that it is better to delete some text than to replace it if
possible, because the fixing tool (@code{adactl_fix}) handles
conflicts between deletions better than conflicts between
insertions/replacements. For example, to remove unnecessary
parentheses, the rule @code{Simplifiable_Expressions(Parentheses)}
removes the opening and closing parentheses, rather than replace the
@code{A_Parenthesized_Expression} with its content (the
@code{Expression_Parenthesized}).

@node The package Framework.Language, The package Framework.Variables, The package Framework.Fixes, The framework and utilities packages
@section The package Framework.Language
The package @code{Framework.Language} provides functionalities
for parsing parameters, as well as the rest of the command language;
but of course only the subprograms used to parse parameters are
relevant to the writing of rules.

The functionalities provided here allow a good deal of freedom for
defining the syntax of a rule's parameters (although it is a good idea
to stay as close as possible to the syntax of other rules). Look at
the syntax of various rules to see what can be accomplished.

The package provides a @code{Parameter_Exists} function that returns
@code{True} if there are parameters left to parse. The kind of the
next parameter can be checked with the @code{Is_Integer_Parameter},
@code{Is_Float_Parameter}, or @code{Is_String_Parameter}
functions. The corresponding parameter value can be retrieved with the
@code{Get_Integer_Parameter}, @code{Get_Float_Parameter},
@code{Get_Name_Parameter}, @code{Get_File_Parameter},
@code{Get_String_Parameter}, or @code{Get_Entity_Parameter}
functions. The latter function returns an entity specification, i.e. a
descriptor for something which is expected to be a general
specification for an Ada entity (including overloading information,
for example). Such an entity can be used as a key for a context.

There is a generic package @code{Flag_Utilities} to help manage flags
(keywords) parameters defined by an enumerated type. An instantiation
of this package provides a @code{Get_Flag_Parameter} procedure to
parse the flags, an @code{Image} function to get a string
representation of a flag, and a @code{Help_On_Flags} function to print
the help message that enumerates all possible flag values.

There is a @code{Get_Modifier} to process modifiers (things like
``not'' or ``case_sensitive'' in front of a parameter). For more
sophisticated modifiers, you can instantiate the generic package
@code{Modifier_Utilities}, which works like @code{Flag_Utilities}, but
also provides the notion of sets of modifiers.

Note that if you instantiate @code{Flag_Utilities} or
@code{Modifier_Utilities} in a library package (as will be the case
most of the time), you @i{must} put a @code{pragma Elaborate
(Framework.Language);} on top of the package. Failing to do so will
result in circular elaboration problems; (@code{pragma Elaborate_All},
as implicitely provided by GNAT, does @i{not} work).

@node The package Framework.Variables, The package Framework.Plugs, The package Framework.Language, The framework and utilities packages
@section The package Framework.Variables
This package manages rule variables (the ones that can be set with
the @code{set} command of the language).

A rule may use any number of rule variables for adjusting its
behaviour. A rule variable holds a value, and various subprograms are
provided for setting and getting the associated value.

Rule variables are extensions of
@code{Framework.Variables.Object}. Typically, they extend this type
with a value that can be of any type. Abstract subprograms that need
to be overriden include @code{Set} and @code{Value_Image} for setting
and getting a value from/to a string and @code{All_Values} to give
possible values for help messages.

Generic packages are provided to make it easier to define variable
types associated to enumerated types and integer types. In addition,
the package @code{Framework.Variables.Shared_Types} provides variable
types for commonly used associated types.

When a rule needs a rule variable, it declares an object of the
appropriate type, and registers it to the framework by calling
@code{Framework.Variables.Register}, passing a pointer to the object
and the name used to refer to it. This name must be given in upper
case, and start with the rule's name, like
``@code{EXPRESSIONS.CALLED_INFO}'' for example. Of course, it is
better to use @code{Rule_Id} for building the name, like in:
@example
Framework.Variables.Register
   (Called_Info'Access,
    Variable_Name => Rule_Id & ".CALLED_INFO");
@end example
This call is typically put in the initalization part of the rule's
package, after the registration of the rule itself.

The rule @code{Expressions} (in file @code{rules-expressions.adb})
includes a typical usage of a rule variable.

@node  The package Framework.Plugs, The package Scope_Manager, The package Framework.Variables, The framework and utilities packages
@section The package Framework.Plugs
Procedures in the package @code{Framework.Plugs} are called during the
traversal of the Ada source code. Unlike the rest of the framework,
this package does not provide services to rules, but instead @i{calls}
processing procedures defined in the rules packages. Therefore, it is
necessary to @i{plug} the corresponding calls in this package. This is
described in details in @ref{Plugging-in a new rule into the
framework}.

@node The package Scope_Manager, The package Rules, The package Framework.Plugs, The framework and utilities packages
@section The package Scope_Manager
The package @code{Scope_Manager} provides facilities for rules that
need to follow scoping rules (i.e. which identifiers are visible at a
given place). It provides subprograms to query currently active
scopes, and a generic package that allows associating any kind of
information to a scope. Scopes are automatically managed: the
information will disappear when the corresponding scope is exited,
except for information associated to package specifications that will
be restored when the corresponding body is entered.

The scope manager follows strictly the visibility rules for child
units: when entering a public child unit, the scope from the visible
part of the parent is restored, and when entering the private part of
the child, the scope of the private part of the parent is restored. In
the case of a private child, the full scope of the parent is restored
upon entering.

See the package specification for more details.

Note: this package used to be a child of @code{Framework} in previous
versions of AdaControl. This has been changed to be an autonomous
package to make it reusable by other programs.

@node The package Rules, The package Utilities, The package Scope_Manager, The framework and utilities packages
@section The package Rules
The package @code{Rules} is (almost) empty. It's  purpose is to serve as the
parent package of all rules.

It simply provides an empty state type (@code{Null_State}), and a null procedure that can
be used for instantiating @code{Traverse_Element} in simple cases.

@node The package Utilities, The packages Thick_Queries and Framework.Queries, The package Rules, The framework and utilities packages
@section The package Utilities
This package provides various general facilities that are not specific
to AdaControl. The main elements provided are:

@itemize
@item
@code{User_Message} and @code{User_Log}. Both procedures output a
message, the difference being that @code{User_Log} outputs its message
only in verbose mode. @code{User_Message} is used to print help
messages. @code{User_Log} could be used if some rule wanted to print
some extra information in verbose mode. Note that these procedures
should @i{not} be used to report the result of a check or search (use
@code{Framework.Reports.Report} instead).

@item
String handling services, see package specification

@item
Error management. The @code{Error} procedure is not to be called
directly, use @code{Framework.Language.Parameter_Error} instead to
report errors in user provided parameters. In most cases, parameters
are checked in the @code{Add_Control} procedure of the rule
(@pxref{Writing a new rule}), and therefore errors are reported during
the parsing of the commands. In some cases, incorrect parameters are
discovered while traversing the code. It is acceptable to call
@code{Framework.Language.Parameter_Error} at any time, but be aware
that this will immediately stop all analysis. See the
@code{Rules.Unsafe_Paired_Calls} for an example of this.

The @code{Failure} procedure is used to report internal failures. It
is frequent in ASIS programming to have a big case statement over the
various kinds of elements, of which only a few values are interesting
or possible given the context. We strongly encourage to call
@code{Failure} in the @b{when others} part of the case statement to
trap unexpected cases. Note that the procedure is overloaded with a
version that allows to print information about the failing element.

@item
Debugging facilities. Several @code{Trace} procedures allow you to
output a message, possibly with a boolean value, or the context of an
ASIS element or element list. There is also an @code{Assert} procedure
that calls @code{Failure} if its condition is false; well placed
@code{Assert} calls are very helpfull in debugging. Note that traces
are output only in debug mode.

@item
Other facilities for managing the output that are called by the
framework, but not useful for writing rules.

@end itemize

@node  The packages Thick_Queries and Framework.Queries, The packages Linear_Queue and Binary_Map, The package Utilities, The framework and utilities packages
@section The packages Thick_Queries and Framework.Queries
These packages contain high level services that are built on top of
Asis queries, and can therefore be quite useful to the writing of
rules. The queries are documented in the specification of the
packages.

The difference between the packages is that @code{Thick_Queries} does
not depend in any way on the other parts of AdaControl (and notably on
the framework); it is therefore directly reusable for any ASIS
application. On the other hand, @code{Framework.Queries} requires
facilities provided by the framework, and is therefore not directly
reusable outside of AdaControl.

@node The packages Linear_Queue and Binary_Map, The package A4G_Bugs, The packages Thick_Queries and Framework.Queries, The framework and utilities packages
@section The packages Linear_Queue and Binary_Map
These packages provide simple generic containers that are needed by several rules.

The generic package @code{Linear_Queue} can be instantiated with any
(non-limited) @code{Component} type, and provides a simple queue of
elements. Note that this queue has @i{value} semantics: when a queue
is assigned, its content is duplicated. Queues are controlled, and
therefore all internal storage allocations are internally managed. The
package @code{Framework.Element_Queue} is an instantiation of
@code{Linear_Queue} with the type @code{Asis.Element}.

The generic package @code{Binary_Map} can be instantiated with a
@code{Key_Type} and a @code{Value_Type}, and associates values of
@code{Value_Type} to values of the @code{Key_Type}. The mapping uses a
binary tree; if you use it to keep user information, it is appropriate
to rebalance the tree before starting the actual
processing. @xref{Prepare}.

See existing rules for examples of using this package.

@node The package A4G_Bugs,  , The packages Linear_Queue and Binary_Map, The framework and utilities packages
@section The package A4G_Bugs
AdaControl is quite demanding on the ASIS implementation, and we found
some bugs in ASIS-for-GNAT during its development. These have been
reported to ACT, and are fixed in the wavefront version of GNAT, or
should be fixed very soon.

However, many people do not have access to the wavefront version, or
prefer to stay with the stable version. This package provides
replacements for some ASIS subprograms that do not behave as
expected. Subprograms in this package have specifications identical to
the corresponding ASIS subprograms, and are designed in such a way that
there is no harm in using them with a version of ASIS that does not
exhibit the bug. Therefore, it is strongly recommended to use the
subprograms in this package rather than their ASIS equivalent.

Note that if you run the rules file @code{src/verif.aru} on your code,
it will spot any use of an ASIS function for which there is a
replacement in @code{A4G_Bugs}.

@node Writing a new rule, Plugging-in a new rule into the framework, The framework and utilities packages, Top
@chapter Writing a new rule
There are two kinds of rules: @i{semantic} rules, which operate on Ada
elements, and @i{textual} rules, which operate on the source text. In
some rare cases, a rule can be of both kinds at the same time; see the
rule ``Style'' for an example of this. Note that a semantic rule can
still access the text of an Ada construct with the facilities provided
by the package @code{Asis.Text}, this does not require the rule to be
@code{Semantic_Textual}.

All rules currently provided follow a common pattern, described below;
it is recommended that new rules do the same, in order to make
maintenance easier.

The first thing to do before adding a new rule is to read the source
for existing rules, as they provide good examples of how a rule is
implemented. For an example of a simple rule, see @code{Rules.Entity};
for an example of a sophisticated one, see
@code{Rules.Unnecessary_Use}. For an example of a textual rule, see
@code{Rules.Max_Line_Length}. Note that @code{Rules.Entity} can be
used as a template for writing new semantic rules, as most rules will
follow the same general structure, just making more elaborated
processing of relevant entities.

@section General considerations
A rule is implemented as a child package of package @code{Rules}. The
following sections describe the structure of the specification and
body of a rule package.

It is good practice to use only one string type all over a program,
and since ASIS is based on @code{Wide_String}, a rule should not use
the type @code{String}, but rather use @code{Wide_String} instead.

@section Specification
The specification of a rule package must contain the following
elements:

@subsection Rule_ID
Rule_ID is a constant of type @code{Wide_String}. It is the unique
rule identifier of a rule. It is used by the package
@code{Framework.Rules_Manager} as the key in the rules list to
dispatch to the corresponding registered operation, and as the rule
name used by the user on the command line to parameterize and use the
rule. The name of the rule must be given in upper-case (to allow for
case-independant recognition).

Ex:
@example
Rule_Id : @b{constant} Wide_String := "PRAGMAS";
@end example

Note that from a language point of view, this declaration could be in
the body of the package; however, for identification purposes, it is
more convenient to put it in the specification.

@subsection Process
One (or more) procedure(s) may be necessary to process the rule
(collectively named the @code{Process} procedures in this
document). These procedures are called from @code{Framework.Plugs} at
appropriate places, and therefore must be declared in the
specification of the rule. @xref{Plugging-in a new rule into the
framework}.

Process procedures of a semantic rule take one parameter of type
@code{Asis.Element}. Although all element kinds are equivalent from
the point of view of Ada's type checking, it is recommended to follow
general ASIS practice, and to define the parameter with the ASIS
element kind expected by the procedure.

Process procedures of a textual rule take two parameters: an input
line, and the corresponding location.

 Ex:
@example
-- Semantic rule:
@b{procedure} Process_Pragma (Pragma_Element : @b{in} Asis.Pragma_Element);

-- Textual rule:
@b{procedure} Process_Line (Line : @b{in} Asis.Program_Text;
                        Loc  : @b{in} Framework.Location);
@end example

@section Body
It is a good habit to start the body of a rule by giving a comment
explaining the general principles of the algorithm used, especially if
the algorithm is not trivial. To be honest, not all current rules do
provide this information, and some crucial information may be missing
in the rules that do... You are more than welcome to improve these
comments, especially if you think that some fundamental information
should have been provided here.

The body must contain a @code{Help}, an @code{Add_Control}, and a
@code{Command} procedure. It may also optionnally contain a
@code{Prepare} and a @code{Finalize} procedure. These procedures are
call-backs that are registered to the framework by calling
@code{Framework.Rules_Manager.Register} in the statements part of the
body. Note that there is a parameter to this procedure that tells
whether the rule is semantic, textual, or both.  This procedure has
@b{@code{null}} defaults for the optional subprograms.

@subsection Help
Help is a procedure that displays a short help message to the standard
output for the rule. It takes no parameter.

The procedure @code{Help} is called when the user specifies a ``-h'' option
for the rule. It must display a useful message by calling
@code{Utilities.User_Message}. In order to have a uniform presentation
for all rules, the message must be structured as follows:

@itemize @bullet
@item
The word ``Rule:'' followed by the rule ID.
@item
A short description of the purpose of the rule. This description can span
several lines, but don't make it too long.
@item
A blank line (call @code{Utilities.User_Message} without parameter).
@item
The word ``Parameter(s):'' followed by a description of parameters. Note that if
you have a parameter of an enumerated type, the package @code{Flag_Utilities}
features a @code{Help_On_Flag} procedure that formats automatically the values.

If the different parameters have different meanings, you can use the
form  ``Parameter(1):'', ``Parameter(2):'' etc. instead. If the rule
has no parameters, just say ``Parameters: none''.

@end itemize
Note that the command:
@example
adactl -h all
@end example
outputs the help messages for all rules, providing examples of how you
should write your own help messages.

Ex:
@example
@b{procedure} Help @b{is}
  @b{use} Utilities;
@b{begin}
  User_Message ("Rule: " & Rule_Id);
  User_Message ("Control occurrences of aspect specifications");
  User_Message;
  User_Message ("Parameter(s): <Aspect_Mark> | implicit_true | all");
  User_Message ("             (optional, default = all)");
@b{end} Help;
@end example

@subsection Add_Control
@code{Add_Control} is a procedure which is called by the rules parser
when it finds a control command that refers to the corresponding
rule. It is passed the corresponding label (an empty string if there
is no label), and the control's kind (@code{Check}, @code{Search} or
@code{Count}). It will typically loop over the parameters with the
various @code{Get_XXX_Parameters} from package @code{Rules.Language}
to process the parameters.

If for some reason a parameter is not appropriate to the rule, the
rule should call @code{Rules.Language.Parameter_Error} with an
appropriate message. This procedure will raise the exception
@code{User_Error}, and the @code{Add_Control} procedure should not handle
it; the exception will be processed by the framework.

Note that @code{Add_Control} may be called several times if the same rule
is activated with different parameters in a rules file. If a rule can
be specified only once, it is up to the rule to check this and call
@code{Parameter_Error} in case it is given more than once.

Ex:
@example
@b{procedure} Add_Control (Label    : @b{in} Label;
                   Ctl_Type : @b{in} Control_Kinds) @b{is}
@b{begin}
   @b{while} Parameter_Exists @b{loop}
      -- process parameter
   @b{end} @b{loop};
@b{end} Add_Control;
@end example
There is no special requirement on the implementation of the @code{Add}
procedure. The programmer is free to interpret the parameters as
necessary and do whatever initialisation processing they
imply. Typically, for a rule that searches for the occurrence of an
identifier, this procedure would add the identifier to some internal
context table.

@subsection Command
@code{Command} is a procedure used by the framework to send
``commands'' to the rule in order to change its state. It has a
parameter of an enumeration type that can take the values
@code{Clear}, @code{Suspend}, and @code{Resume}.

@itemize
@item
@code{Clear}: @code{Command} is called with this value whenever a
``clear'' command is given. The rule must reset the rule to the ``not
used'' state, and free any allocated data structure.
@item
@code{Suspend}: @code{Command} is called with this value whenever the
rule is inhibited. The rule must preserve its current ``used'' state,
and enter the ``not used'' state.
@item
@code{Resume}: @code{Command} is called with this value whenever the
rule is no more inhibited. The rule must restore its state from the
copy saved by the previous @code{Suspend}
@end itemize

This procedure is required, since it must at least deal with the
@code{Rule_Used} flag (@pxref{Process}). Note that it is guaranteed
that @code{Suspend}/@code{Resume} are properly paired, and that
@code{Suspend} is not called on an already suspended rule. Therefore,
a simple variable can be used to save the current state.

Ex:
@example
@b{procedure} Command (Action : Framework.Rules_Manager.Rule_Action) @b{is}
   @b{use} Framework.Rules_Manager;
@b{begin}
   @b{case} Action @b{is}
      @b{when} Clear =>
         Rule_Used := False;
         -- Free internal data structures if necessary
      @b{when} Suspend =>
         Save_Used := Rule_Used;
         Rule_Used := False;
      @b{when} Resume =>
         Rule_Used := Save_Used;
   @b{end} @b{case};
@b{end} Command;
@end example

@anchor{Prepare}
@subsection Prepare
@code{Prepare} is a procedure that performs some initialisations that
must be done after all controls refering to the rule have been parsed,
and before processing the units. It is optional (i.e. a
@code{@b{null}} pointer can be passed for it to the @code{Register}
procedure, or simply not mentionned since @code{@b{null}} is the
default).

A typical use of @code{Prepare} is to balance the tree from a binary
map to improve efficiency.

@anchor{Process}
@subsection Process
There is no special requirement on the implementation of the
@code{Process} procedure(s). The programmer is free to do whatever is
necessary to the rule. It is possible to use ASIS query functions, or
any other service deemed appropriate.

It is also possible to have several @code{Process} procedures (e.g. if
the programmer wants to do some processing when going down the ASIS
tree, and some other processing when going up).

A @code{Process} procedure should return immediately if no
corresponding @code{Add_Control} has ever been called. In most cases, this
is conveniently done by having a @code{Rule_Used} global boolean
variable which is set to @code{True} in @code{Add_Control}, and checked at
the beginning of @code{Process}. For efficiency reasons, avoid doing
any call to the ASIS library before this check. This means that if you
need objects initialized with such calls, they should be declared in a
block @i{after} the test, rather than in the declarative part of the
@code{Process} procedure.

After this test, the rule should immediately call
@code{Rules_Manager.Enter} (with the rule name as the parameter). In
case of a problem, this allows the system to report which rule failed.

A special case arises for rules that follow the call graph. Such rules
may traverse elements outside the current unit, but should avoid
analyzing units to which an @code{inhibit all} applies (so-called
@i{banned} units). The framework features an @code{Is_Banned} function
that tells if an element should not be traversed due to it being
declared in a banned unit. See @code{Rules.Global_References} for an
example of this.

@subsection Finalize
@code{Finalize} is called at the end of a "Go" command, after all
units have been processed. It is useful for rules that report on
global usage of entities, and therefore can report findings only at
the end. It is optionnal (i.e. a @code{@b{null}} pointer can be passed
for it to the @code{Register} procedure, or simply not mentionned
since @code{@b{null}} is the default).

Ex:
@example
@b{procedure} Finalize @b{is}
@b{begin}
   -- Report findings
@b{end} Finalize;
@end example

@subsection Package statements
The package body statements part should include a call to
@code{Framework.Rules_Manager.Register} in order to register
the rule and its associated @code{Help}, @code{Add_Control},
@code{Command}, and optionally @code{Prepare} and @code{Finalize},
procedures. Note that the second parameter of @code{Register} tells
whether it is a semantic, textual, or semantic_textual rule.

Ex:
@example
@b{begin}
   Framework.Rules_Manager.Register (Rule_Id,
                                     Rules_Manager.Semantic,
                                     Help        => Help'Access,
                                     Add_Control => Add_Control'Access,
                                     Command     => Command'Access,
                                     Prepare     => Prepare'Access);
@b{end} Rules.Pragmas;
@end example

@section Programming rules and tips
@subsection style
We try to maintain a consistent style in AdaControl, therefore the code you write should
match the style of the rest of the program. Have a look at other rules, and run @code{src/verif.aru}
on your code. In addition, please note the following:
@itemize @bullet
@item
The @code{@b{use}} clause is allowed, but its scope should be
restricted to the innermost declarative region where it is useful. Use
a @code{@b{use}} clause for ASIS units, and another one for other
units.  Sort units alphabetically in the clause.
@item
The only output of a rule should be by calling
@code{Report}. Especially, no rule should use @code{Wide_Text_IO}
directly.
@item
If your rule encounters a dynamic construct that prevents normal checking,
call @code{Framework.Reports.Uncheckable} to warn the user.
@item
The framework should be sufficient for all your needs. If you have a
special need that you think cannot be satisfied by the current
framework, get in touch with us and we'll discuss it.
@end itemize

@subsection Things to care about
Each time you want the name of something, remember that the name may
be given in selected notation. In most cases, you should call
@code{Thick_Queries.Simple_Name} on the result of any query that
returns a name to get rid of the possible selectors. Otherwise, you
should inspect the returned expression to see if its
@code{Expression_Kind} is @code{A_Selected_Component}, and take the
@code{Selector} if it is.

When designing a rule, consider the implications of renamings and
generics.

If you want to output the Element_Image of some element, beware that
it will be preceded by spaces. Do not use
@code{Ada.Strings.Wide_Fixed.Trim} to eliminate them, since it
wont remove tab characters. Use @code{Utilities.trim_all}, which will
do the right thing.

@subsection Using ASIS efficiently.
Remember that ASIS queries can be costly. Declare local variables (or
constants) rather than evaluating several times the same query.

There are issues with some ASIS queries. The rule whose label is
``Avoid_Query'' in @code{verif.aru} will remind you if you use one of
these queries.
@table @asis
@item Asis.Definitions.Subtype_Mark
There might be confusion with @code{Asis.Subtype_Mark}; moreover, you
normally want to get rid of selected components (see above).  Use
@code{Thick_Queries.Subtype_Simple_Name} instead.

@item Asis.Definitions.Corresponding_Root_Type
This query return a @code{Nil_Element} if any type in the derivation
chain is a @code{'Base} attribute (to be honnest, versions of ASIS
before the latest 5.05 will loop indefinitely in this case). Use
@code{Thick_Queries.Corresponding_Root_Type_Name} instead, and consider what
you want to do if there is a @code{'Base} in the derivation chain.

@item Asis.Definitions.Corresponding_Parent_Subtype
This query suffers from the same problem as
@code{Corresponding_Root_Type}. Don't use it, rather take
the @code{Subtype_Simple_name} of the @code{Parent_Subtype_Indication},
and do your own analysis, depending on whether the returned
@code{Expression_Kind} is @code{An_Attribute_Reference} or not.
@end table

@node Plugging-in a new rule into the framework, Testing and debugging a rule, Writing a new rule, Top
@chapter Plugging-in a new rule into the framework

@menu
* Normal case::
* Specific rules::
* User documentation::
@end menu

@node Normal case, Specific rules, Plugging-in a new rule into the framework, Plugging-in a new rule into the framework
@section Normal case
Adding a new rule to the tool requires only simple modifications to
the package @code{Framework.Plugs}.

The package @code{Framework.Plugs} contains several procedures that
are called during the traversal of the code under the following
circumstances:
@itemize @bullet
@item
@code{Enter_Unit}: Called when entering a compilation unit, before any
other processing.
@item
@code{Exit_Unit}: Called when leaving a compilation unit, after any
other processing.
@item
@code{Enter_Scope}: Called when entering a new scope (i.e. a construct
that can contain declarations).
@item
@code{Exit_Scope}: Called when leaving a scope.
@item
@code{Pre_Procedure}: Called when entering a syntax node (this is like
the usual @code{Pre_Procedure} used in the instantiation of
@code{ASIS.Iterator.Traverse_Element}, except that there is no
@code{State_Information} and no @code{Control}).
@item
@code{Post_Procedure}: Called when leaving a syntax node.
@item
@code{True_Identifier}: Called when entering an @code{An_Identifier},
@code{An_Operator_Symbol}, or @code{An_Enumeration_Literal} node that
corresponds to a real identifier, i.e. not to a pragma name or other
forms of irrelevant names. This avoids special cases in rules dealing
with identifiers.
@item
@code{Text_Analysis}: Called on every source line of the code.
@end itemize

These procedures have the usual "big case" structure of an ASIS
application (i.e. a first level case statement on @code{Element_Kind},
with each case alternative containing other case statements to further
refine the kind of node that is being dealt with).

The following modifications must be done to the body of this package:

@enumerate
@item
Add a with clause naming the rule package:

Ex:
@example
@b{with} Rules.Pragmas;
@end example

@item
Add calls to the rule's @code{Process} procedure(s) at the appropriate
place(s) in the body of the provided procedures. For textual rules,
@code{Text_Analysis} is the only appropriate place.

Ex:
@example
@b{procedure} Pre_Procedure (Element : @b{in} Asis.Element) is
   @b{use} Asis;
   @b{use} Asis.Elements;
@b{begin}
   @b{case} Element_Kind (Element) @b{is}
      @b{when} A_Pragma =>
         Rules.Pragmas.Process_Pragma (Element);
       ...
@b{end} Pre_Procedure;
@end example
@end enumerate

Many alternatives of the big case statement cover a number of
values. It may happen that a new rule requires calling its
@code{Process} procedure for some, but not all of these values. In
this case, the case alternative must be split. This is not a problem,
but do not forget to duplicate the statements from the original
alternative before adding the new calls, to make sure that the split
does not break existing rules.

It is always possible to plug a @code{Process} procedure in
@code{Pre_Procedure} or in @code{Post_Procedure}. However, some
``natural'' places for plugging rules correspond to many branches of
the big case statement. For example, there are many places where you
enter a scope. That's why the package @code{Framework.Plugs} includes
other procedures that are called in ``interesting'' contexts. If
appropriate, it is better practice to plug calls to @code{Process}
procedures here, rather than all over the place in various
alternatives of the big case statement.

@node Specific rules, User documentation, Normal case, Plugging-in a new rule into the framework
@section Specific rules
In some cases, you may want to keep your rules separate from the
general purpose ones. This may happen if you have developped some very
specific rules that take the structure of your project into account,
and hence would not be of interest to anybody else. Or it may be that
your local lawyer does not allow you to publish your rules as free
software.

This should not prevent you from using AdaControl. Just write the
rules as usual, but instead of plugging them in
@code{Framework.Plugs}, use the package
@code{Framework.Specific_Plugs} instead. This package has subprograms
identical to those described above for plugging-in rules, and they are
called in the same contexts. But it is guaranteed that no rule from
the public release of AdaControl will ever be plugged-in into this
package. This way, you can keep your rules separate from the public
ones, and you can upgrade to a new version of AdaControl without
needing to merge the modifications for your rules.

If you have specific rules plugged into
@code{Framework.Specific_Plugs}, change the constant
@code{Specific_Version} in the specification of the package to
something that identifies the specific version (like your company's
name for example). This way, the version number of AdaControl will
show that it is a specific version.

@node User documentation,  , Specific rules, Plugging-in a new rule into the framework
@section User documentation
Of course, you should update the user's guide with the information
about your rules.  This guide is written in Texinfo, see
@uref{http://www.gnu.org/software/texinfo/}. Note however that you
don't need to understand all the possibilities of Texinfo to update
the manual; look at the description of other rules, the few commands
you need will be quite straightforward to understand.

@node Testing and debugging a rule,  , Plugging-in a new rule into the framework, Top
@chapter Testing and debugging a rule

@menu
* Testing::
* Debugging aids::
* Integrating the test in the test suite::
@end menu

@node Testing, Debugging aids, Testing and debugging a rule, Testing and debugging a rule
@section Testing
Once the rule is written, you will test it. Of course, you'll first
write a small test case to make sure that it works as expected. But
that's not enough.

Our experience with existing rules has shown that getting the rule 90%
right is quite easy, but the last 10% can be tricky. Ada offers
constructs that you often didn't think about when writing the rule;
for example, if you are expecting a name at some place, did you take
care of selected names (we got trapped by this one several times)?
Therefore, it is extremely important that you check your rule against
as much code as you can, the minimum being the code of AdaControl itself.

Note that if your rule encountered some uncheckable cases, you should
add a child for your rule to the test @code{t_uncheckable}, and also
modify the @code{t_uncheckable.aru} file accordingly. Look at how it
is done currently, and do the same.

@node Debugging aids, Integrating the test in the test suite, Testing, Testing and debugging a rule
@section Debugging aids
As mentionned above, it is often the case when writing a new rule, as
well as with any kind of ASIS programming, that one comes across
unexpected contexts. This is due to the rich features of Ada, but it
is sometimes difficult to understand what is happenning.

The framework provides some facilities that help in debugging. Don't
hesitate to use the @code{Trace} and @code{Assert}
utilities. @xref{The package Utilities}. Note that the @code{Trace}
procedures may be given an element (or an element list) whose basic
characteritics are printed. If the @code{With_Source} parameter is
@code{True}, the source correponding to the element is also printed.

In the case where AdaControls enters an endless loop, the first thing
to do is to determine the place where the loop is happening. To ease
this, AdaControl may be compiled in ``interruptible'' mode. In normal
mode, the package @code{Framework.Interrupt} is a renaming of
@code{Framework.Interrupt_Std}, a dummy package that does
nothing. Edit  @code{Framework.Interrupt} to make it a renaming of
@code{Framework.Interrupt_Dbg} (instructions provided in the package)
and recompile.

Now, when you hit Ctrl-C while AdaControl is running with the ``-d''
option, execution of the current ``go'' command is interrupted with a
message telling which rule is active, and on which compilation
unit. If the ``-x'' option is also given, the whole execution is
stopped.

Of course, when you are done, reestablish the normal package by doing the
inverse manipulation. The reason we didn't put the debug version in the
regular version is that it drags in the whole tasking run-time, with a
measurable impact on efficiency (we measured 18% extra time for
running AdaControl on the ACATS).

In addition, a small stand-alone utility called @code{ptree} is
provided. It prints the logical nesting of ASIS elements for a
unit. The syntax of Ptree is:
@example
ptree [-sS] [-p <project_file>] <unit>[:<span>] -- <ASIS_Options>
<span> ::=   <line_number>
           | [<first_line>]-[<last_line>]
           | <line_number>:<column_number>
@end example
If the ``-s'' option is given, @code{ptree} processes the
specification of the unit, otherwise it processes the body. If the
``-S'' option is given, the span of each element is also printed. The
``-p'' option has the same meaning as in AdaControl itself. ASIS
options can be passed, like for AdaControl, after a ``-@w{}-'' (but
-FS is the default).

The <unit> is given either as an Ada unit, or as a file name, provided
the extension is ``.ads'' or ``.adb'' (as in AdaControl). If a span is
mentionned behind the unit name, only the constructs that cover the
indicated span are output. The syntax of the span is the same used
by pfni. This is useful if you are interested in just one particular
structure in a big unit.

If you come across a situation where you don't understand the logical
nesting of elements, try to reduce it to a very simple example, then
run @code{ptree} on it. It can be quite instructive!

Of course, a more elaborated, but less convenient solution is to use
Asistant. Please refer to your ASIS documentation to learn how to use
Asistant.

Finally, if you come to suspect that you get a strange result from an
ASIS provided operation, check whether there is an equivalent
operation in the package @code{A4G_Bugs}, and if yes, use it
instead. @xref{The package A4G_Bugs}.

@node Integrating the test in the test suite,  , Debugging aids, Testing and debugging a rule
@section Integrating the test in the test suite
When your rule has been carefully tested and is ready for integration,
run the rule file @code{src/verif.aru} on every unit that you have
written or changed. This will control that you match the programming
rules for AdaControl. There can be some ``found'' messages (try to
minimize them if possible), but there should be no ``Error''
message. Then, the last thing you have to do is to write a test for
non-regression verification purpose. Don't forget to include examples
of the tricky cases in the test.

Go to the @code{test} directory. You'll notice that all test programs
have a name of the form @code{t_name.adb} (or in some rare cases,
@code{ts_name.adb}). The @code{name} is the rule name. You'll notice
also that some units have a name like @code{tfw_name.adb}; these are
tests for the framework, you should normally ignore them. Name your
test file according to this convention, normally using @code{t_},
unless the test requires some weird parameters that prevent it from
being run normally, in which case it should use @code{ts_} (``s''
stands for special). It is OK for your test to have child units (whose
names will be dictated by the Gnat naming convention). If your test
requires other units, name them like @code{x_name} or
@code{x_name_complement}. Then, go to the @code{test/conf} directory,
and put your rule file under the name @code{t_name.aru} (with the same
@code{name} of course).

Go back to the @code{test} directory, and run @code{test.sh}. All
tests should report PASSED, except the @code{tfw_help} and
@code{tfw_check} tests. Your test will not be reported, because its
expected output is not yet in the directory @code{test/ref}; test
@code{tfw_help} will report FAILED because this test prints all help
messages, and that the help message for your rule has been added; test
@code{tfw_check} will report FAILED because there is now one extra
message (from the extra rule file) saying ``No error found''.

Check that the result of your test is OK (in the file
@code{test/res/t_name.txt}), and copy this file to the directory
@code{test/ref/}. Do the following command:
@example
diff test/ref/tfw_help.txt test/res/tfw_help.txt
@end example
and check that the only difference is the addition of the help message
from your rule.

Do the following command:
@example
diff test/ref/tfw_check.txt test/res/tfw_check.txt
@end example
and check that the only difference is the addition of one ``No error
found'' message.

Then copy @code{test/res/tfw_help.txt} and
@code{test/res/tfw_check.txt} to the directory @code{test/ref/}. Run
@code{test.sh} again: it should print PASSED for all tests, including
yours. Pay special attention to the last test, called
@code{tfw_stress}. This test runs all rules against all test units. If
it fails, the file @code{res/tfw_stress.txt} contains the whole
listing of the run (with @code{-dv} options), so you'll find all the
context of the problem.

In case of problems, note that options can be passed to
@code{test.sh}; check the comments at the top of the file for details.

When everything is OK, all you have to do is send your modifications
(including the tests) to
@uref{mailto::rosen@@adalog.fr,,rosen@@adalog.fr}, for inclusion in
the next release of AdaControl!
@bye
