home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 11 Util / 11-Util.zip / txtut122.zip / textutil / src / tr.c < prev    next >
C/C++ Source or Header  |  1998-04-11  |  59KB  |  2,079 lines

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