OSDN Git Service

* Make-lang.in (gnat_ug_unx.info): Add dependency on stmp-docobjdir.
[pf3gnuchains/gcc-fork.git] / gcc / ada / g-awk.ads
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              G N A T . A W K                             --
6 --                                                                          --
7 --                                 S p e c                                  --
8 --                                                                          --
9 --           Copyright (C) 2000-2001 Ada Core Technologies, Inc.            --
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,  59 Temple Place - Suite 330,  Boston, --
20 -- MA 02111-1307, 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 is maintained by Ada Core Technologies Inc (http://www.gnat.com).   --
30 --                                                                          --
31 ------------------------------------------------------------------------------
32 --
33 --  This is an AWK-like unit. It provides an easy interface for parsing one
34 --  or more files containing formatted data. The file can be viewed seen as
35 --  a database where each record is a line and a field is a data element in
36 --  this line. In this implementation an AWK record is a line. This means
37 --  that a record cannot span multiple lines. The operating procedure is to
38 --  read files line by line, with each line being presented to the user of
39 --  the package. The interface provides services to access specific fields
40 --  in the line. Thus it is possible to control actions takn on a line based
41 --  on values of some fields. This can be achieved directly or by registering
42 --  callbacks triggered on programmed conditions.
43 --
44 --  The state of an AWK run is recorded in an object of type session.
45 --  The following is the procedure for using a session to control an
46 --  AWK run:
47 --
48 --     1) Specify which session is to be used. It is possible to use the
49 --        default session or to create a new one by declaring an object of
50 --        type Session_Type. For example:
51 --
52 --           Computers : Session_Type;
53 --
54 --     2) Specify how to cut a line into fields. There are two modes: using
55 --        character fields separators or column width. This is done by using
56 --        Set_Fields_Separators or Set_Fields_Width. For example by:
57 --
58 --           AWK.Set_Field_Separators (";,", Computers);
59 --
60 --        or by using iterators' Separators parameter.
61 --
62 --     3) Specify which files to parse. This is done with Add_File/Add_Files
63 --        services, or by using the iterators' Filename parameter. For
64 --        example:
65 --
66 --           AWK.Add_File ("myfile.db", Computers);
67 --
68 --     4) Run the AWK session using one of the provided iterators.
69 --
70 --           Parse
71 --              This is the most automated iterator. You can gain control on
72 --              the session only by registering one or more callbacks (see
73 --              Register).
74 --
75 --           Get_Line/End_Of_Data
76 --              This is a manual iterator to be used with a loop. You have
77 --              complete control on the session. You can use callbacks but
78 --              this is not required.
79 --
80 --           For_Every_Line
81 --              This provides a mixture of manual/automated iterator action.
82 --
83 --        Examples of these three approaches appear below
84 --
85 --  There is many ways to use this package. The following discussion shows
86 --  three approaches, using the three iterator forms, to using this package.
87 --  All examples will use the following file (computer.db):
88 --
89 --     Pluton;Windows-NT;Pentium III
90 --     Mars;Linux;Pentium Pro
91 --     Venus;Solaris;Sparc
92 --     Saturn;OS/2;i486
93 --     Jupiter;MacOS;PPC
94 --
95 --  1) Using Parse iterator
96 --
97 --     Here the first step is to register some action associated to a pattern
98 --     and then to call the Parse iterator (this is the simplest way to use
99 --     this unit). The default session is used here. For example to output the
100 --     second field (the OS) of computer "Saturn".
101 --
102 --           procedure Action is
103 --           begin
104 --              Put_Line (AWK.Field (2));
105 --           end Action;
106 --
107 --        begin
108 --           AWK.Register (1, "Saturn", Action'Access);
109 --           AWK.Parse (";", "computer.db");
110 --
111 --
112 --  2) Using the Get_Line/End_Of_Data iterator
113 --
114 --     Here you have full control. For example to do the same as
115 --     above but using a specific session, you could write:
116 --
117 --           Computer_File : Session_Type;
118 --
119 --        begin
120 --           AWK.Set_Current (Computer_File);
121 --           AWK.Open (Separators => ";",
122 --                     Filename   => "computer.db");
123 --
124 --           --  Display Saturn OS
125 --
126 --           while not AWK.End_Of_File loop
127 --              AWK.Get_Line;
128 --
129 --              if AWK.Field (1) = "Saturn" then
130 --                 Put_Line (AWK.Field (2));
131 --              end if;
132 --           end loop;
133 --
134 --           AWK.Close (Computer_File);
135 --
136 --
137 --  3) Using For_Every_Line iterator
138 --
139 --     In this case you use a provided iterator and you pass the procedure
140 --     that must be called for each record. You could code the previous
141 --     example could be coded as follows (using the iterator quick interface
142 --     but without using the current session):
143 --
144 --           Computer_File : Session_Type;
145 --
146 --           procedure Action (Quit : in out Boolean) is
147 --           begin
148 --              if AWK.Field (1, Computer_File) = "Saturn" then
149 --                 Put_Line (AWK.Field (2, Computer_File));
150 --              end if;
151 --           end Action;
152 --
153 --           procedure Look_For_Saturn is
154 --              new AWK.For_Every_Line (Action);
155 --
156 --        begin
157 --           Look_For_Saturn (Separators => ";",
158 --                            Filename   => "computer.db",
159 --                            Session    => Computer_File);
160 --
161 --           Integer_Text_IO.Put
162 --             (Integer (AWK.NR (Session => Computer_File)));
163 --           Put_Line (" line(s) have been processed.");
164 --
165 --  You can also use a regular expression for the pattern. Let us output
166 --  the computer name for all computer for which the OS has a character
167 --  O in its name.
168 --
169 --           Regexp   : String := ".*O.*";
170 --
171 --           Matcher  : Regpat.Pattern_Matcher := Regpat.Compile (Regexp);
172 --
173 --           procedure Action is
174 --           begin
175 --              Text_IO.Put_Line (AWK.Field (2));
176 --           end Action;
177 --
178 --        begin
179 --           AWK.Register (2, Matcher, Action'Unrestricted_Access);
180 --           AWK.Parse (";", "computer.db");
181 --
182
183 with Ada.Finalization;
184 with GNAT.Regpat;
185
186 package GNAT.AWK is
187
188    Session_Error : exception;
189    --  Raised when a Session is reused but is not closed.
190
191    File_Error : exception;
192    --  Raised when there is a file problem (see below).
193
194    End_Error : exception;
195    --  Raised when an attempt is made to read beyond the end of the last
196    --  file of a session.
197
198    Field_Error : exception;
199    --  Raised when accessing a field value which does not exist.
200
201    Data_Error : exception;
202    --  Raised when it is not possible to convert a field value to a specific
203    --  type.
204
205    type Count is new Natural;
206
207    type Widths_Set is array (Positive range <>) of Positive;
208    --  Used to store a set of columns widths.
209
210    Default_Separators : constant String := " " & ASCII.HT;
211
212    Use_Current : constant String := "";
213    --  Value used when no separator or filename is specified in iterators.
214
215    type Session_Type is limited private;
216    --  This is the main exported type. A session is used to keep the state of
217    --  a full AWK run. The state comprises a list of files, the current file,
218    --  the number of line processed, the current line, the number of fields in
219    --  the current line... A default session is provided (see Set_Current,
220    --  Current_Session and Default_Session above).
221
222    ----------------------------
223    -- Package initialization --
224    ----------------------------
225
226    --  To be thread safe it is not possible to use the default provided
227    --  session. Each task must used a specific session and specify it
228    --  explicitly for every services.
229
230    procedure Set_Current (Session : Session_Type);
231    --  Set the session to be used by default. This file will be used when the
232    --  Session parameter in following services is not specified.
233
234    function Current_Session return Session_Type;
235    --  Returns the session used by default by all services. This is the
236    --  latest session specified by Set_Current service or the session
237    --  provided by default with this implementation.
238
239    function Default_Session return Session_Type;
240    --  Returns the default session provided by this package. Note that this is
241    --  the session return by Current_Session if Set_Current has not been used.
242
243    procedure Set_Field_Separators
244      (Separators : String       := Default_Separators;
245       Session    : Session_Type := Current_Session);
246    --  Set the field separators. Each character in the string is a field
247    --  separator. When a line is read it will be split by field using the
248    --  separators set here. Separators can be changed at any point and in this
249    --  case the current line is split according to the new separators. In the
250    --  special case that Separators is a space and a tabulation
251    --  (Default_Separators), fields are separated by runs of spaces and/or
252    --  tabs.
253
254    procedure Set_FS
255      (Separators : String       := Default_Separators;
256       Session    : Session_Type := Current_Session)
257      renames Set_Field_Separators;
258    --  FS is the AWK abbreviation for above service.
259
260    procedure Set_Field_Widths
261      (Field_Widths : Widths_Set;
262       Session      : Session_Type := Current_Session);
263    --  This is another way to split a line by giving the length (in number of
264    --  characters) of each field in a line. Field widths can be changed at any
265    --  point and in this case the current line is split according to the new
266    --  field lengths. A line split with this method must have a length equal or
267    --  greater to the total of the field widths. All characters remaining on
268    --  the line after the latest field are added to a new automatically
269    --  created field.
270
271    procedure Add_File
272      (Filename : String;
273       Session  : Session_Type := Current_Session);
274    --  Add Filename to the list of file to be processed. There is no limit on
275    --  the number of files that can be added. Files are processed in the order
276    --  they have been added (i.e. the filename list is FIFO). If Filename does
277    --  not exist or if it is not readable, File_Error is raised.
278
279    procedure Add_Files
280      (Directory             : String;
281       Filenames             : String;
282       Number_Of_Files_Added : out Natural;
283       Session               : Session_Type := Current_Session);
284    --  Add all files matching the regular expression Filenames in the specified
285    --  directory to the list of file to be processed. There is no limit on
286    --  the number of files that can be added. Each file is processed in
287    --  the same order they have been added (i.e. the filename list is FIFO).
288    --  The number of files (possibly 0) added is returned in
289    --  Number_Of_Files_Added.
290
291    -------------------------------------
292    -- Information about current state --
293    -------------------------------------
294
295    function Number_Of_Fields
296      (Session : Session_Type := Current_Session)
297       return    Count;
298    pragma Inline (Number_Of_Fields);
299    --  Returns the number of fields in the current record. It returns 0 when
300    --  no file is being processed.
301
302    function NF
303      (Session : Session_Type := Current_Session)
304       return    Count
305      renames Number_Of_Fields;
306    --  AWK abbreviation for above service.
307
308    function Number_Of_File_Lines
309      (Session : Session_Type := Current_Session)
310       return    Count;
311    pragma Inline (Number_Of_File_Lines);
312    --  Returns the current line number in the processed file. It returns 0 when
313    --  no file is being processed.
314
315    function FNR
316      (Session : Session_Type := Current_Session)
317       return    Count renames Number_Of_File_Lines;
318    --  AWK abbreviation for above service.
319
320    function Number_Of_Lines
321      (Session : Session_Type := Current_Session)
322       return    Count;
323    pragma Inline (Number_Of_Lines);
324    --  Returns the number of line processed until now. This is equal to number
325    --  of line in each already processed file plus FNR. It returns 0 when
326    --  no file is being processed.
327
328    function NR
329      (Session : Session_Type := Current_Session)
330       return    Count
331      renames Number_Of_Lines;
332    --  AWK abbreviation for above service.
333
334    function Number_Of_Files
335      (Session : Session_Type := Current_Session)
336       return    Natural;
337    pragma Inline (Number_Of_Files);
338    --  Returns the number of files associated with Session. This is the total
339    --  number of files added with Add_File and Add_Files services.
340
341    function File
342      (Session : Session_Type := Current_Session)
343       return    String;
344    --  Returns the name of the file being processed. It returns the empty
345    --  string when no file is being processed.
346
347    ---------------------
348    -- Field accessors --
349    ---------------------
350
351    function Field
352      (Rank    : Count;
353       Session : Session_Type := Current_Session)
354       return    String;
355    --  Returns field number Rank value of the current record. If Rank = 0 it
356    --  returns the current record (i.e. the line as read in the file). It
357    --  raises Field_Error if Rank > NF or if Session is not open.
358
359    function Field
360      (Rank    : Count;
361       Session : Session_Type := Current_Session)
362       return    Integer;
363    --  Returns field number Rank value of the current record as an integer. It
364    --  raises Field_Error if Rank > NF or if Session is not open. It
365    --  raises Data_Error if the field value cannot be converted to an integer.
366
367    function Field
368      (Rank    : Count;
369       Session : Session_Type := Current_Session)
370       return    Float;
371    --  Returns field number Rank value of the current record as a float. It
372    --  raises Field_Error if Rank > NF or if Session is not open. It
373    --  raises Data_Error if the field value cannot be converted to a float.
374
375    generic
376       type Discrete is (<>);
377    function Discrete_Field
378      (Rank    : Count;
379       Session : Session_Type := Current_Session)
380       return    Discrete;
381    --  Returns field number Rank value of the current record as a type
382    --  Discrete. It raises Field_Error if Rank > NF. It raises Data_Error if
383    --  the field value cannot be converted to type Discrete.
384
385    --------------------
386    -- Pattern/Action --
387    --------------------
388
389    --  AWK defines rules like "PATTERN { ACTION }". Which means that ACTION
390    --  will be executed if PATTERN match. A pattern in this implementation can
391    --  be a simple string (match function is equality), a regular expression,
392    --  a function returning a boolean. An action is associated to a pattern
393    --  using the Register services.
394    --
395    --  Each procedure Register will add a rule to the set of rules for the
396    --  session. Rules are examined in the order they have been added.
397
398    type Pattern_Callback is access function return Boolean;
399    --  This is a pattern function pointer. When it returns True the associated
400    --  action will be called.
401
402    type Action_Callback is access procedure;
403    --  A simple action pointer
404
405    type Match_Action_Callback is
406      access procedure (Matches : GNAT.Regpat.Match_Array);
407    --  An advanced action pointer used with a regular expression pattern. It
408    --  returns an array of all the matches. See GNAT.Regpat for further
409    --  information.
410
411    procedure Register
412      (Field   : Count;
413       Pattern : String;
414       Action  : Action_Callback;
415       Session : Session_Type := Current_Session);
416    --  Register an Action associated with a Pattern. The pattern here is a
417    --  simple string that must match exactly the field number specified.
418
419    procedure Register
420      (Field   : Count;
421       Pattern : GNAT.Regpat.Pattern_Matcher;
422       Action  : Action_Callback;
423       Session : Session_Type := Current_Session);
424    --  Register an Action associated with a Pattern. The pattern here is a
425    --  simple regular expression which must match the field number specified.
426
427    procedure Register
428      (Field   : Count;
429       Pattern : GNAT.Regpat.Pattern_Matcher;
430       Action  : Match_Action_Callback;
431       Session : Session_Type := Current_Session);
432    --  Same as above but it pass the set of matches to the action
433    --  procedure. This is useful to analyse further why and where a regular
434    --  expression did match.
435
436    procedure Register
437      (Pattern : Pattern_Callback;
438       Action  : Action_Callback;
439       Session : Session_Type := Current_Session);
440    --  Register an Action associated with a Pattern. The pattern here is a
441    --  function that must return a boolean. Action callback will be called if
442    --  the pattern callback returns True and nothing will happen if it is
443    --  False. This version is more general, the two other register services
444    --  trigger an action based on the value of a single field only.
445
446    procedure Register
447      (Action  : Action_Callback;
448       Session : Session_Type := Current_Session);
449    --  Register an Action that will be called for every line. This is
450    --  equivalent to a Pattern_Callback function always returning True.
451
452    --------------------
453    -- Parse iterator --
454    --------------------
455
456    procedure Parse
457      (Separators : String := Use_Current;
458       Filename   : String := Use_Current;
459       Session    : Session_Type := Current_Session);
460    --  Launch the iterator, it will read every line in all specified
461    --  session's files. Registered callbacks are then called if the associated
462    --  pattern match. It is possible to specify a filename and a set of
463    --  separators directly. This offer a quick way to parse a single
464    --  file. These parameters will override those specified by Set_FS and
465    --  Add_File. The Session will be opened and closed automatically.
466    --  File_Error is raised if there is no file associated with Session, or if
467    --  a file associated with Session is not longer readable. It raises
468    --  Session_Error is Session is already open.
469
470    -----------------------------------
471    -- Get_Line/End_Of_Data Iterator --
472    -----------------------------------
473
474    type Callback_Mode is (None, Only, Pass_Through);
475    --  These mode are used for Get_Line/End_Of_Data and For_Every_Line
476    --  iterators. The associated semantic is:
477    --
478    --    None
479    --       callbacks are not active. This is the default mode for
480    --       Get_Line/End_Of_Data and For_Every_Line iterators.
481    --
482    --    Only
483    --       callbacks are active, if at least one pattern match, the associated
484    --       action is called and this line will not be passed to the user. In
485    --       the Get_Line case the next line will be read (if there is some
486    --       line remaining), in the For_Every_Line case Action will
487    --       not be called for this line.
488    --
489    --    Pass_Through
490    --       callbacks are active, for patterns which match the associated
491    --       action is called. Then the line is passed to the user. It means
492    --       that Action procedure is called in the For_Every_Line case and
493    --       that Get_Line returns with the current line active.
494    --
495
496    procedure Open
497      (Separators : String := Use_Current;
498       Filename   : String := Use_Current;
499       Session    : Session_Type := Current_Session);
500    --  Open the first file and initialize the unit. This must be called once
501    --  before using Get_Line. It is possible to specify a filename and a set of
502    --  separators directly. This offer a quick way to parse a single file.
503    --  These parameters will override those specified by Set_FS and Add_File.
504    --  File_Error is raised if there is no file associated with Session, or if
505    --  the first file associated with Session is no longer readable. It raises
506    --  Session_Error is Session is already open.
507
508    procedure Get_Line
509      (Callbacks : Callback_Mode := None;
510       Session   : Session_Type  := Current_Session);
511    --  Read a line from the current input file. If the file index is at the
512    --  end of the current input file (i.e. End_Of_File is True) then the
513    --  following file is opened. If there is no more file to be processed,
514    --  exception End_Error will be raised. File_Error will be raised if Open
515    --  has not been called. Next call to Get_Line will return the following
516    --  line in the file. By default the registered callbacks are not called by
517    --  Get_Line, this can activated by setting Callbacks (see Callback_Mode
518    --  description above). File_Error may be raised if a file associated with
519    --  Session is not readable.
520    --
521    --  When Callbacks is not None, it is possible to exhaust all the lines
522    --  of all the files associated with Session. In this case, File_Error
523    --  is not raised.
524    --
525    --  This procedure can be used from a subprogram called by procedure Parse
526    --  or by an instantiation of For_Every_Line (see below).
527
528    function End_Of_Data
529      (Session : Session_Type := Current_Session)
530       return    Boolean;
531    pragma Inline (End_Of_Data);
532    --  Returns True if there is no more data to be processed in Session. It
533    --  means that the latest session's file is being processed and that
534    --  there is no more data to be read in this file (End_Of_File is True).
535
536    function End_Of_File
537      (Session : Session_Type := Current_Session)
538       return    Boolean;
539    pragma Inline (End_Of_File);
540    --  Returns True when there is no more data to be processed on the current
541    --  session's file.
542
543    procedure Close (Session : Session_Type);
544    --  Release all associated data with Session. All memory allocated will
545    --  be freed, the current file will be closed if needed, the callbacks
546    --  will be unregistered. Close is convenient in reestablishing a session
547    --  for new use. Get_Line is no longer usable (will raise File_Error)
548    --  except after a successful call to Open, Parse or an instantiation
549    --  of For_Every_Line.
550
551    -----------------------------
552    -- For_Every_Line iterator --
553    -----------------------------
554
555    generic
556       with procedure Action (Quit : in out Boolean);
557    procedure For_Every_Line
558      (Separators : String := Use_Current;
559       Filename   : String := Use_Current;
560       Callbacks  : Callback_Mode := None;
561       Session    : Session_Type := Current_Session);
562    --  This is another iterator. Action will be called for each new
563    --  record. The iterator's termination can be controlled by setting Quit
564    --  to True. It is by default set to False. It is possible to specify a
565    --  filename and a set of separators directly. This offer a quick way to
566    --  parse a single file. These parameters will override those specified by
567    --  Set_FS and Add_File. By default the registered callbacks are not called
568    --  by For_Every_Line, this can activated by setting Callbacks (see
569    --  Callback_Mode description above). The Session will be opened and
570    --  closed automatically. File_Error is raised if there is no file
571    --  associated with Session. It raises Session_Error is Session is already
572    --  open.
573
574 private
575    type Session_Data;
576    type Session_Data_Access is access Session_Data;
577
578    type Session_Type is new Ada.Finalization.Limited_Controlled with record
579       Data : Session_Data_Access;
580    end record;
581
582    procedure Initialize (Session : in out Session_Type);
583    procedure Finalize   (Session : in out Session_Type);
584
585 end GNAT.AWK;