Subject: Regexp, List Utils patch to the Moo Server

From: Clay Luther <[email-masked]>
Date: Thu, 6 Feb 1992 14:45:28 -0800

What follows is a shar file of the regular expression and list utils
additions we have made to the GodNet moo server.

The list utils additions are minor server optimizations.  However, the
regular expression primitives are important and valuable additions to the
moo server (imho ;)).

The regular expression primitives are based on Henry Spencer's regexp
library.

The GodNet moo server, gnoo, is also available via anonymous ftp from
morticia.cnns.unt.edu, /pub/mud.

----------- cut here
#! /bin/sh
# This is a shell archive.  Remove anything before this line, then unpack
# it by saving it into a file and typing "sh file".  To overwrite existing
# files, type "sh file -c".  You can also feed this as standard input via
# unshar, or by typing "sh <file", e.g..  If this archive is complete, you
# will see the following message at the end:
#		"End of shell archive."
# Contents:  README.gnoo REGEXP moo.patch regerror.c regexp.3 regexp.c
#   regexp.c.orig regexp.h regmagic.h regsub.c
# Wrapped by cluther@morticia on Thu Feb  6 16:40:55 1992
PATH=/bin:/usr/bin:/usr/ucb ; export PATH
if test -f 'README.gnoo' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'README.gnoo'\"
else
echo shar: Extracting \"'README.gnoo'\" \(1057 characters\)
sed "s/^X//" >'README.gnoo' <<'END_OF_FILE'
XThese are the current GodNet patches to the Moo server.  They include the 
Xaddition of the regular expression parser and substitution mechanism and a
Xthe addition of listassoc() and listiassoc() primitives.
X
XFor more information on the regular expression primitives, see the file
XREGEXP.
X
XListassoc() and listiassoc() implement the LambdaCore $list_utils verbs
Xassoc() and iassoc() in the server.  This was done since, in the GodNet at 
Xleast, we found that the $list_utils was a bottleneck.  Since assoc() and
Xiassoc() were used in over 130 verb calls, worked only an primitive datatypes,
Xand were demonstrably slow, we moved these functions to the server.  As a 
Xresult, we have seen a marked increase in many verbs, from the @mail suite to
Xthe player database. [We changed $list_utils:assoc() and :iassoc() to call the
Xprimitives for backward compatibility]
X
XIf you have any questions or suggestions, or if you find a bug, PLEASE send
Xemail to me.
X
XThanks.  And enjoy.
X
XClay Luther
[email-masked]
XMalraux@GodNet morticia.cnns.unt.edu 7777
END_OF_FILE
if test 1057 -ne `wc -c <'README.gnoo'`; then
    echo shar: \"'README.gnoo'\" unpacked with wrong size!
fi
# end of 'README.gnoo'
fi
if test -f 'REGEXP' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'REGEXP'\"
else
echo shar: Extracting \"'REGEXP'\" \(3428 characters\)
sed "s/^X//" >'REGEXP' <<'END_OF_FILE'
XREGEXP in MOO
X=============
X
XInstalled by Clay Luther
XFrom the regexp library written by Henry Spencer.
X
XVersion 1.5.9r of the server contains two additional functions, regexp() and
Xregsub().  This functions implement the Unix regular expression parser for Moo
Xprogrammers.  The full-range of regular expression parsing is brought to the 
XMoo programmer as a result.
X
X
X
XSYNTAX:
X
X  NUM regexp(STR regexpstr, STR string, [NUM case_matters])
X
X  regexp applies the regular expression found in regexpstr to string.  If a 
X  match is found, TRUE (1) is return, otherwise FALSE (0) is returned. (See 
X  the discussion of regular expressions that follows).
X
X  For example,
X
X  regexp(".* feels .*", "Malraux feels bad.") --> TRUE
X  regexp(".* feels .*", "Malraux eats bad carrots.") --> FALSE
X
X  The optional case_matters parameter is used to change the default behavior 
X  of the regular expression parser.  Normally, regexp() is case-insensitive.
X  If case_matters is non-zero (true), then regexp() performs a case-sensitive
X  parse.
X
X  STR regsub(STR regexp, STR string, STR pattern, [NUM case_matters])
X
X  regsub applies the regular expression found in regexpstr to string.  If a 
X  match is found, then a new string is created, using the substitution pattern
X  found in pattern.
X
X  The regexpstr must follow Unix regular expression rules for selecting 
X  pattern spaces.  That is, the pattern spaces you want to reference in the
X  pattern string must be surround by %( and %).  The pattern string deviates
X  slightly from standard Unix pattern space identification.  To identify a 
X  pattern space, you use % followed by a number, 1 to 9.  %0 returns the 
X  pattern space representing all matched strings.  (Normal Unix regexp 
X  requires a \ followed by a number to identify a pattern space.  Because the
X  Moo parser intercepts \, this would force the programmer to identify spaces
X  via \\n, which seemed unwieldy.)
X
X  If regsub() fails to match the regexpstr to string, a null string "" is 
X  returned.
X
X  For example,
X
X  regsub("(.*) feels (.*)%.", "Malraux feels bad.","Why do you feel %2, %1?")
X    --> "Why do you feel bad, Malraux?"
X
X  regsub("(.*) feels (.*)%.", "Malraux eats bad.","Why do you feel %2, %1?")
X    --> ""
X
X  NOTE:  In both cases, the ending punctuation period was "escaped" with %.
X
X
XREGULAR EXPRESSIONS and PATTERN MATCHING
X
XUnix has a rich and complicated definition of regular expressions.  
X
XPatterns may contain special characters:
X
X. == matches any single character.
X* == matches any number, including 0, of the single character, including .,
X     proceeding the *
X+ == matches *at least one* of the single character, include ., proceeding the
X     +
X[...] == matches any one character enclosed between [ and ]
X^ == requires the character to be at the beginning of the string
X$ == requires the proceeding character to be at the end of the string
X% == treat the next character as an ordinary character. (\\ in Moo)
X() == save the pattern enclosed between \( and \)
X%n == matches the nth pattern space
X& == prints the entire search pattern when used in replacement string.
X
XNOTE: Normal Unix regexp uses the \ character to escape regexp parsing.  Moo
X      regexp uses the % character instead.
X
X******************************************************************************
XMore information about regular expression pattern matching can be found in any
XUnix manual, or the BSD Unix in a Nutshell book.
END_OF_FILE
if test 3428 -ne `wc -c <'REGEXP'`; then
    echo shar: \"'REGEXP'\" unpacked with wrong size!
fi
# end of 'REGEXP'
fi
if test -f 'moo.patch' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'moo.patch'\"
else
echo shar: Extracting \"'moo.patch'\" \(15669 characters\)
sed "s/^X//" >'moo.patch' <<'END_OF_FILE'
Xdiff -c moo/ChangeLog.txt gnoo/ChangeLog.txt
X*** moo/ChangeLog.txt	Fri Dec  6 10:31:18 1991
X--- gnoo/ChangeLog.txt	Thu Feb  6 15:39:44 1992
X***************
X*** 377,379 ****
X--- 377,390 ----
X     either the movee or the destination.
X  -- Fixed several bugs in recycle() that could (and did!) corrupt the contents
X     hierarchy in the database.  The implementation is now much simpler, too!
X+ 
X+ Version 1.5.9r February 6th, 1992,
X+ by Clay Luther ([email-masked])
X+ 
X+ Completed the addition of the following primitives:
X+ 
X+   regexp()
X+   regsub()
X+   listassoc()
X+   listiassoc()
X+ 
Xdiff -c moo/Makefile gnoo/Makefile
X*** moo/Makefile	Fri Dec  6 10:30:40 1991
X--- gnoo/Makefile	Fri Jan 24 15:20:34 1992
X***************
X*** 89,101 ****
X  	chparent.c code_elt.c exceptions.c execute.c functions.c list.c log.c \
X  	malloc.c match.c parse_command.c program.c property.c quota.c \
X  	server.c storage.c streams.c tasks.c timers.c unparse.c utils.c \
X! 	vector.c version.c
X  
X  HDRS = bf_register.h bytecodes.h chparent.h code_elt.h config.h exceptions.h \
X  	execute.h functions.h getpagesize.h list.h log.h match.h network.h \
X  	opcode.h parse_command.h parser.h program.h property.h quota.h \
X  	random.h server.h streams.h structures.h tasks.h timers.h unparse.h \
X! 	utils.h vector.h version.h
X  
X  SYSHDRS = my-in.h my-ioctl.h my-signal.h my-socket.h my-stdarg.h my-stdio.h \
X  	my-stdlib.h my-string.h my-sys-time.h my-time.h my-types.h my-unistd.h
X--- 89,101 ----
X  	chparent.c code_elt.c exceptions.c execute.c functions.c list.c log.c \
X  	malloc.c match.c parse_command.c program.c property.c quota.c \
X  	server.c storage.c streams.c tasks.c timers.c unparse.c utils.c \
X! 	vector.c version.c regerror.c regexp.c regsub.c
X  
X  HDRS = bf_register.h bytecodes.h chparent.h code_elt.h config.h exceptions.h \
X  	execute.h functions.h getpagesize.h list.h log.h match.h network.h \
X  	opcode.h parse_command.h parser.h program.h property.h quota.h \
X  	random.h server.h streams.h structures.h tasks.h timers.h unparse.h \
X! 	utils.h vector.h version.h regmagic.h regexp.h
X  
X  SYSHDRS = my-in.h my-ioctl.h my-signal.h my-socket.h my-stdarg.h my-stdio.h \
X  	my-stdlib.h my-string.h my-sys-time.h my-time.h my-types.h my-unistd.h
X***************
X*** 176,184 ****
X    parse_command.h server.h network.h 
X  bf_num.o : bf_num.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h my-time.h random.h 
X! bf_obj.o : bf_obj.c functions.h structures.h my-stdio.h my-stdarg.h \
X!   bytecodes.h bf_register.h execute.h config.h opcode.h program.h list.h \
X!   utils.h chparent.h quota.h property.h server.h network.h 
X  bf_player.o : bf_player.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h list.h execute.h config.h opcode.h program.h \
X    server.h network.h 
X--- 176,184 ----
X    parse_command.h server.h network.h 
X  bf_num.o : bf_num.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h my-time.h random.h 
X! bf_obj.o : bf_obj.c chparent.h structures.h my-stdio.h my-stdarg.h \
X!   bytecodes.h execute.h config.h opcode.h program.h functions.h bf_register.h \
X!   list.h property.h quota.h server.h network.h utils.h 
X  bf_player.o : bf_player.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h list.h execute.h config.h opcode.h program.h \
X    server.h network.h 
X***************
X*** 187,193 ****
X  bf_server.o : bf_server.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h server.h network.h version.h 
X  bf_str_list.o : bf_str_list.c functions.h structures.h my-stdio.h \
X!   my-stdarg.h bytecodes.h bf_register.h list.h utils.h random.h my-string.h 
X  bf_task.o : bf_task.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h list.h tasks.h execute.h config.h opcode.h \
X    program.h 
X--- 187,194 ----
X  bf_server.o : bf_server.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h server.h network.h version.h 
X  bf_str_list.o : bf_str_list.c functions.h structures.h my-stdio.h \
X!   my-stdarg.h bytecodes.h bf_register.h list.h utils.h random.h my-string.h \
X!   regexp.h 
X  bf_task.o : bf_task.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h list.h tasks.h execute.h config.h opcode.h \
X    program.h 
X***************
X*** 257,262 ****
X--- 258,266 ----
X  vector.o : vector.c vector.h opcode.h code_elt.h my-stdarg.h my-string.h \
X    structures.h my-stdio.h bytecodes.h 
X  version.o : version.c version.h 
X+ regerror.o : regerror.c 
X+ regexp.o : regexp.c regexp.h regmagic.h 
X+ regsub.o : regsub.c regexp.h regmagic.h 
X  bi_create.po : bi_create.c match.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h property.h quota.h utils.h 
X  bf_move.po : bf_move.c my-stdio.h my-stdarg.h execute.h bytecodes.h config.h \
X***************
X*** 264,272 ****
X    parse_command.h server.h network.h 
X  bf_num.po : bf_num.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h my-time.h random.h 
X! bf_obj.po : bf_obj.c functions.h structures.h my-stdio.h my-stdarg.h \
X!   bytecodes.h bf_register.h execute.h config.h opcode.h program.h list.h \
X!   utils.h chparent.h quota.h property.h server.h network.h 
X  bf_player.po : bf_player.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h list.h execute.h config.h opcode.h program.h \
X    server.h network.h 
X--- 268,276 ----
X    parse_command.h server.h network.h 
X  bf_num.po : bf_num.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h my-time.h random.h 
X! bf_obj.po : bf_obj.c chparent.h structures.h my-stdio.h my-stdarg.h \
X!   bytecodes.h execute.h config.h opcode.h program.h functions.h bf_register.h \
X!   list.h property.h quota.h server.h network.h utils.h 
X  bf_player.po : bf_player.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h list.h execute.h config.h opcode.h program.h \
X    server.h network.h 
X***************
X*** 275,281 ****
X  bf_server.po : bf_server.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h server.h network.h version.h 
X  bf_str_list.po : bf_str_list.c functions.h structures.h my-stdio.h \
X!   my-stdarg.h bytecodes.h bf_register.h list.h utils.h random.h my-string.h 
X  bf_task.po : bf_task.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h list.h tasks.h execute.h config.h opcode.h \
X    program.h 
X--- 279,286 ----
X  bf_server.po : bf_server.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h server.h network.h version.h 
X  bf_str_list.po : bf_str_list.c functions.h structures.h my-stdio.h \
X!   my-stdarg.h bytecodes.h bf_register.h list.h utils.h random.h my-string.h \
X!   regexp.h 
X  bf_task.po : bf_task.c functions.h structures.h my-stdio.h my-stdarg.h \
X    bytecodes.h bf_register.h list.h tasks.h execute.h config.h opcode.h \
X    program.h 
X***************
X*** 345,347 ****
X--- 350,355 ----
X  vector.po : vector.c vector.h opcode.h code_elt.h my-stdarg.h my-string.h \
X    structures.h my-stdio.h bytecodes.h 
X  version.po : version.c version.h 
X+ regerror.po : regerror.c 
X+ regexp.po : regexp.c regexp.h regmagic.h 
X+ regsub.po : regsub.c regexp.h regmagic.h 
XOnly in gnoo: REGEXP
Xdiff -c moo/bf_str_list.c gnoo/bf_str_list.c
X*** moo/bf_str_list.c	Fri Aug  9 13:41:38 1991
X--- gnoo/bf_str_list.c	Mon Jan 27 17:21:32 1992
X***************
X*** 3,9 ****
X--- 3,13 ----
X  #include "utils.h" /* strsub, strindex, strrindex */
X  #include "random.h" /* RANDOM() in crypt */
X  #include "my-string.h" /* strlen, strcmp */
X+ /* CWL include for regular expression */
X+ #include "regexp.h"
X+ #include "streams.h"
X  
X+ 
X  /* crypt */
X  extern const char  *crypt(const char *, const char *); /* BSDism */
X  
X***************
X*** 115,120 ****
X--- 119,170 ----
X    return make_var_pack(r);
X  }
X  
X+ /* CWL bf_listassoc additions */
X+ 
X+ static package
X+ bf_listiassoc(Var arglist, Byte next, void *vdata, Parse_Info *pi)
X+ {
X+   Var r;
X+   int index = 1;
X+ 
X+   r.type = TYPE_NUM;
X+   if (arglist.v.list[0].v.num == 3)
X+     index = arglist.v.list[3].v.num;
X+ 
X+   if (index<1) {
X+     free_var(arglist);
X+     return make_error_pack(E_RANGE);
X+   }
X+ 
X+   r.v.num = listiassoc(arglist.v.list[1],arglist.v.list[2],index);
X+ 
X+   free_var(arglist);
X+   return make_var_pack(r);
X+ } /* end listiassoc */
X+ 
X+ 
X+ static package
X+ bf_listassoc(Var arglist, Byte next, void *vdata, Parse_Info *pi)
X+ {
X+   Var r;
X+   int index = 1;
X+ 
X+   if (arglist.v.list[0].v.num==3)
X+     index = arglist.v.list[3].v.num;
X+ 
X+   if (index<1) {
X+     free_var(arglist);
X+     return make_error_pack(E_RANGE);
X+   }
X+ 
X+   r = listassoc(arglist.v.list[1], arglist.v.list[2], index);
X+ 
X+   free_var(arglist);
X+   return make_var_pack(r);
X+ } /* end CWL bf_listassoc */
X+ 
X+ 
X+ 
X  /* 5 functions specific to str */
X  
X  static package
X***************
X*** 157,163 ****
X--- 207,279 ----
X    return make_var_pack(r);
X  }
X  
X+ /* CWL regular expression parse */
X  static package
X+   bf_regexp(Var arglist, Byte next, void *vdata, Parse_Info *pi)
X+ {
X+   /* regexp(string1, string2) */
X+   Var r;
X+   regexp *reg;
X+   int case_matters = 0;
X+   extern void free();
X+ 
X+   if (arglist.v.list[0].v.num == 3)
X+     case_matters = arglist.v.list[3].v.num;
X+   r.type = TYPE_NUM;
X+ 
X+   reg = regcomp(arglist.v.list[1].v.str);
X+   if (reg) {
X+     r.v.num = regexec(reg, arglist.v.list[2].v.str,case_matters);
X+     free(reg);
X+   }
X+   else {
X+     r.v.num = 0;
X+   }
X+   free_var(arglist);
X+   return make_var_pack(r);
X+ } /* end CWL bf_regexp */
X+ 
X+ /* CWL regular expression sub */
X+ static package
X+   bf_regsub(Var arglist, Byte next, void *vdata, Parse_Info *pi)
X+ {
X+   Var r;
X+   regexp *reg;
X+   Stream *astream;
X+   int case_matters = 0;
X+   extern void free();
X+ 
X+   if (arglist.v.list[0].v.num == 4)
X+     case_matters = arglist.v.list[4].v.num;
X+   r.type = TYPE_STR;
X+   reg = regcomp(arglist.v.list[1].v.str);
X+   if (reg) {
X+ 
X+     if (regexec(reg, arglist.v.list[2].v.str,case_matters)) {
X+ 
X+         astream = new_stream(512);
X+         regsub(reg, arglist.v.list[3].v.str, astream);
X+         r.v.str = strdup(stream_contents(astream));
X+ 	free_stream(astream);
X+     }
X+ 
X+     else { /* no regular expression found */
X+       r.v.str = strdup("");
X+     } /* end if regexec else */
X+ 
X+     free(reg); /* Clean up some */
X+   } /* end if reg */
X+ 
X+   else {
X+     r.v.str = strdup("");
X+   } /* end if reg else */
X+ 
X+   free_var(arglist);
X+   return make_var_pack(r);
X+ } /* end CWL bf_regsub */
X+ 
X+ 
X+ static package
X    bf_strcmp(Var arglist, Byte next, void *vdata, Parse_Info *pi)
X  { /* (string1, string2) */
X    Var r;
X***************
X*** 230,235 ****
X--- 346,360 ----
X      = {"strcmp", 2, 2, {TYPE_STR, TYPE_STR}, bf_strcmp};
X    static struct bft_entry bft12 
X      = {"strsub", 3, 4, {TYPE_STR, TYPE_STR, TYPE_STR, TYPE_NUM}, bf_strsub};
X+   /* CWL regexp additions */
X+   static struct bft_entry bft13
X+     = {"regexp", 2, 3, {TYPE_STR, TYPE_STR, TYPE_NUM}, bf_regexp};
X+   static struct bft_entry bft14
X+     = {"regsub", 3, 4, {TYPE_STR, TYPE_STR, TYPE_STR, TYPE_NUM}, bf_regsub};
X+   static struct bft_entry bft15
X+     = {"listassoc", 2, 3, {TYPE_ANY, TYPE_LIST, TYPE_NUM}, bf_listassoc};
X+   static struct bft_entry bft16
X+     = {"listiassoc", 2, 3, {TYPE_ANY, TYPE_LIST, TYPE_NUM}, bf_listiassoc};
X  
X    register_function(bft1);
X    register_function(bft2);
X***************
X*** 243,246 ****
X--- 368,376 ----
X    register_function(bft10);
X    register_function(bft11);
X    register_function(bft12);
X+   /* CWL regexp additions */
X+   register_function(bft13);
X+   register_function(bft14);
X+   register_function(bft15);
X+   register_function(bft16);
X  }
Xdiff -c moo/config.h gnoo/config.h
X*** moo/config.h	Mon Nov 18 16:15:25 1991
X--- gnoo/config.h	Sat Jan 25 11:33:29 1992
X***************
X*** 7,18 ****
X  #define MAX_VERB_DEPTH		50	/* max. number of nested verb calls */
X  
X  				/* max. number of eval() calls */
X! #define FG_TICKS		30000	/* ... foreground tasks */
X! #define BG_TICKS		15000	/* ... background tasks */
X  
X  				/* how long in real time it can run */
X! #define FG_SECONDS		15	/* ... foreground tasks */
X! #define BG_SECONDS		5	/* ... background tasks */
X  
X  /* Objid on which several magic properties are to be found. */
X  #define SYSTEM_OBJECT 0
X--- 7,18 ----
X  #define MAX_VERB_DEPTH		50	/* max. number of nested verb calls */
X  
X  				/* max. number of eval() calls */
X! #define FG_TICKS		90000 /*30000*/	/* ... foreground tasks */
X! #define BG_TICKS		45000 /*15000*/	/* ... background tasks */
X  
X  				/* how long in real time it can run */
X! #define FG_SECONDS		45 /*15*/	/* ... foreground tasks */
X! #define BG_SECONDS		15 /*5*/	/* ... background tasks */
X  
X  /* Objid on which several magic properties are to be found. */
X  #define SYSTEM_OBJECT 0
Xdiff -c moo/list.c gnoo/list.c
X*** moo/list.c	Sun Aug  4 15:29:57 1991
X--- gnoo/list.c	Mon Jan 27 17:22:44 1992
X***************
X*** 148,153 ****
X--- 148,187 ----
X      }
X  }
X  
X+ /* CWL assoc addition */
X+ Var
X+ listassoc(Var vtarget, Var vlist, int vindex)
X+ {
X+   int i;
X+ 
X+   for (i=1; i<=vlist.v.list[0].v.num; i++) {
X+     if (vlist.v.list[i].type == TYPE_LIST &&
X+ 	vlist.v.list[i].v.list[0].v.num >= vindex &&
X+ 	equality(vlist.v.list[i].v.list[vindex], vtarget)) {
X+        
X+        return (vardup(vlist.v.list[i]));
X+     }
X+   }
X+   return (new_list(0));
X+ } /* end CWL listassoc */
X+ 
X+ int
X+ listiassoc(Var vtarget, Var vlist, int vindex)
X+ { 
X+   int i;
X+ 
X+   for (i=1; i<=vlist.v.list[0].v.num; i++) {
X+     if (vlist.v.list[i].type == TYPE_LIST &&
X+         vlist.v.list[i].v.list[0].v.num >= vindex &&
X+         equality(vlist.v.list[i].v.list[vindex], vtarget)) {
X+        
X+        return i;
X+     }      
X+   } 
X+   return 0;
X+ } /* end CWL listiassoc */
X+ 
X+ 
X  Var
X  substr(Var str, int lower, int upper)
X  {
Xdiff -c moo/list.h gnoo/list.h
X*** moo/list.h	Sun Aug  4 15:27:31 1991
X--- gnoo/list.h	Mon Jan 27 17:19:17 1992
X***************
X*** 12,14 ****
X--- 12,17 ----
X  extern Var  substr(Var str, int lower, int upper);
X  extern Var  strget(Var str, Var i);
X  extern Var  new_list(int size);
X+ /* CWL list assoc additions */
X+ extern Var  listassoc(Var vtarget, Var vlist, int vindex);
X+ extern int  listiassoc(Var vtarget, Var vlist, int vindex);
XOnly in gnoo: list:assoc
XOnly in gnoo: reg
XOnly in gnoo: regerror.c
XOnly in gnoo: regexp.3
XOnly in gnoo: regexp.c
XOnly in gnoo: regexp.c.orig
XOnly in gnoo: regexp.h
XOnly in gnoo: regmagic.h
XOnly in gnoo: regsub.c
XOnly in gnoo: strcmp.grep
Xdiff -c moo/utils.c gnoo/utils.c
X*** moo/utils.c	Tue Aug 20 18:15:15 1991
X--- gnoo/utils.c	Sun Jan 26 02:10:56 1992
X***************
X*** 33,38 ****
X--- 33,56 ----
X  \340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\
X  \360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377";
X  
X+ 
X+ char *
X+ mystrcasechr(register char *s, register char t) /* CWL */
X+ {
X+   register char *c = cmap;
X+   register char *sp;
X+   register char ct;
X+ 
X+   sp = s;
X+   ct = c[t];
X+   while (*sp) {
X+     if (c[*sp]==ct)
X+       return sp;
X+     sp++;
X+   }
X+   return NULL;
X+ } /* end CWL */
X+ 
X  #ifndef STRCASE
X  int
X  mystrcasecmp(register const char *s, register const char *t)
Xdiff -c moo/version.c gnoo/version.c
X*** moo/version.c	Thu Dec  5 18:55:20 1991
X--- gnoo/version.c	Fri Jan 24 17:32:05 1992
X***************
X*** 22,25 ****
X  
X  #include "version.h"
X  
X! const char     *server_version = "1.5.9";
X--- 22,25 ----
X  
X  #include "version.h"
X  
X! const char     *server_version = "1.5.9r";
END_OF_FILE
if test 15669 -ne `wc -c <'moo.patch'`; then
    echo shar: \"'moo.patch'\" unpacked with wrong size!
fi
# end of 'moo.patch'
fi
if test -f 'regerror.c' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'regerror.c'\"
else
echo shar: Extracting \"'regerror.c'\" \(260 characters\)
sed "s/^X//" >'regerror.c' <<'END_OF_FILE'
X#include "regexp.h" /* CWL */
X#include <stdio.h>
X
Xvoid
Xregerror(s)
Xconst char *s;
X{
X#ifdef ERRAVAIL
X	error("regexp: %s", s);
X#else
X/*
X	fprintf(stderr, "regexp(3): %s\n", s);
X	exit(1);
X*/
X	return;	  /* let std. egrep handle errors */
X#endif
X	/* NOTREACHED */
X}
END_OF_FILE
if test 260 -ne `wc -c <'regerror.c'`; then
    echo shar: \"'regerror.c'\" unpacked with wrong size!
fi
# end of 'regerror.c'
fi
if test -f 'regexp.3' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'regexp.3'\"
else
echo shar: Extracting \"'regexp.3'\" \(8935 characters\)
sed "s/^X//" >'regexp.3' <<'END_OF_FILE'
X.\" Copyright 1991 The Regents of the University of California.
X.\" All rights reserved.
X.\"
X.\" Redistribution and use in source and binary forms, with or without
X.\" modification, are permitted provided that the following conditions
X.\" are met:
X.\" 1. Redistributions of source code must retain the above copyright
X.\"    notice, this list of conditions and the following disclaimer.
X.\" 2. Redistributions in binary form must reproduce the above copyright
X.\"    notice, this list of conditions and the following disclaimer in the
X.\"    documentation and/or other materials provided with the distribution.
X.\" 3. All advertising materials mentioning features or use of this software
X.\"    must display the following acknowledgement:
X.\"	This product includes software developed by the University of
X.\"	California, Berkeley and its contributors.
X.\" 4. Neither the name of the University nor the names of its contributors
X.\"    may be used to endorse or promote products derived from this software
X.\"    without specific prior written permission.
X.\"
X.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
X.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
X.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
X.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
X.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
X.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
X.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
X.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
X.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
X.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
X.\" SUCH DAMAGE.
X.\"
X.\"     @(#)regexp.3	5.2 (Berkeley) 4/20/91
X.\"
X.Dd April 20, 1991
X.Dt REGEXP 3
X.Os
X.Sh NAME
X.Nm regcomp ,
X.Nm regexec ,
X.Nm regsub ,
X.Nm regerror
X.Nd regular expression handlers
X.Sh SYNOPSIS
X.Fd #include <regexp.h>
X.Ft regexp *
X.Fn regcomp "const char *exp"
X.Ft int
X.Fn regexec "const regexp *prog" "const char *string"
X.Ft void
X.Fn regsub "const regexp *prog" "const char *source" "char *dest"
X.Sh DESCRIPTION
XThe
X.Fn regcomp ,
X.Fn regexec ,
X.Fn regsub ,
Xand
X.Fn regerror
Xfunctions
Ximplement
X.Xr egrep 1 Ns -style
Xregular expressions and supporting facilities.
X.Pp
XThe
X.Fn regcomp
Xfunction
Xcompiles a regular expression into a structure of type
X.Xr regexp ,
Xand returns a pointer to it.
XThe space has been allocated using
X.Xr malloc 3
Xand may be released by
X.Xr free .
X.Pp
XThe
X.Fn regexec
Xfunction
Xmatches a
X.Dv NUL Ns -terminated
X.Fa string
Xagainst the compiled regular expression
Xin
X.Fa prog .
XIt returns 1 for success and 0 for failure, and adjusts the contents of
X.Fa prog Ns 's
X.Em startp
Xand
X.Em endp
X(see below) accordingly.
X.Pp
XThe members of a
X.Xr regexp
Xstructure include at least the following (not necessarily in order):
X.Bd -literal -offset indent
Xchar *startp[NSUBEXP];
Xchar *endp[NSUBEXP];
X.Ed
X.Pp
Xwhere
X.Dv NSUBEXP
Xis defined (as 10) in the header file.
XOnce a successful
X.Fn regexec
Xhas been done using the
X.Fn regexp ,
Xeach
X.Em startp Ns - Em endp
Xpair describes one substring
Xwithin the
X.Fa string ,
Xwith the
X.Em startp
Xpointing to the first character of the substring and
Xthe
X.Em endp
Xpointing to the first character following the substring.
XThe 0th substring is the substring of
X.Fa string
Xthat matched the whole
Xregular expression.
XThe others are those substrings that matched parenthesized expressions
Xwithin the regular expression, with parenthesized expressions numbered
Xin left-to-right order of their opening parentheses.
X.Pp
XThe
X.Fn regsub
Xfunction
Xcopies
X.Fa source
Xto
X.Fa dest ,
Xmaking substitutions according to the
Xmost recent
X.Fn regexec
Xperformed using
X.Fa prog .
XEach instance of `&' in
X.Fa source
Xis replaced by the substring
Xindicated by
X.Em startp Ns Bq
Xand
X.Em endp Ns Bq .
XEach instance of
X.Sq \e Ns Em n ,
Xwhere
X.Em n
Xis a digit, is replaced by
Xthe substring indicated by
X.Em startp Ns Bq Em n
Xand
X.Em endp Ns Bq Em n .
XTo get a literal `&' or
X.Sq \e Ns Em n
Xinto
X.Fa dest ,
Xprefix it with `\e';
Xto get a literal `\e' preceding `&' or
X.Sq \e Ns Em n ,
Xprefix it with
Xanother `\e'.
X.Pp
XThe
X.Fn regerror
Xfunction
Xis called whenever an error is detected in
X.Fn regcomp ,
X.Fn regexec ,
Xor
X.Fn regsub .
XThe default
X.Fn regerror
Xwrites the string
X.Fa msg ,
Xwith a suitable indicator of origin,
Xon the standard
Xerror output
Xand invokes
X.Xr exit 2 .
XThe
X.Fn regerror
Xfunction
Xcan be replaced by the user if other actions are desirable.
X.Sh REGULAR EXPRESSION SYNTAX
XA regular expression is zero or more
X.Em branches ,
Xseparated by `|'.
XIt matches anything that matches one of the branches.
X.Pp
XA branch is zero or more
X.Em pieces ,
Xconcatenated.
XIt matches a match for the first, followed by a match for the second, etc.
X.Pp
XA piece is an
X.Em atom
Xpossibly followed by `*', `+', or `?'.
XAn atom followed by `*' matches a sequence of 0 or more matches of the atom.
XAn atom followed by `+' matches a sequence of 1 or more matches of the atom.
XAn atom followed by `?' matches a match of the atom, or the null string.
X.Pp
XAn atom is a regular expression in parentheses (matching a match for the
Xregular expression), a
X.Em range
X(see below), `.'
X(matching any single character), `^' (matching the null string at the
Xbeginning of the input string), `$' (matching the null string at the
Xend of the input string), a `\e' followed by a single character (matching
Xthat character), or a single character with no other significance
X(matching that character).
X.Pp
XA
X.Em range
Xis a sequence of characters enclosed in `[]'.
XIt normally matches any single character from the sequence.
XIf the sequence begins with `^',
Xit matches any single character
X.Em not
Xfrom the rest of the sequence.
XIf two characters in the sequence are separated by `\-', this is shorthand
Xfor the full list of
X.Tn ASCII
Xcharacters between them
X(e.g. `[0-9]' matches any decimal digit).
XTo include a literal `]' in the sequence, make it the first character
X(following a possible `^').
XTo include a literal `\-', make it the first or last character.
X.Sh AMBIGUITY
XIf a regular expression could match two different parts of the input string,
Xit will match the one which begins earliest.
XIf both begin in the same place but match different lengths, or match
Xthe same length in different ways, life gets messier, as follows.
X.Pp
XIn general, the possibilities in a list of branches are considered in
Xleft-to-right order, the possibilities for `*', `+', and `?' are
Xconsidered longest-first, nested constructs are considered from the
Xoutermost in, and concatenated constructs are considered leftmost-first.
XThe match that will be chosen is the one that uses the earliest
Xpossibility in the first choice that has to be made.
XIf there is more than one choice, the next will be made in the same manner
X(earliest possibility) subject to the decision on the first choice.
XAnd so forth.
X.Pp
XFor example,
X.Sq Li (ab|a)b*c
Xcould match
X`abc' in one of two ways.
XThe first choice is between `ab' and `a'; since `ab' is earlier, and does
Xlead to a successful overall match, it is chosen.
XSince the `b' is already spoken for,
Xthe `b*' must match its last possibility\(emthe empty string\(emsince
Xit must respect the earlier choice.
X.Pp
XIn the particular case where no `|'s are present and there is only one
X`*', `+', or `?', the net effect is that the longest possible
Xmatch will be chosen.
XSo
X.Sq Li ab* ,
Xpresented with `xabbbby', will match `abbbb'.
XNote that if
X.Sq Li ab* ,
Xis tried against `xabyabbbz', it
Xwill match `ab' just after `x', due to the begins-earliest rule.
X(In effect, the decision on where to start the match is the first choice
Xto be made, hence subsequent choices must respect it even if this leads them
Xto less-preferred alternatives.)
X.Sh RETURN VALUES
XThe
X.Fn regcomp
Xfunction
Xreturns
X.Dv NULL
Xfor a failure
X.Pf ( Fn regerror
Xpermitting),
Xwhere failures are syntax errors, exceeding implementation limits,
Xor applying `+' or `*' to a possibly-null operand.
X.Sh SEE ALSO
X.Xr ed 1 ,
X.Xr ex 1 ,
X.Xr expr 1 ,
X.Xr egrep 1 ,
X.Xr fgrep 1 ,
X.Xr grep 1 ,
X.Xr regex 3
X.Sh HISTORY
XBoth code and manual page for
X.Fn regcomp ,
X.Fn regexec ,
X.Fn regsub ,
Xand
X.Fn regerror
Xwere written at the University of Toronto
Xand appeared in
X.Bx 4.3 tahoe .
XThey are intended to be compatible with the Bell V8
X.Xr regexp 3 ,
Xbut are not derived from Bell code.
X.Sh BUGS
XEmpty branches and empty regular expressions are not portable to V8.
X.Pp
XThe restriction against
Xapplying `*' or `+' to a possibly-null operand is an artifact of the
Xsimplistic implementation.
X.Pp
XDoes not support
X.Xr egrep Ns 's
Xnewline-separated branches;
Xneither does the V8
X.Xr regexp 3 ,
Xthough.
X.Pp
XDue to emphasis on
Xcompactness and simplicity,
Xit's not strikingly fast.
XIt does give special attention to handling simple cases quickly.
END_OF_FILE
if test 8935 -ne `wc -c <'regexp.3'`; then
    echo shar: \"'regexp.3'\" unpacked with wrong size!
fi
# end of 'regexp.3'
fi
if test -f 'regexp.c' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'regexp.c'\"
else
echo shar: Extracting \"'regexp.c'\" \(31972 characters\)
sed "s/^X//" >'regexp.c' <<'END_OF_FILE'
X/*
X * regcomp and regexec -- regsub and regerror are elsewhere
X *
X *	Copyright (c) 1986 by University of Toronto.
X *	Written by Henry Spencer.  Not derived from licensed software.
X *
X *	Permission is granted to anyone to use this software for any
X *	purpose on any computer system, and to redistribute it freely,
X *	subject to the following restrictions:
X *
X *	1. The author is not responsible for the consequences of use of
X *		this software, no matter how awful, even if they arise
X *		from defects in it.
X *
X *	2. The origin of this software must not be misrepresented, either
X *		by explicit claim or by omission.
X *
X *	3. Altered versions must be plainly marked as such, and must not
X *		be misrepresented as being the original software.
X *** THIS IS AN ALTERED VERSION.  It was altered by John Gilmore,
X *** hoptoad!gnu, on 27 Dec 1986, to add \n as an alternative to |
X *** to assist in implementing egrep.
X *** THIS IS AN ALTERED VERSION.  It was altered by John Gilmore,
X *** hoptoad!gnu, on 27 Dec 1986, to add \< and \> for word-matching
X *** as in BSD grep and ex.
X *** THIS IS AN ALTERED VERSION.  It was altered by John Gilmore,
X *** hoptoad!gnu, on 28 Dec 1986, to optimize characters quoted with \.
X *** THIS IS AN ALTERED VERSION.  It was altered by James A. Woods,
X *** ames!jaw, on 19 June 1987, to quash a regcomp() redundancy.
X *** THIS CODE HAS BEEN CHANGED TO WORK WITH MOO by Clay Luther,
X *** January 24, 1992.
X *
X * Beware that some of this code is subtly aware of the way operator
X * precedence is structured in regular expressions.  Serious changes in
X * regular-expression syntax might require a total rethink.
X */
X
X/* Changes by CWL for moo */
X
X#include "regexp.h" /* CWL */
X#include <stdio.h>
X#include <ctype.h>
X#include <stdlib.h>
X#include <string.h>
X#include "regmagic.h"
X#include <ctype.h> /* CWL */
X
X/*
X * The "internal use only" fields in regexp.h are present to pass info from
X * compile to execute that permits the execute phase to run lots faster on
X * simple cases.  They are:
X *
X * regstart	char that must begin a match; '\0' if none obvious
X * reganch	is the match anchored (at beginning-of-line only)?
X * regmust	string (pointer into program) that match must include, or NULL
X * regmlen	length of regmust string
X *
X * Regstart and reganch permit very fast decisions on suitable starting points
X * for a match, cutting down the work a lot.  Regmust permits fast rejection
X * of lines that cannot possibly match.  The regmust tests are costly enough
X * that regcomp() supplies a regmust only if the r.e. contains something
X * potentially expensive (at present, the only such thing detected is * or +
X * at the start of the r.e., which can involve a lot of backup).  Regmlen is
X * supplied because the test in regexec() needs it and regcomp() is computing
X * it anyway.
X */
X
X/*
X * Structure for regexp "program".  This is essentially a linear encoding
X * of a nondeterministic finite-state machine (aka syntax charts or
X * "railroad normal form" in parsing technology).  Each node is an opcode
X * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
X * all nodes except BRANCH implement concatenation; a "next" pointer with
X * a BRANCH on both ends of it is connecting two alternatives.  (Here we
X * have one of the subtle syntax dependencies:  an individual BRANCH (as
X * opposed to a collection of them) is never concatenated with anything
X * because of operator precedence.)  The operand of some types of node is
X * a literal string; for others, it is a node leading into a sub-FSM.  In
X * particular, the operand of a BRANCH node is the first node of the branch.
X * (NB this is *not* a tree structure:  the tail of the branch connects
X * to the thing following the set of BRANCHes.)  The opcodes are:
X */
X
X/* definition	number	opnd?	meaning */
X#define	END	0	/* no	End of program. */
X#define	BOL	1	/* no	Match "" at beginning of line. */
X#define	EOL	2	/* no	Match "" at end of line. */
X#define	ANY	3	/* no	Match any one character. */
X#define	ANYOF	4	/* str	Match any character in this string. */
X#define	ANYBUT	5	/* str	Match any character not in this string. */
X#define	BRANCH	6	/* node	Match this alternative, or the next... */
X#define	BACK	7	/* no	Match "", "next" ptr points backward. */
X#define	EXACTLY	8	/* str	Match this string. */
X#define	NOTHING	9	/* no	Match empty string. */
X#define	STAR	10	/* node	Match this (simple) thing 0 or more times. */
X#define	PLUS	11	/* node	Match this (simple) thing 1 or more times. */
X#define	WORDA	12	/* no	Match "" at wordchar, where prev is nonword */
X#define	WORDZ	13	/* no	Match "" at nonwordchar, where prev is word */
X#define	OPEN	20	/* no	Mark this point in input as start of #n. */
X			/*	OPEN+1 is number 1, etc. */
X#define	CLOSE	30	/* no	Analogous to OPEN. */
X
X/*
X * Opcode notes:
X *
X * BRANCH	The set of branches constituting a single choice are hooked
X *		together with their "next" pointers, since precedence prevents
X *		anything being concatenated to any individual branch.  The
X *		"next" pointer of the last BRANCH in a choice points to the
X *		thing following the whole choice.  This is also where the
X *		final "next" pointer of each individual branch points; each
X *		branch starts with the operand node of a BRANCH node.
X *
X * BACK		Normal "next" pointers all implicitly point forward; BACK
X *		exists to make loop structures possible.
X *
X * STAR,PLUS	'?', and complex '*' and '+', are implemented as circular
X *		BRANCH structures using BACK.  Simple cases (one character
X *		per match) are implemented with STAR and PLUS for speed
X *		and to minimize recursive plunges.
X *
X * OPEN,CLOSE	...are numbered at compile time.
X */
X
X/*
X * A node is one char of opcode followed by two chars of "next" pointer.
X * "Next" pointers are stored as two 8-bit pieces, high order first.  The
X * value is a positive offset from the opcode of the node containing it.
X * An operand, if any, simply follows the node.  (Note that much of the
X * code generation knows about this implicit relationship.)
X *
X * Using two bytes for the "next" pointer is vast overkill for most things,
X * but allows patterns to get big without disasters.
X */
X#define	OP(p)	(*(p))
X#define	NEXT(p)	(((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
X#define	OPERAND(p)	((p) + 3)
X
X/*
X * See regmagic.h for one further detail of program structure.
X */
X
X
X/*
X * Utility definitions.
X */
X#ifndef CHARBITS
X#define	UCHARAT(p)	((int)*(unsigned char *)(p))
X#else
X#define	UCHARAT(p)	((int)*(p)&CHARBITS)
X#endif
X
X#define	FAIL(m)	{ regerror(m); return(NULL); }
X#define	ISMULT(c)	((c) == '*' || (c) == '+' || (c) == '?')
X
X/*
X * Flags to be passed up and down.
X */
X#define	HASWIDTH	01	/* Known never to match null string. */
X#define	SIMPLE		02	/* Simple enough to be STAR/PLUS operand. */
X#define	SPSTART		04	/* Starts with * or +. */
X#define	WORST		0	/* Worst case. */
X
X/*
X * Global work variables for regcomp().
X */
Xstatic char *regparse;		/* Input-scan pointer. */
Xstatic int regnpar;		/* () count. */
Xstatic char regdummy;
Xstatic char *regcode;		/* Code-emit pointer; &regdummy = don't. */
Xstatic long regsize;		/* Code size. */
X
X/*
X * Forward declarations for regcomp()'s friends.
X */
X#ifndef STATIC
X#define	STATIC	static
X#endif
XSTATIC char *reg();
XSTATIC char *regbranch();
XSTATIC char *regpiece();
XSTATIC char *regatom();
XSTATIC char *regnode();
XSTATIC char *regnext();
XSTATIC void regc();
XSTATIC void reginsert();
XSTATIC void regtail();
XSTATIC void regoptail();
X#ifdef STRCSPN
XSTATIC int strcspn();
X#endif
X
X/*
X - regcomp - compile a regular expression into internal code
X *
X * We can't allocate space until we know how big the compiled form will be,
X * but we can't compile it (and thus know how big it is) until we've got a
X * place to put the code.  So we cheat:  we compile it twice, once with code
X * generation turned off and size counting turned on, and once "for real".
X * This also means that we don't allocate space until we are sure that the
X * thing really will compile successfully, and we never have to move the
X * code and thus invalidate pointers into it.  (Note that it has to be in
X * one piece because free() must be able to free it all.)
X *
X * Beware that the optimization-preparation code in here knows about some
X * of the structure of the compiled regexp.
X */
Xregexp *
Xregcomp(exp)
Xconst char *exp;
X{
X	register regexp *r;
X	register char *scan;
X	register char *longest;
X	register int len;
X	int flags;
X
X	if (exp == NULL)
X		FAIL("NULL argument");
X
X	/* First pass: determine size, legality. */
X#ifdef notdef
X	if (exp[0] == '.' && exp[1] == '*') exp += 2;  /* aid grep */
X#endif
X	regparse = (char *)exp;
X	regnpar = 1;
X	regsize = 0L;
X	regcode = &regdummy;
X	regc(MAGIC);
X	if (reg(0, &flags) == NULL)
X		return(NULL);
X
X	/* Small enough for pointer-storage convention? */
X	if (regsize >= 32767L)		/* Probably could be 65535L. */
X		FAIL("regexp too big");
X
X	/* Allocate space. */
X	r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
X	if (r == NULL)
X		FAIL("out of space");
X
X	/* Second pass: emit code. */
X	regparse = (char *)exp;
X	regnpar = 1;
X	regcode = r->program;
X	regc(MAGIC);
X	if (reg(0, &flags) == NULL)
X		return(NULL);
X
X	/* Dig out information for optimizations. */
X	r->regstart = '\0';	/* Worst-case defaults. */
X	r->reganch = 0;
X	r->regmust = NULL;
X	r->regmlen = 0;
X	scan = r->program+1;			/* First BRANCH. */
X	if (OP(regnext(scan)) == END) {		/* Only one top-level choice. */
X		scan = OPERAND(scan);
X
X		/* Starting-point info. */
X		if (OP(scan) == EXACTLY)
X			r->regstart = *OPERAND(scan);
X		else if (OP(scan) == BOL)
X			r->reganch++;
X
X		/*
X		 * If there's something expensive in the r.e., find the
X		 * longest literal string that must appear and make it the
X		 * regmust.  Resolve ties in favor of later strings, since
X		 * the regstart check works with the beginning of the r.e.
X		 * and avoiding duplication strengthens checking.  Not a
X		 * strong reason, but sufficient in the absence of others.
X		 */
X		if (flags&SPSTART) {
X			longest = NULL;
X			len = 0;
X			for (; scan != NULL; scan = regnext(scan))
X				if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
X					longest = OPERAND(scan);
X					len = strlen(OPERAND(scan));
X				}
X			r->regmust = longest;
X			r->regmlen = len;
X		}
X	}
X
X	return(r);
X}
X
X/*
X - reg - regular expression, i.e. main body or parenthesized thing
X *
X * Caller must absorb opening parenthesis.
X *
X * Combining parenthesis handling with the base level of regular expression
X * is a trifle forced, but the need to tie the tails of the branches to what
X * follows makes it hard to avoid.
X */
Xstatic char *
Xreg(paren, flagp)
Xint paren;			/* Parenthesized? */
Xint *flagp;
X{
X	register char *ret;
X	register char *br;
X	register char *ender;
X	register int parno = 0;
X	int flags;
X
X	*flagp = HASWIDTH;	/* Tentatively. */
X
X	/* Make an OPEN node, if parenthesized. */
X	if (paren) {
X		if (regnpar >= NSUBEXP)
X			FAIL("too many ()");
X		parno = regnpar;
X		regnpar++;
X		ret = regnode(OPEN+parno);
X	} else
X		ret = NULL;
X
X	/* Pick up the branches, linking them together. */
X	br = regbranch(&flags);
X	if (br == NULL)
X		return(NULL);
X	if (ret != NULL)
X		regtail(ret, br);	/* OPEN -> first. */
X	else
X		ret = br;
X	if (!(flags&HASWIDTH))
X		*flagp &= ~HASWIDTH;
X	*flagp |= flags&SPSTART;
X	while (*regparse == '|' || *regparse == '\n') {
X		regparse++;
X		br = regbranch(&flags);
X		if (br == NULL)
X			return(NULL);
X		regtail(ret, br);	/* BRANCH -> BRANCH. */
X		if (!(flags&HASWIDTH))
X			*flagp &= ~HASWIDTH;
X		*flagp |= flags&SPSTART;
X	}
X
X	/* Make a closing node, and hook it on the end. */
X	ender = regnode((paren) ? CLOSE+parno : END);	
X	regtail(ret, ender);
X
X	/* Hook the tails of the branches to the closing node. */
X	for (br = ret; br != NULL; br = regnext(br))
X		regoptail(br, ender);
X
X	/* Check for proper termination. */
X	if (paren && *regparse++ != ')') {
X		FAIL("unmatched ()");
X	} else if (!paren && *regparse != '\0') {
X		if (*regparse == ')') {
X			FAIL("unmatched ()");
X		} else
X			FAIL("junk on end");	/* "Can't happen". */
X		/* NOTREACHED */
X	}
X
X	return(ret);
X}
X
X/*
X - regbranch - one alternative of an | operator
X *
X * Implements the concatenation operator.
X */
Xstatic char *
Xregbranch(flagp)
Xint *flagp;
X{
X	register char *ret;
X	register char *chain;
X	register char *latest;
X	int flags;
X
X	*flagp = WORST;		/* Tentatively. */
X
X	ret = regnode(BRANCH);
X	chain = NULL;
X	while (*regparse != '\0' && *regparse != ')' &&
X	       *regparse != '\n' && *regparse != '|') {
X		latest = regpiece(&flags);
X		if (latest == NULL)
X			return(NULL);
X		*flagp |= flags&HASWIDTH;
X		if (chain == NULL)	/* First piece. */
X			*flagp |= flags&SPSTART;
X		else
X			regtail(chain, latest);
X		chain = latest;
X	}
X	if (chain == NULL)	/* Loop ran zero times. */
X		(void) regnode(NOTHING);
X
X	return(ret);
X}
X
X/*
X - regpiece - something followed by possible [*+?]
X *
X * Note that the branching code sequences used for ? and the general cases
X * of * and + are somewhat optimized:  they use the same NOTHING node as
X * both the endmarker for their branch list and the body of the last branch.
X * It might seem that this node could be dispensed with entirely, but the
X * endmarker role is not redundant.
X */
Xstatic char *
Xregpiece(flagp)
Xint *flagp;
X{
X	register char *ret;
X	register char op;
X	register char *next;
X	int flags;
X
X	ret = regatom(&flags);
X	if (ret == NULL)
X		return(NULL);
X
X	op = *regparse;
X	if (!ISMULT(op)) {
X		*flagp = flags;
X		return(ret);
X	}
X
X	if (!(flags&HASWIDTH) && op != '?')
X		FAIL("*+ operand could be empty");
X	*flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
X
X	if (op == '*' && (flags&SIMPLE))
X		reginsert(STAR, ret);
X	else if (op == '*') {
X		/* Emit x* as (x&|), where & means "self". */
X		reginsert(BRANCH, ret);			/* Either x */
X		regoptail(ret, regnode(BACK));		/* and loop */
X		regoptail(ret, ret);			/* back */
X		regtail(ret, regnode(BRANCH));		/* or */
X		regtail(ret, regnode(NOTHING));		/* null. */
X	} else if (op == '+' && (flags&SIMPLE))
X		reginsert(PLUS, ret);
X	else if (op == '+') {
X		/* Emit x+ as x(&|), where & means "self". */
X		next = regnode(BRANCH);			/* Either */
X		regtail(ret, next);
X		regtail(regnode(BACK), ret);		/* loop back */
X		regtail(next, regnode(BRANCH));		/* or */
X		regtail(ret, regnode(NOTHING));		/* null. */
X	} else if (op == '?') {
X		/* Emit x? as (x|) */
X		reginsert(BRANCH, ret);			/* Either x */
X		regtail(ret, regnode(BRANCH));		/* or */
X		next = regnode(NOTHING);		/* null. */
X		regtail(ret, next);
X		regoptail(ret, next);
X	}
X	regparse++;
X	if (ISMULT(*regparse))
X		FAIL("nested *?+");
X
X	return(ret);
X}
X
X/*
X - regatom - the lowest level
X *
X * Optimization:  gobbles an entire sequence of ordinary characters so that
X * it can turn them into a single node, which is smaller to store and
X * faster to run.  Backslashed characters are exceptions, each becoming a
X * separate node; the code is simpler that way and it's not worth fixing.
X */
Xstatic char *
Xregatom(flagp)
Xint *flagp;
X{
X	register char *ret;
X	int flags;
X
X	*flagp = WORST;		/* Tentatively. */
X
X	switch (*regparse++) {
X	/* FIXME: these chars only have meaning at beg/end of pat? */
X	case '^':
X		ret = regnode(BOL);
X		break;
X	case '$':
X		ret = regnode(EOL);
X		break;
X	case '.':
X		ret = regnode(ANY);
X		*flagp |= HASWIDTH|SIMPLE;
X		break;
X	case '[': {
X			register int class;
X			register int classend;
X
X			if (*regparse == '^') {	/* Complement of range. */
X				ret = regnode(ANYBUT);
X				regparse++;
X			} else
X				ret = regnode(ANYOF);
X			if (*regparse == ']' || *regparse == '-')
X				regc(*regparse++);
X			while (*regparse != '\0' && *regparse != ']') {
X				if (*regparse == '-') {
X					regparse++;
X					if (*regparse == ']' || *regparse == '\0')
X						regc('-');
X					else {
X						class = UCHARAT(regparse-2)+1;
X						classend = UCHARAT(regparse);
X						if (class > classend+1)
X							FAIL("invalid [] range");
X						for (; class <= classend; class++)
X							regc(class);
X						regparse++;
X					}
X				} else
X					regc(*regparse++);
X			}
X			regc('\0');
X			if (*regparse != ']')
X				FAIL("unmatched []");
X			regparse++;
X			*flagp |= HASWIDTH|SIMPLE;
X		}
X		break;
X	case '(':
X		ret = reg(1, &flags);
X		if (ret == NULL)
X			return(NULL);
X		*flagp |= flags&(HASWIDTH|SPSTART);
X		break;
X	case '\0':
X	case '|':
X	case '\n':
X	case ')':
X		FAIL("internal urp");	/* Supposed to be caught earlier. */
X		break;
X	case '?':
X	case '+':
X	case '*':
X		FAIL("?+* follows nothing");
X		break;
X/*CWL	case '\\':*/
X        case '%':
X		switch (*regparse++) {
X		case '\0':
X			FAIL("trailing \\");
X			break;
X		case '<':
X			ret = regnode(WORDA);
X			break;
X		case '>':
X			ret = regnode(WORDZ);
X			break;
X		/* FIXME: Someday handle \1, \2, ... */
X		default:
X			/* Handle general quoted chars in exact-match routine */
X			goto de_fault;
X		}
X		break;
X	de_fault:
X	default:
X		/*
X		 * Encode a string of characters to be matched exactly.
X		 *
X		 * This is a bit tricky due to quoted chars and due to
X		 * '*', '+', and '?' taking the SINGLE char previous
X		 * as their operand.
X		 *
X		 * On entry, the char at regparse[-1] is going to go
X		 * into the string, no matter what it is.  (It could be
X		 * following a \ if we are entered from the '\' case.)
X		 * 
X		 * Basic idea is to pick up a good char in  ch  and
X		 * examine the next char.  If it's *+? then we twiddle.
X		 * If it's \ then we frozzle.  If it's other magic char
X		 * we push  ch  and terminate the string.  If none of the
X		 * above, we push  ch  on the string and go around again.
X		 *
X		 *  regprev  is used to remember where "the current char"
X		 * starts in the string, if due to a *+? we need to back
X		 * up and put the current char in a separate, 1-char, string.
X		 * When  regprev  is NULL,  ch  is the only char in the
X		 * string; this is used in *+? handling, and in setting
X		 * flags |= SIMPLE at the end.
X		 */
X		{
X			char *regprev;
X			register char ch;
X
X			regparse--;			/* Look at cur char */
X			ret = regnode(EXACTLY);
X			for ( regprev = 0 ; ; ) {
X				ch = *regparse++;	/* Get current char */
X				switch (*regparse) {	/* look at next one */
X
X				default:
X					regc(ch);	/* Add cur to string */
X					break;
X
X				case '.': case '[': case '(':
X				case ')': case '|': case '\n':
X				case '$': case '^':
X				case '\0':
X				/* FIXME, $ and ^ should not always be magic */
X				magic:
X					regc(ch);	/* dump cur char */
X					goto done;	/* and we are done */
X
X				case '?': case '+': case '*':
X					if (!regprev) 	/* If just ch in str, */
X						goto magic;	/* use it */
X					/* End mult-char string one early */
X					regparse = regprev; /* Back up parse */
X					goto done;
X
X/*CWL				case '\\':*/
X				case '%':
X					regc(ch);	/* Cur char OK */
X					switch (regparse[1]){ /* Look after \ */
X					case '\0':
X					case '<':
X					case '>':
X					/* FIXME: Someday handle \1, \2, ... */
X						goto done; /* Not quoted */
X					default:
X						/* Backup point is \, scan							 * point is after it. */
X						regprev = regparse;
X						regparse++; 
X						continue;	/* NOT break; */
X					}
X				}
X				regprev = regparse;	/* Set backup point */
X			}
X		done:
X			regc('\0');
X			*flagp |= HASWIDTH;
X			if (!regprev)		/* One char? */
X				*flagp |= SIMPLE;
X		}
X		break;
X	}
X
X	return(ret);
X}
X
X/*
X - regnode - emit a node
X */
Xstatic char *			/* Location. */
Xregnode(op)
Xchar op;
X{
X	register char *ret;
X	register char *ptr;
X
X	ret = regcode;
X	if (ret == &regdummy) {
X		regsize += 3;
X		return(ret);
X	}
X
X	ptr = ret;
X	*ptr++ = op;
X	*ptr++ = '\0';		/* Null "next" pointer. */
X	*ptr++ = '\0';
X	regcode = ptr;
X
X	return(ret);
X}
X
X/*
X - regc - emit (if appropriate) a byte of code
X */
Xstatic void
Xregc(b)
Xchar b;
X{
X	if (regcode != &regdummy)
X		*regcode++ = b;
X	else
X		regsize++;
X}
X
X/*
X - reginsert - insert an operator in front of already-emitted operand
X *
X * Means relocating the operand.
X */
Xstatic void
Xreginsert(op, opnd)
Xchar op;
Xchar *opnd;
X{
X	register char *src;
X	register char *dst;
X	register char *place;
X
X	if (regcode == &regdummy) {
X		regsize += 3;
X		return;
X	}
X
X	src = regcode;
X	regcode += 3;
X	dst = regcode;
X	while (src > opnd)
X		*--dst = *--src;
X
X	place = opnd;		/* Op node, where operand used to be. */
X	*place++ = op;
X	*place++ = '\0';
X	*place++ = '\0';
X}
X
X/*
X - regtail - set the next-pointer at the end of a node chain
X */
Xstatic void
Xregtail(p, val)
Xchar *p;
Xchar *val;
X{
X	register char *scan;
X	register char *temp;
X	register int offset;
X
X	if (p == &regdummy)
X		return;
X
X	/* Find last node. */
X	scan = p;
X	for (;;) {
X		temp = regnext(scan);
X		if (temp == NULL)
X			break;
X		scan = temp;
X	}
X
X	if (OP(scan) == BACK)
X		offset = scan - val;
X	else
X		offset = val - scan;
X	*(scan+1) = (offset>>8)&0377;
X	*(scan+2) = offset&0377;
X}
X
X/*
X - regoptail - regtail on operand of first argument; nop if operandless
X */
Xstatic void
Xregoptail(p, val)
Xchar *p;
Xchar *val;
X{
X	/* "Operandless" and "op != BRANCH" are synonymous in practice. */
X	if (p == NULL || p == &regdummy || OP(p) != BRANCH)
X		return;
X	regtail(OPERAND(p), val);
X}
X
X/*
X * regexec and friends
X */
X
X/*
X * Global work variables for regexec().
X */
Xstatic char *reginput;		/* String-input pointer. */
Xstatic char *regbol;		/* Beginning of input, for ^ check. */
Xstatic char **regstartp;	/* Pointer to startp array. */
Xstatic char **regendp;		/* Ditto for endp. */
Xstatic int case_flag;                /* CWL case sensitivity flag */
X
Xextern int mystrncasecmp();
Xextern char *mystrcasechr();
Xextern char tolower();
X
X#define CASE(c) ((!case_flag) ? tolower((c)) : (c))
X#define STRCHR(s,c) ((case_flag) ? strchr((s),(c)) : \
X	  mystrcasechr((s),(c)))
X#define STRNCMP(s,c,n) ((case_flag) ? strncmp((s),(c),(n)) : \
X         mystrncasecmp((s),(c),(n)))
X
X/*
X * Forwards.
X */
XSTATIC int regtry();
XSTATIC int regmatch();
XSTATIC int regrepeat();
X
X#ifdef DEBUG
Xint regnarrate = 0;
Xvoid regdump();
XSTATIC char *regprop();
X#endif
X
X/*
X - regexec - match a regexp against a string
X */
Xint
Xregexec(prog, string, case_sense)
Xregister const regexp *prog;
Xregister const char *string;
Xregister const int case_sense;
X{
X	register char *s;
X	extern char *strchr();
X
X	/* CWL */
X	case_flag = case_sense;
X	/* Be paranoid... */
X	if (prog == NULL || string == NULL) {
X		regerror("NULL parameter");
X		return(0);
X	}
X
X	/* Check validity of program. */
X	if (UCHARAT(prog->program) != MAGIC) {
X		regerror("corrupted program");
X		return(0);
X	}
X
X	/* If there is a "must appear" string, look for it. */
X	if (prog->regmust != NULL) {
X		s = (char *)string;
X		while ((s = STRCHR(s, prog->regmust[0])) != NULL) {
X			if (STRNCMP(s, prog->regmust, prog->regmlen) == 0)
X				break;	/* Found it. */
X			s++;
X		}
X		if (s == NULL)	/* Not present. */
X			return(0);
X	}
X	/* Mark beginning of line for ^ . */
X	regbol = (char *)string;
X
X	/* Simplest case:  anchored match need be tried only once. */
X	if (prog->reganch)
X		return(regtry(prog, string));
X
X	/* Messy cases:  unanchored match. */
X	s = (char *)string;
X	if (prog->regstart != '\0')
X		/* We know what char it must start with. */
X		while ((s = STRCHR(s, prog->regstart)) != NULL) {
X			if (regtry(prog, s))
X				return(1);
X			s++;
X		}
X	else
X		/* We don't -- general case. */
X		do {
X			if (regtry(prog, s))
X				return(1);
X		} while (*s++ != '\0');
X
X	/* Failure. */
X	return(0);
X}
X
X/*
X - regtry - try match at specific point
X */
Xstatic int			/* 0 failure, 1 success */
Xregtry(prog, string)
Xregexp *prog;
Xchar *string;
X{
X	register int i;
X	register char **sp;
X	register char **ep;
X
X	reginput = string;
X	regstartp = prog->startp;
X	regendp = prog->endp;
X
X	sp = prog->startp;
X	ep = prog->endp;
X	for (i = NSUBEXP; i > 0; i--) {
X		*sp++ = NULL;
X		*ep++ = NULL;
X	}
X	if (regmatch(prog->program + 1)) {
X		prog->startp[0] = string;
X		prog->endp[0] = reginput;
X		return(1);
X	} else
X		return(0);
X}
X
X/*
X - regmatch - main matching routine
X *
X * Conceptually the strategy is simple:  check to see whether the current
X * node matches, call self recursively to see whether the rest matches,
X * and then act accordingly.  In practice we make some effort to avoid
X * recursion, in particular by going through "ordinary" nodes (that don't
X * need to know whether the rest of the match failed) by a loop instead of
X * by recursion.
X */
Xstatic int			/* 0 failure, 1 success */
Xregmatch(prog)
Xchar *prog;
X{
X	register char *scan;	/* Current node. */
X	char *next;		/* Next node. */
X	extern char *strchr();
X
X	scan = prog;
X#ifdef DEBUG
X	if (scan != NULL && regnarrate)
X		fprintf(stderr, "%s(\n", regprop(scan));
X#endif
X	while (scan != NULL) {
X#ifdef DEBUG
X		if (regnarrate)
X			fprintf(stderr, "%s...\n", regprop(scan));
X#endif
X		next = regnext(scan);
X
X		switch (OP(scan)) {
X		case BOL:
X			if (reginput != regbol)
X				return(0);
X			break;
X		case EOL:
X			if (*reginput != '\0')
X				return(0);
X			break;
X		case WORDA:
X			/* Must be looking at a letter, digit, or _ */
X			if ((!isalnum(*reginput)) && *reginput != '_')
X				return(0);
X			/* Prev must be BOL or nonword */
X			if (reginput > regbol &&
X			    (isalnum(reginput[-1]) || reginput[-1] == '_'))
X				return(0);
X			break;
X		case WORDZ:
X			/* Must be looking at non letter, digit, or _ */
X			if (isalnum(*reginput) || *reginput == '_')
X				return(0);
X			/* We don't care what the previous char was */
X			break;
X		case ANY:
X			if (*reginput == '\0')
X				return(0);
X			reginput++;
X			break;
X		case EXACTLY: {
X				register int len;
X				register char *opnd;
X
X				opnd = OPERAND(scan);
X				/* Inline the first character, for speed. */
X				if (CASE(*opnd) != CASE(*reginput))
X					return(0);
X				len = strlen(opnd);
X				if (len > 1 && STRNCMP(opnd, reginput, len) != 0)
X					return(0);
X				reginput += len;
X			}
X			break;
X		case ANYOF:
X 			if (*reginput == '\0' || STRCHR(OPERAND(scan), *reginput) == NULL)
X				return(0);
X			reginput++;
X			break;
X		case ANYBUT:
X 			if (*reginput == '\0' || STRCHR(OPERAND(scan), *reginput) != NULL)
X				return(0);
X			reginput++;
X			break;
X		case NOTHING:
X			break;
X		case BACK:
X			break;
X		case OPEN+1:
X		case OPEN+2:
X		case OPEN+3:
X		case OPEN+4:
X		case OPEN+5:
X		case OPEN+6:
X		case OPEN+7:
X		case OPEN+8:
X		case OPEN+9: {
X				register int no;
X				register char *save;
X
X				no = OP(scan) - OPEN;
X				save = reginput;
X
X				if (regmatch(next)) {
X					/*
X					 * Don't set startp if some later
X					 * invocation of the same parentheses
X					 * already has.
X					 */
X					if (regstartp[no] == NULL)
X						regstartp[no] = save;
X					return(1);
X				} else
X					return(0);
X			}
X			break;
X		case CLOSE+1:
X		case CLOSE+2:
X		case CLOSE+3:
X		case CLOSE+4:
X		case CLOSE+5:
X		case CLOSE+6:
X		case CLOSE+7:
X		case CLOSE+8:
X		case CLOSE+9: {
X				register int no;
X				register char *save;
X
X				no = OP(scan) - CLOSE;
X				save = reginput;
X
X				if (regmatch(next)) {
X					/*
X					 * Don't set endp if some later
X					 * invocation of the same parentheses
X					 * already has.
X					 */
X					if (regendp[no] == NULL)
X						regendp[no] = save;
X					return(1);
X				} else
X					return(0);
X			}
X			break;
X		case BRANCH: {
X				register char *save;
X
X				if (OP(next) != BRANCH)		/* No choice. */
X					next = OPERAND(scan);	/* Avoid recursion. */
X				else {
X					do {
X						save = reginput;
X						if (regmatch(OPERAND(scan)))
X							return(1);
X						reginput = save;
X						scan = regnext(scan);
X					} while (scan != NULL && OP(scan) == BRANCH);
X					return(0);
X					/* NOTREACHED */
X				}
X			}
X			break;
X		case STAR:
X		case PLUS: {
X				register char nextch;
X				register int no;
X				register char *save;
X				register int min;
X
X				/*
X				 * Lookahead to avoid useless match attempts
X				 * when we know what character comes next.
X				 */
X				nextch = '\0';
X				if (OP(next) == EXACTLY)
X					nextch = *OPERAND(next);
X				min = (OP(scan) == STAR) ? 0 : 1;
X				save = reginput;
X				no = regrepeat(OPERAND(scan));
X				while (no >= min) {
X					/* If it could work, try it. */
X					if (nextch == '\0' 
X					    || CASE(*reginput) == CASE(nextch))
X						if (regmatch(next))
X							return(1);
X					/* Couldn't or didn't -- back up. */
X					no--;
X					reginput = save + no;
X				}
X				return(0);
X			}
X			break;
X		case END:
X			return(1);	/* Success! */
X			break;
X		default:
X			regerror("memory corruption");
X			return(0);
X			break;
X		}
X
X		scan = next;
X	}
X
X	/*
X	 * We get here only if there's trouble -- normally "case END" is
X	 * the terminating point.
X	 */
X	regerror("corrupted pointers");
X	return(0);
X}
X
X/*
X - regrepeat - repeatedly match something simple, report how many
X */
Xstatic int
Xregrepeat(p)
Xchar *p;
X{
X	register int count = 0;
X	register char *scan;
X	register char *opnd;
X
X	scan = reginput;
X	opnd = OPERAND(p);
X	switch (OP(p)) {
X	case ANY:
X		count = strlen(scan);
X		scan += count;
X		break;
X	case EXACTLY:
X		while (CASE(*opnd) == CASE(*scan)) {
X			count++;
X			scan++;
X		}
X		break;
X	case ANYOF:
X		while (*scan != '\0' && STRCHR(opnd, *scan) != NULL) {
X			count++;
X			scan++;
X		}
X		break;
X	case ANYBUT:
X		while (*scan != '\0' && STRCHR(opnd, *scan) == NULL) {
X			count++;
X			scan++;
X		}
X		break;
X	default:		/* Oh dear.  Called inappropriately. */
X		regerror("internal foulup");
X		count = 0;	/* Best compromise. */
X		break;
X	}
X	reginput = scan;
X
X	return(count);
X}
X
X/*
X - regnext - dig the "next" pointer out of a node
X */
Xstatic char *
Xregnext(p)
Xregister char *p;
X{
X	register int offset;
X
X	if (p == &regdummy)
X		return(NULL);
X
X	offset = NEXT(p);
X	if (offset == 0)
X		return(NULL);
X
X	if (OP(p) == BACK)
X		return(p-offset);
X	else
X		return(p+offset);
X}
X
X#ifdef DEBUG
X
XSTATIC char *regprop();
X
X/*
X - regdump - dump a regexp onto stdout in vaguely comprehensible form
X */
Xvoid
Xregdump(r)
Xregexp *r;
X{
X	register char *s;
X	register char op = EXACTLY;	/* Arbitrary non-END op. */
X	register char *next;
X	extern char *strchr();
X
X
X	s = r->program + 1;
X	while (op != END) {	/* While that wasn't END last time... */
X		op = OP(s);
X		printf("%2d%s", s-r->program, regprop(s));	/* Where, what. */
X		next = regnext(s);
X		if (next == NULL)		/* Next ptr. */
X			printf("(0)");
X		else 
X			printf("(%d)", (s-r->program)+(next-s));
X		s += 3;
X		if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
X			/* Literal string, where present. */
X			while (*s != '\0') {
X				putchar(*s);
X				s++;
X			}
X			s++;
X		}
X		putchar('\n');
X	}
X
X	/* Header fields of interest. */
X	if (r->regstart != '\0')
X		printf("start `%c' ", r->regstart);
X	if (r->reganch)
X		printf("anchored ");
X	if (r->regmust != NULL)
X		printf("must have \"%s\"", r->regmust);
X	printf("\n");
X}
X
X/*
X - regprop - printable representation of opcode
X */
Xstatic char *
Xregprop(op)
Xchar *op;
X{
X	register char *p;
X	static char buf[50];
X
X	(void) strcpy(buf, ":");
X
X	switch (OP(op)) {
X	case BOL:
X		p = "BOL";
X		break;
X	case EOL:
X		p = "EOL";
X		break;
X	case ANY:
X		p = "ANY";
X		break;
X	case ANYOF:
X		p = "ANYOF";
X		break;
X	case ANYBUT:
X		p = "ANYBUT";
X		break;
X	case BRANCH:
X		p = "BRANCH";
X		break;
X	case EXACTLY:
X		p = "EXACTLY";
X		break;
X	case NOTHING:
X		p = "NOTHING";
X		break;
X	case BACK:
X		p = "BACK";
X		break;
X	case END:
X		p = "END";
X		break;
X	case OPEN+1:
X	case OPEN+2:
X	case OPEN+3:
X	case OPEN+4:
X	case OPEN+5:
X	case OPEN+6:
X	case OPEN+7:
X	case OPEN+8:
X	case OPEN+9:
X		sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
X		p = NULL;
X		break;
X	case CLOSE+1:
X	case CLOSE+2:
X	case CLOSE+3:
X	case CLOSE+4:
X	case CLOSE+5:
X	case CLOSE+6:
X	case CLOSE+7:
X	case CLOSE+8:
X	case CLOSE+9:
X		sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
X		p = NULL;
X		break;
X	case STAR:
X		p = "STAR";
X		break;
X	case PLUS:
X		p = "PLUS";
X		break;
X	case WORDA:
X		p = "WORDA";
X		break;
X	case WORDZ:
X		p = "WORDZ";
X		break;
X	default:
X		regerror("corrupted opcode");
X		break;
X	}
X	if (p != NULL)
X		(void) strcat(buf, p);
X	return(buf);
X}
X#endif
X
X/*
X * The following is provided for those people who do not have strcspn() in
X * their C libraries.  They should get off their butts and do something
X * about it; at least one public-domain implementation of those (highly
X * useful) string routines has been published on Usenet.
X */
X#ifdef STRCSPN
X/*
X * strcspn - find length of initial segment of s1 consisting entirely
X * of characters not from s2
X */
X
Xstatic int
Xstrcspn(s1, s2)
Xchar *s1;
Xchar *s2;
X{
X	register char *scan1;
X	register char *scan2;
X	register int count;
X
X	count = 0;
X	for (scan1 = s1; *scan1 != '\0'; scan1++) {
X		for (scan2 = s2; *scan2 != '\0';)	/* ++ moved down. */
X			if (CASE(*scan1) == CASE(*scan2++))
X				return(count);
X		count++;
X	}
X	return(count);
X}
X#endif
END_OF_FILE
if test 31972 -ne `wc -c <'regexp.c'`; then
    echo shar: \"'regexp.c'\" unpacked with wrong size!
fi
# end of 'regexp.c'
fi
if test -f 'regexp.c.orig' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'regexp.c.orig'\"
else
echo shar: Extracting \"'regexp.c.orig'\" \(31244 characters\)
sed "s/^X//" >'regexp.c.orig' <<'END_OF_FILE'
X/*
X * regcomp and regexec -- regsub and regerror are elsewhere
X *
X *	Copyright (c) 1986 by University of Toronto.
X *	Written by Henry Spencer.  Not derived from licensed software.
X *
X *	Permission is granted to anyone to use this software for any
X *	purpose on any computer system, and to redistribute it freely,
X *	subject to the following restrictions:
X *
X *	1. The author is not responsible for the consequences of use of
X *		this software, no matter how awful, even if they arise
X *		from defects in it.
X *
X *	2. The origin of this software must not be misrepresented, either
X *		by explicit claim or by omission.
X *
X *	3. Altered versions must be plainly marked as such, and must not
X *		be misrepresented as being the original software.
X *** THIS IS AN ALTERED VERSION.  It was altered by John Gilmore,
X *** hoptoad!gnu, on 27 Dec 1986, to add \n as an alternative to |
X *** to assist in implementing egrep.
X *** THIS IS AN ALTERED VERSION.  It was altered by John Gilmore,
X *** hoptoad!gnu, on 27 Dec 1986, to add \< and \> for word-matching
X *** as in BSD grep and ex.
X *** THIS IS AN ALTERED VERSION.  It was altered by John Gilmore,
X *** hoptoad!gnu, on 28 Dec 1986, to optimize characters quoted with \.
X *** THIS IS AN ALTERED VERSION.  It was altered by James A. Woods,
X *** ames!jaw, on 19 June 1987, to quash a regcomp() redundancy.
X *
X * Beware that some of this code is subtly aware of the way operator
X * precedence is structured in regular expressions.  Serious changes in
X * regular-expression syntax might require a total rethink.
X */
X#include <regexp.h>
X#include <stdio.h>
X#include <ctype.h>
X#include <stdlib.h>
X#include <string.h>
X#include "regmagic.h"
X
X/*
X * The "internal use only" fields in regexp.h are present to pass info from
X * compile to execute that permits the execute phase to run lots faster on
X * simple cases.  They are:
X *
X * regstart	char that must begin a match; '\0' if none obvious
X * reganch	is the match anchored (at beginning-of-line only)?
X * regmust	string (pointer into program) that match must include, or NULL
X * regmlen	length of regmust string
X *
X * Regstart and reganch permit very fast decisions on suitable starting points
X * for a match, cutting down the work a lot.  Regmust permits fast rejection
X * of lines that cannot possibly match.  The regmust tests are costly enough
X * that regcomp() supplies a regmust only if the r.e. contains something
X * potentially expensive (at present, the only such thing detected is * or +
X * at the start of the r.e., which can involve a lot of backup).  Regmlen is
X * supplied because the test in regexec() needs it and regcomp() is computing
X * it anyway.
X */
X
X/*
X * Structure for regexp "program".  This is essentially a linear encoding
X * of a nondeterministic finite-state machine (aka syntax charts or
X * "railroad normal form" in parsing technology).  Each node is an opcode
X * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
X * all nodes except BRANCH implement concatenation; a "next" pointer with
X * a BRANCH on both ends of it is connecting two alternatives.  (Here we
X * have one of the subtle syntax dependencies:  an individual BRANCH (as
X * opposed to a collection of them) is never concatenated with anything
X * because of operator precedence.)  The operand of some types of node is
X * a literal string; for others, it is a node leading into a sub-FSM.  In
X * particular, the operand of a BRANCH node is the first node of the branch.
X * (NB this is *not* a tree structure:  the tail of the branch connects
X * to the thing following the set of BRANCHes.)  The opcodes are:
X */
X
X/* definition	number	opnd?	meaning */
X#define	END	0	/* no	End of program. */
X#define	BOL	1	/* no	Match "" at beginning of line. */
X#define	EOL	2	/* no	Match "" at end of line. */
X#define	ANY	3	/* no	Match any one character. */
X#define	ANYOF	4	/* str	Match any character in this string. */
X#define	ANYBUT	5	/* str	Match any character not in this string. */
X#define	BRANCH	6	/* node	Match this alternative, or the next... */
X#define	BACK	7	/* no	Match "", "next" ptr points backward. */
X#define	EXACTLY	8	/* str	Match this string. */
X#define	NOTHING	9	/* no	Match empty string. */
X#define	STAR	10	/* node	Match this (simple) thing 0 or more times. */
X#define	PLUS	11	/* node	Match this (simple) thing 1 or more times. */
X#define	WORDA	12	/* no	Match "" at wordchar, where prev is nonword */
X#define	WORDZ	13	/* no	Match "" at nonwordchar, where prev is word */
X#define	OPEN	20	/* no	Mark this point in input as start of #n. */
X			/*	OPEN+1 is number 1, etc. */
X#define	CLOSE	30	/* no	Analogous to OPEN. */
X
X/*
X * Opcode notes:
X *
X * BRANCH	The set of branches constituting a single choice are hooked
X *		together with their "next" pointers, since precedence prevents
X *		anything being concatenated to any individual branch.  The
X *		"next" pointer of the last BRANCH in a choice points to the
X *		thing following the whole choice.  This is also where the
X *		final "next" pointer of each individual branch points; each
X *		branch starts with the operand node of a BRANCH node.
X *
X * BACK		Normal "next" pointers all implicitly point forward; BACK
X *		exists to make loop structures possible.
X *
X * STAR,PLUS	'?', and complex '*' and '+', are implemented as circular
X *		BRANCH structures using BACK.  Simple cases (one character
X *		per match) are implemented with STAR and PLUS for speed
X *		and to minimize recursive plunges.
X *
X * OPEN,CLOSE	...are numbered at compile time.
X */
X
X/*
X * A node is one char of opcode followed by two chars of "next" pointer.
X * "Next" pointers are stored as two 8-bit pieces, high order first.  The
X * value is a positive offset from the opcode of the node containing it.
X * An operand, if any, simply follows the node.  (Note that much of the
X * code generation knows about this implicit relationship.)
X *
X * Using two bytes for the "next" pointer is vast overkill for most things,
X * but allows patterns to get big without disasters.
X */
X#define	OP(p)	(*(p))
X#define	NEXT(p)	(((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
X#define	OPERAND(p)	((p) + 3)
X
X/*
X * See regmagic.h for one further detail of program structure.
X */
X
X
X/*
X * Utility definitions.
X */
X#ifndef CHARBITS
X#define	UCHARAT(p)	((int)*(unsigned char *)(p))
X#else
X#define	UCHARAT(p)	((int)*(p)&CHARBITS)
X#endif
X
X#define	FAIL(m)	{ regerror(m); return(NULL); }
X#define	ISMULT(c)	((c) == '*' || (c) == '+' || (c) == '?')
X
X/*
X * Flags to be passed up and down.
X */
X#define	HASWIDTH	01	/* Known never to match null string. */
X#define	SIMPLE		02	/* Simple enough to be STAR/PLUS operand. */
X#define	SPSTART		04	/* Starts with * or +. */
X#define	WORST		0	/* Worst case. */
X
X/*
X * Global work variables for regcomp().
X */
Xstatic char *regparse;		/* Input-scan pointer. */
Xstatic int regnpar;		/* () count. */
Xstatic char regdummy;
Xstatic char *regcode;		/* Code-emit pointer; &regdummy = don't. */
Xstatic long regsize;		/* Code size. */
X
X/*
X * Forward declarations for regcomp()'s friends.
X */
X#ifndef STATIC
X#define	STATIC	static
X#endif
XSTATIC char *reg();
XSTATIC char *regbranch();
XSTATIC char *regpiece();
XSTATIC char *regatom();
XSTATIC char *regnode();
XSTATIC char *regnext();
XSTATIC void regc();
XSTATIC void reginsert();
XSTATIC void regtail();
XSTATIC void regoptail();
X#ifdef STRCSPN
XSTATIC int strcspn();
X#endif
X
X/*
X - regcomp - compile a regular expression into internal code
X *
X * We can't allocate space until we know how big the compiled form will be,
X * but we can't compile it (and thus know how big it is) until we've got a
X * place to put the code.  So we cheat:  we compile it twice, once with code
X * generation turned off and size counting turned on, and once "for real".
X * This also means that we don't allocate space until we are sure that the
X * thing really will compile successfully, and we never have to move the
X * code and thus invalidate pointers into it.  (Note that it has to be in
X * one piece because free() must be able to free it all.)
X *
X * Beware that the optimization-preparation code in here knows about some
X * of the structure of the compiled regexp.
X */
Xregexp *
Xregcomp(exp)
Xconst char *exp;
X{
X	register regexp *r;
X	register char *scan;
X	register char *longest;
X	register int len;
X	int flags;
X
X	if (exp == NULL)
X		FAIL("NULL argument");
X
X	/* First pass: determine size, legality. */
X#ifdef notdef
X	if (exp[0] == '.' && exp[1] == '*') exp += 2;  /* aid grep */
X#endif
X	regparse = (char *)exp;
X	regnpar = 1;
X	regsize = 0L;
X	regcode = &regdummy;
X	regc(MAGIC);
X	if (reg(0, &flags) == NULL)
X		return(NULL);
X
X	/* Small enough for pointer-storage convention? */
X	if (regsize >= 32767L)		/* Probably could be 65535L. */
X		FAIL("regexp too big");
X
X	/* Allocate space. */
X	r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
X	if (r == NULL)
X		FAIL("out of space");
X
X	/* Second pass: emit code. */
X	regparse = (char *)exp;
X	regnpar = 1;
X	regcode = r->program;
X	regc(MAGIC);
X	if (reg(0, &flags) == NULL)
X		return(NULL);
X
X	/* Dig out information for optimizations. */
X	r->regstart = '\0';	/* Worst-case defaults. */
X	r->reganch = 0;
X	r->regmust = NULL;
X	r->regmlen = 0;
X	scan = r->program+1;			/* First BRANCH. */
X	if (OP(regnext(scan)) == END) {		/* Only one top-level choice. */
X		scan = OPERAND(scan);
X
X		/* Starting-point info. */
X		if (OP(scan) == EXACTLY)
X			r->regstart = *OPERAND(scan);
X		else if (OP(scan) == BOL)
X			r->reganch++;
X
X		/*
X		 * If there's something expensive in the r.e., find the
X		 * longest literal string that must appear and make it the
X		 * regmust.  Resolve ties in favor of later strings, since
X		 * the regstart check works with the beginning of the r.e.
X		 * and avoiding duplication strengthens checking.  Not a
X		 * strong reason, but sufficient in the absence of others.
X		 */
X		if (flags&SPSTART) {
X			longest = NULL;
X			len = 0;
X			for (; scan != NULL; scan = regnext(scan))
X				if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
X					longest = OPERAND(scan);
X					len = strlen(OPERAND(scan));
X				}
X			r->regmust = longest;
X			r->regmlen = len;
X		}
X	}
X
X	return(r);
X}
X
X/*
X - reg - regular expression, i.e. main body or parenthesized thing
X *
X * Caller must absorb opening parenthesis.
X *
X * Combining parenthesis handling with the base level of regular expression
X * is a trifle forced, but the need to tie the tails of the branches to what
X * follows makes it hard to avoid.
X */
Xstatic char *
Xreg(paren, flagp)
Xint paren;			/* Parenthesized? */
Xint *flagp;
X{
X	register char *ret;
X	register char *br;
X	register char *ender;
X	register int parno;
X	int flags;
X
X	*flagp = HASWIDTH;	/* Tentatively. */
X
X	/* Make an OPEN node, if parenthesized. */
X	if (paren) {
X		if (regnpar >= NSUBEXP)
X			FAIL("too many ()");
X		parno = regnpar;
X		regnpar++;
X		ret = regnode(OPEN+parno);
X	} else
X		ret = NULL;
X
X	/* Pick up the branches, linking them together. */
X	br = regbranch(&flags);
X	if (br == NULL)
X		return(NULL);
X	if (ret != NULL)
X		regtail(ret, br);	/* OPEN -> first. */
X	else
X		ret = br;
X	if (!(flags&HASWIDTH))
X		*flagp &= ~HASWIDTH;
X	*flagp |= flags&SPSTART;
X	while (*regparse == '|' || *regparse == '\n') {
X		regparse++;
X		br = regbranch(&flags);
X		if (br == NULL)
X			return(NULL);
X		regtail(ret, br);	/* BRANCH -> BRANCH. */
X		if (!(flags&HASWIDTH))
X			*flagp &= ~HASWIDTH;
X		*flagp |= flags&SPSTART;
X	}
X
X	/* Make a closing node, and hook it on the end. */
X	ender = regnode((paren) ? CLOSE+parno : END);	
X	regtail(ret, ender);
X
X	/* Hook the tails of the branches to the closing node. */
X	for (br = ret; br != NULL; br = regnext(br))
X		regoptail(br, ender);
X
X	/* Check for proper termination. */
X	if (paren && *regparse++ != ')') {
X		FAIL("unmatched ()");
X	} else if (!paren && *regparse != '\0') {
X		if (*regparse == ')') {
X			FAIL("unmatched ()");
X		} else
X			FAIL("junk on end");	/* "Can't happen". */
X		/* NOTREACHED */
X	}
X
X	return(ret);
X}
X
X/*
X - regbranch - one alternative of an | operator
X *
X * Implements the concatenation operator.
X */
Xstatic char *
Xregbranch(flagp)
Xint *flagp;
X{
X	register char *ret;
X	register char *chain;
X	register char *latest;
X	int flags;
X
X	*flagp = WORST;		/* Tentatively. */
X
X	ret = regnode(BRANCH);
X	chain = NULL;
X	while (*regparse != '\0' && *regparse != ')' &&
X	       *regparse != '\n' && *regparse != '|') {
X		latest = regpiece(&flags);
X		if (latest == NULL)
X			return(NULL);
X		*flagp |= flags&HASWIDTH;
X		if (chain == NULL)	/* First piece. */
X			*flagp |= flags&SPSTART;
X		else
X			regtail(chain, latest);
X		chain = latest;
X	}
X	if (chain == NULL)	/* Loop ran zero times. */
X		(void) regnode(NOTHING);
X
X	return(ret);
X}
X
X/*
X - regpiece - something followed by possible [*+?]
X *
X * Note that the branching code sequences used for ? and the general cases
X * of * and + are somewhat optimized:  they use the same NOTHING node as
X * both the endmarker for their branch list and the body of the last branch.
X * It might seem that this node could be dispensed with entirely, but the
X * endmarker role is not redundant.
X */
Xstatic char *
Xregpiece(flagp)
Xint *flagp;
X{
X	register char *ret;
X	register char op;
X	register char *next;
X	int flags;
X
X	ret = regatom(&flags);
X	if (ret == NULL)
X		return(NULL);
X
X	op = *regparse;
X	if (!ISMULT(op)) {
X		*flagp = flags;
X		return(ret);
X	}
X
X	if (!(flags&HASWIDTH) && op != '?')
X		FAIL("*+ operand could be empty");
X	*flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
X
X	if (op == '*' && (flags&SIMPLE))
X		reginsert(STAR, ret);
X	else if (op == '*') {
X		/* Emit x* as (x&|), where & means "self". */
X		reginsert(BRANCH, ret);			/* Either x */
X		regoptail(ret, regnode(BACK));		/* and loop */
X		regoptail(ret, ret);			/* back */
X		regtail(ret, regnode(BRANCH));		/* or */
X		regtail(ret, regnode(NOTHING));		/* null. */
X	} else if (op == '+' && (flags&SIMPLE))
X		reginsert(PLUS, ret);
X	else if (op == '+') {
X		/* Emit x+ as x(&|), where & means "self". */
X		next = regnode(BRANCH);			/* Either */
X		regtail(ret, next);
X		regtail(regnode(BACK), ret);		/* loop back */
X		regtail(next, regnode(BRANCH));		/* or */
X		regtail(ret, regnode(NOTHING));		/* null. */
X	} else if (op == '?') {
X		/* Emit x? as (x|) */
X		reginsert(BRANCH, ret);			/* Either x */
X		regtail(ret, regnode(BRANCH));		/* or */
X		next = regnode(NOTHING);		/* null. */
X		regtail(ret, next);
X		regoptail(ret, next);
X	}
X	regparse++;
X	if (ISMULT(*regparse))
X		FAIL("nested *?+");
X
X	return(ret);
X}
X
X/*
X - regatom - the lowest level
X *
X * Optimization:  gobbles an entire sequence of ordinary characters so that
X * it can turn them into a single node, which is smaller to store and
X * faster to run.  Backslashed characters are exceptions, each becoming a
X * separate node; the code is simpler that way and it's not worth fixing.
X */
Xstatic char *
Xregatom(flagp)
Xint *flagp;
X{
X	register char *ret;
X	int flags;
X
X	*flagp = WORST;		/* Tentatively. */
X
X	switch (*regparse++) {
X	/* FIXME: these chars only have meaning at beg/end of pat? */
X	case '^':
X		ret = regnode(BOL);
X		break;
X	case '$':
X		ret = regnode(EOL);
X		break;
X	case '.':
X		ret = regnode(ANY);
X		*flagp |= HASWIDTH|SIMPLE;
X		break;
X	case '[': {
X			register int class;
X			register int classend;
X
X			if (*regparse == '^') {	/* Complement of range. */
X				ret = regnode(ANYBUT);
X				regparse++;
X			} else
X				ret = regnode(ANYOF);
X			if (*regparse == ']' || *regparse == '-')
X				regc(*regparse++);
X			while (*regparse != '\0' && *regparse != ']') {
X				if (*regparse == '-') {
X					regparse++;
X					if (*regparse == ']' || *regparse == '\0')
X						regc('-');
X					else {
X						class = UCHARAT(regparse-2)+1;
X						classend = UCHARAT(regparse);
X						if (class > classend+1)
X							FAIL("invalid [] range");
X						for (; class <= classend; class++)
X							regc(class);
X						regparse++;
X					}
X				} else
X					regc(*regparse++);
X			}
X			regc('\0');
X			if (*regparse != ']')
X				FAIL("unmatched []");
X			regparse++;
X			*flagp |= HASWIDTH|SIMPLE;
X		}
X		break;
X	case '(':
X		ret = reg(1, &flags);
X		if (ret == NULL)
X			return(NULL);
X		*flagp |= flags&(HASWIDTH|SPSTART);
X		break;
X	case '\0':
X	case '|':
X	case '\n':
X	case ')':
X		FAIL("internal urp");	/* Supposed to be caught earlier. */
X		break;
X	case '?':
X	case '+':
X	case '*':
X		FAIL("?+* follows nothing");
X		break;
X	case '\\':
X		switch (*regparse++) {
X		case '\0':
X			FAIL("trailing \\");
X			break;
X		case '<':
X			ret = regnode(WORDA);
X			break;
X		case '>':
X			ret = regnode(WORDZ);
X			break;
X		/* FIXME: Someday handle \1, \2, ... */
X		default:
X			/* Handle general quoted chars in exact-match routine */
X			goto de_fault;
X		}
X		break;
X	de_fault:
X	default:
X		/*
X		 * Encode a string of characters to be matched exactly.
X		 *
X		 * This is a bit tricky due to quoted chars and due to
X		 * '*', '+', and '?' taking the SINGLE char previous
X		 * as their operand.
X		 *
X		 * On entry, the char at regparse[-1] is going to go
X		 * into the string, no matter what it is.  (It could be
X		 * following a \ if we are entered from the '\' case.)
X		 * 
X		 * Basic idea is to pick up a good char in  ch  and
X		 * examine the next char.  If it's *+? then we twiddle.
X		 * If it's \ then we frozzle.  If it's other magic char
X		 * we push  ch  and terminate the string.  If none of the
X		 * above, we push  ch  on the string and go around again.
X		 *
X		 *  regprev  is used to remember where "the current char"
X		 * starts in the string, if due to a *+? we need to back
X		 * up and put the current char in a separate, 1-char, string.
X		 * When  regprev  is NULL,  ch  is the only char in the
X		 * string; this is used in *+? handling, and in setting
X		 * flags |= SIMPLE at the end.
X		 */
X		{
X			char *regprev;
X			register char ch;
X
X			regparse--;			/* Look at cur char */
X			ret = regnode(EXACTLY);
X			for ( regprev = 0 ; ; ) {
X				ch = *regparse++;	/* Get current char */
X				switch (*regparse) {	/* look at next one */
X
X				default:
X					regc(ch);	/* Add cur to string */
X					break;
X
X				case '.': case '[': case '(':
X				case ')': case '|': case '\n':
X				case '$': case '^':
X				case '\0':
X				/* FIXME, $ and ^ should not always be magic */
X				magic:
X					regc(ch);	/* dump cur char */
X					goto done;	/* and we are done */
X
X				case '?': case '+': case '*':
X					if (!regprev) 	/* If just ch in str, */
X						goto magic;	/* use it */
X					/* End mult-char string one early */
X					regparse = regprev; /* Back up parse */
X					goto done;
X
X				case '\\':
X					regc(ch);	/* Cur char OK */
X					switch (regparse[1]){ /* Look after \ */
X					case '\0':
X					case '<':
X					case '>':
X					/* FIXME: Someday handle \1, \2, ... */
X						goto done; /* Not quoted */
X					default:
X						/* Backup point is \, scan							 * point is after it. */
X						regprev = regparse;
X						regparse++; 
X						continue;	/* NOT break; */
X					}
X				}
X				regprev = regparse;	/* Set backup point */
X			}
X		done:
X			regc('\0');
X			*flagp |= HASWIDTH;
X			if (!regprev)		/* One char? */
X				*flagp |= SIMPLE;
X		}
X		break;
X	}
X
X	return(ret);
X}
X
X/*
X - regnode - emit a node
X */
Xstatic char *			/* Location. */
Xregnode(op)
Xchar op;
X{
X	register char *ret;
X	register char *ptr;
X
X	ret = regcode;
X	if (ret == &regdummy) {
X		regsize += 3;
X		return(ret);
X	}
X
X	ptr = ret;
X	*ptr++ = op;
X	*ptr++ = '\0';		/* Null "next" pointer. */
X	*ptr++ = '\0';
X	regcode = ptr;
X
X	return(ret);
X}
X
X/*
X - regc - emit (if appropriate) a byte of code
X */
Xstatic void
Xregc(b)
Xchar b;
X{
X	if (regcode != &regdummy)
X		*regcode++ = b;
X	else
X		regsize++;
X}
X
X/*
X - reginsert - insert an operator in front of already-emitted operand
X *
X * Means relocating the operand.
X */
Xstatic void
Xreginsert(op, opnd)
Xchar op;
Xchar *opnd;
X{
X	register char *src;
X	register char *dst;
X	register char *place;
X
X	if (regcode == &regdummy) {
X		regsize += 3;
X		return;
X	}
X
X	src = regcode;
X	regcode += 3;
X	dst = regcode;
X	while (src > opnd)
X		*--dst = *--src;
X
X	place = opnd;		/* Op node, where operand used to be. */
X	*place++ = op;
X	*place++ = '\0';
X	*place++ = '\0';
X}
X
X/*
X - regtail - set the next-pointer at the end of a node chain
X */
Xstatic void
Xregtail(p, val)
Xchar *p;
Xchar *val;
X{
X	register char *scan;
X	register char *temp;
X	register int offset;
X
X	if (p == &regdummy)
X		return;
X
X	/* Find last node. */
X	scan = p;
X	for (;;) {
X		temp = regnext(scan);
X		if (temp == NULL)
X			break;
X		scan = temp;
X	}
X
X	if (OP(scan) == BACK)
X		offset = scan - val;
X	else
X		offset = val - scan;
X	*(scan+1) = (offset>>8)&0377;
X	*(scan+2) = offset&0377;
X}
X
X/*
X - regoptail - regtail on operand of first argument; nop if operandless
X */
Xstatic void
Xregoptail(p, val)
Xchar *p;
Xchar *val;
X{
X	/* "Operandless" and "op != BRANCH" are synonymous in practice. */
X	if (p == NULL || p == &regdummy || OP(p) != BRANCH)
X		return;
X	regtail(OPERAND(p), val);
X}
X
X/*
X * regexec and friends
X */
X
X/*
X * Global work variables for regexec().
X */
Xstatic char *reginput;		/* String-input pointer. */
Xstatic char *regbol;		/* Beginning of input, for ^ check. */
Xstatic char **regstartp;	/* Pointer to startp array. */
Xstatic char **regendp;		/* Ditto for endp. */
X
X/*
X * Forwards.
X */
XSTATIC int regtry();
XSTATIC int regmatch();
XSTATIC int regrepeat();
X
X#ifdef DEBUG
Xint regnarrate = 0;
Xvoid regdump();
XSTATIC char *regprop();
X#endif
X
X/*
X - regexec - match a regexp against a string
X */
Xint
Xregexec(prog, string)
Xregister const regexp *prog;
Xregister const char *string;
X{
X	register char *s;
X	extern char *strchr();
X
X	/* Be paranoid... */
X	if (prog == NULL || string == NULL) {
X		regerror("NULL parameter");
X		return(0);
X	}
X
X	/* Check validity of program. */
X	if (UCHARAT(prog->program) != MAGIC) {
X		regerror("corrupted program");
X		return(0);
X	}
X
X	/* If there is a "must appear" string, look for it. */
X	if (prog->regmust != NULL) {
X		s = (char *)string;
X		while ((s = strchr(s, prog->regmust[0])) != NULL) {
X			if (strncmp(s, prog->regmust, prog->regmlen) == 0)
X				break;	/* Found it. */
X			s++;
X		}
X		if (s == NULL)	/* Not present. */
X			return(0);
X	}
X
X	/* Mark beginning of line for ^ . */
X	regbol = (char *)string;
X
X	/* Simplest case:  anchored match need be tried only once. */
X	if (prog->reganch)
X		return(regtry(prog, string));
X
X	/* Messy cases:  unanchored match. */
X	s = (char *)string;
X	if (prog->regstart != '\0')
X		/* We know what char it must start with. */
X		while ((s = strchr(s, prog->regstart)) != NULL) {
X			if (regtry(prog, s))
X				return(1);
X			s++;
X		}
X	else
X		/* We don't -- general case. */
X		do {
X			if (regtry(prog, s))
X				return(1);
X		} while (*s++ != '\0');
X
X	/* Failure. */
X	return(0);
X}
X
X/*
X - regtry - try match at specific point
X */
Xstatic int			/* 0 failure, 1 success */
Xregtry(prog, string)
Xregexp *prog;
Xchar *string;
X{
X	register int i;
X	register char **sp;
X	register char **ep;
X
X	reginput = string;
X	regstartp = prog->startp;
X	regendp = prog->endp;
X
X	sp = prog->startp;
X	ep = prog->endp;
X	for (i = NSUBEXP; i > 0; i--) {
X		*sp++ = NULL;
X		*ep++ = NULL;
X	}
X	if (regmatch(prog->program + 1)) {
X		prog->startp[0] = string;
X		prog->endp[0] = reginput;
X		return(1);
X	} else
X		return(0);
X}
X
X/*
X - regmatch - main matching routine
X *
X * Conceptually the strategy is simple:  check to see whether the current
X * node matches, call self recursively to see whether the rest matches,
X * and then act accordingly.  In practice we make some effort to avoid
X * recursion, in particular by going through "ordinary" nodes (that don't
X * need to know whether the rest of the match failed) by a loop instead of
X * by recursion.
X */
Xstatic int			/* 0 failure, 1 success */
Xregmatch(prog)
Xchar *prog;
X{
X	register char *scan;	/* Current node. */
X	char *next;		/* Next node. */
X	extern char *strchr();
X
X	scan = prog;
X#ifdef DEBUG
X	if (scan != NULL && regnarrate)
X		fprintf(stderr, "%s(\n", regprop(scan));
X#endif
X	while (scan != NULL) {
X#ifdef DEBUG
X		if (regnarrate)
X			fprintf(stderr, "%s...\n", regprop(scan));
X#endif
X		next = regnext(scan);
X
X		switch (OP(scan)) {
X		case BOL:
X			if (reginput != regbol)
X				return(0);
X			break;
X		case EOL:
X			if (*reginput != '\0')
X				return(0);
X			break;
X		case WORDA:
X			/* Must be looking at a letter, digit, or _ */
X			if ((!isalnum(*reginput)) && *reginput != '_')
X				return(0);
X			/* Prev must be BOL or nonword */
X			if (reginput > regbol &&
X			    (isalnum(reginput[-1]) || reginput[-1] == '_'))
X				return(0);
X			break;
X		case WORDZ:
X			/* Must be looking at non letter, digit, or _ */
X			if (isalnum(*reginput) || *reginput == '_')
X				return(0);
X			/* We don't care what the previous char was */
X			break;
X		case ANY:
X			if (*reginput == '\0')
X				return(0);
X			reginput++;
X			break;
X		case EXACTLY: {
X				register int len;
X				register char *opnd;
X
X				opnd = OPERAND(scan);
X				/* Inline the first character, for speed. */
X				if (*opnd != *reginput)
X					return(0);
X				len = strlen(opnd);
X				if (len > 1 && strncmp(opnd, reginput, len) != 0)
X					return(0);
X				reginput += len;
X			}
X			break;
X		case ANYOF:
X 			if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
X				return(0);
X			reginput++;
X			break;
X		case ANYBUT:
X 			if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
X				return(0);
X			reginput++;
X			break;
X		case NOTHING:
X			break;
X		case BACK:
X			break;
X		case OPEN+1:
X		case OPEN+2:
X		case OPEN+3:
X		case OPEN+4:
X		case OPEN+5:
X		case OPEN+6:
X		case OPEN+7:
X		case OPEN+8:
X		case OPEN+9: {
X				register int no;
X				register char *save;
X
X				no = OP(scan) - OPEN;
X				save = reginput;
X
X				if (regmatch(next)) {
X					/*
X					 * Don't set startp if some later
X					 * invocation of the same parentheses
X					 * already has.
X					 */
X					if (regstartp[no] == NULL)
X						regstartp[no] = save;
X					return(1);
X				} else
X					return(0);
X			}
X			break;
X		case CLOSE+1:
X		case CLOSE+2:
X		case CLOSE+3:
X		case CLOSE+4:
X		case CLOSE+5:
X		case CLOSE+6:
X		case CLOSE+7:
X		case CLOSE+8:
X		case CLOSE+9: {
X				register int no;
X				register char *save;
X
X				no = OP(scan) - CLOSE;
X				save = reginput;
X
X				if (regmatch(next)) {
X					/*
X					 * Don't set endp if some later
X					 * invocation of the same parentheses
X					 * already has.
X					 */
X					if (regendp[no] == NULL)
X						regendp[no] = save;
X					return(1);
X				} else
X					return(0);
X			}
X			break;
X		case BRANCH: {
X				register char *save;
X
X				if (OP(next) != BRANCH)		/* No choice. */
X					next = OPERAND(scan);	/* Avoid recursion. */
X				else {
X					do {
X						save = reginput;
X						if (regmatch(OPERAND(scan)))
X							return(1);
X						reginput = save;
X						scan = regnext(scan);
X					} while (scan != NULL && OP(scan) == BRANCH);
X					return(0);
X					/* NOTREACHED */
X				}
X			}
X			break;
X		case STAR:
X		case PLUS: {
X				register char nextch;
X				register int no;
X				register char *save;
X				register int min;
X
X				/*
X				 * Lookahead to avoid useless match attempts
X				 * when we know what character comes next.
X				 */
X				nextch = '\0';
X				if (OP(next) == EXACTLY)
X					nextch = *OPERAND(next);
X				min = (OP(scan) == STAR) ? 0 : 1;
X				save = reginput;
X				no = regrepeat(OPERAND(scan));
X				while (no >= min) {
X					/* If it could work, try it. */
X					if (nextch == '\0' || *reginput == nextch)
X						if (regmatch(next))
X							return(1);
X					/* Couldn't or didn't -- back up. */
X					no--;
X					reginput = save + no;
X				}
X				return(0);
X			}
X			break;
X		case END:
X			return(1);	/* Success! */
X			break;
X		default:
X			regerror("memory corruption");
X			return(0);
X			break;
X		}
X
X		scan = next;
X	}
X
X	/*
X	 * We get here only if there's trouble -- normally "case END" is
X	 * the terminating point.
X	 */
X	regerror("corrupted pointers");
X	return(0);
X}
X
X/*
X - regrepeat - repeatedly match something simple, report how many
X */
Xstatic int
Xregrepeat(p)
Xchar *p;
X{
X	register int count = 0;
X	register char *scan;
X	register char *opnd;
X
X	scan = reginput;
X	opnd = OPERAND(p);
X	switch (OP(p)) {
X	case ANY:
X		count = strlen(scan);
X		scan += count;
X		break;
X	case EXACTLY:
X		while (*opnd == *scan) {
X			count++;
X			scan++;
X		}
X		break;
X	case ANYOF:
X		while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
X			count++;
X			scan++;
X		}
X		break;
X	case ANYBUT:
X		while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
X			count++;
X			scan++;
X		}
X		break;
X	default:		/* Oh dear.  Called inappropriately. */
X		regerror("internal foulup");
X		count = 0;	/* Best compromise. */
X		break;
X	}
X	reginput = scan;
X
X	return(count);
X}
X
X/*
X - regnext - dig the "next" pointer out of a node
X */
Xstatic char *
Xregnext(p)
Xregister char *p;
X{
X	register int offset;
X
X	if (p == &regdummy)
X		return(NULL);
X
X	offset = NEXT(p);
X	if (offset == 0)
X		return(NULL);
X
X	if (OP(p) == BACK)
X		return(p-offset);
X	else
X		return(p+offset);
X}
X
X#ifdef DEBUG
X
XSTATIC char *regprop();
X
X/*
X - regdump - dump a regexp onto stdout in vaguely comprehensible form
X */
Xvoid
Xregdump(r)
Xregexp *r;
X{
X	register char *s;
X	register char op = EXACTLY;	/* Arbitrary non-END op. */
X	register char *next;
X	extern char *strchr();
X
X
X	s = r->program + 1;
X	while (op != END) {	/* While that wasn't END last time... */
X		op = OP(s);
X		printf("%2d%s", s-r->program, regprop(s));	/* Where, what. */
X		next = regnext(s);
X		if (next == NULL)		/* Next ptr. */
X			printf("(0)");
X		else 
X			printf("(%d)", (s-r->program)+(next-s));
X		s += 3;
X		if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
X			/* Literal string, where present. */
X			while (*s != '\0') {
X				putchar(*s);
X				s++;
X			}
X			s++;
X		}
X		putchar('\n');
X	}
X
X	/* Header fields of interest. */
X	if (r->regstart != '\0')
X		printf("start `%c' ", r->regstart);
X	if (r->reganch)
X		printf("anchored ");
X	if (r->regmust != NULL)
X		printf("must have \"%s\"", r->regmust);
X	printf("\n");
X}
X
X/*
X - regprop - printable representation of opcode
X */
Xstatic char *
Xregprop(op)
Xchar *op;
X{
X	register char *p;
X	static char buf[50];
X
X	(void) strcpy(buf, ":");
X
X	switch (OP(op)) {
X	case BOL:
X		p = "BOL";
X		break;
X	case EOL:
X		p = "EOL";
X		break;
X	case ANY:
X		p = "ANY";
X		break;
X	case ANYOF:
X		p = "ANYOF";
X		break;
X	case ANYBUT:
X		p = "ANYBUT";
X		break;
X	case BRANCH:
X		p = "BRANCH";
X		break;
X	case EXACTLY:
X		p = "EXACTLY";
X		break;
X	case NOTHING:
X		p = "NOTHING";
X		break;
X	case BACK:
X		p = "BACK";
X		break;
X	case END:
X		p = "END";
X		break;
X	case OPEN+1:
X	case OPEN+2:
X	case OPEN+3:
X	case OPEN+4:
X	case OPEN+5:
X	case OPEN+6:
X	case OPEN+7:
X	case OPEN+8:
X	case OPEN+9:
X		sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
X		p = NULL;
X		break;
X	case CLOSE+1:
X	case CLOSE+2:
X	case CLOSE+3:
X	case CLOSE+4:
X	case CLOSE+5:
X	case CLOSE+6:
X	case CLOSE+7:
X	case CLOSE+8:
X	case CLOSE+9:
X		sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
X		p = NULL;
X		break;
X	case STAR:
X		p = "STAR";
X		break;
X	case PLUS:
X		p = "PLUS";
X		break;
X	case WORDA:
X		p = "WORDA";
X		break;
X	case WORDZ:
X		p = "WORDZ";
X		break;
X	default:
X		regerror("corrupted opcode");
X		break;
X	}
X	if (p != NULL)
X		(void) strcat(buf, p);
X	return(buf);
X}
X#endif
X
X/*
X * The following is provided for those people who do not have strcspn() in
X * their C libraries.  They should get off their butts and do something
X * about it; at least one public-domain implementation of those (highly
X * useful) string routines has been published on Usenet.
X */
X#ifdef STRCSPN
X/*
X * strcspn - find length of initial segment of s1 consisting entirely
X * of characters not from s2
X */
X
Xstatic int
Xstrcspn(s1, s2)
Xchar *s1;
Xchar *s2;
X{
X	register char *scan1;
X	register char *scan2;
X	register int count;
X
X	count = 0;
X	for (scan1 = s1; *scan1 != '\0'; scan1++) {
X		for (scan2 = s2; *scan2 != '\0';)	/* ++ moved down. */
X			if (*scan1 == *scan2++)
X				return(count);
X		count++;
X	}
X	return(count);
X}
X#endif
END_OF_FILE
if test 31244 -ne `wc -c <'regexp.c.orig'`; then
    echo shar: \"'regexp.c.orig'\" unpacked with wrong size!
fi
# end of 'regexp.c.orig'
fi
if test -f 'regexp.h' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'regexp.h'\"
else
echo shar: Extracting \"'regexp.h'\" \(574 characters\)
sed "s/^X//" >'regexp.h' <<'END_OF_FILE'
X/*
X * Definitions etc. for regexp(3) routines.
X *
X * Caveat:  this is V8 regexp(3) [actually, a reimplementation thereof],
X * not the System V one.
X */
X#define NSUBEXP  10
Xtypedef struct regexp {
X	char *startp[NSUBEXP];
X	char *endp[NSUBEXP];
X	char regstart;		/* Internal use only. */
X	char reganch;		/* Internal use only. */
X	char *regmust;		/* Internal use only. */
X	int regmlen;		/* Internal use only. */
X	char program[1];	/* Unwarranted chumminess with compiler. */
X} regexp;
X
Xextern regexp *regcomp();
Xextern int regexec();
Xextern void regsub();
Xextern void regerror();
END_OF_FILE
if test 574 -ne `wc -c <'regexp.h'`; then
    echo shar: \"'regexp.h'\" unpacked with wrong size!
fi
# end of 'regexp.h'
fi
if test -f 'regmagic.h' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'regmagic.h'\"
else
echo shar: Extracting \"'regmagic.h'\" \(153 characters\)
sed "s/^X//" >'regmagic.h' <<'END_OF_FILE'
X/*
X * The first byte of the regexp internal "program" is actually this magic
X * number; the start node begins in the second byte.
X */
X#define	MAGIC	0234
END_OF_FILE
if test 153 -ne `wc -c <'regmagic.h'`; then
    echo shar: \"'regmagic.h'\" unpacked with wrong size!
fi
# end of 'regmagic.h'
fi
if test -f 'regsub.c' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'regsub.c'\"
else
echo shar: Extracting \"'regsub.c'\" \(2502 characters\)
sed "s/^X//" >'regsub.c' <<'END_OF_FILE'
X/*
X * regsub
X *
X *	Copyright (c) 1986 by University of Toronto.
X *	Written by Henry Spencer.  Not derived from licensed software.
X *
X *	Permission is granted to anyone to use this software for any
X *	purpose on any computer system, and to redistribute it freely,
X *	subject to the following restrictions:
X *
X *	1. The author is not responsible for the consequences of use of
X *		this software, no matter how awful, even if they arise
X *		from defects in it.
X *
X *	2. The origin of this software must not be misrepresented, either
X *		by explicit claim or by omission.
X *
X *	3. Altered versions must be plainly marked as such, and must not
X *		be misrepresented as being the original software.
X */
X
X
X/* NOTE THIS HAS BEEN CHANGED TO WORK WITH MOO */
X/* Pattern spaces are referenced with %n instead of \n (n = 0..9) */
X/* Streams are used instead of strings */
X
X#include "regexp.h" /* CWL for moo */
X#include <stdio.h>
X#include <string.h>
X#include "regmagic.h"
X#include "streams.h"
X
X#ifndef CHARBITS
X#define	UCHARAT(p)	((int)*(unsigned char *)(p))
X#else
X#define	UCHARAT(p)	((int)*(p)&CHARBITS)
X#endif
X
X/*
X - regsub - perform substitutions after a regexp match
X */
Xvoid
Xregsub(prog, source, dest)
Xconst regexp *prog;
Xconst char *source;
X/*char *dest;*/
XStream *dest;
X{
X	register char *src;
X	register char *dst;
X	register char c;
X	register int no;
X	register int len;
X	extern char *strncpy();
X	char dstbuf[1024]; /* CWL */
X	register int cntr; /* CWL */
X
X	if (prog == NULL || source == NULL || dest == NULL) {
X		regerror("NULL parm to regsub");
X		return;
X	}
X	if (UCHARAT(prog->program) != MAGIC) {
X		regerror("damaged regexp fed to regsub");
X		return;
X	}
X
X	src = (char *)source;
X	/*dst = dest; CWL */
X	dst = dstbuf;
X	*dst = 0;
X	while ((c = *src++) != '\0') {
X		if (c == '&')
X			no = 0;
X		else if (c == '%' && '0' <= *src && *src <= '9') /* CWL */
X			no = *src++ - '0';
X		else
X			no = -1;
X 		if (no < 0) {	/* Ordinary character. */
X 			if (c == '%' && (*src == '%' || *src == '&'))
X 				c = *src++;
X 			/**dst++ = c; CWL */
X			stream_add_char(dest, c);
X 		} else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
X			len = prog->endp[no] - prog->startp[no];
X			dst = prog->startp[no];
X			for (cntr=0; cntr<len && *dst; cntr++)
X			  stream_add_char(dest, *dst++);
X			/*(void) strncpy(dst, prog->startp[no], len); */
X			/*dst += len;*/
X			/*if (len != 0 && *(dst-1) == '\0') {*/	/* strncpy hit NUL. */
X				/*regerror("damaged match string");*/
X				/*return;*/
X/*			}*/
X		}
X	}
X	/**dst++ = '\0'; CWL */
X}
END_OF_FILE
if test 2502 -ne `wc -c <'regsub.c'`; then
    echo shar: \"'regsub.c'\" unpacked with wrong size!
fi
# end of 'regsub.c'
fi
echo shar: End of shell archive.
exit 0
 
----------- cut here
-- 
Clay W. Luther                  [email-masked]
System Manager                  Center for Network Neuroscience
University of North Texas       PO Box 5218 Denton, Texas 76203
817/565-3896,3472               aka. Malraux@GodNet (Bushashuru!)