* dwarf2out.c (loc_descriptor_from_tree, case CONSTRUCTOR): New case.
[official-gcc.git] / gcc / ada / g-spipat.ads
blob3d08f0be8523a7c0a852e187ca7a4a854c9e68fb
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-1999 Ada Core Technologies, Inc. --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 2, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING. If not, write --
19 -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
20 -- MA 02111-1307, USA. --
21 -- --
22 -- As a special exception, if other files instantiate generics from this --
23 -- unit, or you link this unit with other files to produce an executable, --
24 -- this unit does not by itself cause the resulting executable to be --
25 -- covered by the GNU General Public License. This exception does not --
26 -- however invalidate any other reasons why the executable file might be --
27 -- covered by the GNU Public License. --
28 -- --
29 -- GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com). --
30 -- --
31 ------------------------------------------------------------------------------
33 -- SPITBOL-like pattern construction and matching
35 -- This child package of GNAT.SPITBOL provides a complete implementation
36 -- of the SPITBOL-like pattern construction and matching operations. This
37 -- package is based on Macro-SPITBOL created by Robert Dewar.
39 ------------------------------------------------------------
40 -- Summary of Pattern Matching Packages in GNAT Hierarchy --
41 ------------------------------------------------------------
43 -- There are three related packages that perform pattern maching functions.
44 -- the following is an outline of these packages, to help you determine
45 -- which is best for your needs.
47 -- GNAT.Regexp (files g-regexp.ads/g-regexp.adb)
48 -- This is a simple package providing Unix-style regular expression
49 -- matching with the restriction that it matches entire strings. It
50 -- is particularly useful for file name matching, and in particular
51 -- it provides "globbing patterns" that are useful in implementing
52 -- unix or DOS style wild card matching for file names.
54 -- GNAT.Regpat (files g-regpat.ads/g-regpat.adb)
55 -- This is a more complete implementation of Unix-style regular
56 -- expressions, copied from the original V7 style regular expression
57 -- library written in C by Henry Spencer. It is functionally the
58 -- same as this library, and uses the same internal data structures
59 -- stored in a binary compatible manner.
61 -- GNAT.Spitbol.Patterns (files g-spipat.ads/g-spipat.adb)
62 -- This is a completely general patterm matching package based on the
63 -- pattern language of SNOBOL4, as implemented in SPITBOL. The pattern
64 -- language is modeled on context free grammars, with context sensitive
65 -- extensions that provide full (type 0) computational capabilities.
67 with Ada.Finalization; use Ada.Finalization;
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 (Patterns);
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.
89 -- Concatenation and Alternation
90 -- =============================
92 -- A pattern consists of a series of pattern elements. The pattern is
93 -- built up using either the concatenation operator:
95 -- A & B
97 -- which means match A followed immediately by matching B, or the
98 -- alternation operator:
100 -- A or B
102 -- which means first attempt to match A, and then if that does not
103 -- succeed, match B.
105 -- There is full backtracking, which means that if a given pattern
106 -- element fails to match, then previous alternatives are matched.
107 -- For example if we have the pattern:
109 -- (A or B) & (C or D) & (E or F)
111 -- First we attempt to match A, if that succeeds, then we go on to try
112 -- to match C, and if that succeeds, we go on to try to match E. If E
113 -- fails, then we try F. If F fails, then we go back and try matching
114 -- D instead of C. Let's make this explicit using a specific example,
115 -- and introducing the simplest kind of pattern element, which is a
116 -- literal string. The meaning of this pattern element is simply to
117 -- match the characters that correspond to the string characters. Now
118 -- let's rewrite the above pattern form with specific string literals
119 -- as the pattern elements:
121 -- ("ABC" or "AB") & ("DEF" or "CDE") & ("GH" or "IJ")
123 -- The following strings will be attempted in sequence:
125 -- ABC . DEF . GH
126 -- ABC . DEF . IJ
127 -- ABC . CDE . GH
128 -- ABC . CDE . IJ
129 -- AB . DEF . GH
130 -- AB . DEF . IJ
131 -- AB . CDE . GH
132 -- AB . CDE . IJ
134 -- Here we use the dot simply to separate the pieces of the string
135 -- matched by the three separate elements.
138 -- Moving the Start Point
139 -- ======================
141 -- A pattern is not required to match starting at the first character
142 -- of the string, and is not required to match to the end of the string.
143 -- The first attempt does indeed attempt to match starting at the first
144 -- character of the string, trying all the possible alternatives. But
145 -- if all alternatives fail, then the starting point of the match is
146 -- moved one character, and all possible alternatives are attempted at
147 -- the new anchor point.
149 -- The entire match fails only when every possible starting point has
150 -- been attempted. As an example, suppose that we had the subject
151 -- string
153 -- "ABABCDEIJKL"
155 -- matched using the pattern in the previous example:
157 -- ("ABC" or "AB") & ("DEF" or "CDE") & ("GH" or "IJ")
159 -- would succeed, afer two anchor point moves:
161 -- "ABABCDEIJKL"
162 -- ^^^^^^^
163 -- matched
164 -- section
166 -- This mode of pattern matching is called the unanchored mode. It is
167 -- also possible to put the pattern matcher into anchored mode by
168 -- setting the global variable Anchored_Mode to True. This will cause
169 -- all subsequent matches to be performed in anchored mode, where the
170 -- match is required to start at the first character.
172 -- We will also see later how the effect of an anchored match can be
173 -- obtained for a single specified anchor point if this is desired.
176 -- Other Pattern Elements
177 -- ======================
179 -- In addition to strings (or single characters), there are many special
180 -- pattern elements that correspond to special predefined alternations:
182 -- Arb Matches any string. First it matches the null string, and
183 -- then on a subsequent failure, matches one character, and
184 -- then two characters, and so on. It only fails if the
185 -- entire remaining string is matched.
187 -- Bal Matches a non-empty string that is parentheses balanced
188 -- with respect to ordinary () characters. Examples of
189 -- balanced strings are "ABC", "A((B)C)", and "A(B)C(D)E".
190 -- Bal matches the shortest possible balanced string on the
191 -- first attempt, and if there is a subsequent failure,
192 -- attempts to extend the string.
194 -- Cancel Immediately aborts the entire pattern match, signalling
195 -- failure. This is a specialized pattern element, which is
196 -- useful in conjunction with some of the special pattern
197 -- elements that have side effects.
199 -- Fail The null alternation. Matches no possible strings, so it
200 -- always signals failure. This is a specialized pattern
201 -- element, which is useful in conjunction with some of the
202 -- special pattern elements that have side effects.
204 -- Fence Matches the null string at first, and then if a failure
205 -- causes alternatives to be sought, aborts the match (like
206 -- a Cancel). Note that using Fence at the start of a pattern
207 -- has the same effect as matching in anchored mode.
209 -- Rest Matches from the current point to the last character in
210 -- the string. This is a specialized pattern element, which
211 -- is useful in conjunction with some of the special pattern
212 -- elements that have side effects.
214 -- Succeed Repeatedly matches the null string (it is equivalent to
215 -- the alternation ("" or "" or "" ....). This is a special
216 -- pattern element, which is useful in conjunction with some
217 -- of the special pattern elements that have side effects.
220 -- Pattern Construction Functions
221 -- ==============================
223 -- The following functions construct additional pattern elements
225 -- Any(S) Where S is a string, matches a single character that is
226 -- any one of the characters in S. Fails if the current
227 -- character is not one of the given set of characters.
229 -- Arbno(P) Where P is any pattern, matches any number of instances
230 -- of the pattern, starting with zero occurrences. It is
231 -- thus equivalent to ("" or (P & ("" or (P & ("" ....)))).
232 -- The pattern P may contain any number of pattern elements
233 -- including the use of alternatiion and concatenation.
235 -- Break(S) Where S is a string, matches a string of zero or more
236 -- characters up to but not including a break character
237 -- that is one of the characters given in the string S.
238 -- Can match the null string, but cannot match the last
239 -- character in the string, since a break character is
240 -- required to be present.
242 -- BreakX(S) Where S is a string, behaves exactly like Break(S) when
243 -- it first matches, but if a string is successfully matched,
244 -- then a susequent failure causes an attempt to extend the
245 -- matched string.
247 -- Fence(P) Where P is a pattern, attempts to match the pattern P
248 -- including trying all possible alternatives of P. If none
249 -- of these alternatives succeeds, then the Fence pattern
250 -- fails. If one alternative succeeds, then the pattern
251 -- match proceeds, but on a subsequent failure, no attempt
252 -- is made to search for alternative matches of P. The
253 -- pattern P may contain any number of pattern elements
254 -- including the use of alternatiion and concatenation.
256 -- Len(N) Where N is a natural number, matches the given number of
257 -- characters. For example, Len(10) matches any string that
258 -- is exactly ten characters long.
260 -- NotAny(S) Where S is a string, matches a single character that is
261 -- not one of the characters of S. Fails if the current
262 -- characer is one of the given set of characters.
264 -- NSpan(S) Where S is a string, matches a string of zero or more
265 -- characters that is among the characters given in the
266 -- string. Always matches the longest possible such string.
267 -- Always succeeds, since it can match the null string.
269 -- Pos(N) Where N is a natural number, matches the null string
270 -- if exactly N characters have been matched so far, and
271 -- otherwise fails.
273 -- Rpos(N) Where N is a natural number, matches the null string
274 -- if exactly N characters remain to be matched, and
275 -- otherwise fails.
277 -- Rtab(N) Where N is a natural number, matches characters from
278 -- the current position until exactly N characters remain
279 -- to be matched in the string. Fails if fewer than N
280 -- unmatched characters remain in the string.
282 -- Tab(N) Where N is a natural number, matches characters from
283 -- the current position until exactly N characters have
284 -- been matched in all. Fails if more than N characters
285 -- have already been matched.
287 -- Span(S) Where S is a string, matches a string of one or more
288 -- characters that is among the characters given in the
289 -- string. Always matches the longest possible such string.
290 -- Fails if the current character is not one of the given
291 -- set of characters.
293 -- Recursive Pattern Matching
294 -- ==========================
296 -- The plus operator (+P) where P is a pattern variable, creates
297 -- a recursive pattern that will, at pattern matching time, follow
298 -- the pointer to obtain the referenced pattern, and then match this
299 -- pattern. This may be used to construct recursive patterns. Consider
300 -- for example:
302 -- P := ("A" or ("B" & (+P)))
304 -- On the first attempt, this pattern attempts to match the string "A".
305 -- If this fails, then the alternative matches a "B", followed by an
306 -- attempt to match P again. This second attempt first attempts to
307 -- match "A", and so on. The result is a pattern that will match a
308 -- string of B's followed by a single A.
310 -- This particular example could simply be written as NSpan('B') & 'A',
311 -- but the use of recursive patterns in the general case can construct
312 -- complex patterns which could not otherwise be built.
315 -- Pattern Assignment Operations
316 -- =============================
318 -- In addition to the overall result of a pattern match, which indicates
319 -- success or failure, it is often useful to be able to keep track of
320 -- the pieces of the subject string that are matched by individual
321 -- pattern elements, or subsections of the pattern.
323 -- The pattern assignment operators allow this capability. The first
324 -- form is the immediate assignment:
326 -- P * S
328 -- Here P is an arbitrary pattern, and S is a variable of type VString
329 -- that will be set to the substring matched by P. This assignment
330 -- happens during pattern matching, so if P matches more than once,
331 -- then the assignment happens more than once.
333 -- The deferred assignment operation:
335 -- P ** S
337 -- avoids these multiple assignments by deferring the assignment to the
338 -- end of the match. If the entire match is successful, and if the
339 -- pattern P was part of the successful match, then at the end of the
340 -- matching operation the assignment to S of the string matching P is
341 -- performed.
343 -- The cursor assignment operation:
345 -- Setcur(N'Access)
347 -- assigns the current cursor position to the natural variable N. The
348 -- cursor position is defined as the count of characters that have been
349 -- matched so far (including any start point moves).
351 -- Finally the operations * and ** may be used with values of type
352 -- Text_IO.File_Access. The effect is to do a Put_Line operation of
353 -- the matched substring. These are particularly useful in debugging
354 -- pattern matches.
357 -- Deferred Matching
358 -- =================
360 -- The pattern construction functions (such as Len and Any) all permit
361 -- the use of pointers to natural or string values, or functions that
362 -- return natural or string values. These forms cause the actual value
363 -- to be obtained at pattern matching time. This allows interesting
364 -- possibilities for constructing dynamic patterns as illustrated in
365 -- the examples section.
367 -- In addition the (+S) operator may be used where S is a pointer to
368 -- string or function returning string, with a similar deferred effect.
370 -- A special use of deferred matching is the construction of predicate
371 -- functions. The element (+P) where P is an access to a function that
372 -- returns a Boolean value, causes the function to be called at the
373 -- time the element is matched. If the function returns True, then the
374 -- null string is matched, if the function returns False, then failure
375 -- is signalled and previous alternatives are sought.
377 -- Deferred Replacement
378 -- ====================
380 -- The simple model given for pattern replacement (where the matched
381 -- substring is replaced by the string given as the third argument to
382 -- Match) works fine in simple cases, but this approach does not work
383 -- in the case where the expression used as the replacement string is
384 -- dependent on values set by the match.
386 -- For example, suppose we want to find an instance of a parenthesized
387 -- character, and replace the parentheses with square brackets. At first
388 -- glance it would seem that:
390 -- Match (Subject, '(' & Len (1) * Char & ')', '[' & Char & ']');
392 -- would do the trick, but that does not work, because the third
393 -- argument to Match gets evaluated too early, before the call to
394 -- Match, and before the pattern match has had a chance to set Char.
396 -- To solve this problem we provide the deferred replacement capability.
397 -- With this approach, which of course is only needed if the pattern
398 -- involved has side effects, is to do the match in two stages. The
399 -- call to Match sets a pattern result in a variable of the private
400 -- type Match_Result, and then a subsequent Replace operation uses
401 -- this Match_Result object to perform the required replacement.
403 -- Using this approach, we can now write the above operation properly
404 -- in a manner that will work:
406 -- M : Match_Result;
407 -- ...
408 -- Match (Subject, '(' & Len (1) * Char & ')', M);
409 -- Replace (M, '[' & Char & ']');
411 -- As with other Match cases, there is a function and procedure form
412 -- of this match call. A call to Replace after a failed match has no
413 -- effect. Note that Subject should not be modified between the calls.
415 -- Examples of Pattern Matching
416 -- ============================
418 -- First a simple example of the use of pattern replacement to remove
419 -- a line number from the start of a string. We assume that the line
420 -- number has the form of a string of decimal digits followed by a
421 -- period, followed by one or more spaces.
423 -- Digs : constant Pattern := Span("0123456789");
425 -- Lnum : constant Pattern := Pos(0) & Digs & '.' & Span(' ');
427 -- Now to use this pattern we simply do a match with a replacement:
429 -- Match (Line, Lnum, "");
431 -- which replaces the line number by the null string. Note that it is
432 -- also possible to use an Ada.Strings.Maps.Character_Set value as an
433 -- argument to Span and similar functions, and in particular all the
434 -- useful constants 'in Ada.Strings.Maps.Constants are available. This
435 -- means that we could define Digs as:
437 -- Digs : constant Pattern := Span(Decimal_Digit_Set);
439 -- The style we use here, of defining constant patterns and then using
440 -- them is typical. It is possible to build up patterns dynamically,
441 -- but it is usually more efficient to build them in pieces in advance
442 -- using constant declarations. Note in particular that although it is
443 -- possible to construct a pattern directly as an argument for the
444 -- Match routine, it is much more efficient to preconstruct the pattern
445 -- as we did in this example.
447 -- Now let's look at the use of pattern assignment to break a
448 -- string into sections. Suppose that the input string has two
449 -- unsigned decimal integers, separated by spaces or a comma,
450 -- with spaces allowed anywhere. Then we can isolate the two
451 -- numbers with the following pattern:
453 -- Num1, Num2 : aliased VString;
455 -- B : constant Pattern := NSpan(' ');
457 -- N : constant Pattern := Span("0123456789");
459 -- T : constant Pattern :=
460 -- NSpan(' ') & N * Num1 & Span(" ,") & N * Num2;
462 -- The match operation Match (" 124, 257 ", T) would assign the
463 -- string 124 to Num1 and the string 257 to Num2.
465 -- Now let's see how more complex elements can be built from the
466 -- set of primitive elements. The following pattern matches strings
467 -- that have the syntax of Ada 95 based literals:
469 -- Digs : constant Pattern := Span(Decimal_Digit_Set);
470 -- UDigs : constant Pattern := Digs & Arbno('_' & Digs);
472 -- Edig : constant Pattern := Span(Hexadecimal_Digit_Set);
473 -- UEdig : constant Pattern := Edig & Arbno('_' & Edig);
475 -- Bnum : constant Pattern := Udigs & '#' & UEdig & '#';
477 -- A match against Bnum will now match the desired strings, e.g.
478 -- it will match 16#123_abc#, but not a#b#. However, this pattern
479 -- is not quite complete, since it does not allow colons to replace
480 -- the pound signs. The following is more complete:
482 -- Bchar : constant Pattern := Any("#:");
483 -- Bnum : constant Pattern := Udigs & Bchar & UEdig & Bchar;
485 -- but that is still not quite right, since it allows # and : to be
486 -- mixed, and they are supposed to be used consistently. We solve
487 -- this by using a deferred match.
489 -- Temp : aliased VString;
491 -- Bnum : constant Pattern :=
492 -- Udigs & Bchar * Temp & UEdig & (+Temp)
494 -- Here the first instance of the base character is stored in Temp, and
495 -- then later in the pattern we rematch the value that was assigned.
497 -- For an example of a recursive pattern, let's define a pattern
498 -- that is like the built in Bal, but the string matched is balanced
499 -- with respect to square brackets or curly brackets.
501 -- The language for such strings might be defined in extended BNF as
503 -- ELEMENT ::= <any character other than [] or {}>
504 -- | '[' BALANCED_STRING ']'
505 -- | '{' BALANCED_STRING '}'
507 -- BALANCED_STRING ::= ELEMENT {ELEMENT}
509 -- Here we use {} to indicate zero or more occurrences of a term, as
510 -- is common practice in extended BNF. Now we can translate the above
511 -- BNF into recursive patterns as follows:
513 -- Element, Balanced_String : aliased Pattern;
514 -- .
515 -- .
516 -- .
517 -- Element := NotAny ("[]{}")
518 -- or
519 -- ('[' & (+Balanced_String) & ']')
520 -- or
521 -- ('{' & (+Balanced_String) & '}');
523 -- Balanced_String := Element & Arbno (Element);
525 -- Note the important use of + here to refer to a pattern not yet
526 -- defined. Note also that we use assignments precisely because we
527 -- cannot refer to as yet undeclared variables in initializations.
529 -- Now that this pattern is constructed, we can use it as though it
530 -- were a new primitive pattern element, and for example, the match:
532 -- Match ("xy[ab{cd}]", Balanced_String * Current_Output & Fail);
534 -- will generate the output:
536 -- x
537 -- xy
538 -- xy[ab{cd}]
539 -- y
540 -- y[ab{cd}]
541 -- [ab{cd}]
542 -- a
543 -- ab
544 -- ab{cd}
545 -- b
546 -- b{cd}
547 -- {cd}
548 -- c
549 -- cd
550 -- d
552 -- Note that the function of the fail here is simply to force the
553 -- pattern Balanced_String to match all possible alternatives. Studying
554 -- the operation of this pattern in detail is highly instructive.
556 -- Finally we give a rather elaborate example of the use of deferred
557 -- matching. The following declarations build up a pattern which will
558 -- find the longest string of decimal digits in the subject string.
560 -- Max, Cur : VString;
561 -- Loc : Natural;
563 -- function GtS return Boolean is
564 -- begin
565 -- return Length (Cur) > Length (Max);
566 -- end GtS;
568 -- Digit : constant Character_Set := Decimal_Digit_Set;
570 -- Digs : constant Pattern := Span(Digit);
572 -- Find : constant Pattern :=
573 -- "" * Max & Fence & -- initialize Max to null
574 -- BreakX (Digit) & -- scan looking for digits
575 -- ((Span(Digit) * Cur & -- assign next string to Cur
576 -- (+GtS'Unrestricted_Access) & -- check size(Cur) > Size(Max)
577 -- Setcur(Loc'Access)) -- if so, save location
578 -- * Max) & -- and assign to Max
579 -- Fail; -- seek all alternatives
581 -- As we see from the comments here, complex patterns like this take
582 -- on aspects of sequential programs. In fact they are sequential
583 -- programs with general backtracking. In this pattern, we first use
584 -- a pattern assignment that matches null and assigns it to Max, so
585 -- that it is initialized for the new match. Now BreakX scans to the
586 -- next digit. Arb would do here, but BreakX will be more efficient.
587 -- Once we have found a digit, we scan out the longest string of
588 -- digits with Span, and assign it to Cur. The deferred call to GtS
589 -- tests if the string we assigned to Cur is the longest so far. If
590 -- not, then failure is signalled, and we seek alternatives (this
591 -- means that BreakX will extend and look for the next digit string).
592 -- If the call to GtS succeeds then the matched string is assigned
593 -- as the largest string so far into Max and its location is saved
594 -- in Loc. Finally Fail forces the match to fail and seek alternatives,
595 -- so that the entire string is searched.
597 -- If the pattern Find is matched against a string, the variable Max
598 -- at the end of the pattern will have the longest string of digits,
599 -- and Loc will be the starting character location of the string. For
600 -- example, Match("ab123cd4657ef23", Find) will assign "4657" to Max
601 -- and 11 to Loc (indicating that the string ends with the eleventh
602 -- character of the string).
604 -- Note: the use of Unrestricted_Access to reference GtS will not
605 -- be needed if GtS is defined at the outer level, but definitely
606 -- will be necessary if GtS is a nested function (in which case of
607 -- course the scope of the pattern Find will be restricted to this
608 -- nested scope, and this cannot be checked, i.e. use of the pattern
609 -- outside this scope is erroneous). Generally it is a good idea to
610 -- define patterns and the functions they call at the outer level
611 -- where possible, to avoid such problems.
614 -- Correspondence with Pattern Matching in SPITBOL
615 -- ===============================================
617 -- Generally the Ada syntax and names correspond closely to SPITBOL
618 -- syntax for pattern matching construction.
620 -- The basic pattern construction operators are renamed as follows:
622 -- Spitbol Ada
624 -- (space) &
625 -- | or
626 -- $ *
627 -- . **
629 -- The Ada operators were chosen so that the relative precedences of
630 -- these operators corresponds to that of the Spitbol operators, but
631 -- as always, the use of parentheses is advisable to clarify.
633 -- The pattern construction operators all have similar names except for
635 -- Spitbol Ada
637 -- Abort Cancel
638 -- Rem Rest
640 -- where we have clashes with Ada reserved names.
642 -- Ada requires the use of 'Access to refer to functions used in the
643 -- pattern match, and often the use of 'Unrestricted_Access may be
644 -- necessary to get around the scope restrictions if the functions
645 -- are not declared at the outer level.
647 -- The actual pattern matching syntax is modified in Ada as follows:
649 -- Spitbol Ada
651 -- X Y Match (X, Y);
652 -- X Y = Z Match (X, Y, Z);
654 -- and pattern failure is indicated by returning a Boolean result from
655 -- the Match function (True for success, False for failure).
657 -----------------------
658 -- Type Declarations --
659 -----------------------
661 type Pattern is private;
662 -- Type representing a pattern. This package provides a complete set of
663 -- operations for constructing patterns that can be used in the pattern
664 -- matching operations provided.
666 type Boolean_Func is access function return Boolean;
667 -- General Boolean function type. When this type is used as a formal
668 -- parameter type in this package, it indicates a deferred predicate
669 -- pattern. The function will be called when the pattern element is
670 -- matched and failure signalled if False is returned.
672 type Natural_Func is access function return Natural;
673 -- General Natural function type. When this type is used as a formal
674 -- parameter type in this package, it indicates a deferred pattern.
675 -- The function will be called when the pattern element is matched
676 -- to obtain the currently referenced Natural value.
678 type VString_Func is access function return VString;
679 -- General VString function type. When this type is used as a formal
680 -- parameter type in this package, it indicates a deferred pattern.
681 -- The function will be called when the pattern element is matched
682 -- to obtain the currently referenced string value.
684 subtype PString is String;
685 -- This subtype is used in the remainder of the package to indicate a
686 -- formal parameter that is converted to its corresponding pattern,
687 -- i.e. a pattern that matches the characters of the string.
689 subtype PChar is Character;
690 -- Similarly, this subtype is used in the remainder of the package to
691 -- indicate a formal parameter that is converted to its corresponding
692 -- pattern, i.e. a pattern that matches this one character.
694 subtype VString_Var is VString;
695 subtype Pattern_Var is Pattern;
696 -- These synonyms are used as formal parameter types to a function where,
697 -- if the language allowed, we would use in out parameters, but we are
698 -- not allowed to have in out parameters for functions. Instead we pass
699 -- actuals which must be variables, and with a bit of trickery in the
700 -- body, manage to interprete them properly as though they were indeed
701 -- in out parameters.
703 --------------------------------
704 -- Basic Pattern Construction --
705 --------------------------------
707 function "&" (L : Pattern; R : Pattern) return Pattern;
708 function "&" (L : PString; R : Pattern) return Pattern;
709 function "&" (L : Pattern; R : PString) return Pattern;
710 function "&" (L : PChar; R : Pattern) return Pattern;
711 function "&" (L : Pattern; R : PChar) return Pattern;
713 -- Pattern concatenation. Matches L followed by R.
715 function "or" (L : Pattern; R : Pattern) return Pattern;
716 function "or" (L : PString; R : Pattern) return Pattern;
717 function "or" (L : Pattern; R : PString) return Pattern;
718 function "or" (L : PString; R : PString) return Pattern;
719 function "or" (L : PChar; R : Pattern) return Pattern;
720 function "or" (L : Pattern; R : PChar) return Pattern;
721 function "or" (L : PChar; R : PChar) return Pattern;
722 function "or" (L : PString; R : PChar) return Pattern;
723 function "or" (L : PChar; R : PString) return Pattern;
724 -- Pattern alternation. Creates a pattern that will first try to match
725 -- L and then on a subsequent failure, attempts to match R instead.
727 ----------------------------------
728 -- Pattern Assignment Functions --
729 ----------------------------------
731 function "*" (P : Pattern; Var : VString_Var) return Pattern;
732 function "*" (P : PString; Var : VString_Var) return Pattern;
733 function "*" (P : PChar; Var : VString_Var) return Pattern;
734 -- Matches P, and if the match succeeds, assigns the matched substring
735 -- to the given VString variable S. This assignment happens as soon as
736 -- the substring is matched, and if the pattern P1 is matched more than
737 -- once during the course of the match, then the assignment will occur
738 -- more than once.
740 function "**" (P : Pattern; Var : VString_Var) return Pattern;
741 function "**" (P : PString; Var : VString_Var) return Pattern;
742 function "**" (P : PChar; Var : VString_Var) return Pattern;
743 -- Like "*" above, except that the assignment happens at most once
744 -- after the entire match is completed successfully. If the match
745 -- fails, then no assignment takes place.
747 ----------------------------------
748 -- Deferred Matching Operations --
749 ----------------------------------
751 function "+" (Str : VString_Var) return Pattern;
752 -- Here Str must be a VString variable. This function constructs a
753 -- pattern which at pattern matching time will access the current
754 -- value of this variable, and match against these characters.
756 function "+" (Str : VString_Func) return Pattern;
757 -- Constructs a pattern which at pattern matching time calls the given
758 -- function, and then matches against the string or character value
759 -- that is returned by the call.
761 function "+" (P : Pattern_Var) return Pattern;
762 -- Here P must be a Pattern variable. This function constructs a
763 -- pattern which at pattern matching time will access the current
764 -- value of this variable, and match against the pattern value.
766 function "+" (P : Boolean_Func) return Pattern;
767 -- Constructs a predicate pattern function that at pattern matching time
768 -- calls the given function. If True is returned, then the pattern matches.
769 -- If False is returned, then failure is signalled.
771 --------------------------------
772 -- Pattern Building Functions --
773 --------------------------------
775 function Arb return Pattern;
776 -- Constructs a pattern that will match any string. On the first attempt,
777 -- the pattern matches a null string, then on each successive failure, it
778 -- matches one more character, and only fails if matching the entire rest
779 -- of the string.
781 function Arbno (P : Pattern) return Pattern;
782 function Arbno (P : PString) return Pattern;
783 function Arbno (P : PChar) return Pattern;
784 -- Pattern repetition. First matches null, then on a subsequent failure
785 -- attempts to match an additional instance of the given pattern.
786 -- Equivalent to (but more efficient than) P & ("" or (P & ("" or ...
788 function Any (Str : String) return Pattern;
789 function Any (Str : VString) return Pattern;
790 function Any (Str : Character) return Pattern;
791 function Any (Str : Character_Set) return Pattern;
792 function Any (Str : access VString) return Pattern;
793 function Any (Str : VString_Func) return Pattern;
794 -- Constructs a pattern that matches a single character that is one of
795 -- the characters in the given argument. The pattern fails if the current
796 -- character is not in Str.
798 function Bal return Pattern;
799 -- Constructs a pattern that will match any non-empty string that is
800 -- parentheses balanced with respect to the normal parentheses characters.
801 -- Attempts to extend the string if a subsequent failure occurs.
803 function Break (Str : String) return Pattern;
804 function Break (Str : VString) return Pattern;
805 function Break (Str : Character) return Pattern;
806 function Break (Str : Character_Set) return Pattern;
807 function Break (Str : access VString) return Pattern;
808 function Break (Str : VString_Func) return Pattern;
809 -- Constructs a pattern that matches a (possibly null) string which
810 -- is immediately followed by a character in the given argument. This
811 -- character is not part of the matched string. The pattern fails if
812 -- the remaining characters to be matched do not include any of the
813 -- characters in Str.
815 function BreakX (Str : String) return Pattern;
816 function BreakX (Str : VString) return Pattern;
817 function BreakX (Str : Character) return Pattern;
818 function BreakX (Str : Character_Set) return Pattern;
819 function BreakX (Str : access VString) return Pattern;
820 function BreakX (Str : VString_Func) return Pattern;
821 -- Like Break, but the pattern attempts to extend on a failure to find
822 -- the next occurrence of a character in Str, and only fails when the
823 -- last such instance causes a failure.
825 function Cancel return Pattern;
826 -- Constructs a pattern that immediately aborts the entire match
828 function Fail return Pattern;
829 -- Constructs a pattern that always fails.
831 function Fence return Pattern;
832 -- Constructs a pattern that matches null on the first attempt, and then
833 -- causes the entire match to be aborted if a subsequent failure occurs.
835 function Fence (P : Pattern) return Pattern;
836 -- Constructs a pattern that first matches P. if P fails, then the
837 -- constructed pattern fails. If P succeeds, then the match proceeds,
838 -- but if subsequent failure occurs, alternatives in P are not sought.
839 -- The idea of Fence is that each time the pattern is matched, just
840 -- one attempt is made to match P, without trying alternatives.
842 function Len (Count : Natural) return Pattern;
843 function Len (Count : access Natural) return Pattern;
844 function Len (Count : Natural_Func) return Pattern;
845 -- Constructs a pattern that matches exactly the given number of
846 -- characters. The pattern fails if fewer than this number of characters
847 -- remain to be matched in the string.
849 function NotAny (Str : String) return Pattern;
850 function NotAny (Str : VString) return Pattern;
851 function NotAny (Str : Character) return Pattern;
852 function NotAny (Str : Character_Set) return Pattern;
853 function NotAny (Str : access VString) return Pattern;
854 function NotAny (Str : VString_Func) return Pattern;
855 -- Constructs a pattern that matches a single character that is not
856 -- one of the characters in the given argument. The pattern Fails if
857 -- the current character is in Str.
859 function NSpan (Str : String) return Pattern;
860 function NSpan (Str : VString) return Pattern;
861 function NSpan (Str : Character) return Pattern;
862 function NSpan (Str : Character_Set) return Pattern;
863 function NSpan (Str : access VString) return Pattern;
864 function NSpan (Str : VString_Func) return Pattern;
865 -- Constructs a pattern that matches the longest possible string
866 -- consisting entirely of characters from the given argument. The
867 -- string may be empty, so this pattern always succeeds.
869 function Pos (Count : Natural) return Pattern;
870 function Pos (Count : access Natural) return Pattern;
871 function Pos (Count : Natural_Func) return Pattern;
872 -- Constructs a pattern that matches the null string if exactly Count
873 -- characters have already been matched, and otherwise fails.
875 function Rest return Pattern;
876 -- Constructs a pattern that always succeeds, matching the remaining
877 -- unmatched characters in the pattern.
879 function Rpos (Count : Natural) return Pattern;
880 function Rpos (Count : access Natural) return Pattern;
881 function Rpos (Count : Natural_Func) return Pattern;
882 -- Constructs a pattern that matches the null string if exactly Count
883 -- characters remain to be matched in the string, and otherwise fails.
885 function Rtab (Count : Natural) return Pattern;
886 function Rtab (Count : access Natural) return Pattern;
887 function Rtab (Count : Natural_Func) return Pattern;
888 -- Constructs a pattern that matches from the current location until
889 -- exactly Count characters remain to be matched in the string. The
890 -- pattern fails if fewer than Count characters remain to be matched.
892 function Setcur (Var : access Natural) return Pattern;
893 -- Constructs a pattern that matches the null string, and assigns the
894 -- current cursor position in the string. This value is the number of
895 -- characters matched so far. So it is zero at the start of the match.
897 function Span (Str : String) return Pattern;
898 function Span (Str : VString) return Pattern;
899 function Span (Str : Character) return Pattern;
900 function Span (Str : Character_Set) return Pattern;
901 function Span (Str : access VString) return Pattern;
902 function Span (Str : VString_Func) return Pattern;
903 -- Constructs a pattern that matches the longest possible string
904 -- consisting entirely of characters from the given argument. The
905 -- string cannot be empty , so the pattern fails if the current
906 -- character is not one of the characters in Str.
908 function Succeed return Pattern;
909 -- Constructs a pattern that succeeds matching null, both on the first
910 -- attempt, and on any rematch attempt, i.e. it is equivalent to an
911 -- infinite alternation of null strings.
913 function Tab (Count : Natural) return Pattern;
914 function Tab (Count : access Natural) return Pattern;
915 function Tab (Count : Natural_Func) return Pattern;
916 -- Constructs a pattern that from the current location until Count
917 -- characters have been matched. The pattern fails if more than Count
918 -- characters have already been matched.
920 ---------------------------------
921 -- Pattern Matching Operations --
922 ---------------------------------
924 -- The Match function performs an actual pattern matching operation.
925 -- The versions with three parameters perform a match without modifying
926 -- the subject string and return a Boolean result indicating if the
927 -- match is successful or not. The Anchor parameter is set to True to
928 -- obtain an anchored match in which the pattern is required to match
929 -- the first character of the string. In an unanchored match, which is
931 -- the default, successive attempts are made to match the given pattern
932 -- at each character of the subject string until a match succeeds, or
933 -- until all possibilities have failed.
935 -- Note that pattern assignment functions in the pattern may generate
936 -- side effects, so these functions are not necessarily pure.
938 Anchored_Mode : Boolean := False;
939 -- This global variable can be set True to cause all subsequent pattern
940 -- matches to operate in anchored mode. In anchored mode, no attempt is
941 -- made to move the anchor point, so that if the match succeeds it must
942 -- succeed starting at the first character. Note that the effect of
943 -- anchored mode may be achieved in individual pattern matches by using
944 -- Fence or Pos(0) at the start of the pattern.
946 Pattern_Stack_Overflow : exception;
947 -- Exception raised if internal pattern matching stack overflows. This
948 -- is typically the result of runaway pattern recursion. If there is a
949 -- genuine case of stack overflow, then either the match must be broken
950 -- down into simpler steps, or the stack limit must be reset.
952 Stack_Size : constant Positive := 2000;
953 -- Size used for internal pattern matching stack. Increase this size if
954 -- complex patterns cause Pattern_Stack_Overflow to be raised.
956 -- Simple match functions. The subject is matched against the pattern.
957 -- Any immediate or deferred assignments or writes are executed, and
958 -- the returned value indicates whether or not the match succeeded.
960 function Match
961 (Subject : VString;
962 Pat : Pattern)
963 return Boolean;
965 function Match
966 (Subject : VString;
967 Pat : PString)
968 return Boolean;
970 function Match
971 (Subject : String;
972 Pat : Pattern)
973 return Boolean;
975 function Match
976 (Subject : String;
977 Pat : PString)
978 return Boolean;
980 -- Replacement functions. The subject is matched against the pattern.
981 -- Any immediate or deferred assignments or writes are executed, and
982 -- the returned value indicates whether or not the match succeeded.
983 -- If the match succeeds, then the matched part of the subject string
984 -- is replaced by the given Replace string.
986 function Match
987 (Subject : VString_Var;
988 Pat : Pattern;
989 Replace : VString)
990 return Boolean;
992 function Match
993 (Subject : VString_Var;
994 Pat : PString;
995 Replace : VString)
996 return Boolean;
998 function Match
999 (Subject : VString_Var;
1000 Pat : Pattern;
1001 Replace : String)
1002 return Boolean;
1004 function Match
1005 (Subject : VString_Var;
1006 Pat : PString;
1007 Replace : String)
1008 return Boolean;
1010 -- Simple match procedures. The subject is matched against the pattern.
1011 -- Any immediate or deferred assignments or writes are executed. No
1012 -- indication of success or failure is returned.
1014 procedure Match
1015 (Subject : VString;
1016 Pat : Pattern);
1018 procedure Match
1019 (Subject : VString;
1020 Pat : PString);
1022 procedure Match
1023 (Subject : String;
1024 Pat : Pattern);
1026 procedure Match
1027 (Subject : String;
1028 Pat : PString);
1030 -- Replacement procedures. The subject is matched against the pattern.
1031 -- Any immediate or deferred assignments or writes are executed. No
1032 -- indication of success or failure is returned. If the match succeeds,
1033 -- then the matched part of the subject string is replaced by the given
1034 -- Replace string.
1036 procedure Match
1037 (Subject : in out VString;
1038 Pat : Pattern;
1039 Replace : VString);
1041 procedure Match
1042 (Subject : in out VString;
1043 Pat : PString;
1044 Replace : VString);
1046 procedure Match
1047 (Subject : in out VString;
1048 Pat : Pattern;
1049 Replace : String);
1051 procedure Match
1052 (Subject : in out VString;
1053 Pat : PString;
1054 Replace : String);
1056 -- Deferred Replacement
1058 type Match_Result is private;
1059 -- Type used to record result of pattern match
1061 subtype Match_Result_Var is Match_Result;
1062 -- This synonyms is used as a formal parameter type to a function where,
1063 -- if the language allowed, we would use an in out parameter, but we are
1064 -- not allowed to have in out parameters for functions. Instead we pass
1065 -- actuals which must be variables, and with a bit of trickery in the
1066 -- body, manage to interprete them properly as though they were indeed
1067 -- in out parameters.
1069 function Match
1070 (Subject : VString_Var;
1071 Pat : Pattern;
1072 Result : Match_Result_Var)
1073 return Boolean;
1075 procedure Match
1076 (Subject : in out VString;
1077 Pat : Pattern;
1078 Result : out Match_Result);
1080 procedure Replace
1081 (Result : in out Match_Result;
1082 Replace : VString);
1083 -- Given a previous call to Match which set Result, performs a pattern
1084 -- replacement if the match was successful. Has no effect if the match
1085 -- failed. This call should immediately follow the Match call.
1087 ------------------------
1088 -- Debugging Routines --
1089 ------------------------
1091 -- Debugging pattern matching operations can often be quite complex,
1092 -- since there is no obvious way to trace the progress of the match.
1093 -- The declarations in this section provide some debugging assistance.
1095 Debug_Mode : Boolean := False;
1096 -- This global variable can be set True to generate debugging on all
1097 -- subsequent calls to Match. The debugging output is a full trace of
1098 -- the actions of the pattern matcher, written to Standard_Output. The
1099 -- level of this information is intended to be comprehensible at the
1100 -- abstract level of this package declaration. However, note that the
1101 -- use of this switch often generates large amounts of output.
1103 function "*" (P : Pattern; Fil : File_Access) return Pattern;
1104 function "*" (P : PString; Fil : File_Access) return Pattern;
1105 function "*" (P : PChar; Fil : File_Access) return Pattern;
1106 function "**" (P : Pattern; Fil : File_Access) return Pattern;
1107 function "**" (P : PString; Fil : File_Access) return Pattern;
1108 function "**" (P : PChar; Fil : File_Access) return Pattern;
1109 -- These are similar to the corresponding pattern assignment operations
1110 -- except that instead of setting the value of a variable, the matched
1111 -- substring is written to the appropriate file. This can be useful in
1112 -- following the progress of a match without generating the full amount
1114 -- of information obtained by setting Debug_Mode to True.
1116 Terminal : constant File_Access := Standard_Error;
1117 Output : constant File_Access := Standard_Output;
1118 -- Two handy synonyms for use with the above pattern write operations.
1120 -- Finally we have some routines that are useful for determining what
1121 -- patterns are in use, particularly if they are constructed dynamically.
1123 function Image (P : Pattern) return String;
1124 function Image (P : Pattern) return VString;
1125 -- This procedures yield strings that corresponds to the syntax needed
1126 -- to create the given pattern using the functions in this package. The
1127 -- form of this string is such that it could actually be compiled and
1128 -- evaluated to yield the required pattern except for references to
1129 -- variables and functions, which are output using one of the following
1130 -- forms:
1132 -- access Natural NP(16#...#)
1133 -- access Pattern PP(16#...#)
1134 -- access VString VP(16#...#)
1136 -- Natural_Func NF(16#...#)
1137 -- VString_Func VF(16#...#)
1139 -- where 16#...# is the hex representation of the integer address that
1140 -- corresponds to the given access value
1142 procedure Dump (P : Pattern);
1143 -- This procedure writes information about the pattern to Standard_Out.
1144 -- The format of this information is keyed to the internal data structures
1145 -- used to implement patterns. The information provided by Dump is thus
1146 -- more precise than that yielded by Image, but is also a bit more obscure
1147 -- (i.e. it cannot be interpreted solely in terms of this spec, you have
1148 -- to know something about the data structures).
1150 ------------------
1151 -- Private Part --
1152 ------------------
1154 private
1155 type PE;
1156 -- Pattern element, a pattern is a plex structure of PE's. This type
1157 -- is defined and sdescribed in the body of this package.
1159 type PE_Ptr is access all PE;
1160 -- Pattern reference. PE's use PE_Ptr values to reference other PE's
1162 type Pattern is new Controlled with record
1164 Stk : Natural;
1165 -- Maximum number of stack entries required for matching this
1166 -- pattern. See description of pattern history stack in body.
1168 P : PE_Ptr;
1169 -- Pointer to initial pattern element for pattern
1171 end record;
1173 pragma Finalize_Storage_Only (Pattern);
1175 procedure Adjust (Object : in out Pattern);
1176 -- Adjust routine used to copy pattern objects
1178 procedure Finalize (Object : in out Pattern);
1179 -- Finalization routine used to release storage allocated for a pattern.
1181 type VString_Ptr is access all VString;
1183 type Match_Result is record
1184 Var : VString_Ptr;
1185 -- Pointer to subject string. Set to null if match failed.
1187 Start : Natural;
1188 -- Starting index position (1's origin) of matched section of
1189 -- subject string. Only valid if Var is non-null.
1191 Stop : Natural;
1192 -- Ending index position (1's origin) of matched section of
1193 -- subject string. Only valid if Var is non-null.
1195 end record;
1197 pragma Volatile (Match_Result);
1198 -- This ensures that the Result parameter is passed by reference, so
1199 -- that we can play our games with the bogus Match_Result_Var parameter
1200 -- in the function case to treat it as though it were an in out parameter.
1202 end GNAT.Spitbol.Patterns;