home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 9 / FreshFishVol9-CD2.bin / bbs / gnu / textutils-1.11-src.lha / textutils-1.11 / src / tr.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-13  |  51.5 KB  |  1,913 lines

  1. /* tr -- a filter to translate characters
  2.    Copyright (C) 1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Jim Meyering, meyering@cs.utexas.edu.  */
  19.  
  20. #include <config.h>
  21.  
  22. /* Get isblank from GNU libc.  */
  23. #define _GNU_SOURCE
  24.  
  25. #include <stdio.h>
  26. #include <assert.h>
  27. #include <errno.h>
  28. #include <sys/types.h>
  29. #include "getopt.h"
  30. #include "system.h"
  31. #include "version.h"
  32.  
  33. #ifndef LONG_MAX
  34. #define LONG_MAX 0x7FFFFFFF
  35. #endif
  36.  
  37. #ifndef UCHAR_MAX
  38. #define UCHAR_MAX 0xFF
  39. #endif
  40.  
  41. #define N_CHARS (UCHAR_MAX + 1)
  42.  
  43. /* A pointer to a function that returns an int.  */
  44. typedef int (*PFI) ();
  45.  
  46. /* Convert from character C to its index in the collating
  47.    sequence array.  Just cast to an unsigned int to avoid
  48.    problems with sign-extension.  */
  49. #define ORD(c) (unsigned int)(c)
  50.  
  51. /* The inverse of ORD.  */
  52. #define CHR(i) (unsigned char)(i)
  53.  
  54. /* The value for Spec_list->state that indicates to
  55.    get_next that it should initialize the tail pointer.
  56.    Its value doesn't matter as long as it can't be
  57.    confused with a valid character code.  */
  58. #define BEGIN_STATE (2 * N_CHARS)
  59.  
  60. /* The value for Spec_list->state that indicates to
  61.    get_next that the element pointed to by Spec_list->tail is
  62.    being considered for the first time on this pass through the
  63.    list -- it indicates that get_next should make any necessary
  64.    initializations.  */
  65. #define NEW_ELEMENT (BEGIN_STATE + 1)
  66.  
  67. /* A value distinct from any character that may have been stored in a
  68.    buffer as the result of a block-read in the function squeeze_filter.  */
  69. #define NOT_A_CHAR (unsigned int)(-1)
  70.  
  71. /* The following (but not CC_NO_CLASS) are indices into the array of
  72.    valid character class strings.  */
  73. enum Char_class
  74.   {
  75.     CC_ALNUM = 0, CC_ALPHA = 1, CC_BLANK = 2, CC_CNTRL = 3,
  76.     CC_DIGIT = 4, CC_GRAPH = 5, CC_LOWER = 6, CC_PRINT = 7,
  77.     CC_PUNCT = 8, CC_SPACE = 9, CC_UPPER = 10, CC_XDIGIT = 11,
  78.     CC_NO_CLASS = 9999
  79.   };
  80.  
  81. /* Character class to which a character (returned by get_next) belonged;
  82.    but it is set only if the construct from which the character was obtained
  83.    was one of the character classes [:upper:] or [:lower:].  The value
  84.    is used only when translating and then, only to make sure that upper
  85.    and lower class constructs have the same relative positions in string1
  86.    and string2.  */
  87. enum Upper_Lower_class
  88.   {
  89.     UL_LOWER = 0,
  90.     UL_UPPER = 1,
  91.     UL_NONE = 2
  92.   };
  93.  
  94. /* A shortcut to ensure that when constructing the translation array,
  95.    one of the values returned by paired calls to get_next (from s1 and s2)
  96.    is from [:upper:] and the other is from [:lower:], or neither is from
  97.    upper or lower.  In fact, no other character classes are allowed when
  98.    translating, but that condition is tested elsewhere.  This array is
  99.    indexed by values of type enum Upper_Lower_class.  */
  100. static int const class_ok[3][3] =
  101. {
  102.   {0, 1, 0},
  103.   {1, 0, 0},
  104.   {0, 0, 1}
  105. };
  106.  
  107. /* The type of a List_element.  See build_spec_list for more details.  */
  108. enum Range_element_type
  109.   {
  110.     RE_NO_TYPE = 0,
  111.     RE_NORMAL_CHAR,
  112.     RE_RANGE,
  113.     RE_CHAR_CLASS,
  114.     RE_EQUIV_CLASS,
  115.     RE_REPEATED_CHAR
  116.   };
  117.  
  118. /* One construct in one of tr's argument strings.
  119.    For example, consider the POSIX version of the classic tr command:
  120.        tr -cs 'a-zA-Z_' '[\n*]'
  121.    String1 has 3 constructs, two of which are ranges (a-z and A-Z),
  122.    and a single normal character, `_'.  String2 has one construct.  */
  123. struct List_element
  124.   {
  125.     enum Range_element_type type;
  126.     struct List_element *next;
  127.     union
  128.       {
  129.     int normal_char;
  130.     struct            /* unnamed */
  131.       {
  132.         unsigned int first_char;
  133.         unsigned int last_char;
  134.       }
  135.     range;
  136.     enum Char_class char_class;
  137.     int equiv_code;
  138.     struct            /* unnamed */
  139.       {
  140.         unsigned int the_repeated_char;
  141.         long repeat_count;
  142.       }
  143.     repeated_char;
  144.       }
  145.     u;
  146.   };
  147.  
  148. /* Each of tr's argument strings is parsed into a form that is easier
  149.    to work with: a linked list of constructs (struct List_element).
  150.    Each Spec_list structure also encapsulates various attributes of
  151.    the corresponding argument string.  The attributes are used mainly
  152.    to verify that the strings are legal in the context of any options
  153.    specified (like -s, -d, or -c).  The main exception is the member
  154.    `tail', which is first used to construct the list.  After construction,
  155.    it is used by get_next to save its state when traversing the list.
  156.    The member `state' serves a similar function.  */
  157. struct Spec_list
  158.   {
  159.     /* Points to the head of the list of range elements.
  160.        The first struct is a dummy; its members are never used.  */
  161.     struct List_element *head;
  162.  
  163.     /* When appending, points to the last element.  When traversing via
  164.        get_next(), points to the element to process next.  Setting
  165.        Spec_list.state to the value BEGIN_STATE before calling get_next
  166.        signals get_next to initialize tail to point to head->next.  */
  167.     struct List_element *tail;
  168.  
  169.     /* Used to save state between calls to get_next().  */
  170.     unsigned int state;
  171.  
  172.     /* Length, in the sense that length('a-z[:digit:]123abc')
  173.        is 42 ( = 26 + 10 + 6).  */
  174.     int length;
  175.  
  176.     /* The number of [c*] and [c*0] constructs that appear in this spec.  */
  177.     int n_indefinite_repeats;
  178.  
  179.     /* Non-zero if this spec contains at least one equivalence
  180.        class construct e.g. [=c=].  */
  181.     int has_equiv_class;
  182.  
  183.     /* Non-zero if this spec contains at least one of [:upper:] or
  184.        [:lower:] class constructs.  */
  185.     int has_upper_or_lower;
  186.  
  187.     /* Non-zero if this spec contains at least one of the character class
  188.        constructs (all but upper and lower) that aren't allowed in s2.  */
  189.     int has_restricted_char_class;
  190.   };
  191.  
  192. char *xmalloc ();
  193. char *stpcpy ();
  194. void error ();
  195. int safe_read ();
  196.  
  197. /* The name by which this program was run.  */
  198. char *program_name;
  199.  
  200. /* When non-zero, each sequence in the input of a repeated character
  201.    (call it c) is replaced (in the output) by a single occurrence of c
  202.    for every c in the squeeze set.  */
  203. static int squeeze_repeats = 0;
  204.  
  205. /* When non-zero, removes characters in the delete set from input.  */
  206. static int delete = 0;
  207.  
  208. /* Use the complement of set1 in place of set1.  */
  209. static int complement = 0;
  210.  
  211. /* When non-zero, this flag causes GNU tr to provide strict
  212.    compliance with POSIX draft 1003.2.11.2.  The POSIX spec
  213.    says that when -d is used without -s, string2 (if present)
  214.    must be ignored.  Silently ignoring arguments is a bad idea.
  215.    The default GNU behavior is to give a usage message and exit.
  216.    Additionally, when this flag is non-zero, tr prints warnings
  217.    on stderr if it is being used in a manner that is not portable.
  218.    Applicable warnings are given by default, but are suppressed
  219.    if the environment variable `POSIXLY_CORRECT' is set, since
  220.    being POSIX conformant means we can't issue such messages.
  221.    Warnings on the following topics are suppressed when this
  222.    variable is non-zero:
  223.    1. Ambiguous octal escapes.  */
  224. static int posix_pedantic;
  225.  
  226. /* When tr is performing translation and string1 is longer than string2,
  227.    POSIX says that the result is undefined.  That gives the implementor
  228.    of a POSIX conforming version of tr two reasonable choices for the
  229.    semantics of this case.
  230.  
  231.    * The BSD tr pads string2 to the length of string1 by
  232.    repeating the last character in string2.
  233.  
  234.    * System V tr ignores characters in string1 that have no
  235.    corresponding character in string2.  That is, string1 is effectively
  236.    truncated to the length of string2.
  237.  
  238.    When non-zero, this flag causes GNU tr to imitate the behavior
  239.    of System V tr when translating with string1 longer than string2.
  240.    The default is to emulate BSD tr.  This flag is ignored in modes where
  241.    no translation is performed.  Emulating the System V tr
  242.    in this exceptional case causes the relatively common BSD idiom:
  243.  
  244.        tr -cs A-Za-z0-9 '\012'
  245.  
  246.    to break (it would convert only zero bytes, rather than all
  247.    non-alphanumerics, to newlines).
  248.  
  249.    WARNING: This switch does not provide general BSD or System V
  250.    compatibility.  For example, it doesn't disable the interpretation
  251.    of the POSIX constructs [:alpha:], [=c=], and [c*10], so if by
  252.    some unfortunate coincidence you use such constructs in scripts
  253.    expecting to use some other version of tr, the scripts will break.  */
  254. static int truncate_set1 = 0;
  255.  
  256. /* An alias for (!delete && non_option_args == 2).
  257.    It is set in main and used there and in validate().  */
  258. static int translating;
  259.  
  260. #ifndef BUFSIZ
  261. #define BUFSIZ 8192
  262. #endif
  263.  
  264. #define IO_BUF_SIZE BUFSIZ
  265. static unsigned char io_buf[IO_BUF_SIZE];
  266.  
  267. static char const *const char_class_name[] =
  268. {
  269.   "alnum", "alpha", "blank", "cntrl", "digit", "graph",
  270.   "lower", "print", "punct", "space", "upper", "xdigit"
  271. };
  272. #define N_CHAR_CLASSES (sizeof(char_class_name) / sizeof(char_class_name[0]))
  273.  
  274. typedef char SET_TYPE;
  275.  
  276. /* Array of boolean values.  A character `c' is a member of the
  277.    squeeze set if and only if in_squeeze_set[c] is true.  The squeeze
  278.    set is defined by the last (possibly, the only) string argument
  279.    on the command line when the squeeze option is given.  */
  280. static SET_TYPE in_squeeze_set[N_CHARS];
  281.  
  282. /* Array of boolean values.  A character `c' is a member of the
  283.    delete set if and only if in_delete_set[c] is true.  The delete
  284.    set is defined by the first (or only) string argument on the
  285.    command line when the delete option is given.  */
  286. static SET_TYPE in_delete_set[N_CHARS];
  287.  
  288. /* Array of character values defining the translation (if any) that
  289.    tr is to perform.  Translation is performed only when there are
  290.    two specification strings and the delete switch is not given.  */
  291. static char xlate[N_CHARS];
  292.  
  293. /* If non-zero, display usage information and exit.  */
  294. static int show_help;
  295.  
  296. /* If non-zero, print the version on standard output then exit.  */
  297. static int show_version;
  298.  
  299. static struct option const long_options[] =
  300. {
  301.   {"complement", no_argument, NULL, 'c'},
  302.   {"delete", no_argument, NULL, 'd'},
  303.   {"squeeze-repeats", no_argument, NULL, 's'},
  304.   {"truncate-set1", no_argument, NULL, 't'},
  305.   {"help", no_argument, &show_help, 1},
  306.   {"version", no_argument, &show_version, 1},
  307.   {NULL, 0, NULL, 0}
  308. };
  309.  
  310. static void
  311. usage (status)
  312.      int status;
  313. {
  314.   if (status != 0)
  315.     fprintf (stderr, "Try `%s --help' for more information.\n",
  316.          program_name);
  317.   else
  318.     {
  319.       printf ("\
  320. Usage: %s [OPTION]... SET1 [SET2]\n\
  321. ",
  322.           program_name);
  323.       printf ("\
  324. \n\
  325.   -c, --complement        first complement SET1\n\
  326.   -d, --delete            delete characters in SET1, do not translate\n\
  327.   -s, --squeeze-repeats   replace sequence of characters with one\n\
  328.   -t, --truncate-set1     first truncate SET1 to length of SET2\n\
  329.       --help              display this help and exit\n\
  330.       --version           output version information and exit\n\
  331. ");
  332.       printf ("\
  333. \n\
  334. SETs are specified as strings of characters.  Most represent\n\
  335. themselves.  Here are the special writings:\n\
  336. \n\
  337.   \\NNN            character with octal value NNN (1 to 3 octal digits)\n\
  338.   \\\\              backslash\n\
  339.   \\a              audible BEL\n\
  340.   \\b              backspace\n\
  341.   \\f              form feed\n\
  342.   \\n              new line\n\
  343.   \\r              return\n\
  344.   \\t              horizontal tab\n\
  345.   \\v              vertical tab\n\
  346.   CHAR1-CHAR2     all characters from CHAR1 to CHAR2 in ascending order\n\
  347.   [CHAR1-CHAR2]   same as CHAR1-CHAR2, if both SET1 and SET2 use this\n\
  348.   [CHAR*]         in SET2, copies of CHAR until length of SET1\n\
  349.   [CHAR*REPEAT]   REPEAT copies of CHAR, REPEAT octal if starting with 0\n\
  350.   [:alnum:]       all letters and digits\n\
  351.   [:alpha:]       all letters\n\
  352.   [:blank:]       all horizontal whitespace\n\
  353.   [:cntrl:]       all control characters\n\
  354.   [:digit:]       all digits\n\
  355.   [:graph:]       all printable characters, not including space\n\
  356.   [:lower:]       all lower case letters\n\
  357.   [:print:]       all printable characters, including space\n\
  358.   [:punct:]       all punctuation characters\n\
  359.   [:space:]       all horizontal or vertical whitespace\n\
  360.   [:upper:]       all upper case letters\n\
  361.   [:xdigit:]      all hexadecimal digits\n\
  362.   [=CHAR=]        all characters which are equivalent to CHAR\n\
  363. ");
  364.       printf ("\
  365. \n\
  366. Translation occurs if -d is not given and both SET1 and SET2 appear.\n\
  367. -t may be used only when translating.  SET2 is extended to length of\n\
  368. SET1 by repeating its last character as necessary.  Excess characters\n\
  369. of SET2 are ignored.  Only [:lower:] and [:upper:] are guaranteed to\n\
  370. expand in ascending order; used in SET2 while translating, they may\n\
  371. only be used in pairs to specify case conversion.  -s uses SET1 if not\n\
  372. translating nor deleting; else squeezing uses SET2 and occurs after\n\
  373. translation or deletion.\n\
  374. ");
  375.     }
  376.   exit (status);
  377. }
  378.  
  379. /* Return non-zero if the character C is a member of the
  380.    equivalence class containing the character EQUIV_CLASS.  */
  381.  
  382. static int
  383. is_equiv_class_member (equiv_class, c)
  384.      unsigned int equiv_class;
  385.      unsigned int c;
  386. {
  387.   return (equiv_class == c);
  388. }
  389.  
  390. /* Return non-zero if the character C is a member of the
  391.    character class CHAR_CLASS.  */
  392.  
  393. static int
  394. is_char_class_member (char_class, c)
  395.      enum Char_class char_class;
  396.      unsigned int c;
  397. {
  398.   switch (char_class)
  399.     {
  400.     case CC_ALNUM:
  401.       return ISALNUM (c);
  402.       break;
  403.     case CC_ALPHA:
  404.       return ISALPHA (c);
  405.       break;
  406.     case CC_BLANK:
  407.       return ISBLANK (c);
  408.       break;
  409.     case CC_CNTRL:
  410.       return ISCNTRL (c);
  411.       break;
  412.     case CC_DIGIT:
  413.       return ISDIGIT (c);
  414.       break;
  415.     case CC_GRAPH:
  416.       return ISGRAPH (c);
  417.       break;
  418.     case CC_LOWER:
  419.       return ISLOWER (c);
  420.       break;
  421.     case CC_PRINT:
  422.       return ISPRINT (c);
  423.       break;
  424.     case CC_PUNCT:
  425.       return ISPUNCT (c);
  426.       break;
  427.     case CC_SPACE:
  428.       return ISSPACE (c);
  429.       break;
  430.     case CC_UPPER:
  431.       return ISUPPER (c);
  432.       break;
  433.     case CC_XDIGIT:
  434.       return ISXDIGIT (c);
  435.       break;
  436.     default:
  437.       abort ();
  438.       break;
  439.     }
  440. }
  441.  
  442. /* Perform the first pass over each range-spec argument S, converting all
  443.    \c and \ddd escapes to their one-byte representations.  The conversion
  444.    is done in-place, so S must point to writable storage.  If an invalid
  445.    quote sequence is found print an error message and return non-zero.
  446.    Otherwise set *LEN to the length of the resulting string and return
  447.    zero.  The resulting array of characters may contain zero-bytes;
  448.    however, on input, S is assumed to be null-terminated, and hence
  449.    cannot contain actual (non-escaped) zero bytes.  */
  450.  
  451. static int
  452. unquote (s, len)
  453.      unsigned char *s;
  454.      int *len;
  455. {
  456.   int i, j;
  457.  
  458.   j = 0;
  459.   for (i = 0; s[i]; i++)
  460.     {
  461.       switch (s[i])
  462.     {
  463.       int c;
  464.     case '\\':
  465.       switch (s[i + 1])
  466.         {
  467.           int oct_digit;
  468.         case '\\':
  469.           c = '\\';
  470.           break;
  471.         case 'a':
  472.           c = '\007';
  473.           break;
  474.         case 'b':
  475.           c = '\b';
  476.           break;
  477.         case 'f':
  478.           c = '\f';
  479.           break;
  480.         case 'n':
  481.           c = '\n';
  482.           break;
  483.         case 'r':
  484.           c = '\r';
  485.           break;
  486.         case 't':
  487.           c = '\t';
  488.           break;
  489.         case 'v':
  490.           c = '\v';
  491.           break;
  492.         case '0':
  493.         case '1':
  494.         case '2':
  495.         case '3':
  496.         case '4':
  497.         case '5':
  498.         case '6':
  499.         case '7':
  500.           c = s[i + 1] - '0';
  501.           oct_digit = s[i + 2] - '0';
  502.           if (0 <= oct_digit && oct_digit <= 7)
  503.         {
  504.           c = 8 * c + oct_digit;
  505.           ++i;
  506.           oct_digit = s[i + 2] - '0';
  507.           if (0 <= oct_digit && oct_digit <= 7)
  508.             {
  509.               if (8 * c + oct_digit < N_CHARS)
  510.             {
  511.               c = 8 * c + oct_digit;
  512.               ++i;
  513.             }
  514.               else if (!posix_pedantic)
  515.             {
  516.               /* Any octal number larger than 0377 won't
  517.                  fit in 8 bits.  So we stop when adding the
  518.                  next digit would put us over the limit and
  519.                  give a warning about the ambiguity.  POSIX
  520.                  isn't clear on this, but one person has said
  521.                  that in his interpretation, POSIX says tr
  522.                  can't even give a warning.  */
  523.               error (0, 0, "warning: the ambiguous octal escape \
  524. \\%c%c%c is being\n\tinterpreted as the 2-byte sequence \\0%c%c, `%c'",
  525.                  s[i], s[i + 1], s[i + 2],
  526.                  s[i], s[i + 1], s[i + 2]);
  527.             }
  528.             }
  529.         }
  530.           break;
  531.         case '\0':
  532.           error (0, 0, "invalid backslash escape at end of string");
  533.           return 1;
  534.           break;
  535.         default:
  536.           error (0, 0, "invalid backslash escape `\\%c'", s[i + 1]);
  537.           return 1;
  538.           break;
  539.         }
  540.       ++i;
  541.       s[j++] = c;
  542.       break;
  543.     default:
  544.       s[j++] = s[i];
  545.       break;
  546.     }
  547.     }
  548.   *len = j;
  549.   return 0;
  550. }
  551.  
  552. /* If CLASS_STR is a valid character class string, return its index
  553.    in the global char_class_name array.  Otherwise, return CC_NO_CLASS.  */
  554.  
  555. static enum Char_class
  556. look_up_char_class (class_str)
  557.      unsigned char *class_str;
  558. {
  559.   unsigned int i;
  560.  
  561.   for (i = 0; i < N_CHAR_CLASSES; i++)
  562.     if (strcmp ((const char *) class_str, char_class_name[i]) == 0)
  563.       return (enum Char_class) i;
  564.   return CC_NO_CLASS;
  565. }
  566.  
  567. /* Return a newly allocated string with a printable version of C.
  568.    This function is used solely for formatting error messages.  */
  569.  
  570. static char *
  571. make_printable_char (c)
  572.      unsigned int c;
  573. {
  574.   char *buf = xmalloc (5);
  575.  
  576.   assert (c < N_CHARS);
  577.   if (ISPRINT (c))
  578.     {
  579.       buf[0] = c;
  580.       buf[1] = '\0';
  581.     }
  582.   else
  583.     {
  584.       sprintf (buf, "\\%03o", c);
  585.     }
  586.   return buf;
  587. }
  588.  
  589. /* Return a newly allocated copy of S which is suitable for printing.
  590.    LEN is the number of characters in S.  Most non-printing
  591.    (isprint) characters are represented by a backslash followed by
  592.    3 octal digits.  However, the characters represented by \c escapes
  593.    where c is one of [abfnrtv] are represented by their 2-character \c
  594.    sequences.  This function is used solely for printing error messages.  */
  595.  
  596. static char *
  597. make_printable_str (s, len)
  598.      const unsigned char *s;
  599.      int len;
  600. {
  601.   /* Worst case is that every character expands to a backslash
  602.      followed by a 3-character octal escape sequence.  */
  603.   char *printable_buf = xmalloc (4 * len + 1);
  604.   char *p = printable_buf;
  605.   int i;
  606.  
  607.   for (i = 0; i < len; i++)
  608.     {
  609.       char buf[5];
  610.       char *tmp = NULL;
  611.  
  612.       switch (s[i])
  613.     {
  614.     case '\\':
  615.       tmp = "\\";
  616.       break;
  617.     case '\007':
  618.       tmp = "\\a";
  619.       break;
  620.     case '\b':
  621.       tmp = "\\b";
  622.       break;
  623.     case '\f':
  624.       tmp = "\\f";
  625.       break;
  626.     case '\n':
  627.       tmp = "\\n";
  628.       break;
  629.     case '\r':
  630.       tmp = "\\r";
  631.       break;
  632.     case '\t':
  633.       tmp = "\\t";
  634.       break;
  635.     case '\v':
  636.       tmp = "\\v";
  637.       break;
  638.     default:
  639.       if (ISPRINT (s[i]))
  640.         {
  641.           buf[0] = s[i];
  642.           buf[1] = '\0';
  643.         }
  644.       else
  645.         sprintf (buf, "\\%03o", s[i]);
  646.       tmp = buf;
  647.       break;
  648.     }
  649.       p = stpcpy (p, tmp);
  650.     }
  651.   return printable_buf;
  652. }
  653.  
  654. /* Append a newly allocated structure representing a
  655.    character C to the specification list LIST.  */
  656.  
  657. static void
  658. append_normal_char (list, c)
  659.      struct Spec_list *list;
  660.      unsigned int c;
  661. {
  662.   struct List_element *new;
  663.  
  664.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  665.   new->next = NULL;
  666.   new->type = RE_NORMAL_CHAR;
  667.   new->u.normal_char = c;
  668.   assert (list->tail);
  669.   list->tail->next = new;
  670.   list->tail = new;
  671. }
  672.  
  673. /* Append a newly allocated structure representing the range
  674.    of characters from FIRST to LAST to the specification list LIST.
  675.    Return non-zero if LAST precedes FIRST in the collating sequence,
  676.    zero otherwise.  This means that '[c-c]' is acceptable.  */
  677.  
  678. static int
  679. append_range (list, first, last)
  680.      struct Spec_list *list;
  681.      unsigned int first;
  682.      unsigned int last;
  683. {
  684.   struct List_element *new;
  685.  
  686.   if (ORD (first) > ORD (last))
  687.     {
  688.       char *tmp1 = make_printable_char (first);
  689.       char *tmp2 = make_printable_char (last);
  690.  
  691.       error (0, 0,
  692.        "range-endpoints of `%s-%s' are in reverse collating sequence order",
  693.          tmp1, tmp2);
  694.       free (tmp1);
  695.       free (tmp2);
  696.       return 1;
  697.     }
  698.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  699.   new->next = NULL;
  700.   new->type = RE_RANGE;
  701.   new->u.range.first_char = first;
  702.   new->u.range.last_char = last;
  703.   assert (list->tail);
  704.   list->tail->next = new;
  705.   list->tail = new;
  706.   return 0;
  707. }
  708.  
  709. /* If CHAR_CLASS_STR is a valid character class string, append a
  710.    newly allocated structure representing that character class to the end
  711.    of the specification list LIST and return 0.  If CHAR_CLASS_STR is not
  712.    a valid string, print an error message and return non-zero.  */
  713.  
  714. static int
  715. append_char_class (list, char_class_str, len)
  716.      struct Spec_list *list;
  717.      unsigned char *char_class_str;
  718.      int len;
  719. {
  720.   enum Char_class char_class;
  721.   struct List_element *new;
  722.  
  723.   char_class = look_up_char_class (char_class_str);
  724.   if (char_class == CC_NO_CLASS)
  725.     {
  726.       char *tmp = make_printable_str (char_class_str, len);
  727.  
  728.       error (0, 0, "invalid character class `%s'", tmp);
  729.       free (tmp);
  730.       return 1;
  731.     }
  732.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  733.   new->next = NULL;
  734.   new->type = RE_CHAR_CLASS;
  735.   new->u.char_class = char_class;
  736.   assert (list->tail);
  737.   list->tail->next = new;
  738.   list->tail = new;
  739.   return 0;
  740. }
  741.  
  742. /* Append a newly allocated structure representing a [c*n]
  743.    repeated character construct to the specification list LIST.
  744.    THE_CHAR is the single character to be repeated, and REPEAT_COUNT
  745.    is a non-negative repeat count.  */
  746.  
  747. static void
  748. append_repeated_char (list, the_char, repeat_count)
  749.      struct Spec_list *list;
  750.      unsigned int the_char;
  751.      long int repeat_count;
  752. {
  753.   struct List_element *new;
  754.  
  755.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  756.   new->next = NULL;
  757.   new->type = RE_REPEATED_CHAR;
  758.   new->u.repeated_char.the_repeated_char = the_char;
  759.   new->u.repeated_char.repeat_count = repeat_count;
  760.   assert (list->tail);
  761.   list->tail->next = new;
  762.   list->tail = new;
  763. }
  764.  
  765. /* Given a string, EQUIV_CLASS_STR, from a [=str=] context and
  766.    the length of that string, LEN, if LEN is exactly one, append
  767.    a newly allocated structure representing the specified
  768.    equivalence class to the specification list, LIST and return zero.
  769.    If LEN is not 1, issue an error message and return non-zero.  */
  770.  
  771. static int
  772. append_equiv_class (list, equiv_class_str, len)
  773.      struct Spec_list *list;
  774.      unsigned char *equiv_class_str;
  775.      int len;
  776. {
  777.   struct List_element *new;
  778.  
  779.   if (len != 1)
  780.     {
  781.       char *tmp = make_printable_str (equiv_class_str, len);
  782.  
  783.       error (0, 0, "%s: equivalence class operand must be a single character",
  784.          tmp);
  785.       free (tmp);
  786.       return 1;
  787.     }
  788.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  789.   new->next = NULL;
  790.   new->type = RE_EQUIV_CLASS;
  791.   new->u.equiv_code = *equiv_class_str;
  792.   assert (list->tail);
  793.   list->tail->next = new;
  794.   list->tail = new;
  795.   return 0;
  796. }
  797.  
  798. /* Return a newly allocated copy of the substring P[FIRST_IDX..LAST_IDX].  */
  799.  
  800. static unsigned char *
  801. substr (p, first_idx, last_idx)
  802.      const unsigned char *p;
  803.      int first_idx;
  804.      int last_idx;
  805. {
  806.   int len = last_idx - first_idx + 1;
  807.   unsigned char *tmp = (unsigned char *) xmalloc (len + 1);
  808.  
  809.   assert (first_idx <= last_idx);
  810.   /* We must use bcopy or memcpy rather than strncpy
  811.      because `p' may contain zero-bytes.  */
  812.   bcopy (p + first_idx, tmp, len);
  813.   tmp[len] = '\0';
  814.   return tmp;
  815. }
  816.  
  817. /* Search forward starting at START_IDX for the 2-char sequence
  818.    (PRE_BRACKET_CHAR,']') in the string P of length P_LEN.  If such
  819.    a sequence is found, return the index of the first character,
  820.    otherwise return -1.  P may contain zero bytes.  */
  821.  
  822. static int
  823. find_closing_delim (p, start_idx, p_len, pre_bracket_char)
  824.      const unsigned char *p;
  825.      int start_idx;
  826.      int p_len;
  827.      unsigned int pre_bracket_char;
  828. {
  829.   int i;
  830.  
  831.   for (i = start_idx; i < p_len - 1; i++)
  832.     if (p[i] == pre_bracket_char && p[i + 1] == ']')
  833.       return i;
  834.   return -1;
  835. }
  836.  
  837. /* Convert a string S with explicit length LEN, possibly
  838.    containing embedded zero bytes, to a long integer value.
  839.    If the string represents a negative value, a value larger
  840.    than LONG_MAX, or if all LEN characters do not represent a
  841.    valid integer, return non-zero and do not modify *VAL.
  842.    Otherwise, return zero and set *VAL to the converted value.  */
  843.  
  844. static int
  845. non_neg_strtol (s, len, val)
  846.      const unsigned char *s;
  847.      int len;
  848.      long int *val;
  849. {
  850.   int i;
  851.   long sum = 0;
  852.   unsigned int base;
  853.  
  854.   if (len <= 0)
  855.     return 1;
  856.   if (s[0] == '0')
  857.     base = 8;
  858.   else if (ISDIGIT (s[0]))
  859.     base = 10;
  860.   else
  861.     return 1;
  862.  
  863.   for (i = 0; i < len; i++)
  864.     {
  865.       int c = s[i] - '0';
  866.  
  867.       if (c >= base || c < 0)
  868.     return 1;
  869.       if (i > 8 && sum > (LONG_MAX - c) / base)
  870.     return 1;
  871.       sum = sum * base + c;
  872.     }
  873.   *val = sum;
  874.   return 0;
  875. }
  876.  
  877. /* Parse the bracketed repeat-char syntax.  If the P_LEN characters
  878.    beginning with P[ START_IDX ] comprise a valid [c*n] construct,
  879.    return the character and the repeat count through the arg pointers,
  880.    CHAR_TO_REPEAT and N, and then return the index of the closing
  881.    bracket as the function value.  If the second character following
  882.    the opening bracket is not `*' or if no closing bracket can be
  883.    found, return -1.  If a closing bracket is found and the
  884.    second char is `*', but the string between the `*' and `]' isn't
  885.    empty, an octal number, or a decimal number, print an error message
  886.    and return -2.  */
  887.  
  888. static int
  889. find_bracketed_repeat (p, start_idx, p_len, char_to_repeat, n)
  890.      const unsigned char *p;
  891.      int start_idx;
  892.      int p_len;
  893.      unsigned int *char_to_repeat;
  894.      long int *n;
  895. {
  896.   int i;
  897.  
  898.   assert (start_idx + 1 < p_len);
  899.   if (p[start_idx + 1] != '*')
  900.     return -1;
  901.  
  902.   for (i = start_idx + 2; i < p_len; i++)
  903.     {
  904.       if (p[i] == ']')
  905.     {
  906.       const unsigned char *digit_str;
  907.       int digit_str_len = i - start_idx - 2;
  908.  
  909.       *char_to_repeat = p[start_idx];
  910.       if (digit_str_len == 0)
  911.         {
  912.           /* We've matched [c*] -- no explicit repeat count.  */
  913.           *n = 0;
  914.           return i;
  915.         }
  916.  
  917.       /* Here, we have found [c*s] where s should be a string
  918.          of octal or decimal digits.  */
  919.       digit_str = &p[start_idx + 2];
  920.       if (non_neg_strtol (digit_str, digit_str_len, n))
  921.         {
  922.           char *tmp = make_printable_str (digit_str, digit_str_len);
  923.           error (0, 0, "invalid repeat count `%s' in [c*n] construct", tmp);
  924.           free (tmp);
  925.           return -2;
  926.         }
  927.       return i;
  928.     }
  929.     }
  930.   return -1;            /* No bracket found.  */
  931. }
  932.  
  933. /* Convert string UNESACPED_STRING (which has been preprocessed to
  934.    convert backslash-escape sequences) of length LEN characters into
  935.    a linked list of the following 5 types of constructs:
  936.       - [:str:] Character class where `str' is one of the 12 valid strings.
  937.       - [=c=] Equivalence class where `c' is any single character.
  938.       - [c*n] Repeat the single character `c' `n' times. n may be omitted.
  939.       However, if `n' is present, it must be a non-negative octal or
  940.       decimal integer.
  941.       - r-s Range of characters from `r' to `s'.  The second endpoint must
  942.       not precede the first in the current collating sequence.
  943.       - c Any other character is interpreted as itself.  */
  944.  
  945. static int
  946. build_spec_list (unescaped_string, len, result)
  947.      const unsigned char *unescaped_string;
  948.      int len;
  949.      struct Spec_list *result;
  950. {
  951.   const unsigned char *p;
  952.   int i;
  953.  
  954.   p = unescaped_string;
  955.  
  956.   /* The main for-loop below recognizes the 4 multi-character constructs.
  957.      A character that matches (in its context) none of the multi-character
  958.      constructs is classified as `normal'.  Since all multi-character
  959.      constructs have at least 3 characters, any strings of length 2 or
  960.      less are composed solely of normal characters.  Hence, the index of
  961.      the outer for-loop runs only as far as LEN-2.  */
  962.  
  963.   for (i = 0; i < len - 2;)
  964.     {
  965.       switch (p[i])
  966.     {
  967.       int fall_through;
  968.     case '[':
  969.       fall_through = 0;
  970.       switch (p[i + 1])
  971.         {
  972.           int closing_delim_idx;
  973.           int closing_bracket_idx;
  974.           unsigned int char_to_repeat;
  975.           long repeat_count;
  976.         case ':':
  977.         case '=':
  978.           closing_delim_idx = find_closing_delim (p, i + 2, len, p[i + 1]);
  979.           if (closing_delim_idx >= 0)
  980.         {
  981.           int parse_failed;
  982.           unsigned char *opnd_str = substr (p, i + 2,
  983.                             closing_delim_idx - 1);
  984.           if (p[i + 1] == ':')
  985.             parse_failed = append_char_class (result, opnd_str,
  986.                      (closing_delim_idx - 1) - (i + 2) + 1);
  987.           else
  988.             parse_failed = append_equiv_class (result, opnd_str,
  989.                      (closing_delim_idx - 1) - (i + 2) + 1);
  990.           free (opnd_str);
  991.  
  992.           /* Return non-zero if append_*_class reports a problem.  */
  993.           if (parse_failed)
  994.             return 1;
  995.           else
  996.             i = closing_delim_idx + 2;
  997.           break;
  998.         }
  999.           /* Else fall through.  This could be [:*] or [=*].  */
  1000.         default:
  1001.           /* Determine whether this is a bracketed repeat range
  1002.              matching the RE \[.\*(dec_or_oct_number)?\].  */
  1003.           closing_bracket_idx = find_bracketed_repeat (p, i + 1,
  1004.                        len, &char_to_repeat, &repeat_count);
  1005.           if (closing_bracket_idx >= 0)
  1006.         {
  1007.           append_repeated_char (result, char_to_repeat, repeat_count);
  1008.           i = closing_bracket_idx + 1;
  1009.           break;
  1010.         }
  1011.           else if (closing_bracket_idx == -1)
  1012.         {
  1013.           fall_through = 1;
  1014.         }
  1015.           else
  1016.         /* Found a string that looked like [c*n] but the
  1017.            numeric part was invalid.  */
  1018.         return 1;
  1019.           break;
  1020.         }
  1021.       if (!fall_through)
  1022.         break;
  1023.  
  1024.       /* Here if we've tried to match [c*n], [:str:], and [=c=]
  1025.          and none of them fit.  So we still have to consider the
  1026.          range `[-c' (from `[' to `c').  */
  1027.     default:
  1028.       /* Look ahead one char for ranges like a-z.  */
  1029.       if (p[i + 1] == '-')
  1030.         {
  1031.           if (append_range (result, p[i], p[i + 2]))
  1032.         return 1;
  1033.           i += 3;
  1034.         }
  1035.       else
  1036.         {
  1037.           append_normal_char (result, p[i]);
  1038.           ++i;
  1039.         }
  1040.       break;
  1041.     }
  1042.     }
  1043.  
  1044.   /* Now handle the (2 or fewer) remaining characters p[i]..p[len - 1].  */
  1045.   for (; i < len; i++)
  1046.     append_normal_char (result, p[i]);
  1047.  
  1048.   return 0;
  1049. }
  1050.  
  1051. /* Given a Spec_list S (with its saved state implicit in the values
  1052.    of its members `tail' and `state'), return the next single character
  1053.    in the expansion of S's constructs.  If the last character of S was
  1054.    returned on the previous call or if S was empty, this function
  1055.    returns -1.  For example, successive calls to get_next where S
  1056.    represents the spec-string 'a-d[y*3]' will return the sequence
  1057.    of values a, b, c, d, y, y, y, -1.  Finally, if the construct from
  1058.    which the returned character comes is [:upper:] or [:lower:], the
  1059.    parameter CLASS is given a value to indicate which it was.  Otherwise
  1060.    CLASS is set to UL_NONE.  This value is used only when constructing
  1061.    the translation table to verify that any occurrences of upper and
  1062.    lower class constructs in the spec-strings appear in the same relative
  1063.    positions.  */
  1064.  
  1065. static int
  1066. get_next (s, class)
  1067.      struct Spec_list *s;
  1068.      enum Upper_Lower_class *class;
  1069. {
  1070.   struct List_element *p;
  1071.   int return_val;
  1072.   int i;
  1073.  
  1074.   if (class)
  1075.     *class = UL_NONE;
  1076.  
  1077.   if (s->state == BEGIN_STATE)
  1078.     {
  1079.       s->tail = s->head->next;
  1080.       s->state = NEW_ELEMENT;
  1081.     }
  1082.  
  1083.   p = s->tail;
  1084.   if (p == NULL)
  1085.     return -1;
  1086.  
  1087.   switch (p->type)
  1088.     {
  1089.     case RE_NORMAL_CHAR:
  1090.       return_val = p->u.normal_char;
  1091.       s->state = NEW_ELEMENT;
  1092.       s->tail = p->next;
  1093.       break;
  1094.  
  1095.     case RE_RANGE:
  1096.       if (s->state == NEW_ELEMENT)
  1097.     s->state = ORD (p->u.range.first_char);
  1098.       else
  1099.     ++(s->state);
  1100.       return_val = CHR (s->state);
  1101.       if (s->state == ORD (p->u.range.last_char))
  1102.     {
  1103.       s->tail = p->next;
  1104.       s->state = NEW_ELEMENT;
  1105.     }
  1106.       break;
  1107.  
  1108.     case RE_CHAR_CLASS:
  1109.       if (s->state == NEW_ELEMENT)
  1110.     {
  1111.       for (i = 0; i < N_CHARS; i++)
  1112.         if (is_char_class_member (p->u.char_class, i))
  1113.           break;
  1114.       assert (i < N_CHARS);
  1115.       s->state = i;
  1116.     }
  1117.       assert (is_char_class_member (p->u.char_class, s->state));
  1118.       return_val = CHR (s->state);
  1119.       for (i = s->state + 1; i < N_CHARS; i++)
  1120.     if (is_char_class_member (p->u.char_class, i))
  1121.       break;
  1122.       if (i < N_CHARS)
  1123.     s->state = i;
  1124.       else
  1125.     {
  1126.       s->tail = p->next;
  1127.       s->state = NEW_ELEMENT;
  1128.     }
  1129.       if (class)
  1130.     {
  1131.       switch (p->u.char_class)
  1132.         {
  1133.         case CC_LOWER:
  1134.           *class = UL_LOWER;
  1135.           break;
  1136.         case CC_UPPER:
  1137.           *class = UL_UPPER;
  1138.           break;
  1139.         default:
  1140.           /* empty */
  1141.           break;
  1142.         }
  1143.     }
  1144.       break;
  1145.  
  1146.     case RE_EQUIV_CLASS:
  1147.       /* FIXME: this assumes that each character is alone in its own
  1148.          equivalence class (which appears to be correct for my
  1149.          LC_COLLATE.  But I don't know of any function that allows
  1150.          one to determine a character's equivalence class.  */
  1151.  
  1152.       return_val = p->u.equiv_code;
  1153.       s->state = NEW_ELEMENT;
  1154.       s->tail = p->next;
  1155.       break;
  1156.  
  1157.     case RE_REPEATED_CHAR:
  1158.       /* Here, a repeat count of n == 0 means don't repeat at all.  */
  1159.       assert (p->u.repeated_char.repeat_count >= 0);
  1160.       if (p->u.repeated_char.repeat_count == 0)
  1161.     {
  1162.       s->tail = p->next;
  1163.       s->state = NEW_ELEMENT;
  1164.       return_val = get_next (s, class);
  1165.     }
  1166.       else
  1167.     {
  1168.       if (s->state == NEW_ELEMENT)
  1169.         {
  1170.           s->state = 0;
  1171.         }
  1172.       ++(s->state);
  1173.       return_val = p->u.repeated_char.the_repeated_char;
  1174.       if (p->u.repeated_char.repeat_count > 0
  1175.           && s->state == p->u.repeated_char.repeat_count)
  1176.         {
  1177.           s->tail = p->next;
  1178.           s->state = NEW_ELEMENT;
  1179.         }
  1180.     }
  1181.       break;
  1182.  
  1183.     case RE_NO_TYPE:
  1184.       abort ();
  1185.       break;
  1186.  
  1187.     default:
  1188.       abort ();
  1189.       break;
  1190.     }
  1191.  
  1192.   return return_val;
  1193. }
  1194.  
  1195. /* This is a minor kludge.  This function is called from
  1196.    get_spec_stats to determine the cardinality of a set derived
  1197.    from a complemented string.  It's a kludge in that some of the
  1198.    same operations are (duplicated) performed in set_initialize.  */
  1199.  
  1200. static int
  1201. card_of_complement (s)
  1202.      struct Spec_list *s;
  1203. {
  1204.   int c;
  1205.   int cardinality = N_CHARS;
  1206.   SET_TYPE in_set[N_CHARS];
  1207.  
  1208.   bzero (in_set, N_CHARS * sizeof (in_set[0]));
  1209.   s->state = BEGIN_STATE;
  1210.   while ((c = get_next (s, NULL)) != -1)
  1211.     if (!in_set[c]++)
  1212.       --cardinality;
  1213.   return cardinality;
  1214. }
  1215.  
  1216. /* Gather statistics about the spec-list S in preparation for the tests
  1217.    in validate that determine the legality of the specs.  This function
  1218.    is called at most twice; once for string1, and again for any string2.
  1219.    LEN_S1 < 0 indicates that this is the first call and that S represents
  1220.    string1.  When LEN_S1 >= 0, it is the length of the expansion of the
  1221.    constructs in string1, and we can use its value to resolve any
  1222.    indefinite repeat construct in S (which represents string2).  Hence,
  1223.    this function has the side-effect that it converts a valid [c*]
  1224.    construct in string2 to [c*n] where n is large enough (or 0) to give
  1225.    string2 the same length as string1.  For example, with the command
  1226.    tr a-z 'A[\n*]Z' on the second call to get_spec_stats, LEN_S1 would
  1227.    be 26 and S (representing string2) would be converted to 'A[\n*24]Z'.  */
  1228.  
  1229. static void
  1230. get_spec_stats (s, len_s1)
  1231.      struct Spec_list *s;
  1232.      int len_s1;
  1233. {
  1234.   struct List_element *p;
  1235.   struct List_element *indefinite_repeat_element = NULL;
  1236.   int len = 0;
  1237.  
  1238.   s->n_indefinite_repeats = 0;
  1239.   s->has_equiv_class = 0;
  1240.   s->has_restricted_char_class = 0;
  1241.   s->has_upper_or_lower = 0;
  1242.   for (p = s->head->next; p; p = p->next)
  1243.     {
  1244.       switch (p->type)
  1245.     {
  1246.       int i;
  1247.     case RE_NORMAL_CHAR:
  1248.       ++len;
  1249.       break;
  1250.  
  1251.     case RE_RANGE:
  1252.       assert (p->u.range.last_char >= p->u.range.first_char);
  1253.       len += p->u.range.last_char - p->u.range.first_char + 1;
  1254.       break;
  1255.  
  1256.     case RE_CHAR_CLASS:
  1257.       for (i = 0; i < N_CHARS; i++)
  1258.         if (is_char_class_member (p->u.char_class, i))
  1259.           ++len;
  1260.       switch (p->u.char_class)
  1261.         {
  1262.         case CC_UPPER:
  1263.         case CC_LOWER:
  1264.           s->has_upper_or_lower = 1;
  1265.           break;
  1266.         default:
  1267.           s->has_restricted_char_class = 1;
  1268.           break;
  1269.         }
  1270.       break;
  1271.  
  1272.     case RE_EQUIV_CLASS:
  1273.       for (i = 0; i < N_CHARS; i++)
  1274.         if (is_equiv_class_member (p->u.equiv_code, i))
  1275.           ++len;
  1276.       s->has_equiv_class = 1;
  1277.       break;
  1278.  
  1279.     case RE_REPEATED_CHAR:
  1280.       if (p->u.repeated_char.repeat_count > 0)
  1281.         len += p->u.repeated_char.repeat_count;
  1282.       else if (p->u.repeated_char.repeat_count == 0)
  1283.         {
  1284.           indefinite_repeat_element = p;
  1285.           ++(s->n_indefinite_repeats);
  1286.         }
  1287.       break;
  1288.  
  1289.     case RE_NO_TYPE:
  1290.       assert (0);
  1291.       break;
  1292.     }
  1293.     }
  1294.  
  1295.   if (len_s1 >= len && s->n_indefinite_repeats == 1)
  1296.     {
  1297.       indefinite_repeat_element->u.repeated_char.repeat_count = len_s1 - len;
  1298.       len = len_s1;
  1299.     }
  1300.   if (complement && len_s1 < 0)
  1301.     s->length = card_of_complement (s);
  1302.   else
  1303.     s->length = len;
  1304.   return;
  1305. }
  1306.  
  1307. static void
  1308. spec_init (spec_list)
  1309.      struct Spec_list *spec_list;
  1310. {
  1311.   spec_list->head = spec_list->tail =
  1312.     (struct List_element *) xmalloc (sizeof (struct List_element));
  1313.   spec_list->head->next = NULL;
  1314. }
  1315.  
  1316. /* This function makes two passes over the argument string S.  The first
  1317.    one converts all \c and \ddd escapes to their one-byte representations.
  1318.    The second constructs a linked specification list, SPEC_LIST, of the
  1319.    characters and constructs that comprise the argument string.  If either
  1320.    of these passes detects an error, this function returns non-zero.  */
  1321.  
  1322. static int
  1323. parse_str (s, spec_list)
  1324.      unsigned char *s;
  1325.      struct Spec_list *spec_list;
  1326. {
  1327.   int len;
  1328.  
  1329.   if (unquote (s, &len))
  1330.     return 1;
  1331.   if (build_spec_list (s, len, spec_list))
  1332.     return 1;
  1333.   return 0;
  1334. }
  1335.  
  1336. /* Given two specification lists, S1 and S2, and assuming that
  1337.    S1->length > S2->length, append a single [c*n] element to S2 where c
  1338.    is the last character in the expansion of S2 and n is the difference
  1339.    between the two lengths.
  1340.    Upon successful completion, S2->length is set to S1->length.  The only
  1341.    way this function can fail to make S2 as long as S1 is when S2 has
  1342.    zero-length, since in that case, there is no last character to repeat.
  1343.    So S2->length is required to be at least 1.
  1344.  
  1345.    Providing this functionality allows the user to do some pretty
  1346.    non-BSD (and non-portable) things:  For example, the command
  1347.        tr -cs '[:upper:]0-9' '[:lower:]'
  1348.    is almost guaranteed to give results that depend on your collating
  1349.    sequence.  */
  1350.  
  1351. static void
  1352. string2_extend (s1, s2)
  1353.      const struct Spec_list *s1;
  1354.      struct Spec_list *s2;
  1355. {
  1356.   struct List_element *p;
  1357.   int char_to_repeat;
  1358.   int i;
  1359.  
  1360.   assert (translating);
  1361.   assert (s1->length > s2->length);
  1362.   assert (s2->length > 0);
  1363.  
  1364.   p = s2->tail;
  1365.   switch (p->type)
  1366.     {
  1367.     case RE_NORMAL_CHAR:
  1368.       char_to_repeat = p->u.normal_char;
  1369.       break;
  1370.     case RE_RANGE:
  1371.       char_to_repeat = p->u.range.last_char;
  1372.       break;
  1373.     case RE_CHAR_CLASS:
  1374.       for (i = N_CHARS; i >= 0; i--)
  1375.     if (is_char_class_member (p->u.char_class, i))
  1376.       break;
  1377.       assert (i >= 0);
  1378.       char_to_repeat = CHR (i);
  1379.       break;
  1380.  
  1381.     case RE_REPEATED_CHAR:
  1382.       char_to_repeat = p->u.repeated_char.the_repeated_char;
  1383.       break;
  1384.  
  1385.     case RE_EQUIV_CLASS:
  1386.       /* This shouldn't happen, because validate exits with an error
  1387.          if it finds an equiv class in string2 when translating.  */
  1388.       abort ();
  1389.       break;
  1390.  
  1391.     case RE_NO_TYPE:
  1392.       abort ();
  1393.       break;
  1394.  
  1395.     default:
  1396.       abort ();
  1397.       break;
  1398.     }
  1399.  
  1400.   append_repeated_char (s2, char_to_repeat, s1->length - s2->length);
  1401.   s2->length = s1->length;
  1402.   return;
  1403. }
  1404.  
  1405. /* Die with an error message if S1 and S2 describe strings that
  1406.    are not valid with the given command line switches.
  1407.    A side effect of this function is that if a legal [c*] or
  1408.    [c*0] construct appears in string2, it is converted to [c*n]
  1409.    with a value for n that makes s2->length == s1->length.  By
  1410.    the same token, if the --truncate-set1 option is not
  1411.    given, S2 may be extended.  */
  1412.  
  1413. static void
  1414. validate (s1, s2)
  1415.      const struct Spec_list *s1;
  1416.      struct Spec_list *s2;
  1417. {
  1418.   get_spec_stats (s1, -1);
  1419.   if (s1->n_indefinite_repeats > 0)
  1420.     {
  1421.       error (1, 0, "the [c*] repeat construct may not appear in string1");
  1422.     }
  1423.  
  1424.   /* FIXME: it isn't clear from the POSIX spec that this is invalid,
  1425.      but in the spirit of the other restrictions put on translation
  1426.      with character classes, this seems a logical interpretation.  */
  1427.   if (complement && s1->has_upper_or_lower)
  1428.     {
  1429.       error (1, 0,
  1430.          "character classes may not be used when translating \
  1431. and complementing");
  1432.     }
  1433.  
  1434.   if (s2)
  1435.     {
  1436.       get_spec_stats (s2, s1->length);
  1437.       if (s2->has_restricted_char_class)
  1438.     {
  1439.       error (1, 0,
  1440.          "when translating, the only character classes that may \
  1441. appear in\n\tstring2 are `upper' and `lower'");
  1442.     }
  1443.  
  1444.       if (s2->n_indefinite_repeats > 1)
  1445.     {
  1446.       error (1, 0, "only one [c*] repeat construct may appear in string2");
  1447.     }
  1448.  
  1449.       if (translating)
  1450.     {
  1451.       if (s2->has_equiv_class)
  1452.         {
  1453.           error (1, 0,
  1454.              "[=c=] expressions may not appear in string2 \
  1455. when translating");
  1456.         }
  1457.  
  1458.       if (s1->length > s2->length)
  1459.         {
  1460.           if (!truncate_set1)
  1461.         {
  1462.           /* string2 must be non-empty unless --truncate-set1 is
  1463.              given or string1 is empty.  */
  1464.  
  1465.           if (s2->length == 0)
  1466.             error (1, 0,
  1467.              "when not truncating set1, string2 must be non-empty");
  1468.           string2_extend (s1, s2);
  1469.         }
  1470.         }
  1471.  
  1472.       if (complement && s2->has_upper_or_lower)
  1473.         error (1, 0,
  1474.            "character classes may not be used when translating \
  1475. and complementing");
  1476.     }
  1477.       else
  1478.     /* Not translating.  */
  1479.     {
  1480.       if (s2->n_indefinite_repeats > 0)
  1481.         error (1, 0,
  1482.            "the [c*] construct may appear in string2 only \
  1483. when translating");
  1484.     }
  1485.     }
  1486. }
  1487.  
  1488. /* Read buffers of SIZE bytes via the function READER (if READER is
  1489.    NULL, read from stdin) until EOF.  When non-NULL, READER is either
  1490.    read_and_delete or read_and_xlate.  After each buffer is read, it is
  1491.    processed and written to stdout.  The buffers are processed so that
  1492.    multiple consecutive occurrences of the same character in the input
  1493.    stream are replaced by a single occurrence of that character if the
  1494.    character is in the squeeze set.  */
  1495.  
  1496. static void
  1497. squeeze_filter (buf, size, reader)
  1498.      unsigned char *buf;
  1499.      long int size;
  1500.      PFI reader;
  1501. {
  1502.   unsigned int char_to_squeeze = NOT_A_CHAR;
  1503.   int i = 0;
  1504.   int nr = 0;
  1505.  
  1506.   for (;;)
  1507.     {
  1508.       int begin;
  1509.  
  1510.       if (i >= nr)
  1511.     {
  1512.       if (reader == NULL)
  1513.         nr = safe_read (0, (char *) buf, size);
  1514.       else
  1515.         nr = (*reader) (buf, size, NULL);
  1516.  
  1517.       if (nr < 0)
  1518.         error (1, errno, "read error");
  1519.       if (nr == 0)
  1520.         break;
  1521.       i = 0;
  1522.     }
  1523.  
  1524.       begin = i;
  1525.  
  1526.       if (char_to_squeeze == NOT_A_CHAR)
  1527.     {
  1528.       int out_len;
  1529.       /* Here, by being a little tricky, we can get a significant
  1530.          performance increase in most cases when the input is
  1531.          reasonably large.  Since tr will modify the input only
  1532.          if two consecutive (and identical) input characters are
  1533.          in the squeeze set, we can step by two through the data
  1534.          when searching for a character in the squeeze set.  This
  1535.          means there may be a little more work in a few cases and
  1536.          perhaps twice as much work in the worst cases where most
  1537.          of the input is removed by squeezing repeats.  But most
  1538.          uses of this functionality seem to remove less than 20-30%
  1539.          of the input.  */
  1540.       for (; i < nr && !in_squeeze_set[buf[i]]; i += 2)
  1541.         ;            /* empty */
  1542.  
  1543.       /* There is a special case when i == nr and we've just
  1544.          skipped a character (the last one in buf) that is in
  1545.          the squeeze set.  */
  1546.       if (i == nr && in_squeeze_set[buf[i - 1]])
  1547.         --i;
  1548.  
  1549.       if (i >= nr)
  1550.         out_len = nr - begin;
  1551.       else
  1552.         {
  1553.           char_to_squeeze = buf[i];
  1554.           /* We're about to output buf[begin..i].  */
  1555.           out_len = i - begin + 1;
  1556.  
  1557.           /* But since we stepped by 2 in the loop above,
  1558.              out_len may be one too large.  */
  1559.           if (i > 0 && buf[i - 1] == char_to_squeeze)
  1560.         --out_len;
  1561.  
  1562.           /* Advance i to the index of first character to be
  1563.              considered when looking for a char different from
  1564.              char_to_squeeze.  */
  1565.           ++i;
  1566.         }
  1567.       if (out_len > 0
  1568.           && fwrite ((char *) &buf[begin], 1, out_len, stdout) == 0)
  1569.         error (1, errno, "write error");
  1570.     }
  1571.  
  1572.       if (char_to_squeeze != NOT_A_CHAR)
  1573.     {
  1574.       /* Advance i to index of first char != char_to_squeeze
  1575.          (or to nr if all the rest of the characters in this
  1576.          buffer are the same as char_to_squeeze).  */
  1577.       for (; i < nr && buf[i] == char_to_squeeze; i++)
  1578.         ;            /* empty */
  1579.       if (i < nr)
  1580.         char_to_squeeze = NOT_A_CHAR;
  1581.       /* If (i >= nr) we've squeezed the last character in this buffer.
  1582.          So now we have to read a new buffer and continue comparing
  1583.          characters against char_to_squeeze.  */
  1584.     }
  1585.     }
  1586. }
  1587.  
  1588. /* Read buffers of SIZE bytes from stdin until one is found that
  1589.    contains at least one character not in the delete set.  Store
  1590.    in the array BUF, all characters from that buffer that are not
  1591.    in the delete set, and return the number of characters saved
  1592.    or 0 upon EOF.  */
  1593.  
  1594. static long
  1595. read_and_delete (buf, size, not_used)
  1596.      unsigned char *buf;
  1597.      long int size;
  1598.      PFI not_used;
  1599. {
  1600.   long n_saved;
  1601.   static int hit_eof = 0;
  1602.  
  1603.   assert (not_used == NULL);
  1604.   assert (size > 0);
  1605.  
  1606.   if (hit_eof)
  1607.     return 0;
  1608.  
  1609.   /* This enclosing do-while loop is to make sure that
  1610.      we don't return zero (indicating EOF) when we've
  1611.      just deleted all the characters in a buffer.  */
  1612.   do
  1613.     {
  1614.       int i;
  1615.       int nr = safe_read (0, (char *) buf, size);
  1616.  
  1617.       if (nr < 0)
  1618.     error (1, errno, "read error");
  1619.       if (nr == 0)
  1620.     {
  1621.       hit_eof = 1;
  1622.       return 0;
  1623.     }
  1624.  
  1625.       /* This first loop may be a waste of code, but gives much
  1626.          better performance when no characters are deleted in
  1627.          the beginning of a buffer.  It just avoids the copying
  1628.          of buf[i] into buf[n_saved] when it would be a NOP.  */
  1629.  
  1630.       for (i = 0; i < nr && !in_delete_set[buf[i]]; i++)
  1631.     /* empty */ ;
  1632.       n_saved = i;
  1633.  
  1634.       for (++i; i < nr; i++)
  1635.     if (!in_delete_set[buf[i]])
  1636.       buf[n_saved++] = buf[i];
  1637.     }
  1638.   while (n_saved == 0);
  1639.  
  1640.   return n_saved;
  1641. }
  1642.  
  1643. /* Read at most SIZE bytes from stdin into the array BUF.  Then
  1644.    perform the in-place and one-to-one mapping specified by the global
  1645.    array `xlate'.  Return the number of characters read, or 0 upon EOF.  */
  1646.  
  1647. static long
  1648. read_and_xlate (buf, size, not_used)
  1649.      unsigned char *buf;
  1650.      long int size;
  1651.      PFI not_used;
  1652. {
  1653.   long chars_read = 0;
  1654.   static int hit_eof = 0;
  1655.   int i;
  1656.  
  1657.   assert (not_used == NULL);
  1658.   assert (size > 0);
  1659.  
  1660.   if (hit_eof)
  1661.     return 0;
  1662.  
  1663.   chars_read = safe_read (0, (char *) buf, size);
  1664.   if (chars_read < 0)
  1665.     error (1, errno, "read error");
  1666.   if (chars_read == 0)
  1667.     {
  1668.       hit_eof = 1;
  1669.       return 0;
  1670.     }
  1671.  
  1672.   for (i = 0; i < chars_read; i++)
  1673.     buf[i] = xlate[buf[i]];
  1674.  
  1675.   return chars_read;
  1676. }
  1677.  
  1678. /* Initialize a boolean membership set IN_SET with the character
  1679.    values obtained by traversing the linked list of constructs S
  1680.    using the function `get_next'.  If COMPLEMENT_THIS_SET is
  1681.    non-zero the resulting set is complemented.  */
  1682.  
  1683. static void
  1684. set_initialize (s, complement_this_set, in_set)
  1685.      struct Spec_list *s;
  1686.      int complement_this_set;
  1687.      SET_TYPE *in_set;
  1688. {
  1689.   int c;
  1690.   int i;
  1691.  
  1692.   bzero (in_set, N_CHARS * sizeof (in_set[0]));
  1693.   s->state = BEGIN_STATE;
  1694.   while ((c = get_next (s, NULL)) != -1)
  1695.     in_set[c] = 1;
  1696.   if (complement_this_set)
  1697.     for (i = 0; i < N_CHARS; i++)
  1698.       in_set[i] = (!in_set[i]);
  1699. }
  1700.  
  1701. main (argc, argv)
  1702.      int argc;
  1703.      char **argv;
  1704. {
  1705.   int c;
  1706.   int non_option_args;
  1707.   struct Spec_list buf1, buf2;
  1708.   struct Spec_list *s1 = &buf1;
  1709.   struct Spec_list *s2 = &buf2;
  1710.  
  1711.   program_name = argv[0];
  1712.  
  1713.   while ((c = getopt_long (argc, argv, "cdst", long_options,
  1714.                (int *) 0)) != EOF)
  1715.     {
  1716.       switch (c)
  1717.     {
  1718.     case 0:
  1719.       break;
  1720.  
  1721.     case 'c':
  1722.       complement = 1;
  1723.       break;
  1724.  
  1725.     case 'd':
  1726.       delete = 1;
  1727.       break;
  1728.  
  1729.     case 's':
  1730.       squeeze_repeats = 1;
  1731.       break;
  1732.  
  1733.     case 't':
  1734.       truncate_set1 = 1;
  1735.       break;
  1736.  
  1737.     default:
  1738.       usage (2);
  1739.       break;
  1740.     }
  1741.     }
  1742.  
  1743.   if (show_version)
  1744.     {
  1745.       printf ("tr - %s\n", version_string);
  1746.       exit (0);
  1747.     }
  1748.  
  1749.   if (show_help)
  1750.     usage (0);
  1751.  
  1752.   posix_pedantic = (getenv ("POSIXLY_CORRECT") != NULL);
  1753.  
  1754.   non_option_args = argc - optind;
  1755.   translating = (non_option_args == 2 && !delete);
  1756.  
  1757.   /* Change this test if it is legal to give tr no options and
  1758.      no args at all.  POSIX doesn't specifically say anything
  1759.      either way, but it looks like they implied it's invalid
  1760.      by omission.  If you want to make tr do a slow imitation
  1761.      of `cat' use `tr a a'.  */
  1762.   if (non_option_args > 2)
  1763.     {
  1764.       error (0, 0, "too many arguments");
  1765.       usage (2);
  1766.     }
  1767.  
  1768.   if (!delete && !squeeze_repeats && non_option_args != 2)
  1769.     error (1, 0, "two strings must be given when translating");
  1770.  
  1771.   if (delete && squeeze_repeats && non_option_args != 2)
  1772.     error (1, 0, "two strings must be given when both \
  1773. deleting and squeezing repeats");
  1774.  
  1775.   /* If --delete is given without --squeeze-repeats, then
  1776.      only one string argument may be specified.  But POSIX
  1777.      says to ignore any string2 in this case, so if POSIXLY_CORRECT
  1778.      is set, pretend we never saw string2.  But I think
  1779.      this deserves a fatal error, so that's the default.  */
  1780.   if ((delete && !squeeze_repeats) && non_option_args != 1)
  1781.     {
  1782.       if (posix_pedantic && non_option_args == 2)
  1783.     --non_option_args;
  1784.       else
  1785.     error (1, 0,
  1786.            "only one string may be given when deleting \
  1787. without squeezing repeats");
  1788.     }
  1789.  
  1790.   if (squeeze_repeats && non_option_args == 0)
  1791.     error (1, 0, "at least one string must be given when squeezing repeats");
  1792.  
  1793.   spec_init (s1);
  1794.   if (parse_str ((unsigned char *) argv[optind], s1))
  1795.     exit (1);
  1796.  
  1797.   if (non_option_args == 2)
  1798.     {
  1799.       spec_init (s2);
  1800.       if (parse_str ((unsigned char *) argv[optind + 1], s2))
  1801.     exit (1);
  1802.     }
  1803.   else
  1804.     s2 = NULL;
  1805.  
  1806.   validate (s1, s2);
  1807.  
  1808.   if (squeeze_repeats && non_option_args == 1)
  1809.     {
  1810.       set_initialize (s1, complement, in_squeeze_set);
  1811.       squeeze_filter (io_buf, IO_BUF_SIZE, NULL);
  1812.     }
  1813.   else if (delete && non_option_args == 1)
  1814.     {
  1815.       int nr;
  1816.  
  1817.       set_initialize (s1, complement, in_delete_set);
  1818.       do
  1819.     {
  1820.       nr = read_and_delete (io_buf, IO_BUF_SIZE, NULL);
  1821.       if (nr > 0 && fwrite ((char *) io_buf, 1, nr, stdout) == 0)
  1822.         error (1, errno, "write error");
  1823.     }
  1824.       while (nr > 0);
  1825.     }
  1826.   else if (squeeze_repeats && delete && non_option_args == 2)
  1827.     {
  1828.       set_initialize (s1, complement, in_delete_set);
  1829.       set_initialize (s2, 0, in_squeeze_set);
  1830.       squeeze_filter (io_buf, IO_BUF_SIZE, (PFI) read_and_delete);
  1831.     }
  1832.   else if (translating)
  1833.     {
  1834.       if (complement)
  1835.     {
  1836.       int i;
  1837.       SET_TYPE *in_s1 = in_delete_set;
  1838.  
  1839.       set_initialize (s1, 0, in_s1);
  1840.       s2->state = BEGIN_STATE;
  1841.       for (i = 0; i < N_CHARS; i++)
  1842.         xlate[i] = i;
  1843.       for (i = 0; i < N_CHARS; i++)
  1844.         {
  1845.           if (!in_s1[i])
  1846.         {
  1847.           int ch = get_next (s2, NULL);
  1848.           assert (ch != -1 || truncate_set1);
  1849.           if (ch == -1)
  1850.             {
  1851.               /* This will happen when tr is invoked like e.g.
  1852.                  tr -cs A-Za-z0-9 '\012'.  */
  1853.               break;
  1854.             }
  1855.           xlate[i] = ch;
  1856.         }
  1857.         }
  1858.       assert (get_next (s2, NULL) == -1 || truncate_set1);
  1859.     }
  1860.       else
  1861.     {
  1862.       int c1, c2;
  1863.       int i;
  1864.       enum Upper_Lower_class class_s1;
  1865.       enum Upper_Lower_class class_s2;
  1866.  
  1867.       for (i = 0; i < N_CHARS; i++)
  1868.         xlate[i] = i;
  1869.       s1->state = BEGIN_STATE;
  1870.       s2->state = BEGIN_STATE;
  1871.       for (;;)
  1872.         {
  1873.           c1 = get_next (s1, &class_s1);
  1874.           c2 = get_next (s2, &class_s2);
  1875.           if (!class_ok[(int) class_s1][(int) class_s2])
  1876.         error (1, 0,
  1877.              "misaligned or mismatched upper and/or lower classes");
  1878.           /* The following should have been checked by validate...  */
  1879.           if (c2 == -1)
  1880.         break;
  1881.           xlate[c1] = c2;
  1882.         }
  1883.       assert (c1 == -1 || truncate_set1);
  1884.     }
  1885.       if (squeeze_repeats)
  1886.     {
  1887.       set_initialize (s2, 0, in_squeeze_set);
  1888.       squeeze_filter (io_buf, IO_BUF_SIZE, (PFI) read_and_xlate);
  1889.     }
  1890.       else
  1891.     {
  1892.       int chars_read;
  1893.  
  1894.       do
  1895.         {
  1896.           chars_read = read_and_xlate (io_buf, IO_BUF_SIZE, NULL);
  1897.           if (chars_read > 0
  1898.           && fwrite ((char *) io_buf, 1, chars_read, stdout) == 0)
  1899.         error (1, errno, "write error");
  1900.         }
  1901.       while (chars_read > 0);
  1902.     }
  1903.     }
  1904.  
  1905.   if (fclose (stdout) == EOF)
  1906.     error (2, errno, "write error");
  1907.  
  1908.   if (close (0) != 0)
  1909.     error (2, errno, "standard input");
  1910.  
  1911.   exit (0);
  1912. }
  1913.