1 ------------------------------------------------------------------------------
3 -- GNAT LIBRARY COMPONENTS --
5 -- S Y S T E M . R E G P A T --
9 -- Copyright (C) 1986 by University of Toronto. --
10 -- Copyright (C) 1996-2008, AdaCore --
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, 51 Franklin Street, Fifth Floor, --
21 -- Boston, MA 02110-1301, 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 was originally developed by the GNAT team at New York University. --
31 -- Extensive contributions were provided by Ada Core Technologies Inc. --
33 ------------------------------------------------------------------------------
35 -- This package implements roughly the same set of regular expressions as
36 -- are available in the Perl or Python programming languages.
38 -- This is an extension of the original V7 style regular expression library
39 -- written in C by Henry Spencer. Apart from the translation to Ada, the
40 -- interface has been considerably changed to use the Ada String type
41 -- instead of C-style nul-terminated strings.
43 -- Note: this package is in the System hierarchy so that it can be directly
44 -- be used by other predefined packages. User access to this package is via
45 -- a renaming of this package in GNAT.Regpat (file g-regpat.ads).
47 package System
.Regpat
is
50 -- The grammar is the following:
53 -- ::= ^ expr -- anchor at the beginning of string
54 -- ::= expr $ -- anchor at the end of string
57 -- ::= term | term -- alternation (term or term ...)
60 -- ::= item item ... -- concatenation (item then item)
62 -- item ::= elmt -- match elmt
63 -- ::= elmt * -- zero or more elmt's
64 -- ::= elmt + -- one or more elmt's
65 -- ::= elmt ? -- matches elmt or nothing
66 -- ::= elmt *? -- zero or more times, minimum number
67 -- ::= elmt +? -- one or more times, minimum number
68 -- ::= elmt ?? -- zero or one time, minimum number
69 -- ::= elmt { num } -- matches elmt exactly num times
70 -- ::= elmt { num , } -- matches elmt at least num times
71 -- ::= elmt { num , num2 } -- matches between num and num2 times
72 -- ::= elmt { num }? -- matches elmt exactly num times
73 -- ::= elmt { num , }? -- matches elmt at least num times
75 -- ::= elmt { num , num2 }? -- matches between num and num2 times
78 -- elmt ::= nchr -- matches given character
79 -- ::= [range range ...] -- matches any character listed
80 -- ::= [^ range range ...] -- matches any character not listed
81 -- ::= . -- matches any single character
83 -- ::= ( expr ) -- parens used for grouping
84 -- ::= \ num -- reference to num-th parenthesis
86 -- range ::= char - char -- matches chars in given range
88 -- ::= [: posix :] -- any character in the POSIX range
89 -- ::= [:^ posix :] -- not in the POSIX range
91 -- posix ::= alnum -- alphanumeric characters
92 -- ::= alpha -- alphabetic characters
93 -- ::= ascii -- ascii characters (0 .. 127)
94 -- ::= cntrl -- control chars (0..31, 127..159)
95 -- ::= digit -- digits ('0' .. '9')
96 -- ::= graph -- graphic chars (32..126, 160..255)
97 -- ::= lower -- lower case characters
98 -- ::= print -- printable characters (32..127)
99 -- -- and whitespaces (9 .. 13)
100 -- ::= punct -- printable, except alphanumeric
101 -- ::= space -- space characters
102 -- ::= upper -- upper case characters
103 -- ::= word -- alphanumeric characters
104 -- ::= xdigit -- hexadecimal chars (0..9, a..f)
106 -- char ::= any character, including special characters
107 -- ASCII.NUL is not supported.
109 -- nchr ::= any character except \()[].*+?^ or \char to match char
110 -- \n means a newline (ASCII.LF)
111 -- \t means a tab (ASCII.HT)
112 -- \r means a return (ASCII.CR)
113 -- \b matches the empty string at the beginning or end of a
114 -- word. A word is defined as a set of alphanumerical
115 -- characters (see \w below).
116 -- \B matches the empty string only when *not* at the
117 -- beginning or end of a word.
118 -- \d matches any digit character ([0-9])
119 -- \D matches any non digit character ([^0-9])
120 -- \s matches any white space character. This is equivalent
121 -- to [ \t\n\r\f\v] (tab, form-feed, vertical-tab,...
122 -- \S matches any non-white space character.
123 -- \w matches any alphanumeric character or underscore.
124 -- This include accented letters, as defined in the
125 -- package Ada.Characters.Handling.
126 -- \W matches any non-alphanumeric character.
127 -- \A match the empty string only at the beginning of the
128 -- string, whatever flags are used for Compile (the
129 -- behavior of ^ can change, see Regexp_Flags below).
130 -- \G match the empty string only at the end of the
131 -- string, whatever flags are used for Compile (the
132 -- behavior of $ can change, see Regexp_Flags below).
133 -- ... ::= is used to indication repetition (one or more terms)
135 -- Embedded newlines are not matched by the ^ operator.
136 -- It is possible to retrieve the substring matched a parenthesis
137 -- expression. Although the depth of parenthesis is not limited in the
138 -- regexp, only the first 9 substrings can be retrieved.
140 -- The highest value possible for the arguments to the curly operator ({})
141 -- are given by the constant Max_Curly_Repeat below.
143 -- The operators '*', '+', '?' and '{}' always match the longest possible
144 -- substring. They all have a non-greedy version (with an extra ? after the
145 -- operator), which matches the shortest possible substring.
148 -- regexp="<.*>" string="<h1>title</h1>" matches="<h1>title</h1>"
149 -- regexp="<.*?>" string="<h1>title</h1>" matches="<h1>"
151 -- '{' and '}' are only considered as special characters if they appear
152 -- in a substring that looks exactly like '{n}', '{n,m}' or '{n,}', where
153 -- n and m are digits. No space is allowed. In other contexts, the curly
154 -- braces will simply be treated as normal characters.
156 -- Compiling Regular Expressions
157 -- =============================
159 -- To use this package, you first need to compile the regular expression
160 -- (a string) into a byte-code program, in a Pattern_Matcher structure.
161 -- This first step checks that the regexp is valid, and optimizes the
162 -- matching algorithms of the second step.
164 -- Two versions of the Compile subprogram are given: one in which this
165 -- package will compute itself the best possible size to allocate for the
166 -- byte code; the other where you must allocate enough memory yourself. An
167 -- exception is raised if there is not enough memory.
170 -- Regexp : String := "a|b";
172 -- Matcher : Pattern_Matcher := Compile (Regexp);
173 -- -- The size for matcher is automatically allocated
175 -- Matcher2 : Pattern_Matcher (1000);
176 -- -- Some space is allocated directly.
179 -- Compile (Matcher2, Regexp);
183 -- Note that the second version is significantly faster, since with the
184 -- first version the regular expression has in fact to be compiled twice
185 -- (first to compute the size, then to generate the byte code).
187 -- Note also that you cannot use the function version of Compile if you
188 -- specify the size of the Pattern_Matcher, since the discriminants will
189 -- most probably be different and you will get a Constraint_Error
194 -- Once the regular expression has been compiled, you can use it as often
195 -- as needed to match strings.
197 -- Several versions of the Match subprogram are provided, with different
198 -- parameters and return results.
200 -- See the description under each of these subprograms
202 -- Here is a short example showing how to get the substring matched by
203 -- the first parenthesis pair.
206 -- Matches : Match_Array (0 .. 1);
207 -- Regexp : String := "a(b|c)d";
208 -- Str : String := "gacdg";
211 -- Match (Compile (Regexp), Str, Matches);
212 -- return Str (Matches (1).First .. Matches (1).Last);
216 -- Finding all occurrences
217 -- =======================
219 -- Finding all the occurrences of a regular expression in a string cannot
220 -- be done by simply passing a slice of the string. This wouldn't work for
221 -- anchored regular expressions (the ones starting with "^" or ending with
223 -- Instead, you need to use the last parameter to Match (Data_First), as in
224 -- the following loop:
228 -- "-- first line" & ASCII.LF & "-- second line";
229 -- Matches : Match_Array (0 .. 0);
230 -- Regexp : Pattern_Matcher := Compile ("^--", Multiple_Lines);
231 -- Current : Natural := Str'First;
234 -- Match (Regexp, Str, Matches, Current);
235 -- exit when Matches (0) = No_Match;
237 -- -- Process the match at position Matches (0).First
239 -- Current := Matches (0).Last + 1;
243 -- String Substitution
244 -- ===================
246 -- No subprogram is currently provided for string substitution.
247 -- However, this is easy to simulate with the parenthesis groups, as
250 -- This example swaps the first two words of the string:
253 -- Regexp : String := "([a-z]+) +([a-z]+)";
254 -- Str : String := " first second third ";
255 -- Matches : Match_Array (0 .. 2);
258 -- Match (Compile (Regexp), Str, Matches);
259 -- return Str (Str'First .. Matches (1).First - 1)
260 -- & Str (Matches (2).First .. Matches (2).Last)
262 -- & Str (Matches (1).First .. Matches (1).Last)
263 -- & Str (Matches (2).Last + 1 .. Str'Last);
264 -- -- returns " second first third "
271 Expression_Error
: exception;
272 -- This exception is raised when trying to compile an invalid regular
273 -- expression. All subprograms taking an expression as parameter may raise
276 Max_Paren_Count
: constant := 255;
277 -- Maximum number of parenthesis in a regular expression. This is limited
278 -- by the size of a Character, as found in the byte-compiled version of
279 -- regular expressions.
281 Max_Curly_Repeat
: constant := 32767;
282 -- Maximum number of repetition for the curly operator. The digits in the
283 -- {n}, {n,} and {n,m } operators cannot be higher than this constant,
284 -- since they have to fit on two characters in the byte-compiled version of
285 -- regular expressions.
287 Max_Program_Size
: constant := 2**15 - 1;
288 -- Maximum size that can be allocated for a program
290 type Program_Size
is range 0 .. Max_Program_Size
;
291 for Program_Size
'Size use 16;
292 -- Number of bytes allocated for the byte-compiled version of a regular
293 -- expression. The size required depends on the complexity of the regular
294 -- expression in a complex manner that is undocumented (other than in the
295 -- body of the Compile procedure). Normally the size is automatically set
296 -- and the programmer need not be concerned about it. There are two
297 -- exceptions to this. First in the calls to Match, it is possible to
298 -- specify a non-zero size that is known to be large enough. This can
299 -- slightly increase the efficiency by avoiding a copy. Second, in the case
300 -- of calling compile, it is possible using the procedural form of Compile
301 -- to use a single Pattern_Matcher variable for several different
302 -- expressions by setting its size sufficiently large.
304 Auto_Size
: constant := 0;
305 -- Used in calls to Match to indicate that the Size should be set to
306 -- a value appropriate to the expression being used automatically.
308 type Regexp_Flags
is mod 256;
309 for Regexp_Flags
'Size use 8;
310 -- Flags that can be given at compile time to specify default
311 -- properties for the regular expression.
313 No_Flags
: constant Regexp_Flags
;
314 Case_Insensitive
: constant Regexp_Flags
;
315 -- The automaton is optimized so that the matching is done in a case
316 -- insensitive manner (upper case characters and lower case characters
317 -- are all treated the same way).
319 Single_Line
: constant Regexp_Flags
;
320 -- Treat the Data we are matching as a single line. This means that
321 -- ^ and $ will ignore \n (unless Multiple_Lines is also specified),
322 -- and that '.' will match \n.
324 Multiple_Lines
: constant Regexp_Flags
;
325 -- Treat the Data as multiple lines. This means that ^ and $ will also
326 -- match on internal newlines (ASCII.LF), in addition to the beginning
327 -- and end of the string.
329 -- This can be combined with Single_Line.
335 subtype Match_Count
is Natural range 0 .. Max_Paren_Count
;
337 type Match_Location
is record
338 First
: Natural := 0;
342 type Match_Array
is array (Match_Count
range <>) of Match_Location
;
343 -- Used for regular expressions that can contain parenthesized
344 -- subexpressions. Certain Match subprograms below produce Matches of type
345 -- Match_Array. Each component of Matches is set to the subrange of the
346 -- matches substring, or to No_Match if no match. Matches (N) is for the
347 -- N'th parenthesized subexpressions; Matches (0) is for the whole
350 -- For instance, if your regular expression is: "a((b*)c+)(d+)", then
352 -- Matches (0) is for "a((b*)c+)(d+)" (the entire expression)
353 -- Matches (1) is for "(b*)c+"
354 -- Matches (2) is for "c+"
355 -- Matches (3) is for "d+"
357 -- The number of parenthesis groups that can be retrieved is limited only
358 -- by Max_Paren_Count.
360 -- Normally, the bounds of the Matches actual parameter will be
361 -- 0 .. Paren_Count (Regexp), to get all the matches. However, it is fine
362 -- if Matches is shorter than that on either end; missing components will
363 -- be ignored. Thus, in the above example, you could use 2 .. 2 if all you
364 -- care about it the second parenthesis pair "b*". Likewise, if
365 -- Matches'Last > Paren_Count (Regexp), the extra components will be set to
368 No_Match
: constant Match_Location
:= (First
=> 0, Last
=> 0);
369 -- The No_Match constant is (0, 0) to differentiate between matching a null
370 -- string at position 1, which uses (1, 0) and no match at all.
372 ---------------------------------
373 -- Pattern_Matcher Compilation --
374 ---------------------------------
376 -- The subprograms here are used to precompile regular expressions for use
377 -- in subsequent Match calls. Precompilation improves efficiency if the
378 -- same regular expression is to be used in more than one Match call.
380 type Pattern_Matcher
(Size
: Program_Size
) is private;
381 -- Type used to represent a regular expression compiled into byte code
383 Never_Match
: constant Pattern_Matcher
;
384 -- A regular expression that never matches anything
387 (Expression
: String;
388 Flags
: Regexp_Flags
:= No_Flags
) return Pattern_Matcher
;
389 -- Compile a regular expression into internal code
391 -- Raises Expression_Error if Expression is not a legal regular expression
393 -- The appropriate size is calculated automatically to correspond to the
394 -- provided expression. This is the normal default method of compilation.
395 -- Note that it is generally not possible to assign the result of two
396 -- different calls to this Compile function to the same Pattern_Matcher
397 -- variable, since the sizes will differ.
399 -- Flags is the default value to use to set properties for Expression
400 -- (e.g. case sensitivity,...).
403 (Matcher
: out Pattern_Matcher
;
405 Final_Code_Size
: out Program_Size
;
406 Flags
: Regexp_Flags
:= No_Flags
);
407 -- Compile a regular expression into internal code
409 -- This procedure is significantly faster than the Compile function since
410 -- it avoids the extra step of precomputing the required size.
412 -- However, it requires the user to provide a Pattern_Matcher variable
413 -- whose size is preset to a large enough value. One advantage of this
414 -- approach, in addition to the improved efficiency, is that the same
415 -- Pattern_Matcher variable can be used to hold the compiled code for
416 -- several different regular expressions by setting a size that is large
417 -- enough to accommodate all possibilities.
419 -- In this version of the procedure call, the actual required code size is
420 -- returned. Also if Matcher.Size is zero on entry, then the resulting code
421 -- is not stored. A call with Matcher.Size set to Auto_Size can thus be
422 -- used to determine the space required for compiling the given regular
425 -- This function raises Storage_Error if Matcher is too small to hold
426 -- the resulting code (i.e. Matcher.Size has too small a value).
428 -- Expression_Error is raised if the string Expression does not contain
429 -- a valid regular expression.
431 -- Flags is the default value to use to set properties for Expression (case
435 (Matcher
: out Pattern_Matcher
;
437 Flags
: Regexp_Flags
:= No_Flags
);
438 -- Same procedure as above, expect it does not return the final
439 -- program size, and Matcher.Size cannot be Auto_Size.
441 function Paren_Count
(Regexp
: Pattern_Matcher
) return Match_Count
;
442 pragma Inline
(Paren_Count
);
443 -- Return the number of parenthesis pairs in Regexp.
445 -- This is the maximum index that will be filled if a Match_Array is
446 -- used as an argument to Match.
448 -- Thus, if you want to be sure to get all the parenthesis, you should
449 -- do something like:
452 -- Regexp : Pattern_Matcher := Compile ("a(b*)(c+)");
453 -- Matched : Match_Array (0 .. Paren_Count (Regexp));
455 -- Match (Regexp, "a string", Matched);
462 function Quote
(Str
: String) return String;
463 -- Return a version of Str so that every special character is quoted.
464 -- The resulting string can be used in a regular expression to match
465 -- exactly Str, whatever character was present in Str.
471 -- The Match subprograms are given a regular expression in string
472 -- form, and perform the corresponding match. The following parameters
473 -- are present in all forms of the Match call.
475 -- Expression contains the regular expression to be matched as a string
477 -- Data contains the string to be matched
479 -- Data_First is the lower bound for the match, i.e. Data (Data_First)
480 -- will be the first character to be examined. If Data_First is set to
481 -- the special value of -1 (the default), then the first character to
482 -- be examined is Data (Data_First). However, the regular expression
483 -- character ^ (start of string) still refers to the first character
484 -- of the full string (Data (Data'First)), which is why there is a
485 -- separate mechanism for specifying Data_First.
487 -- Data_Last is the upper bound for the match, i.e. Data (Data_Last)
488 -- will be the last character to be examined. If Data_Last is set to
489 -- the special value of Positive'Last (the default), then the last
490 -- character to be examined is Data (Data_Last). However, the regular
491 -- expression character $ (end of string) still refers to the last
492 -- character of the full string (Data (Data'Last)), which is why there
493 -- is a separate mechanism for specifying Data_Last.
495 -- Note: the use of Data_First and Data_Last is not equivalent to
496 -- simply passing a slice as Expression because of the handling of
497 -- regular expression characters ^ and $.
499 -- Size is the size allocated for the compiled byte code. Normally
500 -- this is defaulted to Auto_Size which means that the appropriate
501 -- size is allocated automatically. It is possible to specify an
502 -- explicit size, which must be sufficiently large. This slightly
503 -- increases the efficiency by avoiding the extra step of computing
504 -- the appropriate size.
506 -- The following exceptions can be raised in calls to Match
508 -- Storage_Error is raised if a non-zero value is given for Size
509 -- and it is too small to hold the compiled byte code.
511 -- Expression_Error is raised if the given expression is not a legal
512 -- regular expression.
515 (Expression
: String;
517 Matches
: out Match_Array
;
518 Size
: Program_Size
:= Auto_Size
;
519 Data_First
: Integer := -1;
520 Data_Last
: Positive := Positive'Last);
521 -- This version returns the result of the match stored in Match_Array;
522 -- see comments under Match_Array above for details.
525 (Expression
: String;
527 Size
: Program_Size
:= Auto_Size
;
528 Data_First
: Integer := -1;
529 Data_Last
: Positive := Positive'Last) return Natural;
530 -- This version returns the position where Data matches, or if there is
531 -- no match, then the value Data'First - 1.
534 (Expression
: String;
536 Size
: Program_Size
:= Auto_Size
;
537 Data_First
: Integer := -1;
538 Data_Last
: Positive := Positive'Last) return Boolean;
539 -- This version returns True if the match succeeds, False otherwise
541 ------------------------------------------------
542 -- Matching a Pre-Compiled Regular Expression --
543 ------------------------------------------------
545 -- The following functions are significantly faster if you need to reuse
546 -- the same regular expression multiple times, since you only have to
547 -- compile it once. For these functions you must first compile the
548 -- expression with a call to Compile as previously described.
550 -- The parameters Data, Data_First and Data_Last are as described
551 -- in the previous section.
554 (Self
: Pattern_Matcher
;
556 Data_First
: Integer := -1;
557 Data_Last
: Positive := Positive'Last) return Natural;
558 -- Match Data using the given pattern matcher. Returns the position
559 -- where Data matches, or (Data'First - 1) if there is no match.
562 (Self
: Pattern_Matcher
;
564 Data_First
: Integer := -1;
565 Data_Last
: Positive := Positive'Last) return Boolean;
566 -- Return True if Data matches using the given pattern matcher
568 pragma Inline
(Match
);
569 -- All except the last one below
572 (Self
: Pattern_Matcher
;
574 Matches
: out Match_Array
;
575 Data_First
: Integer := -1;
576 Data_Last
: Positive := Positive'Last);
577 -- Match Data using the given pattern matcher and store result in Matches;
578 -- see comments under Match_Array above for details.
584 procedure Dump
(Self
: Pattern_Matcher
);
585 -- Dump the compiled version of the regular expression matched by Self
587 --------------------------
588 -- Private Declarations --
589 --------------------------
593 subtype Pointer
is Program_Size
;
594 -- The Pointer type is used to point into Program_Data
596 -- Note that the pointer type is not necessarily 2 bytes
597 -- although it is stored in the program using 2 bytes
599 type Program_Data
is array (Pointer
range <>) of Character;
601 Program_First
: constant := 1;
603 -- The "internal use only" fields in regexp are present to pass info from
604 -- compile to execute that permits the execute phase to run lots faster on
605 -- simple cases. They are:
607 -- First character that must begin a match or ASCII.NUL
608 -- Anchored true iff match must start at beginning of line
609 -- Must_Have pointer to string that match must include or null
610 -- Must_Have_Length length of Must_Have string
612 -- First and Anchored permit very fast decisions on suitable starting
613 -- points for a match, cutting down the work a lot. Must_Have permits fast
614 -- rejection of lines that cannot possibly match.
616 -- The Must_Have tests are costly enough that Optimize supplies a Must_Have
617 -- only if the r.e. contains something potentially expensive (at present,
618 -- the only such thing detected is * or at the start of the r.e., which can
619 -- involve a lot of backup). The length is supplied because the test in
620 -- Execute needs it and Optimize is computing it anyway.
622 -- The initialization is meant to fail-safe in case the user of this
623 -- package tries to use an uninitialized matcher. This takes advantage
624 -- of the knowledge that ASCII.NUL translates to the end-of-program (EOP)
625 -- instruction code of the state machine.
627 No_Flags
: constant Regexp_Flags
:= 0;
628 Case_Insensitive
: constant Regexp_Flags
:= 1;
629 Single_Line
: constant Regexp_Flags
:= 2;
630 Multiple_Lines
: constant Regexp_Flags
:= 4;
632 type Pattern_Matcher
(Size
: Pointer
) is record
633 First
: Character := ASCII
.NUL
; -- internal use only
634 Anchored
: Boolean := False; -- internal use only
635 Must_Have
: Pointer
:= 0; -- internal use only
636 Must_Have_Length
: Natural := 0; -- internal use only
637 Paren_Count
: Natural := 0; -- # paren groups
638 Flags
: Regexp_Flags
:= No_Flags
;
639 Program
: Program_Data
(Program_First
.. Size
) :=
640 (others => ASCII
.NUL
);
643 Never_Match
: constant Pattern_Matcher
:=
644 (0, ASCII
.NUL
, False, 0, 0, 0, No_Flags
, (others => ASCII
.NUL
));