Remove old autovect-branch by moving to "dead" directory.
[official-gcc.git] / old-autovect-branch / gcc / ada / g-spipat.ads
blob31cbef67d6bde761ccbfb661dbce6c571916614f
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT LIBRARY COMPONENTS --
4 -- --
5 -- G N A T . S P I T B O L . P A T T E R N S --
6 -- --
7 -- S p e c --
8 -- --
9 -- Copyright (C) 1997-2005, AdaCore --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 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, 51 Franklin Street, Fifth Floor, --
20 -- Boston, MA 02110-1301, 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 was originally developed by the GNAT team at New York University. --
30 -- Extensive contributions were provided by Ada Core Technologies Inc. --
31 -- --
32 ------------------------------------------------------------------------------
34 -- SPITBOL-like pattern construction and matching
36 -- This child package of GNAT.SPITBOL provides a complete implementation
37 -- of the SPITBOL-like pattern construction and matching operations. This
38 -- package is based on Macro-SPITBOL created by Robert Dewar.
40 ------------------------------------------------------------
41 -- Summary of Pattern Matching Packages in GNAT Hierarchy --
42 ------------------------------------------------------------
44 -- There are three related packages that perform pattern maching functions.
45 -- the following is an outline of these packages, to help you determine
46 -- which is best for your needs.
48 -- GNAT.Regexp (files g-regexp.ads/g-regexp.adb)
49 -- This is a simple package providing Unix-style regular expression
50 -- matching with the restriction that it matches entire strings. It
51 -- is particularly useful for file name matching, and in particular
52 -- it provides "globbing patterns" that are useful in implementing
53 -- unix or DOS style wild card matching for file names.
55 -- GNAT.Regpat (files g-regpat.ads/g-regpat.adb)
56 -- This is a more complete implementation of Unix-style regular
57 -- expressions, copied from the original V7 style regular expression
58 -- library written in C by Henry Spencer. It is functionally the
59 -- same as this library, and uses the same internal data structures
60 -- stored in a binary compatible manner.
62 -- GNAT.Spitbol.Patterns (files g-spipat.ads/g-spipat.adb)
63 -- This is a completely general patterm matching package based on the
64 -- pattern language of SNOBOL4, as implemented in SPITBOL. The pattern
65 -- language is modeled on context free grammars, with context sensitive
66 -- extensions that provide full (type 0) computational capabilities.
68 with Ada.Strings.Maps; use Ada.Strings.Maps;
69 with Ada.Text_IO; use Ada.Text_IO;
71 package GNAT.Spitbol.Patterns is
72 pragma Elaborate_Body;
74 -------------------------------
75 -- Pattern Matching Tutorial --
76 -------------------------------
78 -- A pattern matching operation (a call to one of the Match subprograms)
79 -- takes a subject string and a pattern, and optionally a replacement
80 -- string. The replacement string option is only allowed if the subject
81 -- is a variable.
83 -- The pattern is matched against the subject string, and either the
84 -- match fails, or it succeeds matching a contiguous substring. If a
85 -- replacement string is specified, then the subject string is modified
86 -- by replacing the matched substring with the given replacement.
88 -- Concatenation and Alternation
89 -- =============================
91 -- A pattern consists of a series of pattern elements. The pattern is
92 -- built up using either the concatenation operator:
94 -- A & B
96 -- which means match A followed immediately by matching B, or the
97 -- alternation operator:
99 -- A or B
101 -- which means first attempt to match A, and then if that does not
102 -- succeed, match B.
104 -- There is full backtracking, which means that if a given pattern
105 -- element fails to match, then previous alternatives are matched.
106 -- For example if we have the pattern:
108 -- (A or B) & (C or D) & (E or F)
110 -- First we attempt to match A, if that succeeds, then we go on to try
111 -- to match C, and if that succeeds, we go on to try to match E. If E
112 -- fails, then we try F. If F fails, then we go back and try matching
113 -- D instead of C. Let's make this explicit using a specific example,
114 -- and introducing the simplest kind of pattern element, which is a
115 -- literal string. The meaning of this pattern element is simply to
116 -- match the characters that correspond to the string characters. Now
117 -- let's rewrite the above pattern form with specific string literals
118 -- as the pattern elements:
120 -- ("ABC" or "AB") & ("DEF" or "CDE") & ("GH" or "IJ")
122 -- The following strings will be attempted in sequence:
124 -- ABC . DEF . GH
125 -- ABC . DEF . IJ
126 -- ABC . CDE . GH
127 -- ABC . CDE . IJ
128 -- AB . DEF . GH
129 -- AB . DEF . IJ
130 -- AB . CDE . GH
131 -- AB . CDE . IJ
133 -- Here we use the dot simply to separate the pieces of the string
134 -- matched by the three separate elements.
136 -- Moving the Start Point
137 -- ======================
139 -- A pattern is not required to match starting at the first character
140 -- of the string, and is not required to match to the end of the string.
141 -- The first attempt does indeed attempt to match starting at the first
142 -- character of the string, trying all the possible alternatives. But
143 -- if all alternatives fail, then the starting point of the match is
144 -- moved one character, and all possible alternatives are attempted at
145 -- the new anchor point.
147 -- The entire match fails only when every possible starting point has
148 -- been attempted. As an example, suppose that we had the subject
149 -- string
151 -- "ABABCDEIJKL"
153 -- matched using the pattern in the previous example:
155 -- ("ABC" or "AB") & ("DEF" or "CDE") & ("GH" or "IJ")
157 -- would succeed, afer two anchor point moves:
159 -- "ABABCDEIJKL"
160 -- ^^^^^^^
161 -- matched
162 -- section
164 -- This mode of pattern matching is called the unanchored mode. It is
165 -- also possible to put the pattern matcher into anchored mode by
166 -- setting the global variable Anchored_Mode to True. This will cause
167 -- all subsequent matches to be performed in anchored mode, where the
168 -- match is required to start at the first character.
170 -- We will also see later how the effect of an anchored match can be
171 -- obtained for a single specified anchor point if this is desired.
173 -- Other Pattern Elements
174 -- ======================
176 -- In addition to strings (or single characters), there are many special
177 -- pattern elements that correspond to special predefined alternations:
179 -- Arb Matches any string. First it matches the null string, and
180 -- then on a subsequent failure, matches one character, and
181 -- then two characters, and so on. It only fails if the
182 -- entire remaining string is matched.
184 -- Bal Matches a non-empty string that is parentheses balanced
185 -- with respect to ordinary () characters. Examples of
186 -- balanced strings are "ABC", "A((B)C)", and "A(B)C(D)E".
187 -- Bal matches the shortest possible balanced string on the
188 -- first attempt, and if there is a subsequent failure,
189 -- attempts to extend the string.
191 -- Cancel Immediately aborts the entire pattern match, signalling
192 -- failure. This is a specialized pattern element, which is
193 -- useful in conjunction with some of the special pattern
194 -- elements that have side effects.
196 -- Fail The null alternation. Matches no possible strings, so it
197 -- always signals failure. This is a specialized pattern
198 -- element, which is useful in conjunction with some of the
199 -- special pattern elements that have side effects.
201 -- Fence Matches the null string at first, and then if a failure
202 -- causes alternatives to be sought, aborts the match (like
203 -- a Cancel). Note that using Fence at the start of a pattern
204 -- has the same effect as matching in anchored mode.
206 -- Rest Matches from the current point to the last character in
207 -- the string. This is a specialized pattern element, which
208 -- is useful in conjunction with some of the special pattern
209 -- elements that have side effects.
211 -- Succeed Repeatedly matches the null string (it is equivalent to
212 -- the alternation ("" or "" or "" ....). This is a special
213 -- pattern element, which is useful in conjunction with some
214 -- of the special pattern elements that have side effects.
216 -- Pattern Construction Functions
217 -- ==============================
219 -- The following functions construct additional pattern elements
221 -- Any(S) Where S is a string, matches a single character that is
222 -- any one of the characters in S. Fails if the current
223 -- character is not one of the given set of characters.
225 -- Arbno(P) Where P is any pattern, matches any number of instances
226 -- of the pattern, starting with zero occurrences. It is
227 -- thus equivalent to ("" or (P & ("" or (P & ("" ....)))).
228 -- The pattern P may contain any number of pattern elements
229 -- including the use of alternatiion and concatenation.
231 -- Break(S) Where S is a string, matches a string of zero or more
232 -- characters up to but not including a break character
233 -- that is one of the characters given in the string S.
234 -- Can match the null string, but cannot match the last
235 -- character in the string, since a break character is
236 -- required to be present.
238 -- BreakX(S) Where S is a string, behaves exactly like Break(S) when
239 -- it first matches, but if a string is successfully matched,
240 -- then a susequent failure causes an attempt to extend the
241 -- matched string.
243 -- Fence(P) Where P is a pattern, attempts to match the pattern P
244 -- including trying all possible alternatives of P. If none
245 -- of these alternatives succeeds, then the Fence pattern
246 -- fails. If one alternative succeeds, then the pattern
247 -- match proceeds, but on a subsequent failure, no attempt
248 -- is made to search for alternative matches of P. The
249 -- pattern P may contain any number of pattern elements
250 -- including the use of alternatiion and concatenation.
252 -- Len(N) Where N is a natural number, matches the given number of
253 -- characters. For example, Len(10) matches any string that
254 -- is exactly ten characters long.
256 -- NotAny(S) Where S is a string, matches a single character that is
257 -- not one of the characters of S. Fails if the current
258 -- characer is one of the given set of characters.
260 -- NSpan(S) Where S is a string, matches a string of zero or more
261 -- characters that is among the characters given in the
262 -- string. Always matches the longest possible such string.
263 -- Always succeeds, since it can match the null string.
265 -- Pos(N) Where N is a natural number, matches the null string
266 -- if exactly N characters have been matched so far, and
267 -- otherwise fails.
269 -- Rpos(N) Where N is a natural number, matches the null string
270 -- if exactly N characters remain to be matched, and
271 -- otherwise fails.
273 -- Rtab(N) Where N is a natural number, matches characters from
274 -- the current position until exactly N characters remain
275 -- to be matched in the string. Fails if fewer than N
276 -- unmatched characters remain in the string.
278 -- Tab(N) Where N is a natural number, matches characters from
279 -- the current position until exactly N characters have
280 -- been matched in all. Fails if more than N characters
281 -- have already been matched.
283 -- Span(S) Where S is a string, matches a string of one or more
284 -- characters that is among the characters given in the
285 -- string. Always matches the longest possible such string.
286 -- Fails if the current character is not one of the given
287 -- set of characters.
289 -- Recursive Pattern Matching
290 -- ==========================
292 -- The plus operator (+P) where P is a pattern variable, creates
293 -- a recursive pattern that will, at pattern matching time, follow
294 -- the pointer to obtain the referenced pattern, and then match this
295 -- pattern. This may be used to construct recursive patterns. Consider
296 -- for example:
298 -- P := ("A" or ("B" & (+P)))
300 -- On the first attempt, this pattern attempts to match the string "A".
301 -- If this fails, then the alternative matches a "B", followed by an
302 -- attempt to match P again. This second attempt first attempts to
303 -- match "A", and so on. The result is a pattern that will match a
304 -- string of B's followed by a single A.
306 -- This particular example could simply be written as NSpan('B') & 'A',
307 -- but the use of recursive patterns in the general case can construct
308 -- complex patterns which could not otherwise be built.
310 -- Pattern Assignment Operations
311 -- =============================
313 -- In addition to the overall result of a pattern match, which indicates
314 -- success or failure, it is often useful to be able to keep track of
315 -- the pieces of the subject string that are matched by individual
316 -- pattern elements, or subsections of the pattern.
318 -- The pattern assignment operators allow this capability. The first
319 -- form is the immediate assignment:
321 -- P * S
323 -- Here P is an arbitrary pattern, and S is a variable of type VString
324 -- that will be set to the substring matched by P. This assignment
325 -- happens during pattern matching, so if P matches more than once,
326 -- then the assignment happens more than once.
328 -- The deferred assignment operation:
330 -- P ** S
332 -- avoids these multiple assignments by deferring the assignment to the
333 -- end of the match. If the entire match is successful, and if the
334 -- pattern P was part of the successful match, then at the end of the
335 -- matching operation the assignment to S of the string matching P is
336 -- performed.
338 -- The cursor assignment operation:
340 -- Setcur(N'Access)
342 -- assigns the current cursor position to the natural variable N. The
343 -- cursor position is defined as the count of characters that have been
344 -- matched so far (including any start point moves).
346 -- Finally the operations * and ** may be used with values of type
347 -- Text_IO.File_Access. The effect is to do a Put_Line operation of
348 -- the matched substring. These are particularly useful in debugging
349 -- pattern matches.
351 -- Deferred Matching
352 -- =================
354 -- The pattern construction functions (such as Len and Any) all permit
355 -- the use of pointers to natural or string values, or functions that
356 -- return natural or string values. These forms cause the actual value
357 -- to be obtained at pattern matching time. This allows interesting
358 -- possibilities for constructing dynamic patterns as illustrated in
359 -- the examples section.
361 -- In addition the (+S) operator may be used where S is a pointer to
362 -- string or function returning string, with a similar deferred effect.
364 -- A special use of deferred matching is the construction of predicate
365 -- functions. The element (+P) where P is an access to a function that
366 -- returns a Boolean value, causes the function to be called at the
367 -- time the element is matched. If the function returns True, then the
368 -- null string is matched, if the function returns False, then failure
369 -- is signalled and previous alternatives are sought.
371 -- Deferred Replacement
372 -- ====================
374 -- The simple model given for pattern replacement (where the matched
375 -- substring is replaced by the string given as the third argument to
376 -- Match) works fine in simple cases, but this approach does not work
377 -- in the case where the expression used as the replacement string is
378 -- dependent on values set by the match.
380 -- For example, suppose we want to find an instance of a parenthesized
381 -- character, and replace the parentheses with square brackets. At first
382 -- glance it would seem that:
384 -- Match (Subject, '(' & Len (1) * Char & ')', '[' & Char & ']');
386 -- would do the trick, but that does not work, because the third
387 -- argument to Match gets evaluated too early, before the call to
388 -- Match, and before the pattern match has had a chance to set Char.
390 -- To solve this problem we provide the deferred replacement capability.
391 -- With this approach, which of course is only needed if the pattern
392 -- involved has side effects, is to do the match in two stages. The
393 -- call to Match sets a pattern result in a variable of the private
394 -- type Match_Result, and then a subsequent Replace operation uses
395 -- this Match_Result object to perform the required replacement.
397 -- Using this approach, we can now write the above operation properly
398 -- in a manner that will work:
400 -- M : Match_Result;
401 -- ...
402 -- Match (Subject, '(' & Len (1) * Char & ')', M);
403 -- Replace (M, '[' & Char & ']');
405 -- As with other Match cases, there is a function and procedure form
406 -- of this match call. A call to Replace after a failed match has no
407 -- effect. Note that Subject should not be modified between the calls.
409 -- Examples of Pattern Matching
410 -- ============================
412 -- First a simple example of the use of pattern replacement to remove
413 -- a line number from the start of a string. We assume that the line
414 -- number has the form of a string of decimal digits followed by a
415 -- period, followed by one or more spaces.
417 -- Digs : constant Pattern := Span("0123456789");
419 -- Lnum : constant Pattern := Pos(0) & Digs & '.' & Span(' ');
421 -- Now to use this pattern we simply do a match with a replacement:
423 -- Match (Line, Lnum, "");
425 -- which replaces the line number by the null string. Note that it is
426 -- also possible to use an Ada.Strings.Maps.Character_Set value as an
427 -- argument to Span and similar functions, and in particular all the
428 -- useful constants 'in Ada.Strings.Maps.Constants are available. This
429 -- means that we could define Digs as:
431 -- Digs : constant Pattern := Span(Decimal_Digit_Set);
433 -- The style we use here, of defining constant patterns and then using
434 -- them is typical. It is possible to build up patterns dynamically,
435 -- but it is usually more efficient to build them in pieces in advance
436 -- using constant declarations. Note in particular that although it is
437 -- possible to construct a pattern directly as an argument for the
438 -- Match routine, it is much more efficient to preconstruct the pattern
439 -- as we did in this example.
441 -- Now let's look at the use of pattern assignment to break a
442 -- string into sections. Suppose that the input string has two
443 -- unsigned decimal integers, separated by spaces or a comma,
444 -- with spaces allowed anywhere. Then we can isolate the two
445 -- numbers with the following pattern:
447 -- Num1, Num2 : aliased VString;
449 -- B : constant Pattern := NSpan(' ');
451 -- N : constant Pattern := Span("0123456789");
453 -- T : constant Pattern :=
454 -- NSpan(' ') & N * Num1 & Span(" ,") & N * Num2;
456 -- The match operation Match (" 124, 257 ", T) would assign the
457 -- string 124 to Num1 and the string 257 to Num2.
459 -- Now let's see how more complex elements can be built from the
460 -- set of primitive elements. The following pattern matches strings
461 -- that have the syntax of Ada 95 based literals:
463 -- Digs : constant Pattern := Span(Decimal_Digit_Set);
464 -- UDigs : constant Pattern := Digs & Arbno('_' & Digs);
466 -- Edig : constant Pattern := Span(Hexadecimal_Digit_Set);
467 -- UEdig : constant Pattern := Edig & Arbno('_' & Edig);
469 -- Bnum : constant Pattern := Udigs & '#' & UEdig & '#';
471 -- A match against Bnum will now match the desired strings, e.g.
472 -- it will match 16#123_abc#, but not a#b#. However, this pattern
473 -- is not quite complete, since it does not allow colons to replace
474 -- the pound signs. The following is more complete:
476 -- Bchar : constant Pattern := Any("#:");
477 -- Bnum : constant Pattern := Udigs & Bchar & UEdig & Bchar;
479 -- but that is still not quite right, since it allows # and : to be
480 -- mixed, and they are supposed to be used consistently. We solve
481 -- this by using a deferred match.
483 -- Temp : aliased VString;
485 -- Bnum : constant Pattern :=
486 -- Udigs & Bchar * Temp & UEdig & (+Temp)
488 -- Here the first instance of the base character is stored in Temp, and
489 -- then later in the pattern we rematch the value that was assigned.
491 -- For an example of a recursive pattern, let's define a pattern
492 -- that is like the built in Bal, but the string matched is balanced
493 -- with respect to square brackets or curly brackets.
495 -- The language for such strings might be defined in extended BNF as
497 -- ELEMENT ::= <any character other than [] or {}>
498 -- | '[' BALANCED_STRING ']'
499 -- | '{' BALANCED_STRING '}'
501 -- BALANCED_STRING ::= ELEMENT {ELEMENT}
503 -- Here we use {} to indicate zero or more occurrences of a term, as
504 -- is common practice in extended BNF. Now we can translate the above
505 -- BNF into recursive patterns as follows:
507 -- Element, Balanced_String : aliased Pattern;
508 -- .
509 -- .
510 -- .
511 -- Element := NotAny ("[]{}")
512 -- or
513 -- ('[' & (+Balanced_String) & ']')
514 -- or
515 -- ('{' & (+Balanced_String) & '}');
517 -- Balanced_String := Element & Arbno (Element);
519 -- Note the important use of + here to refer to a pattern not yet
520 -- defined. Note also that we use assignments precisely because we
521 -- cannot refer to as yet undeclared variables in initializations.
523 -- Now that this pattern is constructed, we can use it as though it
524 -- were a new primitive pattern element, and for example, the match:
526 -- Match ("xy[ab{cd}]", Balanced_String * Current_Output & Fail);
528 -- will generate the output:
530 -- x
531 -- xy
532 -- xy[ab{cd}]
533 -- y
534 -- y[ab{cd}]
535 -- [ab{cd}]
536 -- a
537 -- ab
538 -- ab{cd}
539 -- b
540 -- b{cd}
541 -- {cd}
542 -- c
543 -- cd
544 -- d
546 -- Note that the function of the fail here is simply to force the
547 -- pattern Balanced_String to match all possible alternatives. Studying
548 -- the operation of this pattern in detail is highly instructive.
550 -- Finally we give a rather elaborate example of the use of deferred
551 -- matching. The following declarations build up a pattern which will
552 -- find the longest string of decimal digits in the subject string.
554 -- Max, Cur : VString;
555 -- Loc : Natural;
557 -- function GtS return Boolean is
558 -- begin
559 -- return Length (Cur) > Length (Max);
560 -- end GtS;
562 -- Digit : constant Character_Set := Decimal_Digit_Set;
564 -- Digs : constant Pattern := Span(Digit);
566 -- Find : constant Pattern :=
567 -- "" * Max & Fence & -- initialize Max to null
568 -- BreakX (Digit) & -- scan looking for digits
569 -- ((Span(Digit) * Cur & -- assign next string to Cur
570 -- (+GtS'Unrestricted_Access) & -- check size(Cur) > Size(Max)
571 -- Setcur(Loc'Access)) -- if so, save location
572 -- * Max) & -- and assign to Max
573 -- Fail; -- seek all alternatives
575 -- As we see from the comments here, complex patterns like this take
576 -- on aspects of sequential programs. In fact they are sequential
577 -- programs with general backtracking. In this pattern, we first use
578 -- a pattern assignment that matches null and assigns it to Max, so
579 -- that it is initialized for the new match. Now BreakX scans to the
580 -- next digit. Arb would do here, but BreakX will be more efficient.
581 -- Once we have found a digit, we scan out the longest string of
582 -- digits with Span, and assign it to Cur. The deferred call to GtS
583 -- tests if the string we assigned to Cur is the longest so far. If
584 -- not, then failure is signalled, and we seek alternatives (this
585 -- means that BreakX will extend and look for the next digit string).
586 -- If the call to GtS succeeds then the matched string is assigned
587 -- as the largest string so far into Max and its location is saved
588 -- in Loc. Finally Fail forces the match to fail and seek alternatives,
589 -- so that the entire string is searched.
591 -- If the pattern Find is matched against a string, the variable Max
592 -- at the end of the pattern will have the longest string of digits,
593 -- and Loc will be the starting character location of the string. For
594 -- example, Match("ab123cd4657ef23", Find) will assign "4657" to Max
595 -- and 11 to Loc (indicating that the string ends with the eleventh
596 -- character of the string).
598 -- Note: the use of Unrestricted_Access to reference GtS will not
599 -- be needed if GtS is defined at the outer level, but definitely
600 -- will be necessary if GtS is a nested function (in which case of
601 -- course the scope of the pattern Find will be restricted to this
602 -- nested scope, and this cannot be checked, i.e. use of the pattern
603 -- outside this scope is erroneous). Generally it is a good idea to
604 -- define patterns and the functions they call at the outer level
605 -- where possible, to avoid such problems.
607 -- Correspondence with Pattern Matching in SPITBOL
608 -- ===============================================
610 -- Generally the Ada syntax and names correspond closely to SPITBOL
611 -- syntax for pattern matching construction.
613 -- The basic pattern construction operators are renamed as follows:
615 -- Spitbol Ada
617 -- (space) &
618 -- | or
619 -- $ *
620 -- . **
622 -- The Ada operators were chosen so that the relative precedences of
623 -- these operators corresponds to that of the Spitbol operators, but
624 -- as always, the use of parentheses is advisable to clarify.
626 -- The pattern construction operators all have similar names except for
628 -- Spitbol Ada
630 -- Abort Cancel
631 -- Rem Rest
633 -- where we have clashes with Ada reserved names
635 -- Ada requires the use of 'Access to refer to functions used in the
636 -- pattern match, and often the use of 'Unrestricted_Access may be
637 -- necessary to get around the scope restrictions if the functions
638 -- are not declared at the outer level.
640 -- The actual pattern matching syntax is modified in Ada as follows:
642 -- Spitbol Ada
644 -- X Y Match (X, Y);
645 -- X Y = Z Match (X, Y, Z);
647 -- and pattern failure is indicated by returning a Boolean result from
648 -- the Match function (True for success, False for failure).
650 -----------------------
651 -- Type Declarations --
652 -----------------------
654 type Pattern is private;
655 -- Type representing a pattern. This package provides a complete set of
656 -- operations for constructing patterns that can be used in the pattern
657 -- matching operations provided.
659 type Boolean_Func is access function return Boolean;
660 -- General Boolean function type. When this type is used as a formal
661 -- parameter type in this package, it indicates a deferred predicate
662 -- pattern. The function will be called when the pattern element is
663 -- matched and failure signalled if False is returned.
665 type Natural_Func is access function return Natural;
666 -- General Natural function type. When this type is used as a formal
667 -- parameter type in this package, it indicates a deferred pattern.
668 -- The function will be called when the pattern element is matched
669 -- to obtain the currently referenced Natural value.
671 type VString_Func is access function return VString;
672 -- General VString function type. When this type is used as a formal
673 -- parameter type in this package, it indicates a deferred pattern.
674 -- The function will be called when the pattern element is matched
675 -- to obtain the currently referenced string value.
677 subtype PString is String;
678 -- This subtype is used in the remainder of the package to indicate a
679 -- formal parameter that is converted to its corresponding pattern,
680 -- i.e. a pattern that matches the characters of the string.
682 subtype PChar is Character;
683 -- Similarly, this subtype is used in the remainder of the package to
684 -- indicate a formal parameter that is converted to its corresponding
685 -- pattern, i.e. a pattern that matches this one character.
687 subtype VString_Var is VString;
688 subtype Pattern_Var is Pattern;
689 -- These synonyms are used as formal parameter types to a function where,
690 -- if the language allowed, we would use in out parameters, but we are
691 -- not allowed to have in out parameters for functions. Instead we pass
692 -- actuals which must be variables, and with a bit of trickery in the
693 -- body, manage to interprete them properly as though they were indeed
694 -- in out parameters.
696 --------------------------------
697 -- Basic Pattern Construction --
698 --------------------------------
700 function "&" (L : Pattern; R : Pattern) return Pattern;
701 function "&" (L : PString; R : Pattern) return Pattern;
702 function "&" (L : Pattern; R : PString) return Pattern;
703 function "&" (L : PChar; R : Pattern) return Pattern;
704 function "&" (L : Pattern; R : PChar) return Pattern;
706 -- Pattern concatenation. Matches L followed by R
708 function "or" (L : Pattern; R : Pattern) return Pattern;
709 function "or" (L : PString; R : Pattern) return Pattern;
710 function "or" (L : Pattern; R : PString) return Pattern;
711 function "or" (L : PString; R : PString) return Pattern;
712 function "or" (L : PChar; R : Pattern) return Pattern;
713 function "or" (L : Pattern; R : PChar) return Pattern;
714 function "or" (L : PChar; R : PChar) return Pattern;
715 function "or" (L : PString; R : PChar) return Pattern;
716 function "or" (L : PChar; R : PString) return Pattern;
717 -- Pattern alternation. Creates a pattern that will first try to match
718 -- L and then on a subsequent failure, attempts to match R instead.
720 ----------------------------------
721 -- Pattern Assignment Functions --
722 ----------------------------------
724 function "*" (P : Pattern; Var : VString_Var) return Pattern;
725 function "*" (P : PString; Var : VString_Var) return Pattern;
726 function "*" (P : PChar; Var : VString_Var) return Pattern;
727 -- Matches P, and if the match succeeds, assigns the matched substring
728 -- to the given VString variable S. This assignment happens as soon as
729 -- the substring is matched, and if the pattern P1 is matched more than
730 -- once during the course of the match, then the assignment will occur
731 -- more than once.
733 function "**" (P : Pattern; Var : VString_Var) return Pattern;
734 function "**" (P : PString; Var : VString_Var) return Pattern;
735 function "**" (P : PChar; Var : VString_Var) return Pattern;
736 -- Like "*" above, except that the assignment happens at most once
737 -- after the entire match is completed successfully. If the match
738 -- fails, then no assignment takes place.
740 ----------------------------------
741 -- Deferred Matching Operations --
742 ----------------------------------
744 function "+" (Str : VString_Var) return Pattern;
745 -- Here Str must be a VString variable. This function constructs a
746 -- pattern which at pattern matching time will access the current
747 -- value of this variable, and match against these characters.
749 function "+" (Str : VString_Func) return Pattern;
750 -- Constructs a pattern which at pattern matching time calls the given
751 -- function, and then matches against the string or character value
752 -- that is returned by the call.
754 function "+" (P : Pattern_Var) return Pattern;
755 -- Here P must be a Pattern variable. This function constructs a
756 -- pattern which at pattern matching time will access the current
757 -- value of this variable, and match against the pattern value.
759 function "+" (P : Boolean_Func) return Pattern;
760 -- Constructs a predicate pattern function that at pattern matching time
761 -- calls the given function. If True is returned, then the pattern matches.
762 -- If False is returned, then failure is signalled.
764 --------------------------------
765 -- Pattern Building Functions --
766 --------------------------------
768 function Arb return Pattern;
769 -- Constructs a pattern that will match any string. On the first attempt,
770 -- the pattern matches a null string, then on each successive failure, it
771 -- matches one more character, and only fails if matching the entire rest
772 -- of the string.
774 function Arbno (P : Pattern) return Pattern;
775 function Arbno (P : PString) return Pattern;
776 function Arbno (P : PChar) return Pattern;
777 -- Pattern repetition. First matches null, then on a subsequent failure
778 -- attempts to match an additional instance of the given pattern.
779 -- Equivalent to (but more efficient than) P & ("" or (P & ("" or ...
781 function Any (Str : String) return Pattern;
782 function Any (Str : VString) return Pattern;
783 function Any (Str : Character) return Pattern;
784 function Any (Str : Character_Set) return Pattern;
785 function Any (Str : access VString) return Pattern;
786 function Any (Str : VString_Func) return Pattern;
787 -- Constructs a pattern that matches a single character that is one of
788 -- the characters in the given argument. The pattern fails if the current
789 -- character is not in Str.
791 function Bal return Pattern;
792 -- Constructs a pattern that will match any non-empty string that is
793 -- parentheses balanced with respect to the normal parentheses characters.
794 -- Attempts to extend the string if a subsequent failure occurs.
796 function Break (Str : String) return Pattern;
797 function Break (Str : VString) return Pattern;
798 function Break (Str : Character) return Pattern;
799 function Break (Str : Character_Set) return Pattern;
800 function Break (Str : access VString) return Pattern;
801 function Break (Str : VString_Func) return Pattern;
802 -- Constructs a pattern that matches a (possibly null) string which
803 -- is immediately followed by a character in the given argument. This
804 -- character is not part of the matched string. The pattern fails if
805 -- the remaining characters to be matched do not include any of the
806 -- characters in Str.
808 function BreakX (Str : String) return Pattern;
809 function BreakX (Str : VString) return Pattern;
810 function BreakX (Str : Character) return Pattern;
811 function BreakX (Str : Character_Set) return Pattern;
812 function BreakX (Str : access VString) return Pattern;
813 function BreakX (Str : VString_Func) return Pattern;
814 -- Like Break, but the pattern attempts to extend on a failure to find
815 -- the next occurrence of a character in Str, and only fails when the
816 -- last such instance causes a failure.
818 function Cancel return Pattern;
819 -- Constructs a pattern that immediately aborts the entire match
821 function Fail return Pattern;
822 -- Constructs a pattern that always fails
824 function Fence return Pattern;
825 -- Constructs a pattern that matches null on the first attempt, and then
826 -- causes the entire match to be aborted if a subsequent failure occurs.
828 function Fence (P : Pattern) return Pattern;
829 -- Constructs a pattern that first matches P. if P fails, then the
830 -- constructed pattern fails. If P succeeds, then the match proceeds,
831 -- but if subsequent failure occurs, alternatives in P are not sought.
832 -- The idea of Fence is that each time the pattern is matched, just
833 -- one attempt is made to match P, without trying alternatives.
835 function Len (Count : Natural) return Pattern;
836 function Len (Count : access Natural) return Pattern;
837 function Len (Count : Natural_Func) return Pattern;
838 -- Constructs a pattern that matches exactly the given number of
839 -- characters. The pattern fails if fewer than this number of characters
840 -- remain to be matched in the string.
842 function NotAny (Str : String) return Pattern;
843 function NotAny (Str : VString) return Pattern;
844 function NotAny (Str : Character) return Pattern;
845 function NotAny (Str : Character_Set) return Pattern;
846 function NotAny (Str : access VString) return Pattern;
847 function NotAny (Str : VString_Func) return Pattern;
848 -- Constructs a pattern that matches a single character that is not
849 -- one of the characters in the given argument. The pattern Fails if
850 -- the current character is in Str.
852 function NSpan (Str : String) return Pattern;
853 function NSpan (Str : VString) return Pattern;
854 function NSpan (Str : Character) return Pattern;
855 function NSpan (Str : Character_Set) return Pattern;
856 function NSpan (Str : access VString) return Pattern;
857 function NSpan (Str : VString_Func) return Pattern;
858 -- Constructs a pattern that matches the longest possible string
859 -- consisting entirely of characters from the given argument. The
860 -- string may be empty, so this pattern always succeeds.
862 function Pos (Count : Natural) return Pattern;
863 function Pos (Count : access Natural) return Pattern;
864 function Pos (Count : Natural_Func) return Pattern;
865 -- Constructs a pattern that matches the null string if exactly Count
866 -- characters have already been matched, and otherwise fails.
868 function Rest return Pattern;
869 -- Constructs a pattern that always succeeds, matching the remaining
870 -- unmatched characters in the pattern.
872 function Rpos (Count : Natural) return Pattern;
873 function Rpos (Count : access Natural) return Pattern;
874 function Rpos (Count : Natural_Func) return Pattern;
875 -- Constructs a pattern that matches the null string if exactly Count
876 -- characters remain to be matched in the string, and otherwise fails.
878 function Rtab (Count : Natural) return Pattern;
879 function Rtab (Count : access Natural) return Pattern;
880 function Rtab (Count : Natural_Func) return Pattern;
881 -- Constructs a pattern that matches from the current location until
882 -- exactly Count characters remain to be matched in the string. The
883 -- pattern fails if fewer than Count characters remain to be matched.
885 function Setcur (Var : access Natural) return Pattern;
886 -- Constructs a pattern that matches the null string, and assigns the
887 -- current cursor position in the string. This value is the number of
888 -- characters matched so far. So it is zero at the start of the match.
890 function Span (Str : String) return Pattern;
891 function Span (Str : VString) return Pattern;
892 function Span (Str : Character) return Pattern;
893 function Span (Str : Character_Set) return Pattern;
894 function Span (Str : access VString) return Pattern;
895 function Span (Str : VString_Func) return Pattern;
896 -- Constructs a pattern that matches the longest possible string
897 -- consisting entirely of characters from the given argument. The
898 -- string cannot be empty , so the pattern fails if the current
899 -- character is not one of the characters in Str.
901 function Succeed return Pattern;
902 -- Constructs a pattern that succeeds matching null, both on the first
903 -- attempt, and on any rematch attempt, i.e. it is equivalent to an
904 -- infinite alternation of null strings.
906 function Tab (Count : Natural) return Pattern;
907 function Tab (Count : access Natural) return Pattern;
908 function Tab (Count : Natural_Func) return Pattern;
909 -- Constructs a pattern that from the current location until Count
910 -- characters have been matched. The pattern fails if more than Count
911 -- characters have already been matched.
913 ---------------------------------
914 -- Pattern Matching Operations --
915 ---------------------------------
917 -- The Match function performs an actual pattern matching operation.
918 -- The versions with three parameters perform a match without modifying
919 -- the subject string and return a Boolean result indicating if the
920 -- match is successful or not. The Anchor parameter is set to True to
921 -- obtain an anchored match in which the pattern is required to match
922 -- the first character of the string. In an unanchored match, which is
924 -- the default, successive attempts are made to match the given pattern
925 -- at each character of the subject string until a match succeeds, or
926 -- until all possibilities have failed.
928 -- Note that pattern assignment functions in the pattern may generate
929 -- side effects, so these functions are not necessarily pure.
931 Anchored_Mode : Boolean := False;
932 -- This global variable can be set True to cause all subsequent pattern
933 -- matches to operate in anchored mode. In anchored mode, no attempt is
934 -- made to move the anchor point, so that if the match succeeds it must
935 -- succeed starting at the first character. Note that the effect of
936 -- anchored mode may be achieved in individual pattern matches by using
937 -- Fence or Pos(0) at the start of the pattern.
939 Pattern_Stack_Overflow : exception;
940 -- Exception raised if internal pattern matching stack overflows. This
941 -- is typically the result of runaway pattern recursion. If there is a
942 -- genuine case of stack overflow, then either the match must be broken
943 -- down into simpler steps, or the stack limit must be reset.
945 Stack_Size : constant Positive := 2000;
946 -- Size used for internal pattern matching stack. Increase this size if
947 -- complex patterns cause Pattern_Stack_Overflow to be raised.
949 -- Simple match functions. The subject is matched against the pattern.
950 -- Any immediate or deferred assignments or writes are executed, and
951 -- the returned value indicates whether or not the match succeeded.
953 function Match
954 (Subject : VString;
955 Pat : Pattern) return Boolean;
957 function Match
958 (Subject : VString;
959 Pat : PString) return Boolean;
961 function Match
962 (Subject : String;
963 Pat : Pattern) return Boolean;
965 function Match
966 (Subject : String;
967 Pat : PString) return Boolean;
969 -- Replacement functions. The subject is matched against the pattern.
970 -- Any immediate or deferred assignments or writes are executed, and
971 -- the returned value indicates whether or not the match succeeded.
972 -- If the match succeeds, then the matched part of the subject string
973 -- is replaced by the given Replace string.
975 function Match
976 (Subject : VString_Var;
977 Pat : Pattern;
978 Replace : VString) return Boolean;
980 function Match
981 (Subject : VString_Var;
982 Pat : PString;
983 Replace : VString) return Boolean;
985 function Match
986 (Subject : VString_Var;
987 Pat : Pattern;
988 Replace : String) return Boolean;
990 function Match
991 (Subject : VString_Var;
992 Pat : PString;
993 Replace : String) return Boolean;
995 -- Simple match procedures. The subject is matched against the pattern.
996 -- Any immediate or deferred assignments or writes are executed. No
997 -- indication of success or failure is returned.
999 procedure Match
1000 (Subject : VString;
1001 Pat : Pattern);
1003 procedure Match
1004 (Subject : VString;
1005 Pat : PString);
1007 procedure Match
1008 (Subject : String;
1009 Pat : Pattern);
1011 procedure Match
1012 (Subject : String;
1013 Pat : PString);
1015 -- Replacement procedures. The subject is matched against the pattern.
1016 -- Any immediate or deferred assignments or writes are executed. No
1017 -- indication of success or failure is returned. If the match succeeds,
1018 -- then the matched part of the subject string is replaced by the given
1019 -- Replace string.
1021 procedure Match
1022 (Subject : in out VString;
1023 Pat : Pattern;
1024 Replace : VString);
1026 procedure Match
1027 (Subject : in out VString;
1028 Pat : PString;
1029 Replace : VString);
1031 procedure Match
1032 (Subject : in out VString;
1033 Pat : Pattern;
1034 Replace : String);
1036 procedure Match
1037 (Subject : in out VString;
1038 Pat : PString;
1039 Replace : String);
1041 -- Deferred Replacement
1043 type Match_Result is private;
1044 -- Type used to record result of pattern match
1046 subtype Match_Result_Var is Match_Result;
1047 -- This synonyms is used as a formal parameter type to a function where,
1048 -- if the language allowed, we would use an in out parameter, but we are
1049 -- not allowed to have in out parameters for functions. Instead we pass
1050 -- actuals which must be variables, and with a bit of trickery in the
1051 -- body, manage to interprete them properly as though they were indeed
1052 -- in out parameters.
1054 function Match
1055 (Subject : VString_Var;
1056 Pat : Pattern;
1057 Result : Match_Result_Var) return Boolean;
1059 procedure Match
1060 (Subject : in out VString;
1061 Pat : Pattern;
1062 Result : out Match_Result);
1064 procedure Replace
1065 (Result : in out Match_Result;
1066 Replace : VString);
1067 -- Given a previous call to Match which set Result, performs a pattern
1068 -- replacement if the match was successful. Has no effect if the match
1069 -- failed. This call should immediately follow the Match call.
1071 ------------------------
1072 -- Debugging Routines --
1073 ------------------------
1075 -- Debugging pattern matching operations can often be quite complex,
1076 -- since there is no obvious way to trace the progress of the match.
1077 -- The declarations in this section provide some debugging assistance.
1079 Debug_Mode : Boolean := False;
1080 -- This global variable can be set True to generate debugging on all
1081 -- subsequent calls to Match. The debugging output is a full trace of
1082 -- the actions of the pattern matcher, written to Standard_Output. The
1083 -- level of this information is intended to be comprehensible at the
1084 -- abstract level of this package declaration. However, note that the
1085 -- use of this switch often generates large amounts of output.
1087 function "*" (P : Pattern; Fil : File_Access) return Pattern;
1088 function "*" (P : PString; Fil : File_Access) return Pattern;
1089 function "*" (P : PChar; Fil : File_Access) return Pattern;
1090 function "**" (P : Pattern; Fil : File_Access) return Pattern;
1091 function "**" (P : PString; Fil : File_Access) return Pattern;
1092 function "**" (P : PChar; Fil : File_Access) return Pattern;
1093 -- These are similar to the corresponding pattern assignment operations
1094 -- except that instead of setting the value of a variable, the matched
1095 -- substring is written to the appropriate file. This can be useful in
1096 -- following the progress of a match without generating the full amount
1097 -- of information obtained by setting Debug_Mode to True.
1099 Terminal : constant File_Access := Standard_Error;
1100 Output : constant File_Access := Standard_Output;
1101 -- Two handy synonyms for use with the above pattern write operations
1103 -- Finally we have some routines that are useful for determining what
1104 -- patterns are in use, particularly if they are constructed dynamically.
1106 function Image (P : Pattern) return String;
1107 function Image (P : Pattern) return VString;
1108 -- This procedures yield strings that corresponds to the syntax needed
1109 -- to create the given pattern using the functions in this package. The
1110 -- form of this string is such that it could actually be compiled and
1111 -- evaluated to yield the required pattern except for references to
1112 -- variables and functions, which are output using one of the following
1113 -- forms:
1115 -- access Natural NP(16#...#)
1116 -- access Pattern PP(16#...#)
1117 -- access VString VP(16#...#)
1119 -- Natural_Func NF(16#...#)
1120 -- VString_Func VF(16#...#)
1122 -- where 16#...# is the hex representation of the integer address that
1123 -- corresponds to the given access value
1125 procedure Dump (P : Pattern);
1126 -- This procedure writes information about the pattern to Standard_Out.
1127 -- The format of this information is keyed to the internal data structures
1128 -- used to implement patterns. The information provided by Dump is thus
1129 -- more precise than that yielded by Image, but is also a bit more obscure
1130 -- (i.e. it cannot be interpreted solely in terms of this spec, you have
1131 -- to know something about the data structures).
1133 ------------------
1134 -- Private Part --
1135 ------------------
1137 private
1138 type PE;
1139 -- Pattern element, a pattern is a plex structure of PE's. This type
1140 -- is defined and sdescribed in the body of this package.
1142 type PE_Ptr is access all PE;
1143 -- Pattern reference. PE's use PE_Ptr values to reference other PE's
1145 type Pattern is new Controlled with record
1146 Stk : Natural := 0;
1147 -- Maximum number of stack entries required for matching this
1148 -- pattern. See description of pattern history stack in body.
1150 P : PE_Ptr := null;
1151 -- Pointer to initial pattern element for pattern
1152 end record;
1154 pragma Finalize_Storage_Only (Pattern);
1156 procedure Adjust (Object : in out Pattern);
1157 -- Adjust routine used to copy pattern objects
1159 procedure Finalize (Object : in out Pattern);
1160 -- Finalization routine used to release storage allocated for a pattern
1162 type VString_Ptr is access all VString;
1164 type Match_Result is record
1165 Var : VString_Ptr;
1166 -- Pointer to subject string. Set to null if match failed
1168 Start : Natural := 1;
1169 -- Starting index position (1's origin) of matched section of
1170 -- subject string. Only valid if Var is non-null.
1172 Stop : Natural := 0;
1173 -- Ending index position (1's origin) of matched section of
1174 -- subject string. Only valid if Var is non-null.
1176 end record;
1178 pragma Volatile (Match_Result);
1179 -- This ensures that the Result parameter is passed by reference, so
1180 -- that we can play our games with the bogus Match_Result_Var parameter
1181 -- in the function case to treat it as though it were an in out parameter.
1183 end GNAT.Spitbol.Patterns;