* gcc.c-torture/execute/20020307-1.c: New test.
[official-gcc.git] / gcc / ada / g-regpat.ads
blob5d6c4b764992357823239788a9e06ae276883ff3
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT LIBRARY COMPONENTS --
4 -- --
5 -- G N A T . R E G P A T --
6 -- --
7 -- S p e c --
8 -- --
9 -- $Revision: 1.27 $
10 -- --
11 -- Copyright (C) 1986 by University of Toronto. --
12 -- Copyright (C) 1996-2001 Ada Core Technologies, Inc. --
13 -- --
14 -- GNAT is free software; you can redistribute it and/or modify it under --
15 -- terms of the GNU General Public License as published by the Free Soft- --
16 -- ware Foundation; either version 2, or (at your option) any later ver- --
17 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
18 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
19 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
20 -- for more details. You should have received a copy of the GNU General --
21 -- Public License distributed with GNAT; see file COPYING. If not, write --
22 -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
23 -- MA 02111-1307, USA. --
24 -- --
25 -- As a special exception, if other files instantiate generics from this --
26 -- unit, or you link this unit with other files to produce an executable, --
27 -- this unit does not by itself cause the resulting executable to be --
28 -- covered by the GNU General Public License. This exception does not --
29 -- however invalidate any other reasons why the executable file might be --
30 -- covered by the GNU Public License. --
31 -- --
32 -- GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com). --
33 -- --
34 ------------------------------------------------------------------------------
36 -- This package implements roughly the same set of regular expressions as
37 -- are available in the Perl or Python programming languages.
39 -- This is an extension of the original V7 style regular expression library
40 -- written in C by Henry Spencer. Apart from the translation to Ada, the
41 -- interface has been considerably changed to use the Ada String type
42 -- instead of C-style nul-terminated strings.
44 ------------------------------------------------------------
45 -- Summary of Pattern Matching Packages in GNAT Hierarchy --
46 ------------------------------------------------------------
48 -- There are three related packages that perform pattern maching functions.
49 -- the following is an outline of these packages, to help you determine
50 -- which is best for your needs.
52 -- GNAT.Regexp (files g-regexp.ads/g-regexp.adb)
53 -- This is a simple package providing Unix-style regular expression
54 -- matching with the restriction that it matches entire strings. It
55 -- is particularly useful for file name matching, and in particular
56 -- it provides "globbing patterns" that are useful in implementing
57 -- unix or DOS style wild card matching for file names.
59 -- GNAT.Regpat (files g-regpat.ads/g-regpat.adb)
60 -- This is a more complete implementation of Unix-style regular
61 -- expressions, copied from the Perl regular expression engine,
62 -- written originally in C by Henry Spencer. It is functionally the
63 -- same as that library.
65 -- GNAT.Spitbol.Patterns (files g-spipat.ads/g-spipat.adb)
66 -- This is a completely general pattern matching package based on the
67 -- pattern language of SNOBOL4, as implemented in SPITBOL. The pattern
68 -- language is modeled on context free grammars, with context sensitive
69 -- extensions that provide full (type 0) computational capabilities.
71 package GNAT.Regpat is
72 pragma Preelaborate (Regpat);
74 -- The grammar is the following:
76 -- regexp ::= expr
77 -- ::= ^ expr -- anchor at the beginning of string
78 -- ::= expr $ -- anchor at the end of string
79 -- expr ::= term
80 -- ::= term | term -- alternation (term or term ...)
81 -- term ::= item
82 -- ::= item item ... -- concatenation (item then item)
83 -- item ::= elmt -- match elmt
84 -- ::= elmt * -- zero or more elmt's
85 -- ::= elmt + -- one or more elmt's
86 -- ::= elmt ? -- matches elmt or nothing
87 -- ::= elmt *? -- zero or more times, minimum number
88 -- ::= elmt +? -- one or more times, minimum number
89 -- ::= elmt ?? -- zero or one time, minimum number
90 -- ::= elmt { num } -- matches elmt exactly num times
91 -- ::= elmt { num , } -- matches elmt at least num times
92 -- ::= elmt { num , num2 } -- matches between num and num2 times
93 -- ::= elmt { num }? -- matches elmt exactly num times
94 -- ::= elmt { num , }? -- matches elmt at least num times
95 -- non-greedy version
96 -- ::= elmt { num , num2 }? -- matches between num and num2 times
97 -- non-greedy version
98 -- elmt ::= nchr -- matches given character
99 -- ::= [range range ...] -- matches any character listed
100 -- ::= [^ range range ...] -- matches any character not listed
101 -- ::= . -- matches any single character
102 -- -- except newlines
103 -- ::= ( expr ) -- parens used for grouping
104 -- ::= \ num -- reference to num-th parenthesis
105 -- range ::= char - char -- matches chars in given range
106 -- ::= nchr
107 -- ::= [: posix :] -- any character in the POSIX range
108 -- ::= [:^ posix :] -- not in the POSIX range
109 -- posix ::= alnum -- alphanumeric characters
110 -- ::= alpha -- alphabetic characters
111 -- ::= ascii -- ascii characters (0 .. 127)
112 -- ::= cntrl -- control chars (0..31, 127..159)
113 -- ::= digit -- digits ('0' .. '9')
114 -- ::= graph -- graphic chars (32..126, 160..255)
115 -- ::= lower -- lower case characters
116 -- ::= print -- printable characters (32..127)
117 -- ::= punct -- printable, except alphanumeric
118 -- ::= space -- space characters
119 -- ::= upper -- upper case characters
120 -- ::= word -- alphanumeric characters
121 -- ::= xdigit -- hexadecimal chars (0..9, a..f)
123 -- char ::= any character, including special characters
124 -- ASCII.NUL is not supported.
125 -- nchr ::= any character except \()[].*+?^ or \char to match char
126 -- \n means a newline (ASCII.LF)
127 -- \t means a tab (ASCII.HT)
128 -- \r means a return (ASCII.CR)
129 -- \b matches the empty string at the beginning or end of a
130 -- word. A word is defined as a set of alphanumerical
131 -- characters (see \w below).
132 -- \B matches the empty string only when *not* at the
133 -- beginning or end of a word.
134 -- \d matches any digit character ([0-9])
135 -- \D matches any non digit character ([^0-9])
136 -- \s matches any white space character. This is equivalent
137 -- to [ \t\n\r\f\v] (tab, form-feed, vertical-tab,...
138 -- \S matches any non-white space character.
139 -- \w matches any alphanumeric character or underscore.
140 -- This include accented letters, as defined in the
141 -- package Ada.Characters.Handling.
142 -- \W matches any non-alphanumeric character.
143 -- \A match the empty string only at the beginning of the
144 -- string, whatever flags are used for Compile (the
145 -- behavior of ^ can change, see Regexp_Flags below).
146 -- \G match the empty string only at the end of the
147 -- string, whatever flags are used for Compile (the
148 -- behavior of $ can change, see Regexp_Flags below).
149 -- ... ::= is used to indication repetition (one or more terms)
151 -- Embedded newlines are not matched by the ^ operator.
152 -- It is possible to retrieve the substring matched a parenthesis
153 -- expression. Although the depth of parenthesis is not limited in the
154 -- regexp, only the first 9 substrings can be retrieved.
156 -- The highest value possible for the arguments to the curly operator ({})
157 -- are given by the constant Max_Curly_Repeat below.
159 -- The operators '*', '+', '?' and '{}' always match the longest possible
160 -- substring. They all have a non-greedy version (with an extra ? after the
161 -- operator), which matches the shortest possible substring.
163 -- For instance:
164 -- regexp="<.*>" string="<h1>title</h1>" matches="<h1>title</h1>"
165 -- regexp="<.*?>" string="<h1>title</h1>" matches="<h1>"
167 -- '{' and '}' are only considered as special characters if they appear
168 -- in a substring that looks exactly like '{n}', '{n,m}' or '{n,}', where
169 -- n and m are digits. No space is allowed. In other contexts, the curly
170 -- braces will simply be treated as normal characters.
172 -- Compiling Regular Expressions
173 -- =============================
175 -- To use this package, you first need to compile the regular expression
176 -- (a string) into a byte-code program, in a Pattern_Matcher structure.
177 -- This first step checks that the regexp is valid, and optimizes the
178 -- matching algorithms of the second step.
180 -- Two versions of the Compile subprogram are given: one in which this
181 -- package will compute itself the best possible size to allocate for the
182 -- byte code; the other where you must allocate enough memory yourself. An
183 -- exception is raised if there is not enough memory.
185 -- declare
186 -- Regexp : String := "a|b";
188 -- Matcher : Pattern_Matcher := Compile (Regexp);
189 -- -- The size for matcher is automatically allocated
191 -- Matcher2 : Pattern_Matcher (1000);
192 -- -- Some space is allocated directly.
194 -- begin
195 -- Compile (Matcher2, Regexp);
196 -- ...
197 -- end;
199 -- Note that the second version is significantly faster, since with the
200 -- first version the regular expression has in fact to be compiled twice
201 -- (first to compute the size, then to generate the byte code).
203 -- Note also that you can not use the function version of Compile if you
204 -- specify the size of the Pattern_Matcher, since the discriminants will
205 -- most probably be different and you will get a Constraint_Error
207 -- Matching Strings
208 -- ================
210 -- Once the regular expression has been compiled, you can use it as often
211 -- as needed to match strings.
213 -- Several versions of the Match subprogram are provided, with different
214 -- parameters and return results.
216 -- See the description under each of these subprograms.
218 -- Here is a short example showing how to get the substring matched by
219 -- the first parenthesis pair.
221 -- declare
222 -- Matches : Match_Array;
223 -- Regexp : String := "a(b|c)d";
224 -- Str : String := "gacdg";
226 -- begin
227 -- Match (Compile (Regexp), Str, Matches);
228 -- return Str (Matches (1).First .. Matches (1).Last);
229 -- -- returns 'c'
230 -- end;
232 -- String Substitution
233 -- ===================
235 -- No subprogram is currently provided for string substitution.
236 -- However, this is easy to simulate with the parenthesis groups, as
237 -- shown below.
239 -- This example swaps the first two words of the string:
241 -- declare
242 -- Regexp : String := "([a-z]+) +([a-z]+)";
243 -- Str : String := " first second third ";
244 -- Matches : Match_Array;
246 -- begin
247 -- Match (Compile (Regexp), Str, Matches);
248 -- return Str (Str'First .. Matches (1).First - 1)
249 -- & Str (Matches (2).First .. Matches (2).Last)
250 -- & " "
251 -- & Str (Matches (1).First .. Matches (1).Last)
252 -- & Str (Matches (2).Last + 1 .. Str'Last);
253 -- -- returns " second first third "
254 -- end;
256 ---------------
257 -- Constants --
258 ---------------
260 Expression_Error : exception;
261 -- This exception is raised when trying to compile an invalid
262 -- regular expression. All subprograms taking an expression
263 -- as parameter may raise Expression_Error.
265 Max_Paren_Count : constant := 255;
266 -- Maximum number of parenthesis in a regular expression.
267 -- This is limited by the size of a Character, as found in the
268 -- byte-compiled version of regular expressions.
270 Max_Program_Size : constant := 2**15 - 1;
271 -- Maximum size that can be allocated for a program.
273 Max_Curly_Repeat : constant := 32767;
274 -- Maximum number of repetition for the curly operator.
275 -- The digits in the {n}, {n,} and {n,m } operators can not be higher
276 -- than this constant, since they have to fit on two characters in the
277 -- byte-compiled version of regular expressions.
279 type Program_Size is range 0 .. Max_Program_Size;
280 for Program_Size'Size use 16;
281 -- Number of bytes allocated for the byte-compiled version of a regular
282 -- expression.
284 type Regexp_Flags is mod 256;
285 for Regexp_Flags'Size use 8;
286 -- Flags that can be given at compile time to specify default
287 -- properties for the regular expression.
289 No_Flags : constant Regexp_Flags;
290 Case_Insensitive : constant Regexp_Flags;
291 -- The automaton is optimized so that the matching is done in a case
292 -- insensitive manner (upper case characters and lower case characters
293 -- are all treated the same way).
295 Single_Line : constant Regexp_Flags;
296 -- Treat the Data we are matching as a single line. This means that
297 -- ^ and $ will ignore \n (unless Multiple_Lines is also specified),
298 -- and that '.' will match \n.
300 Multiple_Lines : constant Regexp_Flags;
301 -- Treat the Data as multiple lines. This means that ^ and $ will also
302 -- match on internal newlines (ASCII.LF), in addition to the beginning
303 -- and end of the string.
305 -- This can be combined with Single_Line.
307 -----------------
308 -- Match_Array --
309 -----------------
311 subtype Match_Count is Natural range 0 .. Max_Paren_Count;
313 type Match_Location is record
314 First : Natural := 0;
315 Last : Natural := 0;
316 end record;
318 type Match_Array is array (Match_Count range <>) of Match_Location;
319 -- The substring matching a given pair of parenthesis.
320 -- Index 0 is the whole substring that matched the full regular
321 -- expression.
323 -- For instance, if your regular expression is something like:
324 -- "a(b*)(c+)", then Match_Array(1) will be the indexes of the
325 -- substring that matched "b*" and Match_Array(2) will be the substring
326 -- that matched "c+".
328 -- The number of parenthesis groups that can be retrieved is unlimited,
329 -- and all the Match subprograms below can use a Match_Array of any size.
330 -- Indexes that do not have any matching parenthesis are set to
331 -- No_Match.
333 No_Match : constant Match_Location := (First => 0, Last => 0);
334 -- The No_Match constant is (0, 0) to differentiate between
335 -- matching a null string at position 1, which uses (1, 0)
336 -- and no match at all.
338 ------------------------------
339 -- Pattern_Matcher Creation --
340 ------------------------------
342 type Pattern_Matcher (Size : Program_Size) is private;
343 -- Type used to represent a regular expression compiled into byte code
345 Never_Match : constant Pattern_Matcher;
346 -- A regular expression that never matches anything
348 function Compile
349 (Expression : String;
350 Flags : Regexp_Flags := No_Flags)
351 return Pattern_Matcher;
352 -- Compile a regular expression into internal code.
353 -- Raises Expression_Error if Expression is not a legal regular expression.
354 -- The appropriate size is calculated automatically, but this means that
355 -- the regular expression has to be compiled twice (the first time to
356 -- calculate the size, the second time to actually generate the byte code).
358 -- Flags is the default value to use to set properties for Expression (case
359 -- sensitivity,...).
361 procedure Compile
362 (Matcher : out Pattern_Matcher;
363 Expression : String;
364 Final_Code_Size : out Program_Size;
365 Flags : Regexp_Flags := No_Flags);
366 -- Compile a regular expression into into internal code
367 -- This procedure is significantly faster than the function
368 -- Compile, as there is a known maximum size for the matcher.
369 -- This function raises Storage_Error if Matcher is too small
370 -- to hold the resulting code, or Expression_Error is Expression
371 -- is not a legal regular expression.
373 -- Flags is the default value to use to set properties for Expression (case
374 -- sensitivity,...).
376 procedure Compile
377 (Matcher : out Pattern_Matcher;
378 Expression : String;
379 Flags : Regexp_Flags := No_Flags);
380 -- Same procedure as above, expect it does not return the final
381 -- program size.
383 function Paren_Count (Regexp : Pattern_Matcher) return Match_Count;
384 pragma Inline (Paren_Count);
386 -- Return the number of parenthesis pairs in Regexp.
388 -- This is the maximum index that will be filled if a Match_Array is
389 -- used as an argument to Match.
391 -- Thus, if you want to be sure to get all the parenthesis, you should
392 -- do something like:
394 -- declare
395 -- Regexp : Pattern_Matcher := Compile ("a(b*)(c+)");
396 -- Matched : Match_Array (0 .. Paren_Count (Regexp));
397 -- begin
398 -- Match (Regexp, "a string", Matched);
399 -- end;
401 -------------
402 -- Quoting --
403 -------------
405 function Quote (Str : String) return String;
406 -- Return a version of Str so that every special character is quoted.
407 -- The resulting string can be used in a regular expression to match
408 -- exactly Str, whatever character was present in Str.
410 --------------
411 -- Matching --
412 --------------
414 procedure Match
415 (Expression : String;
416 Data : String;
417 Matches : out Match_Array;
418 Size : Program_Size := 0);
419 -- Match Expression against Data and store result in Matches.
420 -- Function raises Storage_Error if Size is too small for Expression,
421 -- or Expression_Error if Expression is not a legal regular expression.
422 -- If Size is 0, then the appropriate size is automatically calculated
423 -- by this package, but this is slightly slower.
425 -- At most Matches'Length parenthesis are returned.
427 function Match
428 (Expression : String;
429 Data : String;
430 Size : Program_Size := 0)
431 return Natural;
432 -- Return the position where Data matches, or (Data'First - 1) if there is
433 -- no match.
434 -- Function raises Storage_Error if Size is too small for Expression
435 -- or Expression_Error if Expression is not a legal regular expression
436 -- If Size is 0, then the appropriate size is automatically calculated
437 -- by this package, but this is slightly slower.
439 function Match
440 (Expression : String;
441 Data : String;
442 Size : Program_Size := 0)
443 return Boolean;
444 -- Return True if Data matches Expression. Match raises Storage_Error
445 -- if Size is too small for Expression, or Expression_Error if Expression
446 -- is not a legal regular expression.
448 -- If Size is 0, then the appropriate size is automatically calculated
449 -- by this package, but this is slightly slower.
451 ------------------------------------------------
452 -- Matching a pre-compiled regular expression --
453 ------------------------------------------------
455 -- The following functions are significantly faster if you need to reuse
456 -- the same regular expression multiple times, since you only have to
457 -- compile it once.
459 function Match
460 (Self : Pattern_Matcher;
461 Data : String)
462 return Natural;
463 -- Return the position where Data matches, or (Data'First - 1) if there is
464 -- no match. Raises Expression_Error if Expression is not a legal regular
465 -- expression.
467 pragma Inline (Match);
468 -- All except the last one below.
470 procedure Match
471 (Self : Pattern_Matcher;
472 Data : String;
473 Matches : out Match_Array);
474 -- Match Data using the given pattern matcher and store result in Matches.
475 -- Raises Expression_Error if Expression is not a legal regular expression.
476 -- The expression matches if Matches (0) /= No_Match.
478 -- At most Matches'Length parenthesis are returned.
480 -----------
481 -- Debug --
482 -----------
484 procedure Dump (Self : Pattern_Matcher);
485 -- Dump the compiled version of the regular expression matched by Self.
487 --------------------------
488 -- Private Declarations --
489 --------------------------
491 private
493 subtype Pointer is Program_Size;
494 -- The Pointer type is used to point into Program_Data
496 -- Note that the pointer type is not necessarily 2 bytes
497 -- although it is stored in the program using 2 bytes
499 type Program_Data is array (Pointer range <>) of Character;
501 Program_First : constant := 1;
503 -- The "internal use only" fields in regexp are present to pass
504 -- info from compile to execute that permits the execute phase
505 -- to run lots faster on simple cases. They are:
507 -- First character that must begin a match or ASCII.Nul
508 -- Anchored true iff match must start at beginning of line
509 -- Must_Have pointer to string that match must include or null
510 -- Must_Have_Length length of Must_Have string
512 -- First and Anchored permit very fast decisions on suitable
513 -- starting points for a match, cutting down the work a lot.
514 -- Must_Have permits fast rejection of lines that cannot possibly
515 -- match.
517 -- The Must_Have tests are costly enough that Optimize
518 -- supplies a Must_Have only if the r.e. contains something potentially
519 -- expensive (at present, the only such thing detected is * or +
520 -- at the start of the r.e., which can involve a lot of backup).
521 -- The length is supplied because the test in Execute needs it
522 -- and Optimize is computing it anyway.
524 -- The initialization is meant to fail-safe in case the user of this
525 -- package tries to use an uninitialized matcher. This takes advantage
526 -- of the knowledge that ASCII.Nul translates to the end-of-program (EOP)
527 -- instruction code of the state machine.
529 No_Flags : constant Regexp_Flags := 0;
530 Case_Insensitive : constant Regexp_Flags := 1;
531 Single_Line : constant Regexp_Flags := 2;
532 Multiple_Lines : constant Regexp_Flags := 4;
534 type Pattern_Matcher (Size : Pointer) is record
535 First : Character := ASCII.NUL; -- internal use only
536 Anchored : Boolean := False; -- internal use only
537 Must_Have : Pointer := 0; -- internal use only
538 Must_Have_Length : Natural := 0; -- internal use only
539 Paren_Count : Natural := 0; -- # paren groups
540 Flags : Regexp_Flags := No_Flags;
541 Program : Program_Data (Program_First .. Size) :=
542 (others => ASCII.NUL);
543 end record;
545 Never_Match : constant Pattern_Matcher :=
546 (0, ASCII.NUL, False, 0, 0, 0, No_Flags, (others => ASCII.NUL));
548 end GNAT.Regpat;