OSDN Git Service

2008-04-08 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / s-regpat.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT LIBRARY COMPONENTS                          --
4 --                                                                          --
5 --                          G N A T . R E G P A T                           --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --               Copyright (C) 1986 by University of Toronto.               --
10 --                      Copyright (C) 1999-2008, AdaCore                    --
11 --                                                                          --
12 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
13 -- terms of the  GNU General Public License as published  by the Free Soft- --
14 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
15 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
16 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
17 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
18 -- for  more details.  You should have  received  a copy of the GNU General --
19 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
20 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
21 -- Boston, MA 02110-1301, USA.                                              --
22 --                                                                          --
23 -- As a special exception,  if other files  instantiate  generics from this --
24 -- unit, or you link  this unit with other files  to produce an executable, --
25 -- this  unit  does not  by itself cause  the resulting  executable  to  be --
26 -- covered  by the  GNU  General  Public  License.  This exception does not --
27 -- however invalidate  any other reasons why  the executable file  might be --
28 -- covered by the  GNU Public License.                                      --
29 --                                                                          --
30 -- GNAT was originally developed  by the GNAT team at  New York University. --
31 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
32 --                                                                          --
33 ------------------------------------------------------------------------------
34
35 --  This is an altered Ada 95 version of the original V8 style regular
36 --  expression library written in C by Henry Spencer. Apart from the
37 --  translation to Ada, the interface has been considerably changed to
38 --  use the Ada String type instead of C-style nul-terminated strings.
39
40 --  Beware that some of this code is subtly aware of the way operator
41 --  precedence is structured in regular expressions. Serious changes in
42 --  regular-expression syntax might require a total rethink.
43
44 with System.IO;               use System.IO;
45 with Ada.Characters.Handling; use Ada.Characters.Handling;
46 with Ada.Unchecked_Conversion;
47
48 package body System.Regpat is
49
50    MAGIC : constant Character := Character'Val (10#0234#);
51    --  The first byte of the regexp internal "program" is actually
52    --  this magic number; the start node begins in the second byte.
53    --
54    --  This is used to make sure that a regular expression was correctly
55    --  compiled.
56
57    ----------------------------
58    -- Implementation details --
59    ----------------------------
60
61    --  This is essentially a linear encoding of a nondeterministic
62    --  finite-state machine, also known as syntax charts or
63    --  "railroad normal form" in parsing technology.
64
65    --  Each node is an opcode plus a "next" pointer, possibly plus an
66    --  operand. "Next" pointers of all nodes except BRANCH implement
67    --  concatenation; a "next" pointer with a BRANCH on both ends of it
68    --  is connecting two alternatives.
69
70    --  The operand of some types of node is a literal string; for others,
71    --  it is a node leading into a sub-FSM. In particular, the operand of
72    --  a BRANCH node is the first node of the branch.
73    --  (NB this is *not* a tree structure:  the tail of the branch connects
74    --  to the thing following the set of BRANCHes).
75
76    --  You can see the exact byte-compiled version by using the Dump
77    --  subprogram. However, here are a few examples:
78
79    --  (a|b):  1 : MAGIC
80    --          2 : BRANCH  (next at  10)
81    --          5 :    EXACT  (next at  18)   operand=a
82    --         10 : BRANCH  (next at  18)
83    --         13 :    EXACT  (next at  18)   operand=b
84    --         18 : EOP  (next at 0)
85    --
86    --  (ab)*:  1 : MAGIC
87    --          2 : CURLYX  (next at  26)  { 0, 32767}
88    --          9 :    OPEN 1  (next at  13)
89    --         13 :       EXACT  (next at  19)   operand=ab
90    --         19 :    CLOSE 1  (next at  23)
91    --         23 :    WHILEM  (next at 0)
92    --         26 : NOTHING  (next at  29)
93    --         29 : EOP  (next at 0)
94
95    --  The opcodes are:
96
97    type Opcode is
98
99       --  Name          Operand?  Meaning
100
101      (EOP,        -- no        End of program
102       MINMOD,     -- no        Next operator is not greedy
103
104       --  Classes of characters
105
106       ANY,        -- no        Match any one character except newline
107       SANY,       -- no        Match any character, including new line
108       ANYOF,      -- class     Match any character in this class
109       EXACT,      -- str       Match this string exactly
110       EXACTF,     -- str       Match this string (case-folding is one)
111       NOTHING,    -- no        Match empty string
112       SPACE,      -- no        Match any whitespace character
113       NSPACE,     -- no        Match any non-whitespace character
114       DIGIT,      -- no        Match any numeric character
115       NDIGIT,     -- no        Match any non-numeric character
116       ALNUM,      -- no        Match any alphanumeric character
117       NALNUM,     -- no        Match any non-alphanumeric character
118
119       --  Branches
120
121       BRANCH,     -- node      Match this alternative, or the next
122
123       --  Simple loops (when the following node is one character in length)
124
125       STAR,       -- node      Match this simple thing 0 or more times
126       PLUS,       -- node      Match this simple thing 1 or more times
127       CURLY,      -- 2num node Match this simple thing between n and m times.
128
129       --  Complex loops
130
131       CURLYX,     -- 2num node Match this complex thing {n,m} times
132       --                       The nums are coded on two characters each
133
134       WHILEM,     -- no        Do curly processing and see if rest matches
135
136       --  Matches after or before a word
137
138       BOL,        -- no        Match "" at beginning of line
139       MBOL,       -- no        Same, assuming mutiline (match after \n)
140       SBOL,       -- no        Same, assuming single line (don't match at \n)
141       EOL,        -- no        Match "" at end of line
142       MEOL,       -- no        Same, assuming mutiline (match before \n)
143       SEOL,       -- no        Same, assuming single line (don't match at \n)
144
145       BOUND,      -- no        Match "" at any word boundary
146       NBOUND,     -- no        Match "" at any word non-boundary
147
148       --  Parenthesis groups handling
149
150       REFF,       -- num       Match some already matched string, folded
151       OPEN,       -- num       Mark this point in input as start of #n
152       CLOSE);     -- num       Analogous to OPEN
153
154    for Opcode'Size use 8;
155
156    --  Opcode notes:
157
158    --  BRANCH
159    --    The set of branches constituting a single choice are hooked
160    --    together with their "next" pointers, since precedence prevents
161    --    anything being concatenated to any individual branch. The
162    --    "next" pointer of the last BRANCH in a choice points to the
163    --    thing following the whole choice. This is also where the
164    --    final "next" pointer of each individual branch points; each
165    --    branch starts with the operand node of a BRANCH node.
166
167    --  STAR,PLUS
168    --    '?', and complex '*' and '+', are implemented with CURLYX.
169    --    branches. Simple cases (one character per match) are implemented with
170    --    STAR and PLUS for speed and to minimize recursive plunges.
171
172    --  OPEN,CLOSE
173    --    ...are numbered at compile time.
174
175    --  EXACT, EXACTF
176    --    There are in fact two arguments, the first one is the length (minus
177    --    one of the string argument), coded on one character, the second
178    --    argument is the string itself, coded on length + 1 characters.
179
180    --  A node is one char of opcode followed by two chars of "next" pointer.
181    --  "Next" pointers are stored as two 8-bit pieces, high order first. The
182    --  value is a positive offset from the opcode of the node containing it.
183    --  An operand, if any, simply follows the node. (Note that much of the
184    --  code generation knows about this implicit relationship.)
185
186    --  Using two bytes for the "next" pointer is vast overkill for most
187    --  things, but allows patterns to get big without disasters.
188
189    -----------------------
190    -- Character classes --
191    -----------------------
192    --  This is the implementation for character classes ([...]) in the
193    --  syntax for regular expressions. Each character (0..256) has an
194    --  entry into the table. This makes for a very fast matching
195    --  algorithm.
196
197    type Class_Byte is mod 256;
198    type Character_Class is array (Class_Byte range 0 .. 31) of Class_Byte;
199
200    type Bit_Conversion_Array is array (Class_Byte range 0 .. 7) of Class_Byte;
201    Bit_Conversion : constant Bit_Conversion_Array :=
202                       (1, 2, 4, 8, 16, 32, 64, 128);
203
204    type Std_Class is (ANYOF_NONE,
205                       ANYOF_ALNUM,   --  Alphanumeric class [a-zA-Z0-9]
206                       ANYOF_NALNUM,
207                       ANYOF_SPACE,   --  Space class [ \t\n\r\f]
208                       ANYOF_NSPACE,
209                       ANYOF_DIGIT,   --  Digit class [0-9]
210                       ANYOF_NDIGIT,
211                       ANYOF_ALNUMC,  --  Alphanumeric class [a-zA-Z0-9]
212                       ANYOF_NALNUMC,
213                       ANYOF_ALPHA,   --  Alpha class [a-zA-Z]
214                       ANYOF_NALPHA,
215                       ANYOF_ASCII,   --  Ascii class (7 bits) 0..127
216                       ANYOF_NASCII,
217                       ANYOF_CNTRL,   --  Control class
218                       ANYOF_NCNTRL,
219                       ANYOF_GRAPH,   --  Graphic class
220                       ANYOF_NGRAPH,
221                       ANYOF_LOWER,   --  Lower case class [a-z]
222                       ANYOF_NLOWER,
223                       ANYOF_PRINT,   --  printable class
224                       ANYOF_NPRINT,
225                       ANYOF_PUNCT,   --
226                       ANYOF_NPUNCT,
227                       ANYOF_UPPER,   --  Upper case class [A-Z]
228                       ANYOF_NUPPER,
229                       ANYOF_XDIGIT,  --  Hexadecimal digit
230                       ANYOF_NXDIGIT
231                       );
232
233    procedure Set_In_Class
234      (Bitmap : in out Character_Class;
235       C      : Character);
236    --  Set the entry to True for C in the class Bitmap
237
238    function Get_From_Class
239      (Bitmap : Character_Class;
240       C      : Character) return Boolean;
241    --  Return True if the entry is set for C in the class Bitmap
242
243    procedure Reset_Class (Bitmap : out Character_Class);
244    --  Clear all the entries in the class Bitmap
245
246    pragma Inline (Set_In_Class);
247    pragma Inline (Get_From_Class);
248    pragma Inline (Reset_Class);
249
250    -----------------------
251    -- Local Subprograms --
252    -----------------------
253
254    function "=" (Left : Character; Right : Opcode) return Boolean;
255
256    function Is_Alnum (C : Character) return Boolean;
257    --  Return True if C is an alphanum character or an underscore ('_')
258
259    function Is_White_Space (C : Character) return Boolean;
260    --  Return True if C is a whitespace character
261
262    function Is_Printable (C : Character) return Boolean;
263    --  Return True if C is a printable character
264
265    function Operand (P : Pointer) return Pointer;
266    --  Return a pointer to the first operand of the node at P
267
268    function String_Length
269      (Program : Program_Data;
270       P       : Pointer) return Program_Size;
271    --  Return the length of the string argument of the node at P
272
273    function String_Operand (P : Pointer) return Pointer;
274    --  Return a pointer to the string argument of the node at P
275
276    procedure Bitmap_Operand
277      (Program : Program_Data;
278       P       : Pointer;
279       Op      : out Character_Class);
280    --  Return a pointer to the string argument of the node at P
281
282    function Get_Next_Offset
283      (Program : Program_Data;
284       IP      : Pointer) return Pointer;
285    --  Get the offset field of a node. Used by Get_Next
286
287    function Get_Next
288      (Program : Program_Data;
289       IP      : Pointer) return Pointer;
290    --  Dig the next instruction pointer out of a node
291
292    procedure Optimize (Self : in out Pattern_Matcher);
293    --  Optimize a Pattern_Matcher by noting certain special cases
294
295    function Read_Natural
296      (Program : Program_Data;
297       IP      : Pointer) return Natural;
298    --  Return the 2-byte natural coded at position IP
299
300    --  All of the subprograms above are tiny and should be inlined
301
302    pragma Inline ("=");
303    pragma Inline (Is_Alnum);
304    pragma Inline (Is_White_Space);
305    pragma Inline (Get_Next);
306    pragma Inline (Get_Next_Offset);
307    pragma Inline (Operand);
308    pragma Inline (Read_Natural);
309    pragma Inline (String_Length);
310    pragma Inline (String_Operand);
311
312    type Expression_Flags is record
313       Has_Width,            -- Known never to match null string
314       Simple,               -- Simple enough to be STAR/PLUS operand
315       SP_Start  : Boolean;  -- Starts with * or +
316    end record;
317
318    Worst_Expression : constant Expression_Flags := (others => False);
319    --  Worst case
320
321    ---------
322    -- "=" --
323    ---------
324
325    function "=" (Left : Character; Right : Opcode) return Boolean is
326    begin
327       return Character'Pos (Left) = Opcode'Pos (Right);
328    end "=";
329
330    --------------------
331    -- Bitmap_Operand --
332    --------------------
333
334    procedure Bitmap_Operand
335      (Program : Program_Data;
336       P       : Pointer;
337       Op      : out Character_Class)
338    is
339       function Convert is new Ada.Unchecked_Conversion
340         (Program_Data, Character_Class);
341
342    begin
343       Op (0 .. 31) := Convert (Program (P + 3 .. P + 34));
344    end Bitmap_Operand;
345
346    -------------
347    -- Compile --
348    -------------
349
350    procedure Compile
351      (Matcher         : out Pattern_Matcher;
352       Expression      : String;
353       Final_Code_Size : out Program_Size;
354       Flags           : Regexp_Flags := No_Flags)
355    is
356       --  We can't allocate space until we know how big the compiled form
357       --  will be, but we can't compile it (and thus know how big it is)
358       --  until we've got a place to put the code. So we cheat: we compile
359       --  it twice, once with code generation turned off and size counting
360       --  turned on, and once "for real".
361
362       --  This also means that we don't allocate space until we are sure
363       --  that the thing really will compile successfully, and we never
364       --  have to move the code and thus invalidate pointers into it.
365
366       --  Beware that the optimization-preparation code in here knows
367       --  about some of the structure of the compiled regexp.
368
369       PM        : Pattern_Matcher renames Matcher;
370       Program   : Program_Data renames PM.Program;
371
372       Emit_Code : constant Boolean := PM.Size > 0;
373       Emit_Ptr  : Pointer := Program_First;
374
375       Parse_Pos : Natural := Expression'First; -- Input-scan pointer
376       Parse_End : constant Natural := Expression'Last;
377
378       ----------------------------
379       -- Subprograms for Create --
380       ----------------------------
381
382       procedure Emit (B : Character);
383       --  Output the Character B to the Program. If code-generation is
384       --  disabled, simply increments the program counter.
385
386       function  Emit_Node (Op : Opcode) return Pointer;
387       --  If code-generation is enabled, Emit_Node outputs the
388       --  opcode Op and reserves space for a pointer to the next node.
389       --  Return value is the location of new opcode, ie old Emit_Ptr.
390
391       procedure Emit_Natural (IP : Pointer; N : Natural);
392       --  Split N on two characters at position IP
393
394       procedure Emit_Class (Bitmap : Character_Class);
395       --  Emits a character class
396
397       procedure Case_Emit (C : Character);
398       --  Emit C, after converting is to lower-case if the regular
399       --  expression is case insensitive.
400
401       procedure Parse
402         (Parenthesized : Boolean;
403          Flags         : out Expression_Flags;
404          IP            : out Pointer);
405       --  Parse regular expression, i.e. main body or parenthesized thing
406       --  Caller must absorb opening parenthesis.
407
408       procedure Parse_Branch
409         (Flags         : out Expression_Flags;
410          First         : Boolean;
411          IP            : out Pointer);
412       --  Implements the concatenation operator and handles '|'
413       --  First should be true if this is the first item of the alternative.
414
415       procedure Parse_Piece
416         (Expr_Flags : out Expression_Flags;
417          IP         : out Pointer);
418       --  Parse something followed by possible [*+?]
419
420       procedure Parse_Atom
421         (Expr_Flags : out Expression_Flags;
422          IP         : out Pointer);
423       --  Parse_Atom is the lowest level parse procedure.
424       --  Optimization:  gobbles an entire sequence of ordinary characters
425       --  so that it can turn them into a single node, which is smaller to
426       --  store and faster to run. Backslashed characters are exceptions,
427       --  each becoming a separate node; the code is simpler that way and
428       --  it's not worth fixing.
429
430       procedure Insert_Operator
431         (Op       : Opcode;
432          Operand  : Pointer;
433          Greedy   : Boolean := True);
434       --  Insert_Operator inserts an operator in front of an
435       --  already-emitted operand and relocates the operand.
436       --  This applies to PLUS and STAR.
437       --  If Minmod is True, then the operator is non-greedy.
438
439       procedure Insert_Curly_Operator
440         (Op      : Opcode;
441          Min     : Natural;
442          Max     : Natural;
443          Operand : Pointer;
444          Greedy  : Boolean := True);
445       --  Insert an operator for CURLY ({Min}, {Min,} or {Min,Max}).
446       --  If Minmod is True, then the operator is non-greedy.
447
448       procedure Link_Tail (P, Val : Pointer);
449       --  Link_Tail sets the next-pointer at the end of a node chain
450
451       procedure Link_Operand_Tail (P, Val : Pointer);
452       --  Link_Tail on operand of first argument; nop if operandless
453
454       function  Next_Instruction (P : Pointer) return Pointer;
455       --  Dig the "next" pointer out of a node
456
457       procedure Fail (M : String);
458       pragma No_Return (Fail);
459       --  Fail with a diagnostic message, if possible
460
461       function Is_Curly_Operator (IP : Natural) return Boolean;
462       --  Return True if IP is looking at a '{' that is the beginning
463       --  of a curly operator, ie it matches {\d+,?\d*}
464
465       function Is_Mult (IP : Natural) return Boolean;
466       --  Return True if C is a regexp multiplier: '+', '*' or '?'
467
468       procedure Get_Curly_Arguments
469         (IP     : Natural;
470          Min    : out Natural;
471          Max    : out Natural;
472          Greedy : out Boolean);
473       --  Parse the argument list for a curly operator.
474       --  It is assumed that IP is indeed pointing at a valid operator.
475       --  So what is IP and how come IP is not referenced in the body ???
476
477       procedure Parse_Character_Class (IP : out Pointer);
478       --  Parse a character class.
479       --  The calling subprogram should consume the opening '[' before.
480
481       procedure Parse_Literal
482         (Expr_Flags : out Expression_Flags;
483          IP         : out Pointer);
484       --  Parse_Literal encodes a string of characters to be matched exactly
485
486       function Parse_Posix_Character_Class return Std_Class;
487       --  Parse a posic character class, like [:alpha:] or [:^alpha:].
488       --  The called is suppoed to absorbe the opening [.
489
490       pragma Inline (Is_Mult);
491       pragma Inline (Emit_Natural);
492       pragma Inline (Parse_Character_Class); --  since used only once
493
494       ---------------
495       -- Case_Emit --
496       ---------------
497
498       procedure Case_Emit (C : Character) is
499       begin
500          if (Flags and Case_Insensitive) /= 0 then
501             Emit (To_Lower (C));
502
503          else
504             --  Dump current character
505
506             Emit (C);
507          end if;
508       end Case_Emit;
509
510       ----------
511       -- Emit --
512       ----------
513
514       procedure Emit (B : Character) is
515       begin
516          if Emit_Code then
517             Program (Emit_Ptr) := B;
518          end if;
519
520          Emit_Ptr := Emit_Ptr + 1;
521       end Emit;
522
523       ----------------
524       -- Emit_Class --
525       ----------------
526
527       procedure Emit_Class (Bitmap : Character_Class) is
528          subtype Program31 is Program_Data (0 .. 31);
529
530          function Convert is new Ada.Unchecked_Conversion
531            (Character_Class, Program31);
532
533       begin
534          if Emit_Code then
535             Program (Emit_Ptr .. Emit_Ptr + 31) := Convert (Bitmap);
536          end if;
537
538          Emit_Ptr := Emit_Ptr + 32;
539       end Emit_Class;
540
541       ------------------
542       -- Emit_Natural --
543       ------------------
544
545       procedure Emit_Natural (IP : Pointer; N : Natural) is
546       begin
547          if Emit_Code then
548             Program (IP + 1) := Character'Val (N / 256);
549             Program (IP) := Character'Val (N mod 256);
550          end if;
551       end Emit_Natural;
552
553       ---------------
554       -- Emit_Node --
555       ---------------
556
557       function Emit_Node (Op : Opcode) return Pointer is
558          Result : constant Pointer := Emit_Ptr;
559
560       begin
561          if Emit_Code then
562             Program (Emit_Ptr) := Character'Val (Opcode'Pos (Op));
563             Program (Emit_Ptr + 1) := ASCII.NUL;
564             Program (Emit_Ptr + 2) := ASCII.NUL;
565          end if;
566
567          Emit_Ptr := Emit_Ptr + 3;
568          return Result;
569       end Emit_Node;
570
571       ----------
572       -- Fail --
573       ----------
574
575       procedure Fail (M : String) is
576       begin
577          raise Expression_Error with M;
578       end Fail;
579
580       -------------------------
581       -- Get_Curly_Arguments --
582       -------------------------
583
584       procedure Get_Curly_Arguments
585         (IP     : Natural;
586          Min    : out Natural;
587          Max    : out Natural;
588          Greedy : out Boolean)
589       is
590          pragma Unreferenced (IP);
591
592          Save_Pos : Natural := Parse_Pos + 1;
593
594       begin
595          Min := 0;
596          Max := Max_Curly_Repeat;
597
598          while Expression (Parse_Pos) /= '}'
599            and then Expression (Parse_Pos) /= ','
600          loop
601             Parse_Pos := Parse_Pos + 1;
602          end loop;
603
604          Min := Natural'Value (Expression (Save_Pos .. Parse_Pos - 1));
605
606          if Expression (Parse_Pos) = ',' then
607             Save_Pos := Parse_Pos + 1;
608             while Expression (Parse_Pos) /= '}' loop
609                Parse_Pos := Parse_Pos + 1;
610             end loop;
611
612             if Save_Pos /= Parse_Pos then
613                Max := Natural'Value (Expression (Save_Pos .. Parse_Pos - 1));
614             end if;
615
616          else
617             Max := Min;
618          end if;
619
620          if Parse_Pos < Expression'Last
621            and then Expression (Parse_Pos + 1) = '?'
622          then
623             Greedy := False;
624             Parse_Pos := Parse_Pos + 1;
625
626          else
627             Greedy := True;
628          end if;
629       end Get_Curly_Arguments;
630
631       ---------------------------
632       -- Insert_Curly_Operator --
633       ---------------------------
634
635       procedure Insert_Curly_Operator
636         (Op      : Opcode;
637          Min     : Natural;
638          Max     : Natural;
639          Operand : Pointer;
640          Greedy  : Boolean := True)
641       is
642          Dest   : constant Pointer := Emit_Ptr;
643          Old    : Pointer;
644          Size   : Pointer := 7;
645
646       begin
647          --  If the operand is not greedy, insert an extra operand before it
648
649          if not Greedy then
650             Size := Size + 3;
651          end if;
652
653          --  Move the operand in the byte-compilation, so that we can insert
654          --  the operator before it.
655
656          if Emit_Code then
657             Program (Operand + Size .. Emit_Ptr + Size) :=
658               Program (Operand .. Emit_Ptr);
659          end if;
660
661          --  Insert the operator at the position previously occupied by the
662          --  operand.
663
664          Emit_Ptr := Operand;
665
666          if not Greedy then
667             Old := Emit_Node (MINMOD);
668             Link_Tail (Old, Old + 3);
669          end if;
670
671          Old := Emit_Node (Op);
672          Emit_Natural (Old + 3, Min);
673          Emit_Natural (Old + 5, Max);
674
675          Emit_Ptr := Dest + Size;
676       end Insert_Curly_Operator;
677
678       ---------------------
679       -- Insert_Operator --
680       ---------------------
681
682       procedure Insert_Operator
683         (Op      : Opcode;
684          Operand : Pointer;
685          Greedy  : Boolean := True)
686       is
687          Dest : constant Pointer := Emit_Ptr;
688          Old  : Pointer;
689          Size : Pointer := 3;
690
691          Discard : Pointer;
692          pragma Warnings (Off, Discard);
693
694       begin
695          --  If not greedy, we have to emit another opcode first
696
697          if not Greedy then
698             Size := Size + 3;
699          end if;
700
701          --  Move the operand in the byte-compilation, so that we can insert
702          --  the operator before it.
703
704          if Emit_Code then
705             Program (Operand + Size .. Emit_Ptr + Size) :=
706               Program (Operand .. Emit_Ptr);
707          end if;
708
709          --  Insert the operator at the position previously occupied by the
710          --  operand.
711
712          Emit_Ptr := Operand;
713
714          if not Greedy then
715             Old := Emit_Node (MINMOD);
716             Link_Tail (Old, Old + 3);
717          end if;
718
719          Discard := Emit_Node (Op);
720          Emit_Ptr := Dest + Size;
721       end Insert_Operator;
722
723       -----------------------
724       -- Is_Curly_Operator --
725       -----------------------
726
727       function Is_Curly_Operator (IP : Natural) return Boolean is
728          Scan : Natural := IP;
729
730       begin
731          if Expression (Scan) /= '{'
732            or else Scan + 2 > Expression'Last
733            or else not Is_Digit (Expression (Scan + 1))
734          then
735             return False;
736          end if;
737
738          Scan := Scan + 1;
739
740          --  The first digit
741
742          loop
743             Scan := Scan + 1;
744
745             if Scan > Expression'Last then
746                return False;
747             end if;
748
749             exit when not Is_Digit (Expression (Scan));
750          end loop;
751
752          if Expression (Scan) = ',' then
753             loop
754                Scan := Scan + 1;
755
756                if Scan > Expression'Last then
757                   return False;
758                end if;
759
760                exit when not Is_Digit (Expression (Scan));
761             end loop;
762          end if;
763
764          return Expression (Scan) = '}';
765       end Is_Curly_Operator;
766
767       -------------
768       -- Is_Mult --
769       -------------
770
771       function Is_Mult (IP : Natural) return Boolean is
772          C : constant Character := Expression (IP);
773
774       begin
775          return     C = '*'
776            or else  C = '+'
777            or else  C = '?'
778            or else (C = '{' and then Is_Curly_Operator (IP));
779       end Is_Mult;
780
781       -----------------------
782       -- Link_Operand_Tail --
783       -----------------------
784
785       procedure Link_Operand_Tail (P, Val : Pointer) is
786       begin
787          if Emit_Code and then Program (P) = BRANCH then
788             Link_Tail (Operand (P), Val);
789          end if;
790       end Link_Operand_Tail;
791
792       ---------------
793       -- Link_Tail --
794       ---------------
795
796       procedure Link_Tail (P, Val : Pointer) is
797          Scan   : Pointer;
798          Temp   : Pointer;
799          Offset : Pointer;
800
801       begin
802          if not Emit_Code then
803             return;
804          end if;
805
806          --  Find last node
807
808          Scan := P;
809          loop
810             Temp := Next_Instruction (Scan);
811             exit when Temp = 0;
812             Scan := Temp;
813          end loop;
814
815          Offset := Val - Scan;
816
817          Emit_Natural (Scan + 1, Natural (Offset));
818       end Link_Tail;
819
820       ----------------------
821       -- Next_Instruction --
822       ----------------------
823
824       function Next_Instruction (P : Pointer) return Pointer is
825          Offset : Pointer;
826
827       begin
828          if not Emit_Code then
829             return 0;
830          end if;
831
832          Offset := Get_Next_Offset (Program, P);
833
834          if Offset = 0 then
835             return 0;
836          end if;
837
838          return P + Offset;
839       end Next_Instruction;
840
841       -----------
842       -- Parse --
843       -----------
844
845       --  Combining parenthesis handling with the base level
846       --  of regular expression is a trifle forced, but the
847       --  need to tie the tails of the branches to what follows
848       --  makes it hard to avoid.
849
850       procedure Parse
851         (Parenthesized  : Boolean;
852          Flags          : out Expression_Flags;
853          IP             : out Pointer)
854       is
855          E              : String renames Expression;
856          Br             : Pointer;
857          Ender          : Pointer;
858          Par_No         : Natural;
859          New_Flags      : Expression_Flags;
860          Have_Branch    : Boolean := False;
861
862       begin
863          Flags := (Has_Width => True, others => False);  -- Tentatively
864
865          --  Make an OPEN node, if parenthesized
866
867          if Parenthesized then
868             if Matcher.Paren_Count > Max_Paren_Count then
869                Fail ("too many ()");
870             end if;
871
872             Par_No := Matcher.Paren_Count + 1;
873             Matcher.Paren_Count := Matcher.Paren_Count + 1;
874             IP := Emit_Node (OPEN);
875             Emit (Character'Val (Par_No));
876
877          else
878             IP := 0;
879             Par_No := 0;
880          end if;
881
882          --  Pick up the branches, linking them together
883
884          Parse_Branch (New_Flags, True, Br);
885
886          if Br = 0 then
887             IP := 0;
888             return;
889          end if;
890
891          if Parse_Pos <= Parse_End
892            and then E (Parse_Pos) = '|'
893          then
894             Insert_Operator (BRANCH, Br);
895             Have_Branch := True;
896          end if;
897
898          if IP /= 0 then
899             Link_Tail (IP, Br);   -- OPEN -> first
900          else
901             IP := Br;
902          end if;
903
904          if not New_Flags.Has_Width then
905             Flags.Has_Width := False;
906          end if;
907
908          Flags.SP_Start := Flags.SP_Start or New_Flags.SP_Start;
909
910          while Parse_Pos <= Parse_End
911            and then (E (Parse_Pos) = '|')
912          loop
913             Parse_Pos := Parse_Pos + 1;
914             Parse_Branch (New_Flags, False, Br);
915
916             if Br = 0 then
917                IP := 0;
918                return;
919             end if;
920
921             Link_Tail (IP, Br);   -- BRANCH -> BRANCH
922
923             if not New_Flags.Has_Width then
924                Flags.Has_Width := False;
925             end if;
926
927             Flags.SP_Start := Flags.SP_Start or New_Flags.SP_Start;
928          end loop;
929
930          --  Make a closing node, and hook it on the end
931
932          if Parenthesized then
933             Ender := Emit_Node (CLOSE);
934             Emit (Character'Val (Par_No));
935          else
936             Ender := Emit_Node (EOP);
937          end if;
938
939          Link_Tail (IP, Ender);
940
941          if Have_Branch then
942
943             --  Hook the tails of the branches to the closing node
944
945             Br := IP;
946             loop
947                exit when Br = 0;
948                Link_Operand_Tail (Br, Ender);
949                Br := Next_Instruction (Br);
950             end loop;
951          end if;
952
953          --  Check for proper termination
954
955          if Parenthesized then
956             if Parse_Pos > Parse_End or else E (Parse_Pos) /= ')' then
957                Fail ("unmatched ()");
958             end if;
959
960             Parse_Pos := Parse_Pos + 1;
961
962          elsif Parse_Pos <= Parse_End then
963             if E (Parse_Pos) = ')'  then
964                Fail ("unmatched ()");
965             else
966                Fail ("junk on end");         -- "Can't happen"
967             end if;
968          end if;
969       end Parse;
970
971       ----------------
972       -- Parse_Atom --
973       ----------------
974
975       procedure Parse_Atom
976         (Expr_Flags : out Expression_Flags;
977          IP         : out Pointer)
978       is
979          C : Character;
980
981       begin
982          --  Tentatively set worst expression case
983
984          Expr_Flags := Worst_Expression;
985
986          C := Expression (Parse_Pos);
987          Parse_Pos := Parse_Pos + 1;
988
989          case (C) is
990             when '^' =>
991                if (Flags and Multiple_Lines) /= 0  then
992                   IP := Emit_Node (MBOL);
993                elsif (Flags and Single_Line) /= 0 then
994                   IP := Emit_Node (SBOL);
995                else
996                   IP := Emit_Node (BOL);
997                end if;
998
999             when '$' =>
1000                if (Flags and Multiple_Lines) /= 0  then
1001                   IP := Emit_Node (MEOL);
1002                elsif (Flags and Single_Line) /= 0 then
1003                   IP := Emit_Node (SEOL);
1004                else
1005                   IP := Emit_Node (EOL);
1006                end if;
1007
1008             when '.' =>
1009                if (Flags and Single_Line) /= 0 then
1010                   IP := Emit_Node (SANY);
1011                else
1012                   IP := Emit_Node (ANY);
1013                end if;
1014
1015                Expr_Flags.Has_Width := True;
1016                Expr_Flags.Simple := True;
1017
1018             when '[' =>
1019                Parse_Character_Class (IP);
1020                Expr_Flags.Has_Width := True;
1021                Expr_Flags.Simple := True;
1022
1023             when '(' =>
1024                declare
1025                   New_Flags : Expression_Flags;
1026
1027                begin
1028                   Parse (True, New_Flags, IP);
1029
1030                   if IP = 0 then
1031                      return;
1032                   end if;
1033
1034                   Expr_Flags.Has_Width :=
1035                     Expr_Flags.Has_Width or New_Flags.Has_Width;
1036                   Expr_Flags.SP_Start :=
1037                     Expr_Flags.SP_Start or New_Flags.SP_Start;
1038                end;
1039
1040             when '|' | ASCII.LF | ')' =>
1041                Fail ("internal urp");  --  Supposed to be caught earlier
1042
1043             when '?' | '+' | '*' =>
1044                Fail (C & " follows nothing");
1045
1046             when '{' =>
1047                if Is_Curly_Operator (Parse_Pos - 1) then
1048                   Fail (C & " follows nothing");
1049                else
1050                   Parse_Literal (Expr_Flags, IP);
1051                end if;
1052
1053             when '\' =>
1054                if Parse_Pos > Parse_End then
1055                   Fail ("trailing \");
1056                end if;
1057
1058                Parse_Pos := Parse_Pos + 1;
1059
1060                case Expression (Parse_Pos - 1) is
1061                   when 'b'        =>
1062                      IP := Emit_Node (BOUND);
1063
1064                   when 'B'        =>
1065                      IP := Emit_Node (NBOUND);
1066
1067                   when 's'        =>
1068                      IP := Emit_Node (SPACE);
1069                      Expr_Flags.Simple := True;
1070                      Expr_Flags.Has_Width := True;
1071
1072                   when 'S'        =>
1073                      IP := Emit_Node (NSPACE);
1074                      Expr_Flags.Simple := True;
1075                      Expr_Flags.Has_Width := True;
1076
1077                   when 'd'        =>
1078                      IP := Emit_Node (DIGIT);
1079                      Expr_Flags.Simple := True;
1080                      Expr_Flags.Has_Width := True;
1081
1082                   when 'D'        =>
1083                      IP := Emit_Node (NDIGIT);
1084                      Expr_Flags.Simple := True;
1085                      Expr_Flags.Has_Width := True;
1086
1087                   when 'w'        =>
1088                      IP := Emit_Node (ALNUM);
1089                      Expr_Flags.Simple := True;
1090                      Expr_Flags.Has_Width := True;
1091
1092                   when 'W'        =>
1093                      IP := Emit_Node (NALNUM);
1094                      Expr_Flags.Simple := True;
1095                      Expr_Flags.Has_Width := True;
1096
1097                   when 'A'        =>
1098                      IP := Emit_Node (SBOL);
1099
1100                   when 'G'        =>
1101                      IP := Emit_Node (SEOL);
1102
1103                   when '0' .. '9' =>
1104                      IP := Emit_Node (REFF);
1105
1106                      declare
1107                         Save : constant Natural := Parse_Pos - 1;
1108
1109                      begin
1110                         while Parse_Pos <= Expression'Last
1111                           and then Is_Digit (Expression (Parse_Pos))
1112                         loop
1113                            Parse_Pos := Parse_Pos + 1;
1114                         end loop;
1115
1116                         Emit (Character'Val (Natural'Value
1117                                (Expression (Save .. Parse_Pos - 1))));
1118                      end;
1119
1120                   when others =>
1121                      Parse_Pos := Parse_Pos - 1;
1122                      Parse_Literal (Expr_Flags, IP);
1123                end case;
1124
1125             when others =>
1126                Parse_Literal (Expr_Flags, IP);
1127          end case;
1128       end Parse_Atom;
1129
1130       ------------------
1131       -- Parse_Branch --
1132       ------------------
1133
1134       procedure Parse_Branch
1135         (Flags : out Expression_Flags;
1136          First : Boolean;
1137          IP    : out Pointer)
1138       is
1139          E         : String renames Expression;
1140          Chain     : Pointer;
1141          Last      : Pointer;
1142          New_Flags : Expression_Flags;
1143
1144          Discard : Pointer;
1145          pragma Warnings (Off, Discard);
1146
1147       begin
1148          Flags := Worst_Expression;    -- Tentatively
1149
1150          if First then
1151             IP := Emit_Ptr;
1152          else
1153             IP := Emit_Node (BRANCH);
1154          end if;
1155
1156          Chain := 0;
1157
1158          while Parse_Pos <= Parse_End
1159            and then E (Parse_Pos) /= ')'
1160            and then E (Parse_Pos) /= ASCII.LF
1161            and then E (Parse_Pos) /= '|'
1162          loop
1163             Parse_Piece (New_Flags, Last);
1164
1165             if Last = 0 then
1166                IP := 0;
1167                return;
1168             end if;
1169
1170             Flags.Has_Width := Flags.Has_Width or New_Flags.Has_Width;
1171
1172             if Chain = 0 then            -- First piece
1173                Flags.SP_Start := Flags.SP_Start or New_Flags.SP_Start;
1174             else
1175                Link_Tail (Chain, Last);
1176             end if;
1177
1178             Chain := Last;
1179          end loop;
1180
1181          --  Case where loop ran zero CURLY
1182
1183          if Chain = 0 then
1184             Discard := Emit_Node (NOTHING);
1185          end if;
1186       end Parse_Branch;
1187
1188       ---------------------------
1189       -- Parse_Character_Class --
1190       ---------------------------
1191
1192       procedure Parse_Character_Class (IP : out Pointer) is
1193          Bitmap      : Character_Class;
1194          Invert      : Boolean := False;
1195          In_Range    : Boolean := False;
1196          Named_Class : Std_Class := ANYOF_NONE;
1197          Value       : Character;
1198          Last_Value  : Character := ASCII.NUL;
1199
1200       begin
1201          Reset_Class (Bitmap);
1202
1203          --  Do we have an invert character class ?
1204
1205          if Parse_Pos <= Parse_End
1206            and then Expression (Parse_Pos) = '^'
1207          then
1208             Invert := True;
1209             Parse_Pos := Parse_Pos + 1;
1210          end if;
1211
1212          --  First character can be ] or - without closing the class
1213
1214          if Parse_Pos <= Parse_End
1215            and then (Expression (Parse_Pos) = ']'
1216                       or else Expression (Parse_Pos) = '-')
1217          then
1218             Set_In_Class (Bitmap, Expression (Parse_Pos));
1219             Parse_Pos := Parse_Pos + 1;
1220          end if;
1221
1222          --  While we don't have the end of the class
1223
1224          while Parse_Pos <= Parse_End
1225            and then Expression (Parse_Pos) /= ']'
1226          loop
1227             Named_Class := ANYOF_NONE;
1228             Value := Expression (Parse_Pos);
1229             Parse_Pos := Parse_Pos + 1;
1230
1231             --  Do we have a Posix character class
1232             if Value = '[' then
1233                Named_Class := Parse_Posix_Character_Class;
1234
1235             elsif Value = '\' then
1236                if Parse_Pos = Parse_End then
1237                   Fail ("Trailing \");
1238                end if;
1239                Value := Expression (Parse_Pos);
1240                Parse_Pos := Parse_Pos + 1;
1241
1242                case Value is
1243                   when 'w' => Named_Class := ANYOF_ALNUM;
1244                   when 'W' => Named_Class := ANYOF_NALNUM;
1245                   when 's' => Named_Class := ANYOF_SPACE;
1246                   when 'S' => Named_Class := ANYOF_NSPACE;
1247                   when 'd' => Named_Class := ANYOF_DIGIT;
1248                   when 'D' => Named_Class := ANYOF_NDIGIT;
1249                   when 'n' => Value := ASCII.LF;
1250                   when 'r' => Value := ASCII.CR;
1251                   when 't' => Value := ASCII.HT;
1252                   when 'f' => Value := ASCII.FF;
1253                   when 'e' => Value := ASCII.ESC;
1254                   when 'a' => Value := ASCII.BEL;
1255
1256                   --  when 'x'  => ??? hexadecimal value
1257                   --  when 'c'  => ??? control character
1258                   --  when '0'..'9' => ??? octal character
1259
1260                   when others => null;
1261                end case;
1262             end if;
1263
1264             --  Do we have a character class?
1265
1266             if Named_Class /= ANYOF_NONE then
1267
1268                --  A range like 'a-\d' or 'a-[:digit:] is not a range
1269
1270                if In_Range then
1271                   Set_In_Class (Bitmap, Last_Value);
1272                   Set_In_Class (Bitmap, '-');
1273                   In_Range := False;
1274                end if;
1275
1276                --  Expand the range
1277
1278                case Named_Class is
1279                   when ANYOF_NONE => null;
1280
1281                   when ANYOF_ALNUM | ANYOF_ALNUMC =>
1282                      for Value in Class_Byte'Range loop
1283                         if Is_Alnum (Character'Val (Value)) then
1284                            Set_In_Class (Bitmap, Character'Val (Value));
1285                         end if;
1286                      end loop;
1287
1288                   when ANYOF_NALNUM | ANYOF_NALNUMC =>
1289                      for Value in Class_Byte'Range loop
1290                         if not Is_Alnum (Character'Val (Value)) then
1291                            Set_In_Class (Bitmap, Character'Val (Value));
1292                         end if;
1293                      end loop;
1294
1295                   when ANYOF_SPACE =>
1296                      for Value in Class_Byte'Range loop
1297                         if Is_White_Space (Character'Val (Value)) then
1298                            Set_In_Class (Bitmap, Character'Val (Value));
1299                         end if;
1300                      end loop;
1301
1302                   when ANYOF_NSPACE =>
1303                      for Value in Class_Byte'Range loop
1304                         if not Is_White_Space (Character'Val (Value)) then
1305                            Set_In_Class (Bitmap, Character'Val (Value));
1306                         end if;
1307                      end loop;
1308
1309                   when ANYOF_DIGIT =>
1310                      for Value in Class_Byte'Range loop
1311                         if Is_Digit (Character'Val (Value)) then
1312                            Set_In_Class (Bitmap, Character'Val (Value));
1313                         end if;
1314                      end loop;
1315
1316                   when ANYOF_NDIGIT =>
1317                      for Value in Class_Byte'Range loop
1318                         if not Is_Digit (Character'Val (Value)) then
1319                            Set_In_Class (Bitmap, Character'Val (Value));
1320                         end if;
1321                      end loop;
1322
1323                   when ANYOF_ALPHA =>
1324                      for Value in Class_Byte'Range loop
1325                         if Is_Letter (Character'Val (Value)) then
1326                            Set_In_Class (Bitmap, Character'Val (Value));
1327                         end if;
1328                      end loop;
1329
1330                   when ANYOF_NALPHA =>
1331                      for Value in Class_Byte'Range loop
1332                         if not Is_Letter (Character'Val (Value)) then
1333                            Set_In_Class (Bitmap, Character'Val (Value));
1334                         end if;
1335                      end loop;
1336
1337                   when ANYOF_ASCII =>
1338                      for Value in 0 .. 127 loop
1339                         Set_In_Class (Bitmap, Character'Val (Value));
1340                      end loop;
1341
1342                   when ANYOF_NASCII =>
1343                      for Value in 128 .. 255 loop
1344                         Set_In_Class (Bitmap, Character'Val (Value));
1345                      end loop;
1346
1347                   when ANYOF_CNTRL =>
1348                      for Value in Class_Byte'Range loop
1349                         if Is_Control (Character'Val (Value)) then
1350                            Set_In_Class (Bitmap, Character'Val (Value));
1351                         end if;
1352                      end loop;
1353
1354                   when ANYOF_NCNTRL =>
1355                      for Value in Class_Byte'Range loop
1356                         if not Is_Control (Character'Val (Value)) then
1357                            Set_In_Class (Bitmap, Character'Val (Value));
1358                         end if;
1359                      end loop;
1360
1361                   when ANYOF_GRAPH =>
1362                      for Value in Class_Byte'Range loop
1363                         if Is_Graphic (Character'Val (Value)) then
1364                            Set_In_Class (Bitmap, Character'Val (Value));
1365                         end if;
1366                      end loop;
1367
1368                   when ANYOF_NGRAPH =>
1369                      for Value in Class_Byte'Range loop
1370                         if not Is_Graphic (Character'Val (Value)) then
1371                            Set_In_Class (Bitmap, Character'Val (Value));
1372                         end if;
1373                      end loop;
1374
1375                   when ANYOF_LOWER =>
1376                      for Value in Class_Byte'Range loop
1377                         if Is_Lower (Character'Val (Value)) then
1378                            Set_In_Class (Bitmap, Character'Val (Value));
1379                         end if;
1380                      end loop;
1381
1382                   when ANYOF_NLOWER =>
1383                      for Value in Class_Byte'Range loop
1384                         if not Is_Lower (Character'Val (Value)) then
1385                            Set_In_Class (Bitmap, Character'Val (Value));
1386                         end if;
1387                      end loop;
1388
1389                   when ANYOF_PRINT =>
1390                      for Value in Class_Byte'Range loop
1391                         if Is_Printable (Character'Val (Value)) then
1392                            Set_In_Class (Bitmap, Character'Val (Value));
1393                         end if;
1394                      end loop;
1395
1396                   when ANYOF_NPRINT =>
1397                      for Value in Class_Byte'Range loop
1398                         if not Is_Printable (Character'Val (Value)) then
1399                            Set_In_Class (Bitmap, Character'Val (Value));
1400                         end if;
1401                      end loop;
1402
1403                   when ANYOF_PUNCT =>
1404                      for Value in Class_Byte'Range loop
1405                         if Is_Printable (Character'Val (Value))
1406                           and then not Is_White_Space (Character'Val (Value))
1407                           and then not Is_Alnum (Character'Val (Value))
1408                         then
1409                            Set_In_Class (Bitmap, Character'Val (Value));
1410                         end if;
1411                      end loop;
1412
1413                   when ANYOF_NPUNCT =>
1414                      for Value in Class_Byte'Range loop
1415                         if not Is_Printable (Character'Val (Value))
1416                           or else Is_White_Space (Character'Val (Value))
1417                           or else Is_Alnum (Character'Val (Value))
1418                         then
1419                            Set_In_Class (Bitmap, Character'Val (Value));
1420                         end if;
1421                      end loop;
1422
1423                   when ANYOF_UPPER =>
1424                      for Value in Class_Byte'Range loop
1425                         if Is_Upper (Character'Val (Value)) then
1426                            Set_In_Class (Bitmap, Character'Val (Value));
1427                         end if;
1428                      end loop;
1429
1430                   when ANYOF_NUPPER =>
1431                      for Value in Class_Byte'Range loop
1432                         if not Is_Upper (Character'Val (Value)) then
1433                            Set_In_Class (Bitmap, Character'Val (Value));
1434                         end if;
1435                      end loop;
1436
1437                   when ANYOF_XDIGIT =>
1438                      for Value in Class_Byte'Range loop
1439                         if Is_Hexadecimal_Digit (Character'Val (Value)) then
1440                            Set_In_Class (Bitmap, Character'Val (Value));
1441                         end if;
1442                      end loop;
1443
1444                   when ANYOF_NXDIGIT =>
1445                      for Value in Class_Byte'Range loop
1446                         if not Is_Hexadecimal_Digit
1447                           (Character'Val (Value))
1448                         then
1449                            Set_In_Class (Bitmap, Character'Val (Value));
1450                         end if;
1451                      end loop;
1452
1453                end case;
1454
1455             --  Not a character range
1456
1457             elsif not In_Range then
1458                Last_Value := Value;
1459
1460                if Parse_Pos > Expression'Last then
1461                   Fail ("Empty character class []");
1462                end if;
1463
1464                if Expression (Parse_Pos) = '-'
1465                  and then Parse_Pos < Parse_End
1466                  and then Expression (Parse_Pos + 1) /= ']'
1467                then
1468                   Parse_Pos := Parse_Pos + 1;
1469
1470                   --  Do we have a range like '\d-a' and '[:space:]-a'
1471                   --  which is not a real range
1472
1473                   if Named_Class /= ANYOF_NONE then
1474                      Set_In_Class (Bitmap, '-');
1475                   else
1476                      In_Range := True;
1477                   end if;
1478
1479                else
1480                   Set_In_Class (Bitmap, Value);
1481
1482                end if;
1483
1484             --  Else in a character range
1485
1486             else
1487                if Last_Value > Value then
1488                   Fail ("Invalid Range [" & Last_Value'Img
1489                         & "-" & Value'Img & "]");
1490                end if;
1491
1492                while Last_Value <= Value loop
1493                   Set_In_Class (Bitmap, Last_Value);
1494                   Last_Value := Character'Succ (Last_Value);
1495                end loop;
1496
1497                In_Range := False;
1498
1499             end if;
1500
1501          end loop;
1502
1503          --  Optimize case-insensitive ranges (put the upper case or lower
1504          --  case character into the bitmap)
1505
1506          if (Flags and Case_Insensitive) /= 0 then
1507             for C in Character'Range loop
1508                if Get_From_Class (Bitmap, C) then
1509                   Set_In_Class (Bitmap, To_Lower (C));
1510                   Set_In_Class (Bitmap, To_Upper (C));
1511                end if;
1512             end loop;
1513          end if;
1514
1515          --  Optimize inverted classes
1516
1517          if Invert then
1518             for J in Bitmap'Range loop
1519                Bitmap (J) := not Bitmap (J);
1520             end loop;
1521          end if;
1522
1523          Parse_Pos := Parse_Pos + 1;
1524
1525          --  Emit the class
1526
1527          IP := Emit_Node (ANYOF);
1528          Emit_Class (Bitmap);
1529       end Parse_Character_Class;
1530
1531       -------------------
1532       -- Parse_Literal --
1533       -------------------
1534
1535       --  This is a bit tricky due to quoted chars and due to
1536       --  the multiplier characters '*', '+', and '?' that
1537       --  take the SINGLE char previous as their operand.
1538
1539       --  On entry, the character at Parse_Pos - 1 is going to go
1540       --  into the string, no matter what it is. It could be
1541       --  following a \ if Parse_Atom was entered from the '\' case.
1542
1543       --  Basic idea is to pick up a good char in C and examine
1544       --  the next char. If Is_Mult (C) then twiddle, if it's a \
1545       --  then frozzle and if it's another magic char then push C and
1546       --  terminate the string. If none of the above, push C on the
1547       --  string and go around again.
1548
1549       --  Start_Pos is used to remember where "the current character"
1550       --  starts in the string, if due to an Is_Mult we need to back
1551       --  up and put the current char in a separate 1-character string.
1552       --  When Start_Pos is 0, C is the only char in the string;
1553       --  this is used in Is_Mult handling, and in setting the SIMPLE
1554       --  flag at the end.
1555
1556       procedure Parse_Literal
1557         (Expr_Flags : out Expression_Flags;
1558          IP         : out Pointer)
1559       is
1560          Start_Pos  : Natural := 0;
1561          C          : Character;
1562          Length_Ptr : Pointer;
1563
1564          Has_Special_Operator : Boolean := False;
1565
1566       begin
1567          Parse_Pos := Parse_Pos - 1;      --  Look at current character
1568
1569          if (Flags and Case_Insensitive) /= 0 then
1570             IP := Emit_Node (EXACTF);
1571          else
1572             IP := Emit_Node (EXACT);
1573          end if;
1574
1575          Length_Ptr := Emit_Ptr;
1576          Emit_Ptr := String_Operand (IP);
1577
1578          Parse_Loop :
1579          loop
1580             C := Expression (Parse_Pos); --  Get current character
1581
1582             case C is
1583                when '.' | '[' | '(' | ')' | '|' | ASCII.LF | '$' | '^' =>
1584
1585                   if Start_Pos = 0 then
1586                      Start_Pos := Parse_Pos;
1587                      Emit (C);         --  First character is always emitted
1588                   else
1589                      exit Parse_Loop;  --  Else we are done
1590                   end if;
1591
1592                when '?' | '+' | '*' | '{' =>
1593
1594                   if Start_Pos = 0 then
1595                      Start_Pos := Parse_Pos;
1596                      Emit (C);         --  First character is always emitted
1597
1598                   --  Are we looking at an operator, or is this
1599                   --  simply a normal character ?
1600
1601                   elsif not Is_Mult (Parse_Pos) then
1602                      Start_Pos := Parse_Pos;
1603                      Case_Emit (C);
1604
1605                   else
1606                      --  We've got something like "abc?d".  Mark this as a
1607                      --  special case. What we want to emit is a first
1608                      --  constant string for "ab", then one for "c" that will
1609                      --  ultimately be transformed with a CURLY operator, A
1610                      --  special case has to be handled for "a?", since there
1611                      --  is no initial string to emit.
1612
1613                      Has_Special_Operator := True;
1614                      exit Parse_Loop;
1615                   end if;
1616
1617                when '\' =>
1618                   Start_Pos := Parse_Pos;
1619
1620                   if Parse_Pos = Parse_End then
1621                      Fail ("Trailing \");
1622
1623                   else
1624                      case Expression (Parse_Pos + 1) is
1625                         when 'b' | 'B' | 's' | 'S' | 'd' | 'D'
1626                           | 'w' | 'W' | '0' .. '9' | 'G' | 'A'
1627                           => exit Parse_Loop;
1628                         when 'n'         => Emit (ASCII.LF);
1629                         when 't'         => Emit (ASCII.HT);
1630                         when 'r'         => Emit (ASCII.CR);
1631                         when 'f'         => Emit (ASCII.FF);
1632                         when 'e'         => Emit (ASCII.ESC);
1633                         when 'a'         => Emit (ASCII.BEL);
1634                         when others      => Emit (Expression (Parse_Pos + 1));
1635                      end case;
1636
1637                      Parse_Pos := Parse_Pos + 1;
1638                   end if;
1639
1640                when others =>
1641                   Start_Pos := Parse_Pos;
1642                   Case_Emit (C);
1643             end case;
1644
1645             exit Parse_Loop when Emit_Ptr - Length_Ptr = 254;
1646
1647             Parse_Pos := Parse_Pos + 1;
1648
1649             exit Parse_Loop when Parse_Pos > Parse_End;
1650          end loop Parse_Loop;
1651
1652          --  Is the string followed by a '*+?{' operator ? If yes, and if there
1653          --  is an initial string to emit, do it now.
1654
1655          if Has_Special_Operator
1656            and then Emit_Ptr >= Length_Ptr + 3
1657          then
1658             Emit_Ptr := Emit_Ptr - 1;
1659             Parse_Pos := Start_Pos;
1660          end if;
1661
1662          if Emit_Code then
1663             Program (Length_Ptr) := Character'Val (Emit_Ptr - Length_Ptr - 2);
1664          end if;
1665
1666          Expr_Flags.Has_Width := True;
1667
1668          --  Slight optimization when there is a single character
1669
1670          if Emit_Ptr = Length_Ptr + 2 then
1671             Expr_Flags.Simple := True;
1672          end if;
1673       end Parse_Literal;
1674
1675       -----------------
1676       -- Parse_Piece --
1677       -----------------
1678
1679       --  Note that the branching code sequences used for '?' and the
1680       --  general cases of '*' and + are somewhat optimized: they use
1681       --  the same NOTHING node as both the endmarker for their branch
1682       --  list and the body of the last branch. It might seem that
1683       --  this node could be dispensed with entirely, but the endmarker
1684       --  role is not redundant.
1685
1686       procedure Parse_Piece
1687         (Expr_Flags : out Expression_Flags;
1688          IP         : out Pointer)
1689       is
1690          Op        : Character;
1691          New_Flags : Expression_Flags;
1692          Greedy    : Boolean := True;
1693
1694       begin
1695          Parse_Atom (New_Flags, IP);
1696
1697          if IP = 0 then
1698             return;
1699          end if;
1700
1701          if Parse_Pos > Parse_End
1702            or else not Is_Mult (Parse_Pos)
1703          then
1704             Expr_Flags := New_Flags;
1705             return;
1706          end if;
1707
1708          Op := Expression (Parse_Pos);
1709
1710          if Op /= '+' then
1711             Expr_Flags := (SP_Start => True, others => False);
1712          else
1713             Expr_Flags := (Has_Width => True, others => False);
1714          end if;
1715
1716          --  Detect non greedy operators in the easy cases
1717
1718          if Op /= '{'
1719            and then Parse_Pos + 1 <= Parse_End
1720            and then Expression (Parse_Pos + 1) = '?'
1721          then
1722             Greedy := False;
1723             Parse_Pos := Parse_Pos + 1;
1724          end if;
1725
1726          --  Generate the byte code
1727
1728          case Op is
1729             when '*' =>
1730
1731                if New_Flags.Simple then
1732                   Insert_Operator (STAR, IP, Greedy);
1733                else
1734                   Link_Tail (IP, Emit_Node (WHILEM));
1735                   Insert_Curly_Operator
1736                     (CURLYX, 0, Max_Curly_Repeat, IP, Greedy);
1737                   Link_Tail (IP, Emit_Node (NOTHING));
1738                end if;
1739
1740             when '+' =>
1741
1742                if New_Flags.Simple then
1743                   Insert_Operator (PLUS, IP, Greedy);
1744                else
1745                   Link_Tail (IP, Emit_Node (WHILEM));
1746                   Insert_Curly_Operator
1747                     (CURLYX, 1, Max_Curly_Repeat, IP, Greedy);
1748                   Link_Tail (IP, Emit_Node (NOTHING));
1749                end if;
1750
1751             when '?' =>
1752                if New_Flags.Simple then
1753                   Insert_Curly_Operator (CURLY, 0, 1, IP, Greedy);
1754                else
1755                   Link_Tail (IP, Emit_Node (WHILEM));
1756                   Insert_Curly_Operator (CURLYX, 0, 1, IP, Greedy);
1757                   Link_Tail (IP, Emit_Node (NOTHING));
1758                end if;
1759
1760             when '{' =>
1761                declare
1762                   Min, Max : Natural;
1763
1764                begin
1765                   Get_Curly_Arguments (Parse_Pos, Min, Max, Greedy);
1766
1767                   if New_Flags.Simple then
1768                      Insert_Curly_Operator (CURLY, Min, Max, IP, Greedy);
1769                   else
1770                      Link_Tail (IP, Emit_Node (WHILEM));
1771                      Insert_Curly_Operator (CURLYX, Min, Max, IP, Greedy);
1772                      Link_Tail (IP, Emit_Node (NOTHING));
1773                   end if;
1774                end;
1775
1776             when others =>
1777                null;
1778          end case;
1779
1780          Parse_Pos := Parse_Pos + 1;
1781
1782          if Parse_Pos <= Parse_End
1783            and then Is_Mult (Parse_Pos)
1784          then
1785             Fail ("nested *+{");
1786          end if;
1787       end Parse_Piece;
1788
1789       ---------------------------------
1790       -- Parse_Posix_Character_Class --
1791       ---------------------------------
1792
1793       function Parse_Posix_Character_Class return Std_Class is
1794          Invert : Boolean := False;
1795          Class  : Std_Class := ANYOF_NONE;
1796          E      : String renames Expression;
1797
1798          --  Class names. Note that code assumes that the length of all
1799          --  classes starting with the same letter have the same length.
1800
1801          Alnum   : constant String := "alnum:]";
1802          Alpha   : constant String := "alpha:]";
1803          Ascii_C : constant String := "ascii:]";
1804          Cntrl   : constant String := "cntrl:]";
1805          Digit   : constant String := "digit:]";
1806          Graph   : constant String := "graph:]";
1807          Lower   : constant String := "lower:]";
1808          Print   : constant String := "print:]";
1809          Punct   : constant String := "punct:]";
1810          Space   : constant String := "space:]";
1811          Upper   : constant String := "upper:]";
1812          Word    : constant String := "word:]";
1813          Xdigit  : constant String := "xdigit:]";
1814
1815       begin
1816          --  Case of character class specified
1817
1818          if Parse_Pos <= Parse_End
1819            and then Expression (Parse_Pos) = ':'
1820          then
1821             Parse_Pos := Parse_Pos + 1;
1822
1823             --  Do we have something like:  [[:^alpha:]]
1824
1825             if Parse_Pos <= Parse_End
1826               and then Expression (Parse_Pos) = '^'
1827             then
1828                Invert := True;
1829                Parse_Pos := Parse_Pos + 1;
1830             end if;
1831
1832             --  Check for class names based on first letter
1833
1834             case Expression (Parse_Pos) is
1835                when 'a' =>
1836
1837                   --  All 'a' classes have the same length (Alnum'Length)
1838
1839                   if Parse_Pos + Alnum'Length - 1 <= Parse_End then
1840                      if
1841                        E (Parse_Pos .. Parse_Pos + Alnum'Length - 1) = Alnum
1842                      then
1843                         if Invert then
1844                            Class := ANYOF_NALNUMC;
1845                         else
1846                            Class := ANYOF_ALNUMC;
1847                         end if;
1848
1849                         Parse_Pos := Parse_Pos + Alnum'Length;
1850
1851                      elsif
1852                        E (Parse_Pos .. Parse_Pos + Alpha'Length - 1) = Alpha
1853                      then
1854                         if Invert then
1855                            Class := ANYOF_NALPHA;
1856                         else
1857                            Class := ANYOF_ALPHA;
1858                         end if;
1859
1860                         Parse_Pos := Parse_Pos + Alpha'Length;
1861
1862                      elsif E (Parse_Pos .. Parse_Pos + Ascii_C'Length - 1) =
1863                                                                       Ascii_C
1864                      then
1865                         if Invert then
1866                            Class := ANYOF_NASCII;
1867                         else
1868                            Class := ANYOF_ASCII;
1869                         end if;
1870
1871                         Parse_Pos := Parse_Pos + Ascii_C'Length;
1872
1873                      else
1874                         Fail ("Invalid character class: " & E);
1875                      end if;
1876
1877                   else
1878                      Fail ("Invalid character class: " & E);
1879                   end if;
1880
1881                when 'c' =>
1882                   if Parse_Pos + Cntrl'Length - 1 <= Parse_End
1883                     and then
1884                       E (Parse_Pos .. Parse_Pos + Cntrl'Length - 1) = Cntrl
1885                   then
1886                      if Invert then
1887                         Class := ANYOF_NCNTRL;
1888                      else
1889                         Class := ANYOF_CNTRL;
1890                      end if;
1891
1892                      Parse_Pos := Parse_Pos + Cntrl'Length;
1893
1894                   else
1895                      Fail ("Invalid character class: " & E);
1896                   end if;
1897
1898                when 'd' =>
1899                   if Parse_Pos + Digit'Length - 1 <= Parse_End
1900                     and then
1901                       E (Parse_Pos .. Parse_Pos + Digit'Length - 1) = Digit
1902                   then
1903                      if Invert then
1904                         Class := ANYOF_NDIGIT;
1905                      else
1906                         Class := ANYOF_DIGIT;
1907                      end if;
1908
1909                      Parse_Pos := Parse_Pos + Digit'Length;
1910                   end if;
1911
1912                when 'g' =>
1913                   if Parse_Pos + Graph'Length - 1 <= Parse_End
1914                     and then
1915                       E (Parse_Pos .. Parse_Pos + Graph'Length - 1) = Graph
1916                   then
1917                      if Invert then
1918                         Class := ANYOF_NGRAPH;
1919                      else
1920                         Class := ANYOF_GRAPH;
1921                      end if;
1922
1923                      Parse_Pos := Parse_Pos + Graph'Length;
1924
1925                   else
1926                      Fail ("Invalid character class: " & E);
1927                   end if;
1928
1929                when 'l' =>
1930                   if Parse_Pos + Lower'Length - 1 <= Parse_End
1931                     and then
1932                       E (Parse_Pos .. Parse_Pos + Lower'Length - 1) = Lower
1933                   then
1934                      if Invert then
1935                         Class := ANYOF_NLOWER;
1936                      else
1937                         Class := ANYOF_LOWER;
1938                      end if;
1939
1940                      Parse_Pos := Parse_Pos + Lower'Length;
1941
1942                   else
1943                      Fail ("Invalid character class: " & E);
1944                   end if;
1945
1946                when 'p' =>
1947
1948                   --  All 'p' classes have the same length
1949
1950                   if Parse_Pos + Print'Length - 1 <= Parse_End then
1951                      if
1952                        E (Parse_Pos .. Parse_Pos + Print'Length - 1) = Print
1953                      then
1954                         if Invert then
1955                            Class := ANYOF_NPRINT;
1956                         else
1957                            Class := ANYOF_PRINT;
1958                         end if;
1959
1960                         Parse_Pos := Parse_Pos + Print'Length;
1961
1962                      elsif
1963                        E (Parse_Pos .. Parse_Pos + Punct'Length - 1) = Punct
1964                      then
1965                         if Invert then
1966                            Class := ANYOF_NPUNCT;
1967                         else
1968                            Class := ANYOF_PUNCT;
1969                         end if;
1970
1971                         Parse_Pos := Parse_Pos + Punct'Length;
1972
1973                      else
1974                         Fail ("Invalid character class: " & E);
1975                      end if;
1976
1977                   else
1978                      Fail ("Invalid character class: " & E);
1979                   end if;
1980
1981                when 's' =>
1982                   if Parse_Pos + Space'Length - 1 <= Parse_End
1983                     and then
1984                       E (Parse_Pos .. Parse_Pos + Space'Length - 1) = Space
1985                   then
1986                      if Invert then
1987                         Class := ANYOF_NSPACE;
1988                      else
1989                         Class := ANYOF_SPACE;
1990                      end if;
1991
1992                      Parse_Pos := Parse_Pos + Space'Length;
1993
1994                   else
1995                      Fail ("Invalid character class: " & E);
1996                   end if;
1997
1998                when 'u' =>
1999                   if Parse_Pos + Upper'Length - 1 <= Parse_End
2000                     and then
2001                       E (Parse_Pos .. Parse_Pos + Upper'Length - 1) = Upper
2002                   then
2003                      if Invert then
2004                         Class := ANYOF_NUPPER;
2005                      else
2006                         Class := ANYOF_UPPER;
2007                      end if;
2008
2009                      Parse_Pos := Parse_Pos + Upper'Length;
2010
2011                   else
2012                      Fail ("Invalid character class: " & E);
2013                   end if;
2014
2015                when 'w' =>
2016                   if Parse_Pos + Word'Length - 1 <= Parse_End
2017                     and then
2018                       E (Parse_Pos .. Parse_Pos + Word'Length - 1) = Word
2019                   then
2020                      if Invert then
2021                         Class := ANYOF_NALNUM;
2022                      else
2023                         Class := ANYOF_ALNUM;
2024                      end if;
2025
2026                      Parse_Pos := Parse_Pos + Word'Length;
2027
2028                   else
2029                      Fail ("Invalid character class: " & E);
2030                   end if;
2031
2032                when 'x' =>
2033                   if Parse_Pos + Xdigit'Length - 1 <= Parse_End
2034                     and then
2035                       E (Parse_Pos .. Parse_Pos + Xdigit'Length - 1) = Xdigit
2036                   then
2037                      if Invert then
2038                         Class := ANYOF_NXDIGIT;
2039                      else
2040                         Class := ANYOF_XDIGIT;
2041                      end if;
2042
2043                      Parse_Pos := Parse_Pos + Xdigit'Length;
2044
2045                   else
2046                      Fail ("Invalid character class: " & E);
2047                   end if;
2048
2049                when others =>
2050                   Fail ("Invalid character class: " & E);
2051             end case;
2052
2053          --  Character class not specified
2054
2055          else
2056             return ANYOF_NONE;
2057          end if;
2058
2059          return Class;
2060       end Parse_Posix_Character_Class;
2061
2062       --  Local Declarations
2063
2064       Result : Pointer;
2065
2066       Expr_Flags : Expression_Flags;
2067       pragma Unreferenced (Expr_Flags);
2068
2069    --  Start of processing for Compile
2070
2071    begin
2072       Emit (MAGIC);
2073       Parse (False, Expr_Flags, Result);
2074
2075       if Result = 0 then
2076          Fail ("Couldn't compile expression");
2077       end if;
2078
2079       Final_Code_Size := Emit_Ptr - 1;
2080
2081       --  Do we want to actually compile the expression, or simply get the
2082       --  code size ???
2083
2084       if Emit_Code then
2085          Optimize (PM);
2086       end if;
2087
2088       PM.Flags := Flags;
2089    end Compile;
2090
2091    function Compile
2092      (Expression : String;
2093       Flags      : Regexp_Flags := No_Flags) return Pattern_Matcher
2094    is
2095       Size  : Program_Size;
2096       Dummy : Pattern_Matcher (0);
2097       pragma Unreferenced (Dummy);
2098
2099    begin
2100       Compile (Dummy, Expression, Size, Flags);
2101
2102       declare
2103          Result : Pattern_Matcher (Size);
2104       begin
2105          Compile (Result, Expression, Size, Flags);
2106          return Result;
2107       end;
2108    end Compile;
2109
2110    procedure Compile
2111      (Matcher    : out Pattern_Matcher;
2112       Expression : String;
2113       Flags      : Regexp_Flags := No_Flags)
2114    is
2115       Size : Program_Size;
2116       pragma Unreferenced (Size);
2117    begin
2118       Compile (Matcher, Expression, Size, Flags);
2119    end Compile;
2120
2121    ----------
2122    -- Dump --
2123    ----------
2124
2125    procedure Dump (Self : Pattern_Matcher) is
2126       Op      : Opcode;
2127       Program : Program_Data renames Self.Program;
2128
2129       procedure Dump_Until
2130         (Start  : Pointer;
2131          Till   : Pointer;
2132          Indent : Natural := 0);
2133       --  Dump the program until the node Till (not included) is met.
2134       --  Every line is indented with Index spaces at the beginning
2135       --  Dumps till the end if Till is 0.
2136
2137       ----------------
2138       -- Dump_Until --
2139       ----------------
2140
2141       procedure Dump_Until
2142         (Start  : Pointer;
2143          Till   : Pointer;
2144          Indent : Natural := 0)
2145       is
2146          Next         : Pointer;
2147          Index        : Pointer;
2148          Local_Indent : Natural := Indent;
2149          Length       : Pointer;
2150
2151       begin
2152          Index := Start;
2153          while Index < Till loop
2154             Op := Opcode'Val (Character'Pos ((Self.Program (Index))));
2155
2156             if Op = CLOSE then
2157                Local_Indent := Local_Indent - 3;
2158             end if;
2159
2160             declare
2161                Point : constant String := Pointer'Image (Index);
2162
2163             begin
2164                for J in 1 .. 6 - Point'Length loop
2165                   Put (' ');
2166                end loop;
2167
2168                Put (Point
2169                     & " : "
2170                     & (1 .. Local_Indent => ' ')
2171                     & Opcode'Image (Op));
2172             end;
2173
2174             --  Print the parenthesis number
2175
2176             if Op = OPEN or else Op = CLOSE or else Op = REFF then
2177                Put (Natural'Image (Character'Pos (Program (Index + 3))));
2178             end if;
2179
2180             Next := Index + Get_Next_Offset (Program, Index);
2181
2182             if Next = Index then
2183                Put ("  (next at 0)");
2184             else
2185                Put ("  (next at " & Pointer'Image (Next) & ")");
2186             end if;
2187
2188             case Op is
2189
2190                --  Character class operand
2191
2192                when ANYOF =>  null;
2193                   declare
2194                      Bitmap  : Character_Class;
2195                      Last    : Character := ASCII.NUL;
2196                      Current : Natural := 0;
2197
2198                      Current_Char : Character;
2199
2200                   begin
2201                      Bitmap_Operand (Program, Index, Bitmap);
2202                      Put ("   operand=");
2203
2204                      while Current <= 255 loop
2205                         Current_Char := Character'Val (Current);
2206
2207                         --  First item in a range
2208
2209                         if Get_From_Class (Bitmap, Current_Char) then
2210                            Last := Current_Char;
2211
2212                            --  Search for the last item in the range
2213
2214                            loop
2215                               Current := Current + 1;
2216                               exit when Current > 255;
2217                               Current_Char := Character'Val (Current);
2218                               exit when
2219                                 not Get_From_Class (Bitmap, Current_Char);
2220
2221                            end loop;
2222
2223                            if Last <= ' ' then
2224                               Put (Last'Img);
2225                            else
2226                               Put (Last);
2227                            end if;
2228
2229                            if Character'Succ (Last) /= Current_Char then
2230                               Put ("-" & Character'Pred (Current_Char));
2231                            end if;
2232
2233                         else
2234                            Current := Current + 1;
2235                         end if;
2236                      end loop;
2237
2238                      New_Line;
2239                      Index := Index + 3 + Bitmap'Length;
2240                   end;
2241
2242                --  string operand
2243
2244                when EXACT | EXACTF =>
2245                   Length := String_Length (Program, Index);
2246                   Put ("   operand (length:" & Program_Size'Image (Length + 1)
2247                        & ") ="
2248                        & String (Program (String_Operand (Index)
2249                                           .. String_Operand (Index)
2250                                           + Length)));
2251                   Index := String_Operand (Index) + Length + 1;
2252                   New_Line;
2253
2254                --  Node operand
2255
2256                when BRANCH =>
2257                   New_Line;
2258                   Dump_Until (Index + 3, Next, Local_Indent + 3);
2259                   Index := Next;
2260
2261                when STAR | PLUS =>
2262                   New_Line;
2263
2264                   --  Only one instruction
2265
2266                   Dump_Until (Index + 3, Index + 4, Local_Indent + 3);
2267                   Index := Next;
2268
2269                when CURLY | CURLYX =>
2270                   Put ("  {"
2271                        & Natural'Image (Read_Natural (Program, Index + 3))
2272                        & ","
2273                        & Natural'Image (Read_Natural (Program, Index + 5))
2274                        & "}");
2275                   New_Line;
2276                   Dump_Until (Index + 7, Next, Local_Indent + 3);
2277                   Index := Next;
2278
2279                when OPEN =>
2280                   New_Line;
2281                   Index := Index + 4;
2282                   Local_Indent := Local_Indent + 3;
2283
2284                when CLOSE | REFF =>
2285                   New_Line;
2286                   Index := Index + 4;
2287
2288                when EOP =>
2289                   Index := Index + 3;
2290                   New_Line;
2291                   exit;
2292
2293                --  No operand
2294
2295                when others =>
2296                   Index := Index + 3;
2297                   New_Line;
2298             end case;
2299          end loop;
2300       end Dump_Until;
2301
2302    --  Start of processing for Dump
2303
2304    begin
2305       pragma Assert (Self.Program (Program_First) = MAGIC,
2306                      "Corrupted Pattern_Matcher");
2307
2308       Put_Line ("Must start with (Self.First) = "
2309                 & Character'Image (Self.First));
2310
2311       if (Self.Flags and Case_Insensitive) /= 0 then
2312          Put_Line ("  Case_Insensitive mode");
2313       end if;
2314
2315       if (Self.Flags and Single_Line) /= 0 then
2316          Put_Line ("  Single_Line mode");
2317       end if;
2318
2319       if (Self.Flags and Multiple_Lines) /= 0 then
2320          Put_Line ("  Multiple_Lines mode");
2321       end if;
2322
2323       Put_Line ("     1 : MAGIC");
2324       Dump_Until (Program_First + 1, Self.Program'Last + 1);
2325    end Dump;
2326
2327    --------------------
2328    -- Get_From_Class --
2329    --------------------
2330
2331    function Get_From_Class
2332      (Bitmap : Character_Class;
2333       C      : Character) return Boolean
2334    is
2335       Value : constant Class_Byte := Character'Pos (C);
2336    begin
2337       return
2338         (Bitmap (Value / 8) and Bit_Conversion (Value mod 8)) /= 0;
2339    end Get_From_Class;
2340
2341    --------------
2342    -- Get_Next --
2343    --------------
2344
2345    function Get_Next (Program : Program_Data; IP : Pointer) return Pointer is
2346       Offset : constant Pointer := Get_Next_Offset (Program, IP);
2347    begin
2348       if Offset = 0 then
2349          return 0;
2350       else
2351          return IP + Offset;
2352       end if;
2353    end Get_Next;
2354
2355    ---------------------
2356    -- Get_Next_Offset --
2357    ---------------------
2358
2359    function Get_Next_Offset
2360      (Program : Program_Data;
2361       IP      : Pointer) return Pointer
2362    is
2363    begin
2364       return Pointer (Read_Natural (Program, IP + 1));
2365    end Get_Next_Offset;
2366
2367    --------------
2368    -- Is_Alnum --
2369    --------------
2370
2371    function Is_Alnum (C : Character) return Boolean is
2372    begin
2373       return Is_Alphanumeric (C) or else C = '_';
2374    end Is_Alnum;
2375
2376    ------------------
2377    -- Is_Printable --
2378    ------------------
2379
2380    function Is_Printable (C : Character) return Boolean is
2381    begin
2382       --  Printable if space or graphic character or other whitespace
2383       --  Other white space includes (HT/LF/VT/FF/CR = codes 9-13)
2384
2385       return C in Character'Val (32) .. Character'Val (126)
2386         or else C in ASCII.HT .. ASCII.CR;
2387    end Is_Printable;
2388
2389    --------------------
2390    -- Is_White_Space --
2391    --------------------
2392
2393    function Is_White_Space (C : Character) return Boolean is
2394    begin
2395       --  Note: HT = 9, LF = 10, VT = 11, FF = 12, CR = 13
2396
2397       return C = ' ' or else C in ASCII.HT .. ASCII.CR;
2398    end Is_White_Space;
2399
2400    -----------
2401    -- Match --
2402    -----------
2403
2404    procedure Match
2405      (Self       : Pattern_Matcher;
2406       Data       : String;
2407       Matches    : out Match_Array;
2408       Data_First : Integer := -1;
2409       Data_Last  : Positive := Positive'Last)
2410    is
2411       Program : Program_Data renames Self.Program; -- Shorter notation
2412
2413       First_In_Data : constant Integer := Integer'Max (Data_First, Data'First);
2414       Last_In_Data  : constant Integer := Integer'Min (Data_Last, Data'Last);
2415
2416       --  Global work variables
2417
2418       Input_Pos : Natural;           -- String-input pointer
2419       BOL_Pos   : Natural;           -- Beginning of input, for ^ check
2420       Matched   : Boolean := False;  -- Until proven True
2421
2422       Matches_Full : Match_Array (0 .. Natural'Max (Self.Paren_Count,
2423                                                     Matches'Last));
2424       --  Stores the value of all the parenthesis pairs.
2425       --  We do not use directly Matches, so that we can also use back
2426       --  references (REFF) even if Matches is too small.
2427
2428       type Natural_Array is array (Match_Count range <>) of Natural;
2429       Matches_Tmp : Natural_Array (Matches_Full'Range);
2430       --  Save the opening position of parenthesis
2431
2432       Last_Paren  : Natural := 0;
2433       --  Last parenthesis seen
2434
2435       Greedy : Boolean := True;
2436       --  True if the next operator should be greedy
2437
2438       type Current_Curly_Record;
2439       type Current_Curly_Access is access all Current_Curly_Record;
2440       type Current_Curly_Record is record
2441          Paren_Floor : Natural;  --  How far back to strip parenthesis data
2442          Cur         : Integer;  --  How many instances of scan we've matched
2443          Min         : Natural;  --  Minimal number of scans to match
2444          Max         : Natural;  --  Maximal number of scans to match
2445          Greedy      : Boolean;  --  Whether to work our way up or down
2446          Scan        : Pointer;  --  The thing to match
2447          Next        : Pointer;  --  What has to match after it
2448          Lastloc     : Natural;  --  Where we started matching this scan
2449          Old_Cc      : Current_Curly_Access; --  Before we started this one
2450       end record;
2451       --  Data used to handle the curly operator and the plus and star
2452       --  operators for complex expressions.
2453
2454       Current_Curly : Current_Curly_Access := null;
2455       --  The curly currently being processed
2456
2457       -----------------------
2458       -- Local Subprograms --
2459       -----------------------
2460
2461       function Index (Start : Positive; C : Character) return Natural;
2462       --  Find character C in Data starting at Start and return position
2463
2464       function Repeat
2465         (IP  : Pointer;
2466          Max : Natural := Natural'Last) return Natural;
2467       --  Repeatedly match something simple, report how many
2468       --  It only matches on things of length 1.
2469       --  Starting from Input_Pos, it matches at most Max CURLY.
2470
2471       function Try (Pos : Positive) return Boolean;
2472       --  Try to match at specific point
2473
2474       function Match (IP : Pointer) return Boolean;
2475       --  This is the main matching routine. Conceptually the strategy
2476       --  is simple:  check to see whether the current node matches,
2477       --  call self recursively to see whether the rest matches,
2478       --  and then act accordingly.
2479       --
2480       --  In practice Match makes some effort to avoid recursion, in
2481       --  particular by going through "ordinary" nodes (that don't
2482       --  need to know whether the rest of the match failed) by
2483       --  using a loop instead of recursion.
2484       --  Why is the above comment part of the spec rather than body ???
2485
2486       function Match_Whilem (IP : Pointer) return Boolean;
2487       --  Return True if a WHILEM matches
2488       --  How come IP is unreferenced in the body ???
2489
2490       function Recurse_Match (IP : Pointer; From : Natural) return Boolean;
2491       pragma Inline (Recurse_Match);
2492       --  Calls Match recursively. It saves and restores the parenthesis
2493       --  status and location in the input stream correctly, so that
2494       --  backtracking is possible
2495
2496       function Match_Simple_Operator
2497         (Op     : Opcode;
2498          Scan   : Pointer;
2499          Next   : Pointer;
2500          Greedy : Boolean) return Boolean;
2501       --  Return True it the simple operator (possibly non-greedy) matches
2502
2503       pragma Inline (Index);
2504       pragma Inline (Repeat);
2505
2506       --  These are two complex functions, but used only once
2507
2508       pragma Inline (Match_Whilem);
2509       pragma Inline (Match_Simple_Operator);
2510
2511       -----------
2512       -- Index --
2513       -----------
2514
2515       function Index (Start : Positive; C : Character) return Natural is
2516       begin
2517          for J in Start .. Last_In_Data loop
2518             if Data (J) = C then
2519                return J;
2520             end if;
2521          end loop;
2522
2523          return 0;
2524       end Index;
2525
2526       -------------------
2527       -- Recurse_Match --
2528       -------------------
2529
2530       function Recurse_Match (IP : Pointer; From : Natural) return Boolean is
2531          L : constant Natural := Last_Paren;
2532
2533          Tmp_F : constant Match_Array :=
2534                    Matches_Full (From + 1 .. Matches_Full'Last);
2535
2536          Start : constant Natural_Array :=
2537                    Matches_Tmp (From + 1 .. Matches_Tmp'Last);
2538          Input : constant Natural := Input_Pos;
2539
2540       begin
2541          if Match (IP) then
2542             return True;
2543          end if;
2544
2545          Last_Paren := L;
2546          Matches_Full (Tmp_F'Range) := Tmp_F;
2547          Matches_Tmp (Start'Range) := Start;
2548          Input_Pos := Input;
2549          return False;
2550       end Recurse_Match;
2551
2552       -----------
2553       -- Match --
2554       -----------
2555
2556       function Match (IP : Pointer) return Boolean is
2557          Scan   : Pointer := IP;
2558          Next   : Pointer;
2559          Op     : Opcode;
2560
2561       begin
2562          State_Machine :
2563          loop
2564             pragma Assert (Scan /= 0);
2565
2566             --  Determine current opcode and count its usage in debug mode
2567
2568             Op := Opcode'Val (Character'Pos (Program (Scan)));
2569
2570             --  Calculate offset of next instruction.
2571             --  Second character is most significant in Program_Data.
2572
2573             Next := Get_Next (Program, Scan);
2574
2575             case Op is
2576                when EOP =>
2577                   return True;  --  Success !
2578
2579                when BRANCH =>
2580                   if Program (Next) /= BRANCH then
2581                      Next := Operand (Scan); -- No choice, avoid recursion
2582
2583                   else
2584                      loop
2585                         if Recurse_Match (Operand (Scan), 0) then
2586                            return True;
2587                         end if;
2588
2589                         Scan := Get_Next (Program, Scan);
2590                         exit when Scan = 0 or else Program (Scan) /= BRANCH;
2591                      end loop;
2592
2593                      exit State_Machine;
2594                   end if;
2595
2596                when NOTHING =>
2597                   null;
2598
2599                when BOL =>
2600                   exit State_Machine when Input_Pos /= BOL_Pos
2601                     and then ((Self.Flags and Multiple_Lines) = 0
2602                               or else Data (Input_Pos - 1) /= ASCII.LF);
2603
2604                when MBOL =>
2605                   exit State_Machine when Input_Pos /= BOL_Pos
2606                     and then Data (Input_Pos - 1) /= ASCII.LF;
2607
2608                when SBOL =>
2609                   exit State_Machine when Input_Pos /= BOL_Pos;
2610
2611                when EOL =>
2612                   exit State_Machine when Input_Pos <= Data'Last
2613                     and then ((Self.Flags and Multiple_Lines) = 0
2614                               or else Data (Input_Pos) /= ASCII.LF);
2615
2616                when MEOL =>
2617                   exit State_Machine when Input_Pos <= Data'Last
2618                     and then Data (Input_Pos) /= ASCII.LF;
2619
2620                when SEOL =>
2621                   exit State_Machine when Input_Pos <= Data'Last;
2622
2623                when BOUND | NBOUND =>
2624
2625                   --  Was last char in word ?
2626
2627                   declare
2628                      N  : Boolean := False;
2629                      Ln : Boolean := False;
2630
2631                   begin
2632                      if Input_Pos /= First_In_Data then
2633                         N := Is_Alnum (Data (Input_Pos - 1));
2634                      end if;
2635
2636                      if Input_Pos > Last_In_Data then
2637                         Ln := False;
2638                      else
2639                         Ln := Is_Alnum (Data (Input_Pos));
2640                      end if;
2641
2642                      if Op = BOUND then
2643                         if N = Ln then
2644                            exit State_Machine;
2645                         end if;
2646                      else
2647                         if N /= Ln then
2648                            exit State_Machine;
2649                         end if;
2650                      end if;
2651                   end;
2652
2653                when SPACE =>
2654                   exit State_Machine when Input_Pos > Last_In_Data
2655                     or else not Is_White_Space (Data (Input_Pos));
2656                   Input_Pos := Input_Pos + 1;
2657
2658                when NSPACE =>
2659                   exit State_Machine when Input_Pos > Last_In_Data
2660                     or else Is_White_Space (Data (Input_Pos));
2661                   Input_Pos := Input_Pos + 1;
2662
2663                when DIGIT =>
2664                   exit State_Machine when Input_Pos > Last_In_Data
2665                     or else not Is_Digit (Data (Input_Pos));
2666                   Input_Pos := Input_Pos + 1;
2667
2668                when NDIGIT =>
2669                   exit State_Machine when Input_Pos > Last_In_Data
2670                     or else Is_Digit (Data (Input_Pos));
2671                   Input_Pos := Input_Pos + 1;
2672
2673                when ALNUM =>
2674                   exit State_Machine when Input_Pos > Last_In_Data
2675                     or else not Is_Alnum (Data (Input_Pos));
2676                   Input_Pos := Input_Pos + 1;
2677
2678                when NALNUM =>
2679                   exit State_Machine when Input_Pos > Last_In_Data
2680                     or else Is_Alnum (Data (Input_Pos));
2681                   Input_Pos := Input_Pos + 1;
2682
2683                when ANY =>
2684                   exit State_Machine when Input_Pos > Last_In_Data
2685                     or else Data (Input_Pos) = ASCII.LF;
2686                   Input_Pos := Input_Pos + 1;
2687
2688                when SANY =>
2689                   exit State_Machine when Input_Pos > Last_In_Data;
2690                   Input_Pos := Input_Pos + 1;
2691
2692                when EXACT =>
2693                   declare
2694                      Opnd    : Pointer  := String_Operand (Scan);
2695                      Current : Positive := Input_Pos;
2696
2697                      Last    : constant Pointer :=
2698                                  Opnd + String_Length (Program, Scan);
2699
2700                   begin
2701                      while Opnd <= Last loop
2702                         exit State_Machine when Current > Last_In_Data
2703                           or else Program (Opnd) /= Data (Current);
2704                         Current := Current + 1;
2705                         Opnd := Opnd + 1;
2706                      end loop;
2707
2708                      Input_Pos := Current;
2709                   end;
2710
2711                when EXACTF =>
2712                   declare
2713                      Opnd    : Pointer  := String_Operand (Scan);
2714                      Current : Positive := Input_Pos;
2715
2716                      Last : constant Pointer :=
2717                               Opnd + String_Length (Program, Scan);
2718
2719                   begin
2720                      while Opnd <= Last loop
2721                         exit State_Machine when Current > Last_In_Data
2722                           or else Program (Opnd) /= To_Lower (Data (Current));
2723                         Current := Current + 1;
2724                         Opnd := Opnd + 1;
2725                      end loop;
2726
2727                      Input_Pos := Current;
2728                   end;
2729
2730                when ANYOF =>
2731                   declare
2732                      Bitmap : Character_Class;
2733                   begin
2734                      Bitmap_Operand (Program, Scan, Bitmap);
2735                      exit State_Machine when Input_Pos > Last_In_Data
2736                        or else not Get_From_Class (Bitmap, Data (Input_Pos));
2737                      Input_Pos := Input_Pos + 1;
2738                   end;
2739
2740                when OPEN =>
2741                   declare
2742                      No : constant Natural :=
2743                             Character'Pos (Program (Operand (Scan)));
2744                   begin
2745                      Matches_Tmp (No) := Input_Pos;
2746                   end;
2747
2748                when CLOSE =>
2749                   declare
2750                      No : constant Natural :=
2751                             Character'Pos (Program (Operand (Scan)));
2752
2753                   begin
2754                      Matches_Full (No) := (Matches_Tmp (No), Input_Pos - 1);
2755
2756                      if Last_Paren < No then
2757                         Last_Paren := No;
2758                      end if;
2759                   end;
2760
2761                when REFF =>
2762                   declare
2763                      No : constant Natural :=
2764                             Character'Pos (Program (Operand (Scan)));
2765
2766                      Data_Pos : Natural;
2767
2768                   begin
2769                      --  If we haven't seen that parenthesis yet
2770
2771                      if Last_Paren < No then
2772                         return False;
2773                      end if;
2774
2775                      Data_Pos := Matches_Full (No).First;
2776
2777                      while Data_Pos <= Matches_Full (No).Last loop
2778                         if Input_Pos > Last_In_Data
2779                           or else Data (Input_Pos) /= Data (Data_Pos)
2780                         then
2781                            return False;
2782                         end if;
2783
2784                         Input_Pos := Input_Pos + 1;
2785                         Data_Pos := Data_Pos + 1;
2786                      end loop;
2787                   end;
2788
2789                when MINMOD =>
2790                   Greedy := False;
2791
2792                when STAR | PLUS | CURLY =>
2793                   declare
2794                      Greed : constant Boolean := Greedy;
2795                   begin
2796                      Greedy := True;
2797                      return Match_Simple_Operator (Op, Scan, Next, Greed);
2798                   end;
2799
2800                when CURLYX =>
2801
2802                   --  Looking at something like:
2803
2804                   --    1: CURLYX {n,m}  (->4)
2805                   --    2:   code for complex thing  (->3)
2806                   --    3:   WHILEM (->0)
2807                   --    4: NOTHING
2808
2809                   declare
2810                      Min : constant Natural :=
2811                              Read_Natural (Program, Scan + 3);
2812                      Max : constant Natural :=
2813                              Read_Natural (Program, Scan + 5);
2814                      Cc  : aliased Current_Curly_Record;
2815
2816                      Has_Match : Boolean;
2817
2818                   begin
2819                      Cc := (Paren_Floor => Last_Paren,
2820                             Cur         => -1,
2821                             Min         => Min,
2822                             Max         => Max,
2823                             Greedy      => Greedy,
2824                             Scan        => Scan + 7,
2825                             Next        => Next,
2826                             Lastloc     => 0,
2827                             Old_Cc      => Current_Curly);
2828                      Current_Curly := Cc'Unchecked_Access;
2829
2830                      Has_Match := Match (Next - 3);
2831
2832                      --  Start on the WHILEM
2833
2834                      Current_Curly := Cc.Old_Cc;
2835                      return Has_Match;
2836                   end;
2837
2838                when WHILEM =>
2839                   return Match_Whilem (IP);
2840             end case;
2841
2842             Scan := Next;
2843          end loop State_Machine;
2844
2845          --  If we get here, there is no match.
2846          --  For successful matches when EOP is the terminating point.
2847
2848          return False;
2849       end Match;
2850
2851       ---------------------------
2852       -- Match_Simple_Operator --
2853       ---------------------------
2854
2855       function Match_Simple_Operator
2856         (Op     : Opcode;
2857          Scan   : Pointer;
2858          Next   : Pointer;
2859          Greedy : Boolean) return Boolean
2860       is
2861          Next_Char       : Character := ASCII.NUL;
2862          Next_Char_Known : Boolean := False;
2863          No              : Integer;  --  Can be negative
2864          Min             : Natural;
2865          Max             : Natural := Natural'Last;
2866          Operand_Code    : Pointer;
2867          Old             : Natural;
2868          Last_Pos        : Natural;
2869          Save            : constant Natural := Input_Pos;
2870
2871       begin
2872          --  Lookahead to avoid useless match attempts
2873          --  when we know what character comes next.
2874
2875          if Program (Next) = EXACT then
2876             Next_Char := Program (String_Operand (Next));
2877             Next_Char_Known := True;
2878          end if;
2879
2880          --  Find the minimal and maximal values for the operator
2881
2882          case Op is
2883             when STAR =>
2884                Min := 0;
2885                Operand_Code := Operand (Scan);
2886
2887             when PLUS =>
2888                Min := 1;
2889                Operand_Code := Operand (Scan);
2890
2891             when others =>
2892                Min := Read_Natural (Program, Scan + 3);
2893                Max := Read_Natural (Program, Scan + 5);
2894                Operand_Code := Scan + 7;
2895          end case;
2896
2897          --  Non greedy operators
2898
2899          if not Greedy then
2900
2901             --  Test the minimal repetitions
2902
2903             if Min /= 0
2904               and then Repeat (Operand_Code, Min) < Min
2905             then
2906                return False;
2907             end if;
2908
2909             Old := Input_Pos;
2910
2911             --  Find the place where 'next' could work
2912
2913             if Next_Char_Known then
2914                --  Last position to check
2915
2916                if Max = Natural'Last then
2917                   Last_Pos := Last_In_Data;
2918                else
2919                   Last_Pos := Input_Pos + Max;
2920
2921                   if Last_Pos > Last_In_Data then
2922                      Last_Pos := Last_In_Data;
2923                   end if;
2924                end if;
2925
2926                --  Look for the first possible opportunity
2927
2928                loop
2929                   --  Find the next possible position
2930
2931                   while Input_Pos <= Last_Pos
2932                     and then Data (Input_Pos) /= Next_Char
2933                   loop
2934                      Input_Pos := Input_Pos + 1;
2935                   end loop;
2936
2937                   if Input_Pos > Last_Pos then
2938                      return False;
2939                   end if;
2940
2941                   --  Check that we still match if we stop
2942                   --  at the position we just found.
2943
2944                   declare
2945                      Num : constant Natural := Input_Pos - Old;
2946
2947                   begin
2948                      Input_Pos := Old;
2949
2950                      if Repeat (Operand_Code, Num) < Num then
2951                         return False;
2952                      end if;
2953                   end;
2954
2955                   --  Input_Pos now points to the new position
2956
2957                   if Match (Get_Next (Program, Scan)) then
2958                      return True;
2959                   end if;
2960
2961                   Old := Input_Pos;
2962                   Input_Pos := Input_Pos + 1;
2963                end loop;
2964
2965             --  We know what the next character is
2966
2967             else
2968                while Max >= Min loop
2969
2970                   --  If the next character matches
2971
2972                   if Match (Next) then
2973                      return True;
2974                   end if;
2975
2976                   Input_Pos := Save + Min;
2977
2978                   --  Could not or did not match -- move forward
2979
2980                   if Repeat (Operand_Code, 1) /= 0 then
2981                      Min := Min + 1;
2982                   else
2983                      return False;
2984                   end if;
2985                end loop;
2986             end if;
2987
2988             return False;
2989
2990          --  Greedy operators
2991
2992          else
2993             No := Repeat (Operand_Code, Max);
2994
2995             --  ??? Perl has some special code here in case the
2996             --  next instruction is of type EOL, since $ and \Z
2997             --  can match before *and* after newline at the end.
2998
2999             --  ??? Perl has some special code here in case (paren)
3000             --  is True.
3001
3002             --  Else, if we don't have any parenthesis
3003
3004             while No >= Min loop
3005                if not Next_Char_Known
3006                  or else (Input_Pos <= Last_In_Data
3007                            and then Data (Input_Pos) = Next_Char)
3008                then
3009                   if Match (Next) then
3010                      return True;
3011                   end if;
3012                end if;
3013
3014                --  Could not or did not work, we back up
3015
3016                No := No - 1;
3017                Input_Pos := Save + No;
3018             end loop;
3019
3020             return False;
3021          end if;
3022       end Match_Simple_Operator;
3023
3024       ------------------
3025       -- Match_Whilem --
3026       ------------------
3027
3028       --  This is really hard to understand, because after we match what we
3029       --  are trying to match, we must make sure the rest of the REx is going
3030       --  to match for sure, and to do that we have to go back UP the parse
3031       --  tree by recursing ever deeper.  And if it fails, we have to reset
3032       --  our parent's current state that we can try again after backing off.
3033
3034       function Match_Whilem (IP : Pointer) return Boolean is
3035          pragma Unreferenced (IP);
3036
3037          Cc : constant Current_Curly_Access := Current_Curly;
3038          N  : constant Natural              := Cc.Cur + 1;
3039          Ln : Natural                       := 0;
3040
3041          Lastloc : constant Natural := Cc.Lastloc;
3042          --  Detection of 0-len
3043
3044       begin
3045          --  If degenerate scan matches "", assume scan done
3046
3047          if Input_Pos = Cc.Lastloc
3048            and then N >= Cc.Min
3049          then
3050             --  Temporarily restore the old context, and check that we
3051             --  match was comes after CURLYX.
3052
3053             Current_Curly := Cc.Old_Cc;
3054
3055             if Current_Curly /= null then
3056                Ln := Current_Curly.Cur;
3057             end if;
3058
3059             if Match (Cc.Next) then
3060                return True;
3061             end if;
3062
3063             if Current_Curly /= null then
3064                Current_Curly.Cur := Ln;
3065             end if;
3066
3067             Current_Curly := Cc;
3068             return False;
3069          end if;
3070
3071          --  First, just match a string of min scans
3072
3073          if N < Cc.Min then
3074             Cc.Cur := N;
3075             Cc.Lastloc := Input_Pos;
3076
3077             if Match (Cc.Scan) then
3078                return True;
3079             end if;
3080
3081             Cc.Cur := N - 1;
3082             Cc.Lastloc := Lastloc;
3083             return False;
3084          end if;
3085
3086          --  Prefer next over scan for minimal matching
3087
3088          if not Cc.Greedy then
3089             Current_Curly := Cc.Old_Cc;
3090
3091             if Current_Curly /= null then
3092                Ln := Current_Curly.Cur;
3093             end if;
3094
3095             if Recurse_Match (Cc.Next, Cc.Paren_Floor) then
3096                return True;
3097             end if;
3098
3099             if Current_Curly /= null then
3100                Current_Curly.Cur := Ln;
3101             end if;
3102
3103             Current_Curly := Cc;
3104
3105             --  Maximum greed exceeded ?
3106
3107             if N >= Cc.Max then
3108                return False;
3109             end if;
3110
3111             --  Try scanning more and see if it helps
3112             Cc.Cur := N;
3113             Cc.Lastloc := Input_Pos;
3114
3115             if Recurse_Match (Cc.Scan, Cc.Paren_Floor) then
3116                return True;
3117             end if;
3118
3119             Cc.Cur := N - 1;
3120             Cc.Lastloc := Lastloc;
3121             return False;
3122          end if;
3123
3124          --  Prefer scan over next for maximal matching
3125
3126          if N < Cc.Max then   --  more greed allowed ?
3127             Cc.Cur := N;
3128             Cc.Lastloc := Input_Pos;
3129
3130             if Recurse_Match (Cc.Scan, Cc.Paren_Floor) then
3131                return True;
3132             end if;
3133          end if;
3134
3135          --  Failed deeper matches of scan, so see if this one works
3136
3137          Current_Curly := Cc.Old_Cc;
3138
3139          if Current_Curly /= null then
3140             Ln := Current_Curly.Cur;
3141          end if;
3142
3143          if Match (Cc.Next) then
3144             return True;
3145          end if;
3146
3147          if Current_Curly /= null then
3148             Current_Curly.Cur := Ln;
3149          end if;
3150
3151          Current_Curly := Cc;
3152          Cc.Cur := N - 1;
3153          Cc.Lastloc := Lastloc;
3154          return False;
3155       end Match_Whilem;
3156
3157       ------------
3158       -- Repeat --
3159       ------------
3160
3161       function Repeat
3162         (IP  : Pointer;
3163          Max : Natural := Natural'Last) return Natural
3164       is
3165          Scan  : Natural := Input_Pos;
3166          Last  : Natural;
3167          Op    : constant Opcode := Opcode'Val (Character'Pos (Program (IP)));
3168          Count : Natural;
3169          C     : Character;
3170          Is_First : Boolean := True;
3171          Bitmap   : Character_Class;
3172
3173       begin
3174          if Max = Natural'Last or else Scan + Max - 1 > Last_In_Data then
3175             Last := Last_In_Data;
3176          else
3177             Last := Scan + Max - 1;
3178          end if;
3179
3180          case Op is
3181             when ANY =>
3182                while Scan <= Last
3183                  and then Data (Scan) /= ASCII.LF
3184                loop
3185                   Scan := Scan + 1;
3186                end loop;
3187
3188             when SANY =>
3189                Scan := Last + 1;
3190
3191             when EXACT =>
3192
3193                --  The string has only one character if Repeat was called
3194
3195                C := Program (String_Operand (IP));
3196                while Scan <= Last
3197                  and then C = Data (Scan)
3198                loop
3199                   Scan := Scan + 1;
3200                end loop;
3201
3202             when EXACTF =>
3203
3204                --  The string has only one character if Repeat was called
3205
3206                C := Program (String_Operand (IP));
3207                while Scan <= Last
3208                  and then To_Lower (C) = Data (Scan)
3209                loop
3210                   Scan := Scan + 1;
3211                end loop;
3212
3213             when ANYOF =>
3214                if Is_First then
3215                   Bitmap_Operand (Program, IP, Bitmap);
3216                   Is_First := False;
3217                end if;
3218
3219                while Scan <= Last
3220                  and then Get_From_Class (Bitmap, Data (Scan))
3221                loop
3222                   Scan := Scan + 1;
3223                end loop;
3224
3225             when ALNUM =>
3226                while Scan <= Last
3227                  and then Is_Alnum (Data (Scan))
3228                loop
3229                   Scan := Scan + 1;
3230                end loop;
3231
3232             when NALNUM =>
3233                while Scan <= Last
3234                  and then not Is_Alnum (Data (Scan))
3235                loop
3236                   Scan := Scan + 1;
3237                end loop;
3238
3239             when SPACE =>
3240                while Scan <= Last
3241                  and then Is_White_Space (Data (Scan))
3242                loop
3243                   Scan := Scan + 1;
3244                end loop;
3245
3246             when NSPACE =>
3247                while Scan <= Last
3248                  and then not Is_White_Space (Data (Scan))
3249                loop
3250                   Scan := Scan + 1;
3251                end loop;
3252
3253             when DIGIT  =>
3254                while Scan <= Last
3255                  and then Is_Digit (Data (Scan))
3256                loop
3257                   Scan := Scan + 1;
3258                end loop;
3259
3260             when NDIGIT  =>
3261                while Scan <= Last
3262                  and then not Is_Digit (Data (Scan))
3263                loop
3264                   Scan := Scan + 1;
3265                end loop;
3266
3267             when others =>
3268                raise Program_Error;
3269          end case;
3270
3271          Count := Scan - Input_Pos;
3272          Input_Pos := Scan;
3273          return Count;
3274       end Repeat;
3275
3276       ---------
3277       -- Try --
3278       ---------
3279
3280       function Try (Pos : Positive) return Boolean is
3281       begin
3282          Input_Pos  := Pos;
3283          Last_Paren := 0;
3284          Matches_Full := (others => No_Match);
3285
3286          if Match (Program_First + 1) then
3287             Matches_Full (0) := (Pos, Input_Pos - 1);
3288             return True;
3289          end if;
3290
3291          return False;
3292       end Try;
3293
3294    --  Start of processing for Match
3295
3296    begin
3297       --  Do we have the regexp Never_Match?
3298
3299       if Self.Size = 0 then
3300          Matches := (others => No_Match);
3301          return;
3302       end if;
3303
3304       --  Check validity of program
3305
3306       pragma Assert
3307         (Program (Program_First) = MAGIC,
3308          "Corrupted Pattern_Matcher");
3309
3310       --  If there is a "must appear" string, look for it
3311
3312       if Self.Must_Have_Length > 0 then
3313          declare
3314             First      : constant Character := Program (Self.Must_Have);
3315             Must_First : constant Pointer := Self.Must_Have;
3316             Must_Last  : constant Pointer :=
3317                            Must_First + Pointer (Self.Must_Have_Length - 1);
3318             Next_Try   : Natural := Index (First_In_Data, First);
3319
3320          begin
3321             while Next_Try /= 0
3322               and then Data (Next_Try .. Next_Try + Self.Must_Have_Length - 1)
3323                           = String (Program (Must_First .. Must_Last))
3324             loop
3325                Next_Try := Index (Next_Try + 1, First);
3326             end loop;
3327
3328             if Next_Try = 0 then
3329                Matches := (others => No_Match);
3330                return;                  -- Not present
3331             end if;
3332          end;
3333       end if;
3334
3335       --  Mark beginning of line for ^
3336
3337       BOL_Pos := Data'First;
3338
3339       --  Simplest case first: an anchored match need be tried only once
3340
3341       if Self.Anchored and then (Self.Flags and Multiple_Lines) = 0 then
3342          Matched := Try (First_In_Data);
3343
3344       elsif Self.Anchored then
3345          declare
3346             Next_Try : Natural := First_In_Data;
3347          begin
3348             --  Test the first position in the buffer
3349             Matched := Try (Next_Try);
3350
3351             --  Else only test after newlines
3352
3353             if not Matched then
3354                while Next_Try <= Last_In_Data loop
3355                   while Next_Try <= Last_In_Data
3356                     and then Data (Next_Try) /= ASCII.LF
3357                   loop
3358                      Next_Try := Next_Try + 1;
3359                   end loop;
3360
3361                   Next_Try := Next_Try + 1;
3362
3363                   if Next_Try <= Last_In_Data then
3364                      Matched := Try (Next_Try);
3365                      exit when Matched;
3366                   end if;
3367                end loop;
3368             end if;
3369          end;
3370
3371       elsif Self.First /= ASCII.NUL then
3372          --  We know what char it must start with
3373
3374          declare
3375             Next_Try : Natural := Index (First_In_Data, Self.First);
3376
3377          begin
3378             while Next_Try /= 0 loop
3379                Matched := Try (Next_Try);
3380                exit when Matched;
3381                Next_Try := Index (Next_Try + 1, Self.First);
3382             end loop;
3383          end;
3384
3385       else
3386          --  Messy cases: try all locations (including for the empty string)
3387
3388          Matched := Try (First_In_Data);
3389
3390          if not Matched then
3391             for S in First_In_Data + 1 .. Last_In_Data loop
3392                Matched := Try (S);
3393                exit when Matched;
3394             end loop;
3395          end if;
3396       end if;
3397
3398       --  Matched has its value
3399
3400       for J in Last_Paren + 1 .. Matches'Last loop
3401          Matches_Full (J) := No_Match;
3402       end loop;
3403
3404       Matches := Matches_Full (Matches'Range);
3405    end Match;
3406
3407    -----------
3408    -- Match --
3409    -----------
3410
3411    function Match
3412      (Self       : Pattern_Matcher;
3413       Data       : String;
3414       Data_First : Integer := -1;
3415       Data_Last  : Positive := Positive'Last) return Natural
3416    is
3417       Matches : Match_Array (0 .. 0);
3418
3419    begin
3420       Match (Self, Data, Matches, Data_First, Data_Last);
3421       if Matches (0) = No_Match then
3422          return Data'First - 1;
3423       else
3424          return Matches (0).First;
3425       end if;
3426    end Match;
3427
3428    function Match
3429      (Self       : Pattern_Matcher;
3430       Data       : String;
3431       Data_First : Integer  := -1;
3432       Data_Last  : Positive := Positive'Last) return Boolean
3433    is
3434       Matches : Match_Array (0 .. 0);
3435
3436    begin
3437       Match (Self, Data, Matches, Data_First, Data_Last);
3438       return Matches (0).First >= Data'First;
3439    end Match;
3440
3441    procedure Match
3442      (Expression : String;
3443       Data       : String;
3444       Matches    : out Match_Array;
3445       Size       : Program_Size := Auto_Size;
3446       Data_First : Integer      := -1;
3447       Data_Last  : Positive     := Positive'Last)
3448    is
3449       PM            : Pattern_Matcher (Size);
3450       Finalize_Size : Program_Size;
3451       pragma Unreferenced (Finalize_Size);
3452    begin
3453       if Size = 0 then
3454          Match (Compile (Expression), Data, Matches, Data_First, Data_Last);
3455       else
3456          Compile (PM, Expression, Finalize_Size);
3457          Match (PM, Data, Matches, Data_First, Data_Last);
3458       end if;
3459    end Match;
3460
3461    -----------
3462    -- Match --
3463    -----------
3464
3465    function Match
3466      (Expression : String;
3467       Data       : String;
3468       Size       : Program_Size := Auto_Size;
3469       Data_First : Integer      := -1;
3470       Data_Last  : Positive     := Positive'Last) return Natural
3471    is
3472       PM         : Pattern_Matcher (Size);
3473       Final_Size : Program_Size;
3474       pragma Unreferenced (Final_Size);
3475    begin
3476       if Size = 0 then
3477          return Match (Compile (Expression), Data, Data_First, Data_Last);
3478       else
3479          Compile (PM, Expression, Final_Size);
3480          return Match (PM, Data, Data_First, Data_Last);
3481       end if;
3482    end Match;
3483
3484    -----------
3485    -- Match --
3486    -----------
3487
3488    function  Match
3489      (Expression : String;
3490       Data       : String;
3491       Size       : Program_Size := Auto_Size;
3492       Data_First : Integer      := -1;
3493       Data_Last  : Positive     := Positive'Last) return Boolean
3494    is
3495       Matches    : Match_Array (0 .. 0);
3496       PM         : Pattern_Matcher (Size);
3497       Final_Size : Program_Size;
3498       pragma Unreferenced (Final_Size);
3499    begin
3500       if Size = 0 then
3501          Match (Compile (Expression), Data, Matches, Data_First, Data_Last);
3502       else
3503          Compile (PM, Expression, Final_Size);
3504          Match (PM, Data, Matches, Data_First, Data_Last);
3505       end if;
3506
3507       return Matches (0).First >= Data'First;
3508    end Match;
3509
3510    -------------
3511    -- Operand --
3512    -------------
3513
3514    function Operand (P : Pointer) return Pointer is
3515    begin
3516       return P + 3;
3517    end Operand;
3518
3519    --------------
3520    -- Optimize --
3521    --------------
3522
3523    procedure Optimize (Self : in out Pattern_Matcher) is
3524       Scan    : Pointer;
3525       Program : Program_Data renames Self.Program;
3526
3527    begin
3528       --  Start with safe defaults (no optimization):
3529       --    *  No known first character of match
3530       --    *  Does not necessarily start at beginning of line
3531       --    *  No string known that has to appear in data
3532
3533       Self.First := ASCII.NUL;
3534       Self.Anchored := False;
3535       Self.Must_Have := Program'Last + 1;
3536       Self.Must_Have_Length := 0;
3537
3538       Scan := Program_First + 1;  --  First instruction (can be anything)
3539
3540       if Program (Scan) = EXACT then
3541          Self.First := Program (String_Operand (Scan));
3542
3543       elsif Program (Scan) = BOL
3544         or else Program (Scan) = SBOL
3545         or else Program (Scan) = MBOL
3546       then
3547          Self.Anchored := True;
3548       end if;
3549    end Optimize;
3550
3551    -----------------
3552    -- Paren_Count --
3553    -----------------
3554
3555    function Paren_Count (Regexp : Pattern_Matcher) return Match_Count is
3556    begin
3557       return Regexp.Paren_Count;
3558    end Paren_Count;
3559
3560    -----------
3561    -- Quote --
3562    -----------
3563
3564    function Quote (Str : String) return String is
3565       S    : String (1 .. Str'Length * 2);
3566       Last : Natural := 0;
3567
3568    begin
3569       for J in Str'Range loop
3570          case Str (J) is
3571             when '^' | '$' | '|' | '*' | '+' | '?' | '{' |
3572                  '}' | '[' | ']' | '(' | ')' | '\' | '.' =>
3573
3574                S (Last + 1) := '\';
3575                S (Last + 2) := Str (J);
3576                Last := Last + 2;
3577
3578             when others =>
3579                S (Last + 1) := Str (J);
3580                Last := Last + 1;
3581          end case;
3582       end loop;
3583
3584       return S (1 .. Last);
3585    end Quote;
3586
3587    ------------------
3588    -- Read_Natural --
3589    ------------------
3590
3591    function Read_Natural
3592      (Program : Program_Data;
3593       IP      : Pointer) return Natural
3594    is
3595    begin
3596       return Character'Pos (Program (IP)) +
3597                256 * Character'Pos (Program (IP + 1));
3598    end Read_Natural;
3599
3600    -----------------
3601    -- Reset_Class --
3602    -----------------
3603
3604    procedure Reset_Class (Bitmap : out Character_Class) is
3605    begin
3606       Bitmap := (others => 0);
3607    end Reset_Class;
3608
3609    ------------------
3610    -- Set_In_Class --
3611    ------------------
3612
3613    procedure Set_In_Class
3614      (Bitmap : in out Character_Class;
3615       C      : Character)
3616    is
3617       Value : constant Class_Byte := Character'Pos (C);
3618    begin
3619       Bitmap (Value / 8) := Bitmap (Value / 8)
3620         or Bit_Conversion (Value mod 8);
3621    end Set_In_Class;
3622
3623    -------------------
3624    -- String_Length --
3625    -------------------
3626
3627    function String_Length
3628      (Program : Program_Data;
3629       P       : Pointer) return Program_Size
3630    is
3631    begin
3632       pragma Assert (Program (P) = EXACT or else Program (P) = EXACTF);
3633       return Character'Pos (Program (P + 3));
3634    end String_Length;
3635
3636    --------------------
3637    -- String_Operand --
3638    --------------------
3639
3640    function String_Operand (P : Pointer) return Pointer is
3641    begin
3642       return P + 4;
3643    end String_Operand;
3644
3645 end System.Regpat;