OSDN Git Service

2010-10-12 Javier Miranda <miranda@adacore.com>
[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 --  This package is flexible enough to accommodate various needs: optional
47 --  switch parameters, various characters to separate a switch and its
48 --  parameter, whether to stop the parsing at the first non-switch argument
49 --  encountered, etc.
50
51 --  begin
52 --     loop
53 --        case Getopt ("a b: ad") is  -- Accepts '-a', '-ad', or '-b argument'
54 --           when ASCII.NUL => exit;
55
56 --           when 'a' =>
57 --                 if Full_Switch = "a" then
58 --                    Put_Line ("Got a");
59 --                 else
60 --                    Put_Line ("Got ad");
61 --                 end if;
62
63 --           when 'b' =>
64 --              Put_Line ("Got b + " & Parameter);
65
66 --           when others =>
67 --              raise Program_Error;         -- cannot occur!
68 --        end case;
69 --     end loop;
70
71 --     loop
72 --        declare
73 --           S : constant String := Get_Argument (Do_Expansion => True);
74 --        begin
75 --           exit when S'Length = 0;
76 --           Put_Line ("Got " & S);
77 --        end;
78 --     end loop;
79
80 --  exception
81 --     when Invalid_Switch    => Put_Line ("Invalid Switch " & Full_Switch);
82 --     when Invalid_Parameter => Put_Line ("No parameter for " & Full_Switch);
83 --  end;
84
85 -------------
86 --  Sections
87 -------------
88
89 --  A more complicated example would involve the use of sections for the
90 --  switches, as for instance in gnatmake. The same command line is used to
91 --  provide switches for several tools. Each tool recognizes its switches by
92 --  separating them with special switches that act as section separators.
93 --  Each section acts as a command line of its own.
94
95 --  begin
96 --     Initialize_Option_Scan ('-', False, "largs bargs cargs");
97 --     loop
98 --        --  Same loop as above to get switches and arguments
99 --     end loop;
100
101 --     Goto_Section ("bargs");
102 --     loop
103 --        --  Same loop as above to get switches and arguments
104 --        --  The supported switches in Getopt might be different
105 --     end loop;
106
107 --     Goto_Section ("cargs");
108 --     loop
109 --        --  Same loop as above to get switches and arguments
110 --        --  The supported switches in Getopt might be different
111 --     end loop;
112 --  end;
113
114 ------------------------------
115 --  Parsing a list of strings
116 ------------------------------
117
118 --  The examples above show how to parse the command line when the arguments
119 --  are read directly from Ada.Command_Line. However, these arguments can also
120 --  be read from a list of strings. This can be useful in several contexts,
121 --  either because your system does not support Ada.Command_Line, or because
122 --  you are manipulating other tools and creating their command lines by hand,
123 --  or for any other reason.
124
125 --  To create the list of strings, it is recommended to use
126 --  GNAT.OS_Lib.Argument_String_To_List.
127
128 --  The example below shows how to get the parameters from such a list. Note
129 --  also the use of '*' to get all the switches, and not report errors when an
130 --  unexpected switch was used by the user
131
132 --  declare
133 --     Parser : Opt_Parser;
134 --     Args : constant Argument_List_Access :=
135 --        GNAT.OS_Lib.Argument_String_To_List ("-g -O1 -Ipath");
136 --  begin
137 --     Initialize_Option_Scan (Parser, Args);
138 --     while Getopt ("* g O! I=", Parser) /= ASCII.NUL loop
139 --        Put_Line ("Switch " & Full_Switch (Parser)
140 --                  & " param=" & Parameter (Parser));
141 --     end loop;
142 --     Free (Parser);
143 --  end;
144
145 ----------------------------------------------
146 --  Creating and manipulating the command line
147 ----------------------------------------------
148
149 --  This package provides mechanisms to create and modify command lines by
150 --  adding or removing arguments from them. The resulting command line is kept
151 --  as short as possible by coalescing arguments whenever possible.
152
153 --  Complex command lines can thus be constructed, for example from a GUI
154 --  (although this package does not by itself depend upon any specific GUI
155 --  toolkit). For instance, if you are configuring the command line to use when
156 --  spawning a tool with the following characteristics:
157
158 --    * Specifying -gnatwa is the same as specifying -gnatwu -gnatwv, but
159 --      shorter and more readable
160
161 --    * All switches starting with -gnatw can be grouped, for instance one
162 --      can write -gnatwcd instead of -gnatwc -gnatwd.
163 --      Of course, this can be combined with the above and -gnatwacd is the
164 --      same as -gnatwc -gnatwd -gnatwu -gnatwv
165
166 --    * The switch -T is the same as -gnatwAB
167
168 --    * A switch -foo takes one mandatory parameter
169
170 --  These properties can be configured through this package with the following
171 --  calls:
172
173 --     Config : Command_Line_Configuration;
174 --     Define_Prefix (Config, "-gnatw");
175 --     Define_Alias  (Config, "-gnatwa", "-gnatwuv");
176 --     Define_Alias  (Config, "-T",      "-gnatwAB");
177
178 --  Using this configuration, one can then construct a command line for the
179 --  tool with:
180
181 --     Cmd : Command_Line;
182 --     Set_Configuration (Cmd, Config);
183 --     Add_Switch (Cmd, "-bar");
184 --     Add_Switch (Cmd, "-gnatwu");
185 --     Add_Switch (Cmd, "-gnatwv");  --  will be grouped with the above
186 --     Add_Switch (Cmd, "-T");
187
188 --  The resulting command line can be iterated over to get all its switches,
189 --  There are two modes for this iteration: either you want to get the
190 --  shortest possible command line, which would be:
191
192 --      -bar -gnatwaAB
193
194 --  or on the other hand you want each individual switch (so that your own
195 --  tool does not have to do further complex processing), which would be:
196
197 --      -bar -gnatwu -gnatwv -gnatwA -gnatwB
198
199 --  Of course, we can assume that the tool you want to spawn would understand
200 --  both of these, since they are both compatible with the description we gave
201 --  above. However, the first result is useful if you want to show the user
202 --  what you are spawning (since that keeps the output shorter), and the second
203 --  output is more useful for a tool that would check whether -gnatwu was
204 --  passed (which isn't obvious in the first output). Likewise, the second
205 --  output is more useful if you have a graphical interface since each switch
206 --  can be associated with a widget, and you immediately know whether -gnatwu
207 --  was selected.
208 --
209 --  Some command line arguments can have parameters, which on a command line
210 --  appear as a separate argument that must immediately follow the switch.
211 --  Since the subprograms in this package will reorganize the switches to group
212 --  them, you need to indicate what is a command line
213 --  parameter, and what is a switch argument.
214
215 --  This is done by passing an extra argument to Add_Switch, as in:
216
217 --     Add_Switch (Cmd, "-foo", Parameter => "arg1");
218
219 --  This ensures that "arg1" will always be treated as the argument to -foo,
220 --  and will not be grouped with other parts of the command line.
221
222 ---------------------------------------------------
223 --  Parsing the command line with grouped arguments
224 ---------------------------------------------------
225
226 --  The command line construction facility can also be used in conjunction with
227 --  Getopt to interpret a command line. For example when implementing the tool
228 --  described above, you would do a first loop with Getopt to pass the switches
229 --  and their arguments, and create a temporary representation of the command
230 --  line as a Command_Line object. Finally, you can query each individual
231 --  switch from that object. For instance:
232
233 --    declare
234 --      Cmd  : Command_Line;
235 --      Iter : Command_Line_Iterator;
236
237 --    begin
238 --      while Getopt ("foo: gnatw! T bar") /= ASCII.NUL loop
239 --         Add_Switch (Cmd, Full_Switch, Parameter);
240 --      end loop;
241
242 --      Start (Cmd, Iter, Expanded => True);
243 --      while Has_More (Iter) loop
244 --        if Current_Switch (Iter) = "-gnatwu" then
245 --           ...
246 --        elsif Current_Switch (Iter) = "-gnatwv" then
247 --           ...
248 --        end if;
249 --        Next (Iter);
250 --      end loop;
251
252 --  The above means that your tool does not have to handle on its own whether
253 --  the user passed -gnatwa (in which case -gnatwu was indeed selected), or
254 --  just -gnatwu, or a combination of -gnatw switches as in -gnatwuv.
255
256 with Ada.Command_Line;
257 with GNAT.Directory_Operations;
258 with GNAT.OS_Lib;
259 with GNAT.Regexp;
260
261 package GNAT.Command_Line is
262
263    -------------
264    -- Parsing --
265    -------------
266
267    type Opt_Parser is private;
268    Command_Line_Parser : constant Opt_Parser;
269    --  This object is responsible for parsing a list of arguments, which by
270    --  default are the standard command line arguments from Ada.Command_Line.
271    --  This is really a pointer to actual data, which must therefore be
272    --  initialized through a call to Initialize_Option_Scan, and must be freed
273    --  with a call to Free.
274    --
275    --  As a special case, Command_Line_Parser does not need to be either
276    --  initialized or free-ed.
277
278    procedure Initialize_Option_Scan
279      (Switch_Char              : Character := '-';
280       Stop_At_First_Non_Switch : Boolean := False;
281       Section_Delimiters       : String := "");
282    procedure Initialize_Option_Scan
283      (Parser                   : out Opt_Parser;
284       Command_Line             : GNAT.OS_Lib.Argument_List_Access;
285       Switch_Char              : Character := '-';
286       Stop_At_First_Non_Switch : Boolean := False;
287       Section_Delimiters       : String := "");
288    --  The first procedure resets the internal state of the package to prepare
289    --  to rescan the parameters. It does not need to be called before the first
290    --  use of Getopt (but it could be), but it must be called if you want to
291    --  start rescanning the command line parameters from the start. The
292    --  optional parameter Switch_Char can be used to reset the switch
293    --  character, e.g. to '/' for use in DOS-like systems.
294    --
295    --  The second subprogram initializes a parser that takes its arguments from
296    --  an array of strings rather than directly from the command line. In this
297    --  case, the parser is responsible for freeing the strings stored in
298    --  Command_Line. If you pass null to Command_Line, this will in fact create
299    --  a second parser for Ada.Command_Line, which doesn't share any data with
300    --  the default parser. This parser must be free-ed.
301    --
302    --  The optional parameter Stop_At_First_Non_Switch indicates if Getopt is
303    --  to look for switches on the whole command line, or if it has to stop as
304    --  soon as a non-switch argument is found.
305    --
306    --  Example:
307    --
308    --      Arguments: my_application file1 -c
309    --
310    --      If Stop_At_First_Non_Switch is False, then -c will be considered
311    --      as a switch (returned by getopt), otherwise it will be considered
312    --      as a normal argument (returned by Get_Argument).
313    --
314    --  If Section_Delimiters is set, then every following subprogram
315    --  (Getopt and Get_Argument) will only operate within a section, which
316    --  is delimited by any of these delimiters or the end of the command line.
317    --
318    --  Example:
319    --      Initialize_Option_Scan (Section_Delimiters => "largs bargs cargs");
320    --
321    --      Arguments on command line : my_application -c -bargs -d -e -largs -f
322    --      This line contains three sections, the first one is the default one
323    --      and includes only the '-c' switch, the second one is between -bargs
324    --      and -largs and includes '-d -e' and the last one includes '-f'.
325
326    procedure Free (Parser : in out Opt_Parser);
327    --  Free the memory used by the parser. Calling this is not mandatory for
328    --  the Command_Line_Parser
329
330    procedure Goto_Section
331      (Name   : String := "";
332       Parser : Opt_Parser := Command_Line_Parser);
333    --  Change the current section. The next Getopt or Get_Argument will start
334    --  looking at the beginning of the section. An empty name ("") refers to
335    --  the first section between the program name and the first section
336    --  delimiter. If the section does not exist in Section_Delimiters, then
337    --  Invalid_Section is raised. If the section does not appear on the command
338    --  line, then it is treated as an empty section.
339
340    function Full_Switch
341      (Parser : Opt_Parser := Command_Line_Parser) return String;
342    --  Returns the full name of the last switch found (Getopt only returns the
343    --  first character). Does not include the Switch_Char ('-' by default),
344    --  unless the "*" option of Getopt is used (see below).
345
346    function Getopt
347      (Switches    : String;
348       Concatenate : Boolean := True;
349       Parser      : Opt_Parser := Command_Line_Parser) return Character;
350    --  This function moves to the next switch on the command line (defined as
351    --  switch character followed by a character within Switches, casing being
352    --  significant). The result returned is the first character of the switch
353    --  that is located. If there are no more switches in the current section,
354    --  returns ASCII.NUL. If Concatenate is True (the default), the switches do
355    --  not need to be separated by spaces (they can be concatenated if they do
356    --  not require an argument, e.g. -ab is the same as two separate arguments
357    --  -a -b).
358    --
359    --  Switches is a string of all the possible switches, separated by
360    --  spaces. A switch can be followed by one of the following characters:
361    --
362    --   ':'  The switch requires a parameter. There can optionally be a space
363    --        on the command line between the switch and its parameter.
364    --
365    --   '='  The switch requires a parameter. There can either be a '=' or a
366    --        space on the command line between the switch and its parameter.
367    --
368    --   '!'  The switch requires a parameter, but there can be no space on the
369    --        command line between the switch and its parameter.
370    --
371    --   '?'  The switch may have an optional parameter. There can be no space
372    --        between the switch and its argument.
373    --
374    --        e.g. if Switches has the following value : "a? b",
375    --        The command line can be:
376    --
377    --             -afoo    :  -a switch with 'foo' parameter
378    --             -a foo   :  -a switch and another element on the
379    --                           command line 'foo', returned by Get_Argument
380    --
381    --     Example: if Switches is "-a: -aO:", you can have the following
382    --              command lines:
383    --
384    --                -aarg    :  'a' switch with 'arg' parameter
385    --                -a arg   :  'a' switch with 'arg' parameter
386    --                -aOarg   :  'aO' switch with 'arg' parameter
387    --                -aO arg  :  'aO' switch with 'arg' parameter
388    --
389    --    Example:
390    --
391    --       Getopt ("a b: ac ad?")
392    --
393    --         accept either 'a' or 'ac' with no argument,
394    --         accept 'b' with a required argument
395    --         accept 'ad' with an optional argument
396    --
397    --  If the first item in switches is '*', then Getopt will catch
398    --  every element on the command line that was not caught by any other
399    --  switch. The character returned by GetOpt is '*', but Full_Switch
400    --  contains the full command line argument, including leading '-' if there
401    --  is one. If this character was not returned, there would be no way of
402    --  knowing whether it is there or not.
403    --
404    --    Example
405    --       Getopt ("* a b")
406    --       If the command line is '-a -c toto.o -b', Getopt will return
407    --       successively 'a', '*', '*' and 'b', with Full_Switch returning
408    --       "a", "-c", "toto.o", and "b".
409    --
410    --  When Getopt encounters an invalid switch, it raises the exception
411    --  Invalid_Switch and sets Full_Switch to return the invalid switch.
412    --  When Getopt cannot find the parameter associated with a switch, it
413    --  raises Invalid_Parameter, and sets Full_Switch to return the invalid
414    --  switch.
415    --
416    --  Note: in case of ambiguity, e.g. switches a ab abc, then the longest
417    --  matching switch is returned.
418    --
419    --  Arbitrary characters are allowed for switches, although it is
420    --  strongly recommended to use only letters and digits for portability
421    --  reasons.
422    --
423    --  When Concatenate is False, individual switches need to be separated by
424    --  spaces.
425    --
426    --    Example
427    --       Getopt ("a b", Concatenate => False)
428    --       If the command line is '-ab', exception Invalid_Switch will be
429    --       raised and Full_Switch will return "ab".
430
431    function Get_Argument
432      (Do_Expansion : Boolean := False;
433       Parser       : Opt_Parser := Command_Line_Parser) return String;
434    --  Returns the next element on the command line that is not a switch.  This
435    --  function should not be called before Getopt has returned ASCII.NUL.
436    --
437    --  If Do_Expansion is True, then the parameter on the command line will
438    --  be considered as a filename with wild cards, and will be expanded. The
439    --  matching file names will be returned one at a time. This is useful in
440    --  non-Unix systems for obtaining normal expansion of wild card references.
441    --  When there are no more arguments on the command line, this function
442    --  returns an empty string.
443
444    function Parameter
445      (Parser : Opt_Parser := Command_Line_Parser) return String;
446    --  Returns parameter associated with the last switch returned by Getopt.
447    --  If no parameter was associated with the last switch, or no previous call
448    --  has been made to Get_Argument, raises Invalid_Parameter. If the last
449    --  switch was associated with an optional argument and this argument was
450    --  not found on the command line, Parameter returns an empty string.
451
452    function Separator
453      (Parser : Opt_Parser := Command_Line_Parser) return Character;
454    --  The separator that was between the switch and its parameter. This is
455    --  useful if you want to know exactly what was on the command line. This
456    --  is in general a single character, set to ASCII.NUL if the switch and
457    --  the parameter were concatenated. A space is returned if the switch and
458    --  its argument were in two separate arguments.
459
460    Invalid_Section : exception;
461    --  Raised when an invalid section is selected by Goto_Section
462
463    Invalid_Switch : exception;
464    --  Raised when an invalid switch is detected in the command line
465
466    Invalid_Parameter : exception;
467    --  Raised when a parameter is missing, or an attempt is made to obtain a
468    --  parameter for a switch that does not allow a parameter
469
470    -----------------------------------------
471    -- Expansion of command line arguments --
472    -----------------------------------------
473    --  These subprograms take care of of expanding globbing patterns on the
474    --  command line. On Unix, such expansion is done by the shell before your
475    --  application is called. But on Windows you must do this expansion
476    --  yourself.
477
478    type Expansion_Iterator is limited private;
479    --  Type used during expansion of file names
480
481    procedure Start_Expansion
482      (Iterator     : out Expansion_Iterator;
483       Pattern      : String;
484       Directory    : String := "";
485       Basic_Regexp : Boolean := True);
486    --  Initialize a wild card expansion. The next calls to Expansion will
487    --  return the next file name in Directory which match Pattern (Pattern
488    --  is a regular expression, using only the Unix shell and DOS syntax if
489    --  Basic_Regexp is True). When Directory is an empty string, the current
490    --  directory is searched.
491    --
492    --  Pattern may contain directory separators (as in "src/*/*.ada").
493    --  Subdirectories of Directory will also be searched, up to one
494    --  hundred levels deep.
495    --
496    --  When Start_Expansion has been called, function Expansion should
497    --  be called repeatedly until it returns an empty string, before
498    --  Start_Expansion can be called again with the same Expansion_Iterator
499    --  variable.
500
501    function Expansion (Iterator : Expansion_Iterator) return String;
502    --  Returns the next file in the directory matching the parameters given
503    --  to Start_Expansion and updates Iterator to point to the next entry.
504    --  Returns an empty string when there are no more files.
505    --
506    --  If Expansion is called again after an empty string has been returned,
507    --  then the exception GNAT.Directory_Operations.Directory_Error is raised.
508
509    -----------------
510    -- Configuring --
511    -----------------
512    --  The following subprograms are used to manipulate a command line
513    --  represented as a string (for instance "-g -O2"), as well as parsing
514    --  the switches from such a string. They provide high-level configurations
515    --  to define aliases (a switch is equivalent to one or more other switches)
516    --  or grouping of switches ("-gnatyac" is equivalent to "-gnatya" and
517    --  "-gnatyc").
518    --  See the top of this file for examples on how to use these subprograms
519
520    type Command_Line_Configuration is private;
521
522    procedure Define_Alias
523      (Config   : in out Command_Line_Configuration;
524       Switch   : String;
525       Expanded : String);
526    --  Indicates that whenever Switch appears on the command line, it should
527    --  be expanded as Expanded. For instance, for the GNAT compiler switches,
528    --  we would define "-gnatwa" as an alias for "-gnatwcfijkmopruvz", ie some
529    --  default warnings to be activated.
530
531    procedure Define_Prefix
532      (Config   : in out Command_Line_Configuration;
533       Prefix   : String);
534    --  Indicates that all switches starting with the given prefix should be
535    --  grouped. For instance, for the GNAT compiler we would define "-gnatw" as
536    --  a prefix, so that "-gnatwu -gnatwv" can be grouped into "-gnatwuv" It is
537    --  assumed that the remainder of the switch ("uv") is a set of characters
538    --  whose order is irrelevant. In fact, this package will sort them
539    --  alphabetically.
540
541    procedure Define_Switch
542      (Config : in out Command_Line_Configuration;
543       Switch : String);
544    --  Indicates a new switch. The format of this switch follows the getopt
545    --  format (trailing ':', '?', etc for defining a switch with parameters).
546    --  The switches defined in the Command_Line_Configuration object are used
547    --  when ungrouping switches with more that one character after the prefix.
548
549    procedure Define_Section
550      (Config  : in out Command_Line_Configuration;
551       Section : String);
552    --  Indicates a new switch section. All switches belonging to the same
553    --  section are ordered together, preceded by the section. They are placed
554    --  at the end of the command line (as in "gnatmake somefile.adb -cargs -g")
555
556    function Get_Switches
557      (Config      : Command_Line_Configuration;
558       Switch_Char : Character) return String;
559    --  Get the switches list as expected by Getopt. This list is built using
560    --  all switches defined previously via Define_Switch above.
561
562    procedure Free (Config : in out Command_Line_Configuration);
563    --  Free the memory used by Config
564
565    ------------------------------
566    -- Generating command lines --
567    ------------------------------
568    --  Once the command line configuration has been created, you can build your
569    --  own command line. This will be done in general because you need to spawn
570    --  external tools from your application.
571    --  Although it could be done by concatenating strings, the following
572    --  subprograms will properly take care of grouping switches when possible,
573    --  so as to keep the command line as short as possible. They also provide a
574    --  way to remove a switch from an existing command line.
575
576    type Command_Line is private;
577
578    procedure Set_Configuration
579      (Cmd    : in out Command_Line;
580       Config : Command_Line_Configuration);
581    function Get_Configuration
582      (Cmd : Command_Line) return Command_Line_Configuration;
583    --  Set or retrieve the configuration used for that command line
584
585    procedure Set_Command_Line
586      (Cmd                : in out Command_Line;
587       Switches           : String;
588       Getopt_Description : String    := "";
589       Switch_Char        : Character := '-');
590    --  Set the new content of the command line, by replacing the current
591    --  version with Switches.
592    --
593    --  The parsing of Switches is done through calls to Getopt, by passing
594    --  Getopt_Description as an argument. (A "*" is automatically prepended so
595    --  that all switches and command line arguments are accepted).
596    --
597    --  To properly handle switches that take parameters, you should document
598    --  them in Getopt_Description. Otherwise, the switch and its parameter will
599    --  be recorded as two separate command line arguments as returned by a
600    --  Command_Line_Iterator (which might be fine depending on your
601    --  application).
602    --
603    --  If the command line has sections (such as -bargs -cargs), then they
604    --  should be listed in the Sections parameter (as "-bargs -cargs").
605    --
606    --  This function can be used to reset Cmd by passing an empty string.
607
608    procedure Add_Switch
609      (Cmd        : in out Command_Line;
610       Switch     : String;
611       Parameter  : String    := "";
612       Separator  : Character := ' ';
613       Section    : String    := "";
614       Add_Before : Boolean   := False);
615    --  Add a new switch to the command line, and combine/group it with existing
616    --  switches if possible. Nothing is done if the switch already exists with
617    --  the same parameter.
618    --
619    --  If the Switch takes a parameter, the latter should be specified
620    --  separately, so that the association between the two is always correctly
621    --  recognized even if the order of switches on the command line changes.
622    --  For instance, you should pass "--check=full" as ("--check", "full") so
623    --  that Remove_Switch below can simply take "--check" in parameter. That
624    --  will automatically remove "full" as well. The value of the parameter is
625    --  never modified by this package.
626    --
627    --  On the other hand, you could decide to simply pass "--check=full" as
628    --  the Switch above, and then pass no parameter. This means that you need
629    --  to pass "--check=full" to Remove_Switch as well.
630    --
631    --  A Switch with a parameter will never be grouped with another switch to
632    --  avoid ambiguities as to what the parameter applies to.
633    --
634    --  Separator is the character that goes between the switches and its
635    --  parameter on the command line. If it is set to ASCII.NUL, then no
636    --  separator is applied, and they are concatenated.
637    --
638    --  If the switch is part of a section, then it should be specified so that
639    --  the switch is correctly placed in the command line, and the section
640    --  added if not already present. For example, to add the -g switch into the
641    --  -cargs section, you need to call (Cmd, "-g", Section => "-cargs").
642    --
643    --  Invalid_Section is raised if Section was not defined in the
644    --  configuration of the command line.
645    --
646    --  Add_Before allows insertion of the switch at the beginning of the
647    --  command line.
648
649    procedure Add_Switch
650      (Cmd        : in out Command_Line;
651       Switch     : String;
652       Parameter  : String    := "";
653       Separator  : Character := ' ';
654       Section    : String    := "";
655       Add_Before : Boolean   := False;
656       Success    : out Boolean);
657    --  Same as above, returning the status of the operation
658
659    procedure Remove_Switch
660      (Cmd           : in out Command_Line;
661       Switch        : String;
662       Remove_All    : Boolean := False;
663       Has_Parameter : Boolean := False;
664       Section       : String := "");
665    --  Remove Switch from the command line, and ungroup existing switches if
666    --  necessary.
667    --
668    --  The actual parameter to the switches are ignored. If for instance
669    --  you are removing "-foo", then "-foo param1" and "-foo param2" can
670    --  be removed.
671    --
672    --  If Remove_All is True, then all matching switches are removed, otherwise
673    --  only the first matching one is removed.
674    --
675    --  If Has_Parameter is set to True, then only switches having a parameter
676    --  are removed.
677    --
678    --  If the switch belongs to a section, then this section should be
679    --  specified: Remove_Switch (Cmd_Line, "-g", Section => "-cargs") called
680    --  on the command line "-g -cargs -g" will result in "-g", while if
681    --  called with (Cmd_Line, "-g") this will result in "-cargs -g".
682    --  If Remove_All is set, then both "-g" will be removed.
683
684    procedure Remove_Switch
685      (Cmd           : in out Command_Line;
686       Switch        : String;
687       Remove_All    : Boolean := False;
688       Has_Parameter : Boolean := False;
689       Section       : String  := "";
690       Success       : out Boolean);
691    --  Same as above, reporting the success of the operation (Success is False
692    --  if no switch was removed).
693
694    procedure Remove_Switch
695      (Cmd       : in out Command_Line;
696       Switch    : String;
697       Parameter : String;
698       Section   : String := "");
699    --  Remove a switch with a specific parameter. If Parameter is the empty
700    --  string, then only a switch with no parameter will be removed.
701
702    procedure Free (Cmd : in out Command_Line);
703    --  Free the memory used by Cmd
704
705    ---------------
706    -- Iteration --
707    ---------------
708    --  When a command line was created with the above, you can then iterate
709    --  over its contents using the following iterator.
710
711    type Command_Line_Iterator is private;
712
713    procedure Start
714      (Cmd      : in out Command_Line;
715       Iter     : in out Command_Line_Iterator;
716       Expanded : Boolean := False);
717    --  Start iterating over the command line arguments. If Expanded is true,
718    --  then the arguments are not grouped and no alias is used. For instance,
719    --  "-gnatwv" and "-gnatwu" would be returned instead of "-gnatwuv".
720    --
721    --  The iterator becomes invalid if the command line is changed through a
722    --  call to Add_Switch, Remove_Switch or Set_Command_Line.
723
724    function Current_Switch    (Iter : Command_Line_Iterator) return String;
725    function Is_New_Section    (Iter : Command_Line_Iterator) return Boolean;
726    function Current_Section   (Iter : Command_Line_Iterator) return String;
727    function Current_Separator (Iter : Command_Line_Iterator) return String;
728    function Current_Parameter (Iter : Command_Line_Iterator) return String;
729    --  Return the current switch and its parameter (or the empty string if
730    --  there is no parameter or the switch was added through Add_Switch
731    --  without specifying the parameter.
732    --
733    --  Separator is the string that goes between the switch and its separator.
734    --  It could be the empty string if they should be concatenated, or a space
735    --  for instance. When printing, you should not add any other character.
736
737    function Has_More (Iter : Command_Line_Iterator) return Boolean;
738    --  Return True if there are more switches to be returned
739
740    procedure Next (Iter : in out Command_Line_Iterator);
741    --  Move to the next switch
742
743 private
744
745    Max_Depth : constant := 100;
746    --  Maximum depth of subdirectories
747
748    Max_Path_Length : constant := 1024;
749    --  Maximum length of relative path
750
751    type Depth is range 1 .. Max_Depth;
752
753    type Level is record
754       Name_Last : Natural := 0;
755       Dir       : GNAT.Directory_Operations.Dir_Type;
756    end record;
757
758    type Level_Array is array (Depth) of Level;
759
760    type Section_Number is new Natural range 0 .. 65534;
761    for Section_Number'Size use 16;
762
763    type Parameter_Type is record
764       Arg_Num : Positive;
765       First   : Positive;
766       Last    : Positive;
767       Extra   : Character;
768    end record;
769
770    type Is_Switch_Type is array (Natural range <>) of Boolean;
771    pragma Pack (Is_Switch_Type);
772
773    type Section_Type is array (Natural range <>) of Section_Number;
774    pragma Pack (Section_Type);
775
776    type Expansion_Iterator is limited record
777       Start : Positive := 1;
778       --  Position of the first character of the relative path to check against
779       --  the pattern.
780
781       Dir_Name : String (1 .. Max_Path_Length);
782
783       Current_Depth : Depth := 1;
784
785       Levels : Level_Array;
786
787       Regexp : GNAT.Regexp.Regexp;
788       --  Regular expression built with the pattern
789
790       Maximum_Depth : Depth := 1;
791       --  The maximum depth of directories, reflecting the number of directory
792       --  separators in the pattern.
793    end record;
794
795    type Opt_Parser_Data (Arg_Count : Natural) is record
796       Arguments : GNAT.OS_Lib.Argument_List_Access;
797       --  null if reading from the command line
798
799       The_Parameter : Parameter_Type;
800       The_Separator : Character;
801       The_Switch    : Parameter_Type;
802       --  This type and this variable are provided to store the current switch
803       --  and parameter.
804
805       Is_Switch : Is_Switch_Type (1 .. Arg_Count) := (others => False);
806       --  Indicates wich arguments on the command line are considered not be
807       --  switches or parameters to switches (leaving e.g. filenames,...)
808
809       Section : Section_Type (1 .. Arg_Count) := (others => 1);
810       --  Contains the number of the section associated with the current
811       --  switch. If this number is 0, then it is a section delimiter, which is
812       --  never returned by GetOpt.
813
814       Current_Argument : Natural := 1;
815       --  Number of the current argument parsed on the command line
816
817       Current_Index : Natural := 1;
818       --  Index in the current argument of the character to be processed
819
820       Current_Section : Section_Number := 1;
821
822       Expansion_It : aliased Expansion_Iterator;
823       --  When Get_Argument is expanding a file name, this is the iterator used
824
825       In_Expansion : Boolean := False;
826       --  True if we are expanding a file
827
828       Switch_Character : Character := '-';
829       --  The character at the beginning of the command line arguments,
830       --  indicating the beginning of a switch.
831
832       Stop_At_First : Boolean := False;
833       --  If it is True then Getopt stops at the first non-switch argument
834    end record;
835
836    Command_Line_Parser_Data : aliased Opt_Parser_Data
837      (Ada.Command_Line.Argument_Count);
838    --  The internal data used when parsing the command line
839
840    type Opt_Parser is access all Opt_Parser_Data;
841    Command_Line_Parser : constant Opt_Parser :=
842                            Command_Line_Parser_Data'Access;
843
844    type Command_Line_Configuration_Record is record
845       Prefixes : GNAT.OS_Lib.Argument_List_Access;
846       --  The list of prefixes
847
848       Sections : GNAT.OS_Lib.Argument_List_Access;
849       --  The list of sections
850
851       Aliases    : GNAT.OS_Lib.Argument_List_Access;
852       Expansions : GNAT.OS_Lib.Argument_List_Access;
853       --  The aliases (Both arrays have the same bounds)
854
855       Switches : GNAT.OS_Lib.Argument_List_Access;
856       --  List of expected switches (Used when expanding switch groups)
857    end record;
858    type Command_Line_Configuration is access Command_Line_Configuration_Record;
859
860    type Command_Line is record
861       Config   : Command_Line_Configuration;
862       Expanded : GNAT.OS_Lib.Argument_List_Access;
863
864       Params : GNAT.OS_Lib.Argument_List_Access;
865       --  Parameter for the corresponding switch in Expanded. The first
866       --  character is the separator (or ASCII.NUL if there is no separator).
867
868       Sections : GNAT.OS_Lib.Argument_List_Access;
869       --  The list of sections
870
871       Coalesce          : GNAT.OS_Lib.Argument_List_Access;
872       Coalesce_Params   : GNAT.OS_Lib.Argument_List_Access;
873       Coalesce_Sections : GNAT.OS_Lib.Argument_List_Access;
874       --  Cached version of the command line. This is recomputed every time
875       --  the command line changes. Switches are grouped as much as possible,
876       --  and aliases are used to reduce the length of the command line. The
877       --  parameters are not allocated, they point into Params, so they must
878       --  not be freed.
879    end record;
880
881    type Command_Line_Iterator is record
882       List     : GNAT.OS_Lib.Argument_List_Access;
883       Sections : GNAT.OS_Lib.Argument_List_Access;
884       Params   : GNAT.OS_Lib.Argument_List_Access;
885       Current  : Natural;
886    end record;
887
888 end GNAT.Command_Line;