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