OSDN Git Service

* gcc-interface/Make-lang.in: Update dependencies.
[pf3gnuchains/gcc-fork.git] / gcc / ada / g-comlin.ads
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                    G N A T . C O M M A N D _ L I N E                     --
6 --                                                                          --
7 --                                 S p e c                                  --
8 --                                                                          --
9 --                     Copyright (C) 1999-2010, AdaCore                     --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- As a special exception,  if other files  instantiate  generics from this --
23 -- unit, or you link  this unit with other files  to produce an executable, --
24 -- this  unit  does not  by itself cause  the resulting  executable  to  be --
25 -- covered  by the  GNU  General  Public  License.  This exception does not --
26 -- however invalidate  any other reasons why  the executable file  might be --
27 -- covered by the  GNU Public License.                                      --
28 --                                                                          --
29 -- GNAT was originally developed  by the GNAT team at  New York University. --
30 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
31 --                                                                          --
32 ------------------------------------------------------------------------------
33
34 --  High level package for command line parsing and manipulation
35
36 ----------------------------------------
37 -- Simple Parsing of the Command Line --
38 ----------------------------------------
39
40 --  This package provides an interface for parsing command line arguments,
41 --  when they are either read from Ada.Command_Line or read from a string list.
42 --  As shown in the example below, one should first retrieve the switches
43 --  (special command line arguments starting with '-' by default) and their
44 --  parameters, and then the rest of the command line arguments.
45 --
46 --  While it may appear easy to parse the command line arguments with
47 --  Ada.Command_Line, there are in fact lots of special cases to handle in some
48 --  applications. Those are fully managed by GNAT.Command_Line. Among these are
49 --  switches with optional parameters, grouping switches (for instance "-ab"
50 --  might mean the same as "-a -b"), various characters to separate a switch
51 --  and its parameter (or none: "-a 1" and "-a1" are generally the same, which
52 --  can introduce confusion with grouped switches),...
53 --
54 --  begin
55 --     loop
56 --        case Getopt ("a b: ad") is  -- Accepts '-a', '-ad', or '-b argument'
57 --           when ASCII.NUL => exit;
58
59 --           when 'a' =>
60 --                 if Full_Switch = "a" then
61 --                    Put_Line ("Got a");
62 --                 else
63 --                    Put_Line ("Got ad");
64 --                 end if;
65
66 --           when 'b' => Put_Line ("Got b + " & Parameter);
67
68 --           when others =>
69 --              raise Program_Error;         -- cannot occur!
70 --        end case;
71 --     end loop;
72
73 --     loop
74 --        declare
75 --           S : constant String := Get_Argument (Do_Expansion => True);
76 --        begin
77 --           exit when S'Length = 0;
78 --           Put_Line ("Got " & S);
79 --        end;
80 --     end loop;
81
82 --  exception
83 --     when Invalid_Switch    => Put_Line ("Invalid Switch " & Full_Switch);
84 --     when Invalid_Parameter => Put_Line ("No parameter for " & Full_Switch);
85 --  end;
86
87 --------------
88 -- Sections --
89 --------------
90
91 --  A more complicated example would involve the use of sections for the
92 --  switches, as for instance in gnatmake. The same command line is used to
93 --  provide switches for several tools. Each tool recognizes its switches by
94 --  separating them with special switches that act as section separators.
95 --  Each section acts as a command line of its own.
96
97 --  begin
98 --     Initialize_Option_Scan ('-', False, "largs bargs cargs");
99 --     loop
100 --        --  Same loop as above to get switches and arguments
101 --     end loop;
102
103 --     Goto_Section ("bargs");
104 --     loop
105 --        --  Same loop as above to get switches and arguments
106 --        --  The supported switches in Getopt might be different
107 --     end loop;
108
109 --     Goto_Section ("cargs");
110 --     loop
111 --        --  Same loop as above to get switches and arguments
112 --        --  The supported switches in Getopt might be different
113 --     end loop;
114 --  end;
115
116 -------------------------------
117 -- Parsing a List of Strings --
118 -------------------------------
119
120 --  The examples above show how to parse the command line when the arguments
121 --  are read directly from Ada.Command_Line. However, these arguments can also
122 --  be read from a list of strings. This can be useful in several contexts,
123 --  either because your system does not support Ada.Command_Line, or because
124 --  you are manipulating other tools and creating their command lines by hand,
125 --  or for any other reason.
126
127 --  To create the list of strings, it is recommended to use
128 --  GNAT.OS_Lib.Argument_String_To_List.
129
130 --  The example below shows how to get the parameters from such a list. Note
131 --  also the use of '*' to get all the switches, and not report errors when an
132 --  unexpected switch was used by the user
133
134 --  declare
135 --     Parser : Opt_Parser;
136 --     Args : constant Argument_List_Access :=
137 --        GNAT.OS_Lib.Argument_String_To_List ("-g -O1 -Ipath");
138 --  begin
139 --     Initialize_Option_Scan (Parser, Args);
140 --     while Getopt ("* g O! I=", Parser) /= ASCII.NUL loop
141 --        Put_Line ("Switch " & Full_Switch (Parser)
142 --                  & " param=" & Parameter (Parser));
143 --     end loop;
144 --     Free (Parser);
145 --  end;
146
147 -------------------------------------------
148 -- High-Level Command Line Configuration --
149 -------------------------------------------
150
151 --  As shown above, the code is still relatively low-level. For instance, there
152 --  is no way to indicate which switches are related (thus if "-l" and "--long"
153 --  should have the same effect, your code will need to test for both cases).
154 --  Likewise, it is difficult to handle more advanced constructs, like:
155
156 --    * Specifying -gnatwa is the same as specifying -gnatwu -gnatwv, but
157 --      shorter and more readable
158
159 --    * All switches starting with -gnatw can be grouped, for instance one
160 --      can write -gnatwcd instead of -gnatwc -gnatwd.
161 --      Of course, this can be combined with the above and -gnatwacd is the
162 --      same as -gnatwc -gnatwd -gnatwu -gnatwv
163
164 --    * The switch -T is the same as -gnatwAB (same as -gnatwA -gnatwB)
165
166 --  With the above form of Getopt, you would receive "-gnatwa", "-T" or
167 --  "-gnatwcd" in the examples above, and thus you require additional manual
168 --  parsing of the switch.
169
170 --  Instead, this package provides the type Command_Line_Configuration, which
171 --  stores all the knowledge above. For instance:
172
173 --     Config : Command_Line_Configuration;
174 --     Define_Alias  (Config, "-gnatwa", "-gnatwu -gnatwv");
175 --     Define_Prefix (Config, "-gnatw");
176 --     Define_Alias  (Config, "-T",      "-gnatwAB");
177
178 --  You then need to specify all possible switches in your application by
179 --  calling Define_Switch, for instance:
180
181 --     Define_Switch (Config, "-gnatwu", Help => "warn on unused entities");
182 --     Define_Switch (Config, "-gnatwv", Help => "warn on unassigned var");
183 --     ...
184
185 --  Specifying the help message is optional, but makes it easy to then call
186 --  the function
187 --     Display_Help (Config);
188 --  that will display a properly formatted help message for your application,
189 --  listing all possible switches. That way you have a single place in which
190 --  to maintain the list of switches and their meaning, rather than maintaing
191 --  both the string to pass to Getopt and a subprogram to display the help.
192 --  Both will properly stay synchronized.
193
194 --  Once you have this Config, you just have to call
195 --     Getopt (Config, Callback'Access);
196 --  to parse the command line. The Callback will be called for each switch
197 --  found on the command line (in the case of our example, that is "-gnatwu"
198 --  and then "-gnatwv", not "-gnatwa" itself). This simplifies command line
199 --  parsing a lot.
200
201 --  In fact, this can be further automated for the most command case where the
202 --  parameter passed to a switch is stored in a variable in the application.
203 --  When a switch is defined, you only have to indicate where to store the
204 --  value, and let Getopt do the rest. For instance:
205
206 --     Optimization : aliased Integer;
207 --     Verbose      : aliased Boolean;
208 --
209 --     Define_Switch (Config, Verbose'Access,
210 --                    "-v", Long_Switch => "--verbose",
211 --                    Help => "Output extra verbose information");
212 --     Define_Switch (Config, Optimization'Access,
213 --                    "-O?", Help => "Optimization level");
214 --
215 --     Getopt (Config);  --  No callback
216
217 --  Since all switches are handled automatically, we don't even need to pass
218 --  a callback to Getopt. Once getopt has been called, the two variables
219 --  Optimization and Verbose have been properly initialized, either to the
220 --  default value or to the value found on the command line.
221
222 ------------------------------------------------
223 -- Creating and Manipulating the Command Line --
224 ------------------------------------------------
225
226 --  This package provides mechanisms to create and modify command lines by
227 --  adding or removing arguments from them. The resulting command line is kept
228 --  as short as possible by coalescing arguments whenever possible.
229
230 --  Complex command lines can thus be constructed, for example from a GUI
231 --  (although this package does not by itself depend upon any specific GUI
232 --  toolkit).
233
234 --  Using the configuration defined earlier, one can then construct a command
235 --  line for the tool with:
236
237 --     Cmd : Command_Line;
238 --     Set_Configuration (Cmd, Config);   --  Config created earlier
239 --     Add_Switch (Cmd, "-bar");
240 --     Add_Switch (Cmd, "-gnatwu");
241 --     Add_Switch (Cmd, "-gnatwv");  --  will be grouped with the above
242 --     Add_Switch (Cmd, "-T");
243
244 --  The resulting command line can be iterated over to get all its switches,
245 --  There are two modes for this iteration: either you want to get the
246 --  shortest possible command line, which would be:
247
248 --      -bar -gnatwaAB
249
250 --  or on the other hand you want each individual switch (so that your own
251 --  tool does not have to do further complex processing), which would be:
252
253 --      -bar -gnatwu -gnatwv -gnatwA -gnatwB
254
255 --  Of course, we can assume that the tool you want to spawn would understand
256 --  both of these, since they are both compatible with the description we gave
257 --  above. However, the first result is useful if you want to show the user
258 --  what you are spawning (since that keeps the output shorter), and the second
259 --  output is more useful for a tool that would check whether -gnatwu was
260 --  passed (which isn't obvious in the first output). Likewise, the second
261 --  output is more useful if you have a graphical interface since each switch
262 --  can be associated with a widget, and you immediately know whether -gnatwu
263 --  was selected.
264 --
265 --  Some command line arguments can have parameters, which on a command line
266 --  appear as a separate argument that must immediately follow the switch.
267 --  Since the subprograms in this package will reorganize the switches to group
268 --  them, you need to indicate what is a command line
269 --  parameter, and what is a switch argument.
270
271 --  This is done by passing an extra argument to Add_Switch, as in:
272
273 --     Add_Switch (Cmd, "-foo", Parameter => "arg1");
274
275 --  This ensures that "arg1" will always be treated as the argument to -foo,
276 --  and will not be grouped with other parts of the command line.
277
278 with Ada.Command_Line;
279
280 with GNAT.Directory_Operations;
281 with GNAT.OS_Lib;
282 with GNAT.Regexp;
283 with GNAT.Strings;
284
285 package GNAT.Command_Line is
286
287    -------------
288    -- Parsing --
289    -------------
290
291    type Opt_Parser is private;
292    Command_Line_Parser : constant Opt_Parser;
293    --  This object is responsible for parsing a list of arguments, which by
294    --  default are the standard command line arguments from Ada.Command_Line.
295    --  This is really a pointer to actual data, which must therefore be
296    --  initialized through a call to Initialize_Option_Scan, and must be freed
297    --  with a call to Free.
298    --
299    --  As a special case, Command_Line_Parser does not need to be either
300    --  initialized or free-ed.
301
302    procedure Initialize_Option_Scan
303      (Switch_Char              : Character := '-';
304       Stop_At_First_Non_Switch : Boolean := False;
305       Section_Delimiters       : String := "");
306    procedure Initialize_Option_Scan
307      (Parser                   : out Opt_Parser;
308       Command_Line             : GNAT.OS_Lib.Argument_List_Access;
309       Switch_Char              : Character := '-';
310       Stop_At_First_Non_Switch : Boolean := False;
311       Section_Delimiters       : String := "");
312    --  The first procedure resets the internal state of the package to prepare
313    --  to rescan the parameters. It does not need to be called before the first
314    --  use of Getopt (but it could be), but it must be called if you want to
315    --  start rescanning the command line parameters from the start. The
316    --  optional parameter Switch_Char can be used to reset the switch
317    --  character, e.g. to '/' for use in DOS-like systems.
318    --
319    --  The second subprogram initializes a parser that takes its arguments from
320    --  an array of strings rather than directly from the command line. In this
321    --  case, the parser is responsible for freeing the strings stored in
322    --  Command_Line. If you pass null to Command_Line, this will in fact create
323    --  a second parser for Ada.Command_Line, which doesn't share any data with
324    --  the default parser. This parser must be free-ed.
325    --
326    --  The optional parameter Stop_At_First_Non_Switch indicates if Getopt is
327    --  to look for switches on the whole command line, or if it has to stop as
328    --  soon as a non-switch argument is found.
329    --
330    --  Example:
331    --
332    --      Arguments: my_application file1 -c
333    --
334    --      If Stop_At_First_Non_Switch is False, then -c will be considered
335    --      as a switch (returned by getopt), otherwise it will be considered
336    --      as a normal argument (returned by Get_Argument).
337    --
338    --  If Section_Delimiters is set, then every following subprogram
339    --  (Getopt and Get_Argument) will only operate within a section, which
340    --  is delimited by any of these delimiters or the end of the command line.
341    --
342    --  Example:
343    --      Initialize_Option_Scan (Section_Delimiters => "largs bargs cargs");
344    --
345    --      Arguments on command line : my_application -c -bargs -d -e -largs -f
346    --      This line contains three sections, the first one is the default one
347    --      and includes only the '-c' switch, the second one is between -bargs
348    --      and -largs and includes '-d -e' and the last one includes '-f'.
349
350    procedure Free (Parser : in out Opt_Parser);
351    --  Free the memory used by the parser. Calling this is not mandatory for
352    --  the Command_Line_Parser
353
354    procedure Goto_Section
355      (Name   : String := "";
356       Parser : Opt_Parser := Command_Line_Parser);
357    --  Change the current section. The next Getopt or Get_Argument will start
358    --  looking at the beginning of the section. An empty name ("") refers to
359    --  the first section between the program name and the first section
360    --  delimiter. If the section does not exist in Section_Delimiters, then
361    --  Invalid_Section is raised. If the section does not appear on the command
362    --  line, then it is treated as an empty section.
363
364    function Full_Switch
365      (Parser : Opt_Parser := Command_Line_Parser) return String;
366    --  Returns the full name of the last switch found (Getopt only returns the
367    --  first character). Does not include the Switch_Char ('-' by default),
368    --  unless the "*" option of Getopt is used (see below).
369
370    function Current_Section
371      (Parser : Opt_Parser := Command_Line_Parser) return String;
372    --  Return the name of the current section.
373    --  The list of valid sections is defined through Initialize_Option_Scan
374
375    function Getopt
376      (Switches    : String;
377       Concatenate : Boolean := True;
378       Parser      : Opt_Parser := Command_Line_Parser) return Character;
379    --  This function moves to the next switch on the command line (defined as
380    --  switch character followed by a character within Switches, casing being
381    --  significant). The result returned is the first character of the switch
382    --  that is located. If there are no more switches in the current section,
383    --  returns ASCII.NUL. If Concatenate is True (the default), the switches do
384    --  not need to be separated by spaces (they can be concatenated if they do
385    --  not require an argument, e.g. -ab is the same as two separate arguments
386    --  -a -b).
387    --
388    --  Switches is a string of all the possible switches, separated by
389    --  spaces. A switch can be followed by one of the following characters:
390    --
391    --   ':'  The switch requires a parameter. There can optionally be a space
392    --        on the command line between the switch and its parameter.
393    --
394    --   '='  The switch requires a parameter. There can either be a '=' or a
395    --        space on the command line between the switch and its parameter.
396    --
397    --   '!'  The switch requires a parameter, but there can be no space on the
398    --        command line between the switch and its parameter.
399    --
400    --   '?'  The switch may have an optional parameter. There can be no space
401    --        between the switch and its argument.
402    --
403    --        e.g. if Switches has the following value : "a? b",
404    --        The command line can be:
405    --
406    --             -afoo    :  -a switch with 'foo' parameter
407    --             -a foo   :  -a switch and another element on the
408    --                           command line 'foo', returned by Get_Argument
409    --
410    --     Example: if Switches is "-a: -aO:", you can have the following
411    --              command lines:
412    --
413    --                -aarg    :  'a' switch with 'arg' parameter
414    --                -a arg   :  'a' switch with 'arg' parameter
415    --                -aOarg   :  'aO' switch with 'arg' parameter
416    --                -aO arg  :  'aO' switch with 'arg' parameter
417    --
418    --    Example:
419    --
420    --       Getopt ("a b: ac ad?")
421    --
422    --         accept either 'a' or 'ac' with no argument,
423    --         accept 'b' with a required argument
424    --         accept 'ad' with an optional argument
425    --
426    --  If the first item in switches is '*', then Getopt will catch
427    --  every element on the command line that was not caught by any other
428    --  switch. The character returned by GetOpt is '*', but Full_Switch
429    --  contains the full command line argument, including leading '-' if there
430    --  is one. If this character was not returned, there would be no way of
431    --  knowing whether it is there or not.
432    --
433    --    Example
434    --       Getopt ("* a b")
435    --       If the command line is '-a -c toto.o -b', Getopt will return
436    --       successively 'a', '*', '*' and 'b', with Full_Switch returning
437    --       "a", "-c", "toto.o", and "b".
438    --
439    --  When Getopt encounters an invalid switch, it raises the exception
440    --  Invalid_Switch and sets Full_Switch to return the invalid switch.
441    --  When Getopt cannot find the parameter associated with a switch, it
442    --  raises Invalid_Parameter, and sets Full_Switch to return the invalid
443    --  switch.
444    --
445    --  Note: in case of ambiguity, e.g. switches a ab abc, then the longest
446    --  matching switch is returned.
447    --
448    --  Arbitrary characters are allowed for switches, although it is
449    --  strongly recommended to use only letters and digits for portability
450    --  reasons.
451    --
452    --  When Concatenate is False, individual switches need to be separated by
453    --  spaces.
454    --
455    --    Example
456    --       Getopt ("a b", Concatenate => False)
457    --       If the command line is '-ab', exception Invalid_Switch will be
458    --       raised and Full_Switch will return "ab".
459
460    function Get_Argument
461      (Do_Expansion : Boolean := False;
462       Parser       : Opt_Parser := Command_Line_Parser) return String;
463    --  Returns the next element on the command line that is not a switch.  This
464    --  function should not be called before Getopt has returned ASCII.NUL.
465    --
466    --  If Do_Expansion is True, then the parameter on the command line will
467    --  be considered as a filename with wild cards, and will be expanded. The
468    --  matching file names will be returned one at a time. This is useful in
469    --  non-Unix systems for obtaining normal expansion of wild card references.
470    --  When there are no more arguments on the command line, this function
471    --  returns an empty string.
472
473    function Parameter
474      (Parser : Opt_Parser := Command_Line_Parser) return String;
475    --  Returns parameter associated with the last switch returned by Getopt.
476    --  If no parameter was associated with the last switch, or no previous call
477    --  has been made to Get_Argument, raises Invalid_Parameter. If the last
478    --  switch was associated with an optional argument and this argument was
479    --  not found on the command line, Parameter returns an empty string.
480
481    function Separator
482      (Parser : Opt_Parser := Command_Line_Parser) return Character;
483    --  The separator that was between the switch and its parameter. This is
484    --  useful if you want to know exactly what was on the command line. This
485    --  is in general a single character, set to ASCII.NUL if the switch and
486    --  the parameter were concatenated. A space is returned if the switch and
487    --  its argument were in two separate arguments.
488
489    Invalid_Section : exception;
490    --  Raised when an invalid section is selected by Goto_Section
491
492    Invalid_Switch : exception;
493    --  Raised when an invalid switch is detected in the command line
494
495    Invalid_Parameter : exception;
496    --  Raised when a parameter is missing, or an attempt is made to obtain a
497    --  parameter for a switch that does not allow a parameter
498
499    -----------------------------------------
500    -- Expansion of command line arguments --
501    -----------------------------------------
502    --  These subprograms take care of of expanding globbing patterns on the
503    --  command line. On Unix, such expansion is done by the shell before your
504    --  application is called. But on Windows you must do this expansion
505    --  yourself.
506
507    type Expansion_Iterator is limited private;
508    --  Type used during expansion of file names
509
510    procedure Start_Expansion
511      (Iterator     : out Expansion_Iterator;
512       Pattern      : String;
513       Directory    : String := "";
514       Basic_Regexp : Boolean := True);
515    --  Initialize a wild card expansion. The next calls to Expansion will
516    --  return the next file name in Directory which match Pattern (Pattern
517    --  is a regular expression, using only the Unix shell and DOS syntax if
518    --  Basic_Regexp is True). When Directory is an empty string, the current
519    --  directory is searched.
520    --
521    --  Pattern may contain directory separators (as in "src/*/*.ada").
522    --  Subdirectories of Directory will also be searched, up to one
523    --  hundred levels deep.
524    --
525    --  When Start_Expansion has been called, function Expansion should
526    --  be called repeatedly until it returns an empty string, before
527    --  Start_Expansion can be called again with the same Expansion_Iterator
528    --  variable.
529
530    function Expansion (Iterator : Expansion_Iterator) return String;
531    --  Returns the next file in the directory matching the parameters given
532    --  to Start_Expansion and updates Iterator to point to the next entry.
533    --  Returns an empty string when there are no more files.
534    --
535    --  If Expansion is called again after an empty string has been returned,
536    --  then the exception GNAT.Directory_Operations.Directory_Error is raised.
537
538    -----------------
539    -- Configuring --
540    -----------------
541
542    --  The following subprograms are used to manipulate a command line
543    --  represented as a string (for instance "-g -O2"), as well as parsing
544    --  the switches from such a string. They provide high-level configurations
545    --  to define aliases (a switch is equivalent to one or more other switches)
546    --  or grouping of switches ("-gnatyac" is equivalent to "-gnatya" and
547    --  "-gnatyc").
548
549    --  See the top of this file for examples on how to use these subprograms
550
551    type Command_Line_Configuration is private;
552
553    procedure Define_Section
554      (Config  : in out Command_Line_Configuration;
555       Section : String);
556    --  Indicates a new switch section. All switches belonging to the same
557    --  section are ordered together, preceded by the section. They are placed
558    --  at the end of the command line (as in "gnatmake somefile.adb -cargs -g")
559    --
560    --  The section name should not include the leading '-'. So for instance in
561    --  the case of gnatmake we would use:
562    --
563    --      Define_Section (Config, "cargs");
564    --      Define_Section (Config, "bargs");
565
566    procedure Define_Alias
567      (Config   : in out Command_Line_Configuration;
568       Switch   : String;
569       Expanded : String;
570       Section  : String := "");
571    --  Indicates that whenever Switch appears on the command line, it should
572    --  be expanded as Expanded. For instance, for the GNAT compiler switches,
573    --  we would define "-gnatwa" as an alias for "-gnatwcfijkmopruvz", ie some
574    --  default warnings to be activated.
575    --
576    --  This expansion is only done within the specified section, which must
577    --  have been defined first through a call to [Define_Section].
578
579    procedure Define_Prefix
580      (Config : in out Command_Line_Configuration;
581       Prefix : String);
582    --  Indicates that all switches starting with the given prefix should be
583    --  grouped. For instance, for the GNAT compiler we would define "-gnatw" as
584    --  a prefix, so that "-gnatwu -gnatwv" can be grouped into "-gnatwuv" It is
585    --  assumed that the remainder of the switch ("uv") is a set of characters
586    --  whose order is irrelevant. In fact, this package will sort them
587    --  alphabetically.
588
589    procedure Define_Switch
590      (Config      : in out Command_Line_Configuration;
591       Switch      : String := "";
592       Long_Switch : String := "";
593       Help        : String := "";
594       Section     : String := "");
595    --  Indicates a new switch. The format of this switch follows the getopt
596    --  format (trailing ':', '?', etc for defining a switch with parameters).
597    --
598    --  Switch should also start with the leading '-' (or any other characters).
599    --  They should all start with the same character, though. If this
600    --  character is not '-', you will need to call Initialize_Option_Scan to
601    --  set the proper character for the parser.
602    --
603    --  The switches defined in the command_line_configuration object are used
604    --  when ungrouping switches with more that one character after the prefix.
605    --
606    --  Switch and Long_Switch (when specified) are aliases and can be used
607    --  interchangeably. There is no check that they both take an argument or
608    --  both take no argument.
609    --  Switch can be set to "*" to indicate that any switch is supported (in
610    --  which case Getopt will return '*', see its documentation).
611    --
612    --  Help is used by the Display_Help procedure to describe the supported
613    --  switches.
614    --
615    --  In_Section indicates in which section the switch is valid (you need to
616    --  first define the section through a call to Define_Section).
617
618    procedure Define_Switch
619      (Config      : in out Command_Line_Configuration;
620       Output      : access Boolean;
621       Switch      : String := "";
622       Long_Switch : String := "";
623       Help        : String := "";
624       Section     : String := "";
625       Value       : Boolean := True);
626    --  See Define_Switch for a description of the parameters.
627    --  When the switch is found on the command line, Getopt will set
628    --  Output.all to Value.
629    --  Output is always initially set to "not Value", so that if the switch is
630    --  not found on the command line, Output still has a valid value.
631    --  The switch must not take any parameter.
632    --  Output must exist at least as long as Config, otherwise erroneous memory
633    --  access may happen.
634
635    procedure Define_Switch
636      (Config      : in out Command_Line_Configuration;
637       Output      : access Integer;
638       Switch      : String := "";
639       Long_Switch : String := "";
640       Help        : String := "";
641       Section     : String := "";
642       Initial     : Integer := 0;
643       Default     : Integer := 1);
644    --  See Define_Switch for a description of the parameters.
645    --  When the switch is found on the command line, Getopt will set
646    --  Output.all to the value of the switch's parameter. If the parameter is
647    --  not an integer, Invalid_Parameter is raised.
648    --  Output is always initialized to Initial. If the switch has an optional
649    --  argument which isn't specified by the user, then Output will be set to
650    --  Default.
651
652    procedure Define_Switch
653      (Config      : in out Command_Line_Configuration;
654       Output      : access GNAT.Strings.String_Access;
655       Switch      : String := "";
656       Long_Switch : String := "";
657       Help        : String := "";
658       Section     : String := "");
659    --  Set Output to the value of the switch's parameter when the switch is
660    --  found on the command line.
661    --  Output is always initialized to the empty string.
662
663    procedure Set_Usage
664      (Config : in out Command_Line_Configuration;
665       Usage  : String := "[switches] [arguments]";
666       Help   : String := "");
667    --  Defines the general format of the call to the application, and a short
668    --  help text. These are both displayed by Display_Help
669
670    procedure Display_Help (Config : Command_Line_Configuration);
671    --  Display the help for the tool (ie its usage, and its supported switches)
672
673    function Get_Switches
674      (Config      : Command_Line_Configuration;
675       Switch_Char : Character := '-';
676       Section     : String := "") return String;
677    --  Get the switches list as expected by Getopt, for a specific section of
678    --  the command line. This list is built using all switches defined
679    --  previously via Define_Switch above.
680
681    function Section_Delimiters
682      (Config : Command_Line_Configuration) return String;
683    --  Return a string suitable for use in Initialize_Option_Scan
684
685    procedure Free (Config : in out Command_Line_Configuration);
686    --  Free the memory used by Config
687
688    type Switch_Handler is access procedure
689      (Switch    : String;
690       Parameter : String;
691       Section   : String);
692    --  Called when a switch is found on the command line.
693    --  [Switch] includes any leading '-' that was specified in Define_Switch.
694    --  This is slightly different from the functional version of Getopt above,
695    --  for which Full_Switch omits the first leading '-'.
696
697    Exit_From_Command_Line : exception;
698    --  Emitted when the program should exit.
699    --  This is called when Getopt below has seen -h, --help or an invalid
700    --  switch.
701
702    procedure Getopt
703      (Config   : Command_Line_Configuration;
704       Callback : Switch_Handler := null;
705       Parser   : Opt_Parser := Command_Line_Parser);
706    --  Similar to the standard Getopt function.
707    --  For each switch found on the command line, this calls Callback.
708    --
709    --  The list of valid switches are the ones from the configuration. The
710    --  switches that were declared through Define_Switch with an Output
711    --  parameter are never returned (and result in a modification of the Output
712    --  variable). This function will in fact never call [Callback] if all
713    --  switches were handled automatically and there is nothing left to do.
714    --
715    --  This procedure automatically adds -h and --help to the valid switches,
716    --  to display the help message and raises Exit_From_Command_Line.
717    --  If an invalid switch is specified on the command line, this procedure
718    --  will display an error message and raises Invalid_Switch again.
719    --
720    --  This function automatically expands switches:
721    --   * If Define_Prefix was called (for instance "-gnaty") and the user
722    --     specifies "-gnatycb" on the command line, then Getopt returns
723    --     "-gnatyc" and "-gnatyb" separately.
724    --   * If Define_Alias was called (for instance "-gnatya = -gnatycb") then
725    --     the latter is returned (in this case it also expands -gnaty as per
726    --     the above.
727    --  The goal is to make handling as easy as possible by leaving as much
728    --  work as possible to this package.
729    --
730    --  As opposed to the standard Getopt, this one will analyze all sections
731    --  as defined by Define_Section, and automatically jump from one section to
732    --  the next.
733
734    ------------------------------
735    -- Generating command lines --
736    ------------------------------
737
738    --  Once the command line configuration has been created, you can build your
739    --  own command line. This will be done in general because you need to spawn
740    --  external tools from your application.
741
742    --  Although it could be done by concatenating strings, the following
743    --  subprograms will properly take care of grouping switches when possible,
744    --  so as to keep the command line as short as possible. They also provide a
745    --  way to remove a switch from an existing command line.
746
747    --  For instance:
748    --      declare
749    --         Config : Command_Line_Configuration;
750    --         Line : Command_Line;
751    --         Args : Argument_List_Access;
752    --      begin
753    --         Define_Switch (Config, "-gnatyc");
754    --         Define_Switch (Config, ...);  --  for all valid switches
755    --         Define_Prefix (Config, "-gnaty");
756    --
757    --         Set_Configuration (Line, Config);
758    --         Add_Switch (Line, "-O2");
759    --         Add_Switch (Line, "-gnatyc");
760    --         Add_Switch (Line, "-gnatyd");
761    --
762    --         Build (Line, Args);
763    --         --   Args is now  ["-O2", "-gnatycd"]
764    --      end;
765
766    type Command_Line is private;
767
768    procedure Set_Configuration
769      (Cmd    : in out Command_Line;
770       Config : Command_Line_Configuration);
771    function Get_Configuration
772      (Cmd : Command_Line) return Command_Line_Configuration;
773    --  Set or retrieve the configuration used for that command line
774
775    procedure Set_Command_Line
776      (Cmd                : in out Command_Line;
777       Switches           : String;
778       Getopt_Description : String    := "";
779       Switch_Char        : Character := '-');
780    --  Set the new content of the command line, by replacing the current
781    --  version with Switches.
782    --
783    --  The parsing of Switches is done through calls to Getopt, by passing
784    --  Getopt_Description as an argument. (A "*" is automatically prepended so
785    --  that all switches and command line arguments are accepted).
786    --
787    --  To properly handle switches that take parameters, you should document
788    --  them in Getopt_Description. Otherwise, the switch and its parameter will
789    --  be recorded as two separate command line arguments as returned by a
790    --  Command_Line_Iterator (which might be fine depending on your
791    --  application).
792    --
793    --  If the command line has sections (such as -bargs -cargs), then they
794    --  should be listed in the Sections parameter (as "-bargs -cargs").
795    --
796    --  This function can be used to reset Cmd by passing an empty string.
797
798    procedure Add_Switch
799      (Cmd        : in out Command_Line;
800       Switch     : String;
801       Parameter  : String    := "";
802       Separator  : Character := ' ';
803       Section    : String    := "";
804       Add_Before : Boolean   := False);
805    --  Add a new switch to the command line, and combine/group it with existing
806    --  switches if possible. Nothing is done if the switch already exists with
807    --  the same parameter.
808    --
809    --  If the Switch takes a parameter, the latter should be specified
810    --  separately, so that the association between the two is always correctly
811    --  recognized even if the order of switches on the command line changes.
812    --  For instance, you should pass "--check=full" as ("--check", "full") so
813    --  that Remove_Switch below can simply take "--check" in parameter. That
814    --  will automatically remove "full" as well. The value of the parameter is
815    --  never modified by this package.
816    --
817    --  On the other hand, you could decide to simply pass "--check=full" as
818    --  the Switch above, and then pass no parameter. This means that you need
819    --  to pass "--check=full" to Remove_Switch as well.
820    --
821    --  A Switch with a parameter will never be grouped with another switch to
822    --  avoid ambiguities as to what the parameter applies to.
823    --
824    --  If the switch is part of a section, then it should be specified so that
825    --  the switch is correctly placed in the command line, and the section
826    --  added if not already present. For example, to add the -g switch into the
827    --  -cargs section, you need to call (Cmd, "-g", Section => "-cargs").
828    --
829    --  [Separator] is ignored, and kept for backward compatibility only.
830    --  ??? It might be removed in future versions.
831    --
832    --  Invalid_Section is raised if Section was not defined in the
833    --  configuration of the command line.
834    --
835    --  Add_Before allows insertion of the switch at the beginning of the
836    --  command line.
837
838    procedure Add_Switch
839      (Cmd        : in out Command_Line;
840       Switch     : String;
841       Parameter  : String    := "";
842       Separator  : Character := ' ';
843       Section    : String    := "";
844       Add_Before : Boolean   := False;
845       Success    : out Boolean);
846    --  Same as above, returning the status of the operation
847
848    procedure Remove_Switch
849      (Cmd           : in out Command_Line;
850       Switch        : String;
851       Remove_All    : Boolean := False;
852       Has_Parameter : Boolean := False;
853       Section       : String := "");
854    --  Remove Switch from the command line, and ungroup existing switches if
855    --  necessary.
856    --
857    --  The actual parameter to the switches are ignored. If for instance
858    --  you are removing "-foo", then "-foo param1" and "-foo param2" can
859    --  be removed.
860    --
861    --  If Remove_All is True, then all matching switches are removed, otherwise
862    --  only the first matching one is removed.
863    --
864    --  If Has_Parameter is set to True, then only switches having a parameter
865    --  are removed.
866    --
867    --  If the switch belongs to a section, then this section should be
868    --  specified: Remove_Switch (Cmd_Line, "-g", Section => "-cargs") called
869    --  on the command line "-g -cargs -g" will result in "-g", while if
870    --  called with (Cmd_Line, "-g") this will result in "-cargs -g".
871    --  If Remove_All is set, then both "-g" will be removed.
872
873    procedure Remove_Switch
874      (Cmd           : in out Command_Line;
875       Switch        : String;
876       Remove_All    : Boolean := False;
877       Has_Parameter : Boolean := False;
878       Section       : String  := "";
879       Success       : out Boolean);
880    --  Same as above, reporting the success of the operation (Success is False
881    --  if no switch was removed).
882
883    procedure Remove_Switch
884      (Cmd       : in out Command_Line;
885       Switch    : String;
886       Parameter : String;
887       Section   : String := "");
888    --  Remove a switch with a specific parameter. If Parameter is the empty
889    --  string, then only a switch with no parameter will be removed.
890
891    procedure Free (Cmd : in out Command_Line);
892    --  Free the memory used by Cmd
893
894    ---------------
895    -- Iteration --
896    ---------------
897    --  When a command line was created with the above, you can then iterate
898    --  over its contents using the following iterator.
899
900    type Command_Line_Iterator is private;
901
902    procedure Start
903      (Cmd      : in out Command_Line;
904       Iter     : in out Command_Line_Iterator;
905       Expanded : Boolean := False);
906    --  Start iterating over the command line arguments. If Expanded is true,
907    --  then the arguments are not grouped and no alias is used. For instance,
908    --  "-gnatwv" and "-gnatwu" would be returned instead of "-gnatwuv".
909    --
910    --  The iterator becomes invalid if the command line is changed through a
911    --  call to Add_Switch, Remove_Switch or Set_Command_Line.
912
913    function Current_Switch    (Iter : Command_Line_Iterator) return String;
914    function Is_New_Section    (Iter : Command_Line_Iterator) return Boolean;
915    function Current_Section   (Iter : Command_Line_Iterator) return String;
916    function Current_Separator (Iter : Command_Line_Iterator) return String;
917    function Current_Parameter (Iter : Command_Line_Iterator) return String;
918    --  Return the current switch and its parameter (or the empty string if
919    --  there is no parameter or the switch was added through Add_Switch
920    --  without specifying the parameter.
921    --
922    --  Separator is the string that goes between the switch and its separator.
923    --  It could be the empty string if they should be concatenated, or a space
924    --  for instance. When printing, you should not add any other character.
925
926    function Has_More (Iter : Command_Line_Iterator) return Boolean;
927    --  Return True if there are more switches to be returned
928
929    procedure Next (Iter : in out Command_Line_Iterator);
930    --  Move to the next switch
931
932    procedure Build
933      (Line        : in out Command_Line;
934       Args        : out GNAT.OS_Lib.Argument_List_Access;
935       Expanded    : Boolean := False;
936       Switch_Char : Character := '-');
937    --  This is a wrapper using the Command_Line_Iterator. It provides a simple
938    --  way to get all switches (grouped as much as possible), and possibly
939    --  create an Opt_Parser.
940    --
941    --  Args must be freed by the caller.
942    --  Expanded has the same meaning as in Start.
943
944 private
945
946    Max_Depth : constant := 100;
947    --  Maximum depth of subdirectories
948
949    Max_Path_Length : constant := 1024;
950    --  Maximum length of relative path
951
952    type Depth is range 1 .. Max_Depth;
953
954    type Level is record
955       Name_Last : Natural := 0;
956       Dir       : GNAT.Directory_Operations.Dir_Type;
957    end record;
958
959    type Level_Array is array (Depth) of Level;
960
961    type Section_Number is new Natural range 0 .. 65534;
962    for Section_Number'Size use 16;
963
964    type Parameter_Type is record
965       Arg_Num : Positive;
966       First   : Positive;
967       Last    : Positive;
968       Extra   : Character;
969    end record;
970
971    type Is_Switch_Type is array (Natural range <>) of Boolean;
972    pragma Pack (Is_Switch_Type);
973
974    type Section_Type is array (Natural range <>) of Section_Number;
975    pragma Pack (Section_Type);
976
977    type Expansion_Iterator is limited record
978       Start : Positive := 1;
979       --  Position of the first character of the relative path to check against
980       --  the pattern.
981
982       Dir_Name : String (1 .. Max_Path_Length);
983
984       Current_Depth : Depth := 1;
985
986       Levels : Level_Array;
987
988       Regexp : GNAT.Regexp.Regexp;
989       --  Regular expression built with the pattern
990
991       Maximum_Depth : Depth := 1;
992       --  The maximum depth of directories, reflecting the number of directory
993       --  separators in the pattern.
994    end record;
995
996    type Opt_Parser_Data (Arg_Count : Natural) is record
997       Arguments : GNAT.OS_Lib.Argument_List_Access;
998       --  null if reading from the command line
999
1000       The_Parameter : Parameter_Type;
1001       The_Separator : Character;
1002       The_Switch    : Parameter_Type;
1003       --  This type and this variable are provided to store the current switch
1004       --  and parameter.
1005
1006       Is_Switch : Is_Switch_Type (1 .. Arg_Count) := (others => False);
1007       --  Indicates wich arguments on the command line are considered not be
1008       --  switches or parameters to switches (leaving e.g. filenames,...)
1009
1010       Section : Section_Type (1 .. Arg_Count) := (others => 1);
1011       --  Contains the number of the section associated with the current
1012       --  switch. If this number is 0, then it is a section delimiter, which is
1013       --  never returned by GetOpt.
1014
1015       Current_Argument : Natural := 1;
1016       --  Number of the current argument parsed on the command line
1017
1018       Current_Index : Natural := 1;
1019       --  Index in the current argument of the character to be processed
1020
1021       Current_Section : Section_Number := 1;
1022
1023       Expansion_It : aliased Expansion_Iterator;
1024       --  When Get_Argument is expanding a file name, this is the iterator used
1025
1026       In_Expansion : Boolean := False;
1027       --  True if we are expanding a file
1028
1029       Switch_Character : Character := '-';
1030       --  The character at the beginning of the command line arguments,
1031       --  indicating the beginning of a switch.
1032
1033       Stop_At_First : Boolean := False;
1034       --  If it is True then Getopt stops at the first non-switch argument
1035    end record;
1036
1037    Command_Line_Parser_Data : aliased Opt_Parser_Data
1038                                         (Ada.Command_Line.Argument_Count);
1039    --  The internal data used when parsing the command line
1040
1041    type Opt_Parser is access all Opt_Parser_Data;
1042    Command_Line_Parser : constant Opt_Parser :=
1043                            Command_Line_Parser_Data'Access;
1044
1045    type Switch_Type is (Switch_Untyped,
1046                         Switch_Boolean,
1047                         Switch_Integer,
1048                         Switch_String);
1049
1050    type Switch_Definition (Typ : Switch_Type := Switch_Untyped) is record
1051       Switch      : GNAT.OS_Lib.String_Access;
1052       Long_Switch : GNAT.OS_Lib.String_Access;
1053       Section     : GNAT.OS_Lib.String_Access;
1054       Help        : GNAT.OS_Lib.String_Access;
1055
1056       case Typ is
1057          when Switch_Untyped =>
1058             null;
1059          when Switch_Boolean =>
1060             Boolean_Output : access Boolean;
1061             Boolean_Value  : Boolean;  --  will set Output to that value
1062          when Switch_Integer =>
1063             Integer_Output  : access Integer;
1064             Integer_Initial : Integer;
1065             Integer_Default : Integer;
1066          when Switch_String =>
1067             String_Output   : access GNAT.Strings.String_Access;
1068       end case;
1069    end record;
1070    type Switch_Definitions is array (Natural range <>) of Switch_Definition;
1071    type Switch_Definitions_List is access all Switch_Definitions;
1072    --  [Switch] includes the leading '-'
1073
1074    type Alias_Definition is record
1075       Alias     : GNAT.OS_Lib.String_Access;
1076       Expansion : GNAT.OS_Lib.String_Access;
1077       Section   : GNAT.OS_Lib.String_Access;
1078    end record;
1079    type Alias_Definitions is array (Natural range <>) of Alias_Definition;
1080    type Alias_Definitions_List is access all Alias_Definitions;
1081
1082    type Command_Line_Configuration_Record is record
1083       Prefixes : GNAT.OS_Lib.Argument_List_Access;
1084       --  The list of prefixes
1085
1086       Sections : GNAT.OS_Lib.Argument_List_Access;
1087       --  The list of sections
1088
1089       Aliases  : Alias_Definitions_List;
1090       Usage    : GNAT.OS_Lib.String_Access;
1091       Help     : GNAT.OS_Lib.String_Access;
1092       Switches : Switch_Definitions_List;
1093       --  List of expected switches (Used when expanding switch groups)
1094    end record;
1095    type Command_Line_Configuration is access Command_Line_Configuration_Record;
1096
1097    type Command_Line is record
1098       Config   : Command_Line_Configuration;
1099       Expanded : GNAT.OS_Lib.Argument_List_Access;
1100
1101       Params : GNAT.OS_Lib.Argument_List_Access;
1102       --  Parameter for the corresponding switch in Expanded. The first
1103       --  character is the separator (or ASCII.NUL if there is no separator).
1104
1105       Sections : GNAT.OS_Lib.Argument_List_Access;
1106       --  The list of sections
1107
1108       Coalesce          : GNAT.OS_Lib.Argument_List_Access;
1109       Coalesce_Params   : GNAT.OS_Lib.Argument_List_Access;
1110       Coalesce_Sections : GNAT.OS_Lib.Argument_List_Access;
1111       --  Cached version of the command line. This is recomputed every time
1112       --  the command line changes. Switches are grouped as much as possible,
1113       --  and aliases are used to reduce the length of the command line. The
1114       --  parameters are not allocated, they point into Params, so they must
1115       --  not be freed.
1116    end record;
1117
1118    type Command_Line_Iterator is record
1119       List     : GNAT.OS_Lib.Argument_List_Access;
1120       Sections : GNAT.OS_Lib.Argument_List_Access;
1121       Params   : GNAT.OS_Lib.Argument_List_Access;
1122       Current  : Natural;
1123    end record;
1124
1125 end GNAT.Command_Line;