File: adacontrol_pm.texi

package info (click to toggle)
adacontrol 1.16r11-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 9,008 kB
  • ctags: 709
  • sloc: ada: 55,246; python: 419; xml: 343; sh: 229; makefile: 77; sed: 30
file content (1131 lines) | stat: -rw-r--r-- 50,293 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
\input texinfo   @c -*-texinfo-*-
@c %**start of header
@setfilename adacontrol_pm.info
@settitle AdaControl Programmer Manual V1.16r11
@dircategory GNU Ada tools
@direntry
* AdaControl Programmer's Manual: (adacontrol_pm).  Writing new rules.
@end direntry
@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

@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-2014 Eurocontrol/Adalog,
except for some specific modules that are @copyright{} 2006
Belgocontrol/Adalog, @copyright{} 2006 CSEE/Adalog, or @copyright{}
2006 SAGEM/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-2014
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.Language::
* The package Framework.Scope_Manager::
* The package Framework.Plugs::
* The package Rules::
* The package Utilities::
* The package Thick_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.Language, 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 come 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;
                     Count_Only : @b{in} Boolean := False);
@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).  If @code{Count_Only} is
@code{True}, the message is not issued, but simply counted for the
statistics. This is useful to avoid redundant messages in some cases,
while keeping the number of detections accurate. See an example of
this in @code{Rules.Pragmas}.

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.Language, The package Framework.Scope_Manager, The package Framework.Reports, The framework and utilities packages
@section The package Framework.Language
The package @code{Framework.Language} deals with the command language
used to specify controls used in a rules file. Only the subprograms
used to parse parameters are relevant to the writing of rules.

There is a @code{Parameter_Exists} function that returns @code{True}
if there are parameters left to parse. The corresponding parameter
value can be retrieved with the @code{Get_Integer_Parameter},
@code{Get_String_Parameter}, or @code{Get_Entity_Parameter}
functions. The two former functions return the parameter as an
@code{Integer} or @code{Wide_String}, respectively. The latter one
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.Scope_Manager, The package Framework.Plugs, The package Framework.Language, The framework and utilities packages
@section The package Framework.Scope_Manager
The package @code{Framework.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.

@node  The package Framework.Plugs, The package Rules, The package Framework.Scope_Manager, 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 Rules, The package Utilities, The package Framework.Plugs, 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, and a null procedure that can
be used for instantiating @code{Traverse_Element}in simple cases.

@node The package Utilities, The package Thick_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 procedure 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, 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 package Thick_Queries, The packages Linear_Queue and Binary_Map, The package Utilities, The framework and utilities packages
@section The package Thick_Queries
This package contains high level services that are built on top of
Asis queries, and can therefore be quite useful to the writing of
rules. These queries are documented in the specification of the
package.

@node The packages Linear_Queue and Binary_Map, The package A4G_Bugs, The package Thick_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
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 should be all 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.

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
The word ``Parameters:'' 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.
@item
A helpful message describing the purpose of the rule.
@end itemize

Ex:
@example
@b{procedure} Help @b{is}
   @b{use} Utilities;
@b{begin}
   User_Message ("Rule: " & Rule_Id);
   User_Message ("Parameter(s): pragma name (e.g. Elaborate_Body)");
   User_Message ("This rule can be used to check/search for the usage "
                 & "of a specific pragma.");
@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, recompile AdaControl with the special version of package body
@code{Framework.Interrupt} that handles Ctrl-C:
@itemize @bullet
@item
Rename @code{framework-interrupt.adb} as @code{framework-interrupt-reg.adb}
@item
Rename @code{framework-interrupt-dbg.adb} as @code{framework-interrupt.adb}
@item
Recompile
@end itemize

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 body by doing the
inverse manipulation. The reason we didn't put this body 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