ada: Update copyright notice
[official-gcc.git] / gcc / ada / libgnat / g-comlin.ads
blob46cc7eb0a3e37e979189ebf24d2b66a183430bfc
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-2023, 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 3, 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. --
17 -- --
18 -- As a special exception under Section 7 of GPL version 3, you are granted --
19 -- additional permissions described in the GCC Runtime Library Exception, --
20 -- version 3.1, as published by the Free Software Foundation. --
21 -- --
22 -- You should have received a copy of the GNU General Public License and --
23 -- a copy of the GCC Runtime Library Exception along with this program; --
24 -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
25 -- <http://www.gnu.org/licenses/>. --
26 -- --
27 -- GNAT was originally developed by the GNAT team at New York University. --
28 -- Extensive contributions were provided by Ada Core Technologies Inc. --
29 -- --
30 ------------------------------------------------------------------------------
32 -- High level package for command line parsing and manipulation
34 ----------------------------------------
35 -- Simple Parsing of the Command Line --
36 ----------------------------------------
38 -- This package provides an interface for parsing command line arguments,
39 -- when they are either read from Ada.Command_Line or read from a string list.
40 -- As shown in the example below, one should first retrieve the switches
41 -- (special command line arguments starting with '-' by default) and their
42 -- parameters, and then the rest of the command line arguments.
44 -- While it may appear easy to parse the command line arguments with
45 -- Ada.Command_Line, there are in fact lots of special cases to handle in some
46 -- applications. Those are fully managed by GNAT.Command_Line. Among these are
47 -- switches with optional parameters, grouping switches (for instance "-ab"
48 -- might mean the same as "-a -b"), various characters to separate a switch
49 -- and its parameter (or none: "-a 1" and "-a1" are generally the same, which
50 -- can introduce confusion with grouped switches),...
52 -- begin
53 -- loop
54 -- case Getopt ("a b: ad") is -- Accepts '-a', '-ad', or '-b argument'
55 -- when ASCII.NUL => exit;
57 -- when 'a' =>
58 -- if Full_Switch = "a" then
59 -- Put_Line ("Got a");
60 -- else
61 -- Put_Line ("Got ad");
62 -- end if;
64 -- when 'b' => Put_Line ("Got b + " & Parameter);
66 -- when others =>
67 -- raise Program_Error; -- cannot occur
68 -- end case;
69 -- end loop;
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;
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;
85 --------------
86 -- Sections --
87 --------------
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.
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;
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;
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;
114 -------------------------------
115 -- Parsing a List of Strings --
116 -------------------------------
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.
125 -- To create the list of strings, it is recommended to use
126 -- GNAT.OS_Lib.Argument_String_To_List.
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
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;
145 -------------------------------------------
146 -- High-Level Command Line Configuration --
147 -------------------------------------------
149 -- As shown above, the code is still relatively low-level. For instance, there
150 -- is no way to indicate which switches are related (thus if "-l" and "--long"
151 -- should have the same effect, your code will need to test for both cases).
152 -- Likewise, it is difficult to handle more advanced constructs, like:
154 -- * Specifying -gnatwa is the same as specifying -gnatwu -gnatwv, but
155 -- shorter and more readable
157 -- * All switches starting with -gnatw can be grouped, for instance one
158 -- can write -gnatwcd instead of -gnatwc -gnatwd.
159 -- Of course, this can be combined with the above and -gnatwacd is the
160 -- same as -gnatwc -gnatwd -gnatwu -gnatwv
162 -- * The switch -T is the same as -gnatwAB (same as -gnatwA -gnatwB)
164 -- With the above form of Getopt, you would receive "-gnatwa", "-T" or
165 -- "-gnatwcd" in the examples above, and thus you require additional manual
166 -- parsing of the switch.
168 -- Instead, this package provides the type Command_Line_Configuration, which
169 -- stores all the knowledge above. For instance:
171 -- Config : Command_Line_Configuration;
172 -- Define_Alias (Config, "-gnatwa", "-gnatwu -gnatwv");
173 -- Define_Prefix (Config, "-gnatw");
174 -- Define_Alias (Config, "-T", "-gnatwAB");
176 -- You then need to specify all possible switches in your application by
177 -- calling Define_Switch, for instance:
179 -- Define_Switch (Config, "-gnatwu", Help => "warn on unused entities");
180 -- Define_Switch (Config, "-gnatwv", Help => "warn on unassigned var");
181 -- ...
183 -- Specifying the help message is optional, but makes it easy to then call
184 -- the function:
186 -- 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 maintaining
191 -- both the string to pass to Getopt and a subprogram to display the help.
192 -- Both will properly stay synchronized.
194 -- Once you have this Config, you just have to call:
196 -- Getopt (Config, Callback'Access);
198 -- to parse the command line. The Callback will be called for each switch
199 -- found on the command line (in the case of our example, that is "-gnatwu"
200 -- and then "-gnatwv", not "-gnatwa" itself). This simplifies command line
201 -- parsing a lot.
203 -- In fact, this can be further automated for the most command case where the
204 -- parameter passed to a switch is stored in a variable in the application.
205 -- When a switch is defined, you only have to indicate where to store the
206 -- value, and let Getopt do the rest. For instance:
208 -- Optimization : aliased Integer;
209 -- Verbose : aliased Boolean;
211 -- Define_Switch (Config, Verbose'Access,
212 -- "-v", Long_Switch => "--verbose",
213 -- Help => "Output extra verbose information");
214 -- Define_Switch (Config, Optimization'Access,
215 -- "-O?", Help => "Optimization level");
217 -- Getopt (Config); -- No callback
219 -- Since all switches are handled automatically, we don't even need to pass
220 -- a callback to Getopt. Once getopt has been called, the two variables
221 -- Optimization and Verbose have been properly initialized, either to the
222 -- default value or to the value found on the command line.
224 ------------------------------------------------
225 -- Creating and Manipulating the Command Line --
226 ------------------------------------------------
228 -- This package provides mechanisms to create and modify command lines by
229 -- adding or removing arguments from them. The resulting command line is kept
230 -- as short as possible by coalescing arguments whenever possible.
232 -- Complex command lines can thus be constructed, for example from a GUI
233 -- (although this package does not by itself depend upon any specific GUI
234 -- toolkit).
236 -- Using the configuration defined earlier, one can then construct a command
237 -- line for the tool with:
239 -- Cmd : Command_Line;
240 -- Set_Configuration (Cmd, Config); -- Config created earlier
241 -- Add_Switch (Cmd, "-bar");
242 -- Add_Switch (Cmd, "-gnatwu");
243 -- Add_Switch (Cmd, "-gnatwv"); -- will be grouped with the above
244 -- Add_Switch (Cmd, "-T");
246 -- The resulting command line can be iterated over to get all its switches,
247 -- There are two modes for this iteration: either you want to get the
248 -- shortest possible command line, which would be:
250 -- -bar -gnatwaAB
252 -- or on the other hand you want each individual switch (so that your own
253 -- tool does not have to do further complex processing), which would be:
255 -- -bar -gnatwu -gnatwv -gnatwA -gnatwB
257 -- Of course, we can assume that the tool you want to spawn would understand
258 -- both of these, since they are both compatible with the description we gave
259 -- above. However, the first result is useful if you want to show the user
260 -- what you are spawning (since that keeps the output shorter), and the second
261 -- output is more useful for a tool that would check whether -gnatwu was
262 -- passed (which isn't obvious in the first output). Likewise, the second
263 -- output is more useful if you have a graphical interface since each switch
264 -- can be associated with a widget, and you immediately know whether -gnatwu
265 -- was selected.
267 -- Some command line arguments can have parameters, which on a command line
268 -- appear as a separate argument that must immediately follow the switch.
269 -- Since the subprograms in this package will reorganize the switches to group
270 -- them, you need to indicate what is a command line parameter, and what is a
271 -- switch argument.
273 -- This is done by passing an extra argument to Add_Switch, as in:
275 -- Add_Switch (Cmd, "-foo", Parameter => "arg1");
277 -- This ensures that "arg1" will always be treated as the argument to -foo,
278 -- and will not be grouped with other parts of the command line.
280 with Ada.Command_Line;
282 with GNAT.Directory_Operations;
283 with GNAT.OS_Lib;
284 with GNAT.Regexp;
285 with GNAT.Strings;
287 package GNAT.Command_Line is
289 -------------
290 -- Parsing --
291 -------------
293 type Opt_Parser is private;
294 Command_Line_Parser : constant Opt_Parser;
295 -- This object is responsible for parsing a list of arguments, which by
296 -- default are the standard command line arguments from Ada.Command_Line.
297 -- This is really a pointer to actual data, which must therefore be
298 -- initialized through a call to Initialize_Option_Scan, and must be freed
299 -- with a call to Free.
301 -- As a special case, Command_Line_Parser does not need to be either
302 -- initialized or free-ed.
304 procedure Initialize_Option_Scan
305 (Switch_Char : Character := '-';
306 Stop_At_First_Non_Switch : Boolean := False;
307 Section_Delimiters : String := "");
308 procedure Initialize_Option_Scan
309 (Parser : out Opt_Parser;
310 Command_Line : GNAT.OS_Lib.Argument_List_Access;
311 Switch_Char : Character := '-';
312 Stop_At_First_Non_Switch : Boolean := False;
313 Section_Delimiters : String := "");
314 -- The first procedure resets the internal state of the package to prepare
315 -- to rescan the parameters. It does not need to be called before the
316 -- first use of Getopt (but it could be), but it must be called if you
317 -- want to start rescanning the command line parameters from the start.
318 -- The optional parameter Switch_Char can be used to reset the switch
319 -- character, e.g. to '/' for use in DOS-like systems.
321 -- The second subprogram initializes a parser that takes its arguments
322 -- from an array of strings rather than directly from the command line. In
323 -- this case, the parser is responsible for freeing the strings stored in
324 -- Command_Line. If you pass null to Command_Line, this will in fact create
325 -- a second parser for Ada.Command_Line, which doesn't share any data with
326 -- the default parser. This parser must be free'ed.
328 -- The optional parameter Stop_At_First_Non_Switch indicates if Getopt is
329 -- to look for switches on the whole command line, or if it has to stop as
330 -- soon as a non-switch argument is found.
332 -- Example:
334 -- Arguments: my_application file1 -c
336 -- If Stop_At_First_Non_Switch is False, then -c will be considered
337 -- as a switch (returned by getopt), otherwise it will be considered
338 -- as a normal argument (returned by Get_Argument).
340 -- If Section_Delimiters is set, then every following subprogram
341 -- (Getopt and Get_Argument) will only operate within a section, which
342 -- is delimited by any of these delimiters or the end of the command line.
344 -- Example:
345 -- Initialize_Option_Scan (Section_Delimiters => "largs bargs cargs");
347 -- Arguments on command line : my_application -c -bargs -d -e -largs -f
348 -- This line contains three sections, the first one is the default one
349 -- and includes only the '-c' switch, the second one is between -bargs
350 -- and -largs and includes '-d -e' and the last one includes '-f'.
352 procedure Free (Parser : in out Opt_Parser);
353 -- Free the memory used by the parser. Calling this is not mandatory for
354 -- the Command_Line_Parser
356 procedure Goto_Section
357 (Name : String := "";
358 Parser : Opt_Parser := Command_Line_Parser);
359 -- Change the current section. The next Getopt or Get_Argument will start
360 -- looking at the beginning of the section. An empty name ("") refers to
361 -- the first section between the program name and the first section
362 -- delimiter. If the section does not exist in Section_Delimiters, then
363 -- Invalid_Section is raised. If the section does not appear on the command
364 -- line, then it is treated as an empty section.
366 function Full_Switch
367 (Parser : Opt_Parser := Command_Line_Parser) return String;
368 -- Returns the full name of the last switch found (Getopt only returns the
369 -- first character). Does not include the Switch_Char ('-' by default),
370 -- unless the "*" option of Getopt is used (see below).
372 function Current_Section
373 (Parser : Opt_Parser := Command_Line_Parser) return String;
374 -- Return the name of the current section.
375 -- The list of valid sections is defined through Initialize_Option_Scan
377 function Getopt
378 (Switches : String;
379 Concatenate : Boolean := True;
380 Parser : Opt_Parser := Command_Line_Parser) return Character;
381 -- This function moves to the next switch on the command line (defined as
382 -- switch character followed by a character within Switches, casing being
383 -- significant). The result returned is the first character of the switch
384 -- that is located. If there are no more switches in the current section,
385 -- returns ASCII.NUL. If Concatenate is True (the default), the switches do
386 -- not need to be separated by spaces (they can be concatenated if they do
387 -- not require an argument, e.g. -ab is the same as two separate arguments
388 -- -a -b).
390 -- Switches is a string of all the possible switches, separated by
391 -- spaces. A switch can be followed by one of the following characters:
393 -- ':' The switch requires a parameter. There can optionally be a space
394 -- on the command line between the switch and its parameter.
396 -- '=' The switch requires a parameter. There can either be a '=' or a
397 -- space on the command line between the switch and its parameter.
399 -- '!' The switch requires a parameter, but there can be no space on the
400 -- command line between the switch and its parameter.
402 -- '?' The switch may have an optional parameter. There can be no space
403 -- between the switch and its argument.
405 -- e.g. if Switches has the following value : "a? b",
406 -- The command line can be:
408 -- -afoo : -a switch with 'foo' parameter
409 -- -a foo : -a switch and another element on the
410 -- command line 'foo', returned by Get_Argument
412 -- Example: if Switches is "-a: -aO:", you can have the following
413 -- command lines:
415 -- -aarg : 'a' switch with 'arg' parameter
416 -- -a arg : 'a' switch with 'arg' parameter
417 -- -aOarg : 'aO' switch with 'arg' parameter
418 -- -aO arg : 'aO' switch with 'arg' parameter
420 -- Example:
422 -- Getopt ("a b: ac ad?")
424 -- accept either 'a' or 'ac' with no argument,
425 -- accept 'b' with a required argument
426 -- accept 'ad' with an optional argument
428 -- If the first item in switches is '*', then Getopt will catch
429 -- every element on the command line that was not caught by any other
430 -- switch. The character returned by GetOpt is '*', but Full_Switch
431 -- contains the full command line argument, including leading '-' if there
432 -- is one. If this character was not returned, there would be no way of
433 -- knowing whether it is there or not.
435 -- Example
436 -- Getopt ("* a b")
437 -- If the command line is '-a -c toto.o -b', Getopt will return
438 -- successively 'a', '*', '*' and 'b', with Full_Switch returning
439 -- "a", "-c", "toto.o", and "b".
441 -- When Getopt encounters an invalid switch, it raises the exception
442 -- Invalid_Switch and sets Full_Switch to return the invalid switch.
443 -- When Getopt cannot find the parameter associated with a switch, it
444 -- raises Invalid_Parameter, and sets Full_Switch to return the invalid
445 -- switch.
447 -- Note: in case of ambiguity, e.g. switches a ab abc, then the longest
448 -- matching switch is returned.
450 -- Arbitrary characters are allowed for switches, although it is
451 -- strongly recommended to use only letters and digits for portability
452 -- reasons.
454 -- When Concatenate is False, individual switches need to be separated by
455 -- spaces.
457 -- Example
458 -- Getopt ("a b", Concatenate => False)
459 -- If the command line is '-ab', exception Invalid_Switch will be
460 -- raised and Full_Switch will return "ab".
462 function Get_Argument
463 (Do_Expansion : Boolean := False;
464 Parser : Opt_Parser := Command_Line_Parser) return String;
465 -- Returns the next element on the command line that is not a switch. This
466 -- function should be called either after Getopt has returned ASCII.NUL or
467 -- after Getopt procedure call.
469 -- If Do_Expansion is True, then the parameter on the command line will
470 -- be considered as a filename with wildcards, and will be expanded. The
471 -- matching file names will be returned one at a time. This is useful in
472 -- non-Unix systems for obtaining normal expansion of wildcard references.
473 -- When there are no more arguments on the command line, this function
474 -- returns an empty string.
476 function Get_Argument
477 (Do_Expansion : Boolean := False;
478 Parser : Opt_Parser := Command_Line_Parser;
479 End_Of_Arguments : out Boolean) return String;
480 -- The same as above but able to distinguish empty element in argument list
481 -- from end of arguments.
482 -- End_Of_Arguments is True if the end of the command line has been reached
483 -- (i.e. all available arguments have been returned by previous calls to
484 -- Get_Argument).
486 function Parameter
487 (Parser : Opt_Parser := Command_Line_Parser) return String;
488 -- Returns parameter associated with the last switch returned by Getopt.
489 -- If no parameter was associated with the last switch, or no previous call
490 -- has been made to Get_Argument, raises Invalid_Parameter. If the last
491 -- switch was associated with an optional argument and this argument was
492 -- not found on the command line, Parameter returns an empty string.
494 function Separator
495 (Parser : Opt_Parser := Command_Line_Parser) return Character;
496 -- The separator that was between the switch and its parameter. This is
497 -- useful if you want to know exactly what was on the command line. This
498 -- is in general a single character, set to ASCII.NUL if the switch and
499 -- the parameter were concatenated. A space is returned if the switch and
500 -- its argument were in two separate arguments.
502 Invalid_Section : exception;
503 -- Raised when an invalid section is selected by Goto_Section
505 Invalid_Switch : exception;
506 -- Raised when an invalid switch is detected in the command line
508 Invalid_Parameter : exception;
509 -- Raised when a parameter is missing, or an attempt is made to obtain a
510 -- parameter for a switch that does not allow a parameter.
512 -----------------------------------------
513 -- Expansion of command line arguments --
514 -----------------------------------------
516 -- These subprograms take care of expanding globbing patterns on the
517 -- command line. On Unix, such expansion is done by the shell before your
518 -- application is called. But on Windows you must do this expansion
519 -- yourself.
521 type Expansion_Iterator is limited private;
522 -- Type used during expansion of file names
524 procedure Start_Expansion
525 (Iterator : out Expansion_Iterator;
526 Pattern : String;
527 Directory : String := "";
528 Basic_Regexp : Boolean := True);
529 -- Initialize a wildcard expansion. The next calls to Expansion will
530 -- return the next file name in Directory which match Pattern (Pattern
531 -- is a regular expression, using only the Unix shell and DOS syntax if
532 -- Basic_Regexp is True). When Directory is an empty string, the current
533 -- directory is searched.
535 -- Pattern may contain directory separators (as in "src/*/*.ada").
536 -- Subdirectories of Directory will also be searched, up to one
537 -- hundred levels deep.
539 -- When Start_Expansion has been called, function Expansion should
540 -- be called repeatedly until it returns an empty string, before
541 -- Start_Expansion can be called again with the same Expansion_Iterator
542 -- variable.
544 function Expansion (Iterator : Expansion_Iterator) return String;
545 -- Returns the next file in the directory matching the parameters given
546 -- to Start_Expansion and updates Iterator to point to the next entry.
547 -- Returns an empty string when there are no more files.
549 -- If Expansion is called again after an empty string has been returned,
550 -- then the exception GNAT.Directory_Operations.Directory_Error is raised.
552 -----------------
553 -- Configuring --
554 -----------------
556 -- The following subprograms are used to manipulate a command line
557 -- represented as a string (for instance "-g -O2"), as well as parsing
558 -- the switches from such a string. They provide high-level configurations
559 -- to define aliases (a switch is equivalent to one or more other switches)
560 -- or grouping of switches ("-gnatyac" is equivalent to "-gnatya" and
561 -- "-gnatyc").
563 -- See the top of this file for examples on how to use these subprograms
565 type Command_Line_Configuration is private;
567 procedure Define_Section
568 (Config : in out Command_Line_Configuration;
569 Section : String);
570 -- Indicates a new switch section. All switches belonging to the same
571 -- section are ordered together, preceded by the section. They are placed
572 -- at the end of the command line (as in "gnatmake somefile.adb -cargs -g")
574 -- The section name should not include the leading '-'. So for instance in
575 -- the case of gnatmake we would use:
577 -- Define_Section (Config, "cargs");
578 -- Define_Section (Config, "bargs");
580 procedure Define_Alias
581 (Config : in out Command_Line_Configuration;
582 Switch : String;
583 Expanded : String;
584 Section : String := "");
585 -- Indicates that whenever Switch appears on the command line, it should
586 -- be expanded as Expanded. For instance, for the GNAT compiler switches,
587 -- we would define "-gnatwa" as an alias for "-gnatwcfijkmopruvz", ie some
588 -- default warnings to be activated.
590 -- This expansion is only done within the specified section, which must
591 -- have been defined first through a call to [Define_Section].
593 procedure Define_Prefix
594 (Config : in out Command_Line_Configuration;
595 Prefix : String);
596 -- Indicates that all switches starting with the given prefix should be
597 -- grouped. For instance, for the GNAT compiler we would define "-gnatw" as
598 -- a prefix, so that "-gnatwu -gnatwv" can be grouped into "-gnatwuv" It is
599 -- assumed that the remainder of the switch ("uv") is a set of characters
600 -- whose order is irrelevant. In fact, this package will sort them
601 -- alphabetically.
603 -- When grouping switches that accept arguments (for instance "-gnatyL!"
604 -- as the definition, and "-gnatyaL12b" as the command line), only
605 -- numerical arguments are accepted. The above is equivalent to
606 -- "-gnatya -gnatyL12 -gnatyb".
608 procedure Define_Switch
609 (Config : in out Command_Line_Configuration;
610 Switch : String := "";
611 Long_Switch : String := "";
612 Help : String := "";
613 Section : String := "";
614 Argument : String := "ARG");
615 -- Indicates a new switch. The format of this switch follows the getopt
616 -- format (trailing ':', '?', etc for defining a switch with parameters).
618 -- Switch should also start with the leading '-' (or any other characters).
619 -- If this character is not '-', you need to call Initialize_Option_Scan to
620 -- set the proper character for the parser.
622 -- The switches defined in the command_line_configuration object are used
623 -- when ungrouping switches with more that one character after the prefix.
625 -- Switch and Long_Switch (when specified) are aliases and can be used
626 -- interchangeably. There is no check that they both take an argument or
627 -- both take no argument. Switch can be set to "*" to indicate that any
628 -- switch is supported (in which case Getopt will return '*', see its
629 -- documentation).
631 -- Help is used by the Display_Help procedure to describe the supported
632 -- switches.
634 -- In_Section indicates in which section the switch is valid (you need to
635 -- first define the section through a call to Define_Section).
637 -- Argument is the name of the argument, as displayed in the automatic
638 -- help message. It is always capitalized for consistency.
640 procedure Define_Switch
641 (Config : in out Command_Line_Configuration;
642 Output : access Boolean;
643 Switch : String := "";
644 Long_Switch : String := "";
645 Help : String := "";
646 Section : String := "";
647 Value : Boolean := True);
648 -- See Define_Switch for a description of the parameters.
649 -- When the switch is found on the command line, Getopt will set
650 -- Output.all to Value.
652 -- Output is always initially set to "not Value", so that if the switch is
653 -- not found on the command line, Output still has a valid value.
654 -- The switch must not take any parameter.
656 -- Output must exist at least as long as Config, otherwise an erroneous
657 -- memory access may occur.
659 procedure Define_Switch
660 (Config : in out Command_Line_Configuration;
661 Output : access Integer;
662 Switch : String := "";
663 Long_Switch : String := "";
664 Help : String := "";
665 Section : String := "";
666 Initial : Integer := 0;
667 Default : Integer := 1;
668 Argument : String := "ARG");
669 -- See Define_Switch for a description of the parameters. When the
670 -- switch is found on the command line, Getopt will set Output.all to the
671 -- value of the switch's parameter. If the parameter is not an integer,
672 -- Invalid_Parameter is raised.
674 -- Output is always initialized to Initial. If the switch has an optional
675 -- argument which isn't specified by the user, then Output will be set to
676 -- Default. The switch must accept an argument.
678 procedure Define_Switch
679 (Config : in out Command_Line_Configuration;
680 Output : access GNAT.Strings.String_Access;
681 Switch : String := "";
682 Long_Switch : String := "";
683 Help : String := "";
684 Section : String := "";
685 Argument : String := "ARG");
686 -- Set Output to the value of the switch's parameter when the switch is
687 -- found on the command line. Output is always initialized to the empty
688 -- string if it does not have a value already (otherwise it is left as is
689 -- so that you can specify the default value directly in the declaration
690 -- of the variable). The switch must accept an argument.
692 type Value_Callback is access procedure (Switch, Value : String);
694 procedure Define_Switch
695 (Config : in out Command_Line_Configuration;
696 Callback : not null Value_Callback;
697 Switch : String := "";
698 Long_Switch : String := "";
699 Help : String := "";
700 Section : String := "";
701 Argument : String := "ARG");
702 -- Call Callback for each instance of Switch. The callback is given the
703 -- actual switch and the corresponding value. The switch must accept
704 -- an argument.
706 procedure Set_Usage
707 (Config : in out Command_Line_Configuration;
708 Usage : String := "[switches] [arguments]";
709 Help : String := "";
710 Help_Msg : String := "");
711 -- Defines the general format of the call to the application, and a short
712 -- help text. These are both displayed by Display_Help. When a non-empty
713 -- Help_Msg is given, it is used by Display_Help instead of the
714 -- automatically generated list of supported switches.
716 procedure Display_Help (Config : Command_Line_Configuration);
717 -- Display the help for the tool (i.e. its usage, and its supported
718 -- switches).
720 function Get_Switches
721 (Config : Command_Line_Configuration;
722 Switch_Char : Character := '-';
723 Section : String := "") return String;
724 -- Get the switches list as expected by Getopt, for a specific section of
725 -- the command line. This list is built using all switches defined
726 -- previously via Define_Switch above.
728 function Section_Delimiters
729 (Config : Command_Line_Configuration) return String;
730 -- Return a string suitable for use in Initialize_Option_Scan
732 procedure Free (Config : in out Command_Line_Configuration);
733 -- Free the memory used by Config
735 type Switch_Handler is access procedure
736 (Switch : String;
737 Parameter : String;
738 Section : String);
739 -- Called when a switch is found on the command line. Switch includes
740 -- any leading '-' that was specified in Define_Switch. This is slightly
741 -- different from the functional version of Getopt above, for which
742 -- Full_Switch omits the first leading '-'.
744 Exit_From_Command_Line : exception;
745 -- Raised when the program should exit because Getopt below has seen
746 -- a -h or --help switch.
748 procedure Getopt
749 (Config : Command_Line_Configuration;
750 Callback : Switch_Handler := null;
751 Parser : Opt_Parser := Command_Line_Parser;
752 Concatenate : Boolean := True;
753 Quiet : Boolean := False);
754 -- Similar to the standard Getopt function. For each switch found on the
755 -- command line, this calls Callback, if the switch is not handled
756 -- automatically.
758 -- The list of valid switches are the ones from the configuration. The
759 -- switches that were declared through Define_Switch with an Output
760 -- parameter are never returned (and result in a modification of the Output
761 -- variable). This function will in fact never call [Callback] if all
762 -- switches were handled automatically and there is nothing left to do.
764 -- The option Concatenate is identical to the one of the standard Getopt
765 -- function.
767 -- This procedure automatically adds -h and --help to the valid switches,
768 -- to display the help message and raises Exit_From_Command_Line.
769 -- If an invalid switch is specified on the command line, this procedure
770 -- will display an error message and raises Invalid_Switch again.
771 -- If the Quiet parameter is True then the error message is not displayed.
773 -- This function automatically expands switches:
775 -- If Define_Prefix was called (for instance "-gnaty") and the user
776 -- specifies "-gnatycb" on the command line, then Getopt returns
777 -- "-gnatyc" and "-gnatyb" separately.
779 -- If Define_Alias was called (for instance "-gnatya = -gnatycb") then
780 -- the latter is returned (in this case it also expands -gnaty as per
781 -- the above.
783 -- The goal is to make handling as easy as possible by leaving as much
784 -- work as possible to this package.
786 -- As opposed to the standard Getopt, this one will analyze all sections
787 -- as defined by Define_Section, and automatically jump from one section to
788 -- the next.
790 ------------------------------
791 -- Generating command lines --
792 ------------------------------
794 -- Once the command line configuration has been created, you can build your
795 -- own command line. This will be done in general because you need to spawn
796 -- external tools from your application.
798 -- Although it could be done by concatenating strings, the following
799 -- subprograms will properly take care of grouping switches when possible,
800 -- so as to keep the command line as short as possible. They also provide a
801 -- way to remove a switch from an existing command line.
803 -- For instance:
805 -- declare
806 -- Config : Command_Line_Configuration;
807 -- Line : Command_Line;
808 -- Args : Argument_List_Access;
810 -- begin
811 -- Define_Switch (Config, "-gnatyc");
812 -- Define_Switch (Config, ...); -- for all valid switches
813 -- Define_Prefix (Config, "-gnaty");
815 -- Set_Configuration (Line, Config);
816 -- Add_Switch (Line, "-O2");
817 -- Add_Switch (Line, "-gnatyc");
818 -- Add_Switch (Line, "-gnatyd");
820 -- Build (Line, Args);
821 -- -- Args is now ["-O2", "-gnatycd"]
822 -- end;
824 type Command_Line is private;
826 procedure Set_Configuration
827 (Cmd : in out Command_Line;
828 Config : Command_Line_Configuration);
829 function Get_Configuration
830 (Cmd : Command_Line) return Command_Line_Configuration;
831 -- Set or retrieve the configuration used for that command line. The Config
832 -- must have been initialized first, by calling one of the Define_Switches
833 -- subprograms.
835 procedure Set_Command_Line
836 (Cmd : in out Command_Line;
837 Switches : String;
838 Getopt_Description : String := "";
839 Switch_Char : Character := '-');
840 -- Set the new content of the command line, by replacing the current
841 -- version with Switches.
843 -- The parsing of Switches is done through calls to Getopt, by passing
844 -- Getopt_Description as an argument. (A "*" is automatically prepended so
845 -- that all switches and command line arguments are accepted). If a config
846 -- was defined via Set_Configuration, the Getopt_Description parameter will
847 -- be ignored.
849 -- To properly handle switches that take parameters, you should document
850 -- them in Getopt_Description. Otherwise, the switch and its parameter will
851 -- be recorded as two separate command line arguments as returned by a
852 -- Command_Line_Iterator (which might be fine depending on your
853 -- application).
855 -- If the command line has sections (such as -bargs -cargs), then they
856 -- should be listed in the Sections parameter (as "-bargs -cargs").
858 -- This function can be used to reset Cmd by passing an empty string
860 -- If an invalid switch is found on the command line (i.e. wasn't defined
861 -- in the configuration via Define_Switch), and the configuration wasn't
862 -- set to accept all switches (by defining "*" as a valid switch), then an
863 -- exception Invalid_Switch is raised. The exception message indicates the
864 -- invalid switch.
866 procedure Add_Switch
867 (Cmd : in out Command_Line;
868 Switch : String;
869 Parameter : String := "";
870 Separator : Character := ASCII.NUL;
871 Section : String := "";
872 Add_Before : Boolean := False);
873 -- Add a new switch to the command line, and combine/group it with existing
874 -- switches if possible. Nothing is done if the switch already exists with
875 -- the same parameter.
877 -- If the Switch takes a parameter, the latter should be specified
878 -- separately, so that the association between the two is always correctly
879 -- recognized even if the order of switches on the command line changes.
880 -- For instance, you should pass "--check=full" as ("--check", "full") so
881 -- that Remove_Switch below can simply take "--check" in parameter. That
882 -- will automatically remove "full" as well. The value of the parameter is
883 -- never modified by this package.
885 -- On the other hand, you could decide to simply pass "--check=full" as
886 -- the Switch above, and then pass no parameter. This means that you need
887 -- to pass "--check=full" to Remove_Switch as well.
889 -- A Switch with a parameter will never be grouped with another switch to
890 -- avoid ambiguities as to what the parameter applies to.
892 -- If the switch is part of a section, then it should be specified so that
893 -- the switch is correctly placed in the command line, and the section
894 -- added if not already present. For example, to add the -g switch into the
895 -- -cargs section, you need to call (Cmd, "-g", Section => "-cargs").
897 -- [Separator], if specified, overrides the separator that was defined
898 -- through Define_Switch. For instance, if the switch was defined as
899 -- "-from:", the separator defaults to a space. But if your application
900 -- uses unusual separators not supported by GNAT.Command_Line (for instance
901 -- it requires ":"), you can specify this separator here.
903 -- For instance,
904 -- Add_Switch(Cmd, "-from", "bar", ':')
906 -- results in
907 -- -from:bar
909 -- rather than the default
910 -- -from bar
912 -- Note however that Getopt doesn't know how to handle ":" as a separator.
913 -- So the recommendation is to declare the switch as "-from!" (i.e. no
914 -- space between the switch and its parameter). Then Getopt will return
915 -- ":bar" as the parameter, and you can trim the ":" in your application.
917 -- Invalid_Section is raised if Section was not defined in the
918 -- configuration of the command line.
920 -- Add_Before allows insertion of the switch at the beginning of the
921 -- command line.
923 procedure Add_Switch
924 (Cmd : in out Command_Line;
925 Switch : String;
926 Parameter : String := "";
927 Separator : Character := ASCII.NUL;
928 Section : String := "";
929 Add_Before : Boolean := False;
930 Success : out Boolean);
931 -- Same as above, returning the status of the operation
933 procedure Remove_Switch
934 (Cmd : in out Command_Line;
935 Switch : String;
936 Remove_All : Boolean := False;
937 Has_Parameter : Boolean := False;
938 Section : String := "");
939 -- Remove Switch from the command line, and ungroup existing switches if
940 -- necessary.
942 -- The actual parameter to the switches are ignored. If for instance
943 -- you are removing "-foo", then "-foo param1" and "-foo param2" can
944 -- be removed.
946 -- If Remove_All is True, then all matching switches are removed, otherwise
947 -- only the first matching one is removed.
949 -- If Has_Parameter is set to True, then only switches having a parameter
950 -- are removed.
952 -- If the switch belongs to a section, then this section should be
953 -- specified: Remove_Switch (Cmd_Line, "-g", Section => "-cargs") called
954 -- on the command line "-g -cargs -g" will result in "-g", while if
955 -- called with (Cmd_Line, "-g") this will result in "-cargs -g".
956 -- If Remove_All is set, then both "-g" will be removed.
958 procedure Remove_Switch
959 (Cmd : in out Command_Line;
960 Switch : String;
961 Remove_All : Boolean := False;
962 Has_Parameter : Boolean := False;
963 Section : String := "";
964 Success : out Boolean);
965 -- Same as above, reporting the success of the operation (Success is False
966 -- if no switch was removed).
968 procedure Remove_Switch
969 (Cmd : in out Command_Line;
970 Switch : String;
971 Parameter : String;
972 Section : String := "");
973 -- Remove a switch with a specific parameter. If Parameter is the empty
974 -- string, then only a switch with no parameter will be removed.
976 procedure Free (Cmd : in out Command_Line);
977 -- Free the memory used by Cmd
979 ---------------
980 -- Iteration --
981 ---------------
983 -- When a command line was created with the above, you can then iterate
984 -- over its contents using the following iterator.
986 type Command_Line_Iterator is private;
988 procedure Start
989 (Cmd : in out Command_Line;
990 Iter : in out Command_Line_Iterator;
991 Expanded : Boolean := False);
992 -- Start iterating over the command line arguments. If Expanded is true,
993 -- then the arguments are not grouped and no alias is used. For instance,
994 -- "-gnatwv" and "-gnatwu" would be returned instead of "-gnatwuv".
996 -- The iterator becomes invalid if the command line is changed through a
997 -- call to Add_Switch, Remove_Switch or Set_Command_Line.
999 function Current_Switch (Iter : Command_Line_Iterator) return String;
1000 function Is_New_Section (Iter : Command_Line_Iterator) return Boolean;
1001 function Current_Section (Iter : Command_Line_Iterator) return String;
1002 function Current_Separator (Iter : Command_Line_Iterator) return String;
1003 function Current_Parameter (Iter : Command_Line_Iterator) return String;
1004 -- Return the current switch and its parameter (or the empty string if
1005 -- there is no parameter or the switch was added through Add_Switch
1006 -- without specifying the parameter.
1008 -- Separator is the string that goes between the switch and its separator.
1009 -- It could be the empty string if they should be concatenated, or a space
1010 -- for instance. When printing, you should not add any other character.
1012 function Has_More (Iter : Command_Line_Iterator) return Boolean;
1013 -- Return True if there are more switches to be returned
1015 procedure Next (Iter : in out Command_Line_Iterator);
1016 -- Move to the next switch
1018 procedure Build
1019 (Line : in out Command_Line;
1020 Args : out GNAT.OS_Lib.Argument_List_Access;
1021 Expanded : Boolean := False;
1022 Switch_Char : Character := '-');
1023 -- This is a wrapper using the Command_Line_Iterator. It provides a simple
1024 -- way to get all switches (grouped as much as possible), and possibly
1025 -- create an Opt_Parser.
1027 -- Args must be freed by the caller.
1029 -- Expanded has the same meaning as in Start.
1031 procedure Try_Help;
1032 -- Output a message on standard error to indicate how to get the usage for
1033 -- the executable. This procedure should only be called when the executable
1034 -- accepts switch --help. When this procedure is called by executable xxx,
1035 -- the following message is displayed on standard error:
1036 -- try "xxx --help" for more information.
1038 private
1040 Max_Depth : constant := 100;
1041 -- Maximum depth of subdirectories
1043 Max_Path_Length : constant := 1024;
1044 -- Maximum length of relative path
1046 type Depth is range 1 .. Max_Depth;
1048 type Level is record
1049 Name_Last : Natural := 0;
1050 Dir : GNAT.Directory_Operations.Dir_Type;
1051 end record;
1053 type Level_Array is array (Depth) of Level;
1055 type Section_Number is new Natural range 0 .. 65534;
1056 for Section_Number'Size use 16;
1058 type Parameter_Type is record
1059 Arg_Num : Positive;
1060 First : Positive;
1061 Last : Natural;
1062 Extra : Character;
1063 end record;
1065 type Is_Switch_Type is array (Natural range <>) of Boolean;
1066 pragma Pack (Is_Switch_Type);
1068 type Section_Type is array (Natural range <>) of Section_Number;
1069 pragma Pack (Section_Type);
1071 type Expansion_Iterator is limited record
1072 Start : Positive := 1;
1073 -- Position of the first character of the relative path to check against
1074 -- the pattern.
1076 Dir_Name : String (1 .. Max_Path_Length);
1078 Current_Depth : Depth := 1;
1080 Levels : Level_Array;
1082 Regexp : GNAT.Regexp.Regexp;
1083 -- Regular expression built with the pattern
1085 Maximum_Depth : Depth := 1;
1086 -- The maximum depth of directories, reflecting the number of directory
1087 -- separators in the pattern.
1088 end record;
1090 type Opt_Parser_Data (Arg_Count : Natural) is record
1091 Arguments : GNAT.OS_Lib.Argument_List_Access;
1092 -- null if reading from the command line
1094 The_Parameter : Parameter_Type;
1095 The_Separator : Character;
1096 The_Switch : Parameter_Type;
1097 -- This type and this variable are provided to store the current switch
1098 -- and parameter.
1100 Is_Switch : Is_Switch_Type (1 .. Arg_Count) := [others => False];
1101 -- Indicates wich arguments on the command line are considered not be
1102 -- switches or parameters to switches (leaving e.g. filenames,...)
1104 Section : Section_Type (1 .. Arg_Count) := [others => 1];
1105 -- Contains the number of the section associated with the current
1106 -- switch. If this number is 0, then it is a section delimiter, which is
1107 -- never returned by GetOpt.
1109 Current_Argument : Natural := 1;
1110 -- Number of the current argument parsed on the command line
1112 Current_Index : Natural := 1;
1113 -- Index in the current argument of the character to be processed
1115 Current_Section : Section_Number := 1;
1117 Expansion_It : aliased Expansion_Iterator;
1118 -- When Get_Argument is expanding a file name, this is the iterator used
1120 In_Expansion : Boolean := False;
1121 -- True if we are expanding a file
1123 Switch_Character : Character := '-';
1124 -- The character at the beginning of the command line arguments,
1125 -- indicating the beginning of a switch.
1127 Stop_At_First : Boolean := False;
1128 -- If it is True then Getopt stops at the first non-switch argument
1129 end record;
1131 Command_Line_Parser_Data : aliased Opt_Parser_Data
1132 (Ada.Command_Line.Argument_Count);
1133 -- The internal data used when parsing the command line
1135 type Opt_Parser is access all Opt_Parser_Data;
1136 Command_Line_Parser : constant Opt_Parser :=
1137 Command_Line_Parser_Data'Access;
1139 type Switch_Type is (Switch_Untyped,
1140 Switch_Boolean,
1141 Switch_Integer,
1142 Switch_String,
1143 Switch_Callback);
1145 type Switch_Definition (Typ : Switch_Type := Switch_Untyped) is record
1146 Switch : GNAT.OS_Lib.String_Access;
1147 Long_Switch : GNAT.OS_Lib.String_Access;
1148 Section : GNAT.OS_Lib.String_Access;
1149 Help : GNAT.OS_Lib.String_Access;
1151 Argument : GNAT.OS_Lib.String_Access;
1152 -- null if "ARG".
1153 -- Name of the argument for this switch.
1155 case Typ is
1156 when Switch_Untyped =>
1157 null;
1158 when Switch_Boolean =>
1159 Boolean_Output : access Boolean;
1160 Boolean_Value : Boolean; -- will set Output to that value
1161 when Switch_Integer =>
1162 Integer_Output : access Integer;
1163 Integer_Initial : Integer;
1164 Integer_Default : Integer;
1165 when Switch_String =>
1166 String_Output : access GNAT.Strings.String_Access;
1167 when Switch_Callback =>
1168 Callback : Value_Callback;
1169 end case;
1170 end record;
1171 type Switch_Definitions is array (Natural range <>) of Switch_Definition;
1172 type Switch_Definitions_List is access all Switch_Definitions;
1173 -- [Switch] includes the leading '-'
1175 type Alias_Definition is record
1176 Alias : GNAT.OS_Lib.String_Access;
1177 Expansion : GNAT.OS_Lib.String_Access;
1178 Section : GNAT.OS_Lib.String_Access;
1179 end record;
1180 type Alias_Definitions is array (Natural range <>) of Alias_Definition;
1181 type Alias_Definitions_List is access all Alias_Definitions;
1183 type Command_Line_Configuration_Record is record
1184 Prefixes : GNAT.OS_Lib.Argument_List_Access;
1185 -- The list of prefixes
1187 Sections : GNAT.OS_Lib.Argument_List_Access;
1188 -- The list of sections
1190 Star_Switch : Boolean := False;
1191 -- Whether switches not described in this configuration should be
1192 -- returned to the user (True). If False, an exception Invalid_Switch
1193 -- is raised.
1195 Aliases : Alias_Definitions_List;
1196 Usage : GNAT.OS_Lib.String_Access;
1197 Help : GNAT.OS_Lib.String_Access;
1198 Help_Msg : GNAT.OS_Lib.String_Access;
1199 Switches : Switch_Definitions_List;
1200 -- List of expected switches (Used when expanding switch groups)
1201 end record;
1202 type Command_Line_Configuration is access Command_Line_Configuration_Record;
1204 type Command_Line is record
1205 Config : Command_Line_Configuration;
1206 Expanded : GNAT.OS_Lib.Argument_List_Access;
1208 Params : GNAT.OS_Lib.Argument_List_Access;
1209 -- Parameter for the corresponding switch in Expanded. The first
1210 -- character is the separator (or ASCII.NUL if there is no separator).
1212 Sections : GNAT.OS_Lib.Argument_List_Access;
1213 -- The list of sections
1215 Coalesce : GNAT.OS_Lib.Argument_List_Access;
1216 Coalesce_Params : GNAT.OS_Lib.Argument_List_Access;
1217 Coalesce_Sections : GNAT.OS_Lib.Argument_List_Access;
1218 -- Cached version of the command line. This is recomputed every time
1219 -- the command line changes. Switches are grouped as much as possible,
1220 -- and aliases are used to reduce the length of the command line. The
1221 -- parameters are not allocated, they point into Params, so they must
1222 -- not be freed.
1223 end record;
1225 type Command_Line_Iterator is record
1226 List : GNAT.OS_Lib.Argument_List_Access;
1227 Sections : GNAT.OS_Lib.Argument_List_Access;
1228 Params : GNAT.OS_Lib.Argument_List_Access;
1229 Current : Natural;
1230 end record;
1232 end GNAT.Command_Line;