home *** CD-ROM | disk | FTP | other *** search
/ ftp.mactech.com 2010 / ftp.mactech.com.tar / ftp.mactech.com / online / source / c / compilers / DiffUtils.sit.hqx / DiffUtils / src / diff3.c < prev    next >
Text File  |  1993-11-14  |  48KB  |  1,708 lines

  1. /* Three way file comparison program (diff3) for Project GNU.
  2.    Copyright (C) 1988, 1989, 1992, 1993 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 Randy Smith */
  19.  
  20. #include "system.h"
  21. #include <stdio.h>
  22. #include <ctype.h>
  23. #include "getopt.h"
  24.  
  25. extern char const version_string[];
  26.  
  27. /*
  28.  * Internal data structures and macros for the diff3 program; includes
  29.  * data structures for both diff3 diffs and normal diffs.
  30.  */
  31.  
  32. /* Different files within a three way diff.  */
  33. #define    FILE0    0
  34. #define    FILE1    1
  35. #define    FILE2    2
  36.  
  37. /*
  38.  * A three way diff is built from two two-way diffs; the file which
  39.  * the two two-way diffs share is:
  40.  */
  41. #define    FILEC    FILE2
  42.  
  43. /*
  44.  * Different files within a two way diff.
  45.  * FC is the common file, FO the other file.
  46.  */
  47. #define FO 0
  48. #define FC 1
  49.  
  50. /* The ranges are indexed by */
  51. #define    START    0
  52. #define    END    1
  53.  
  54. enum diff_type {
  55.   ERROR,            /* Should not be used */
  56.   ADD,                /* Two way diff add */
  57.   CHANGE,            /* Two way diff change */
  58.   DELETE,            /* Two way diff delete */
  59.   DIFF_ALL,            /* All three are different */
  60.   DIFF_1ST,            /* Only the first is different */
  61.   DIFF_2ND,            /* Only the second */
  62.   DIFF_3RD            /* Only the third */
  63. };
  64.  
  65. /* Two way diff */
  66. struct diff_block {
  67.   int ranges[2][2];        /* Ranges are inclusive */
  68.   char **lines[2];        /* The actual lines (may contain nulls) */
  69.   size_t *lengths[2];        /* Line lengths (including newlines, if any) */
  70.   struct diff_block *next;
  71. };
  72.  
  73. /* Three way diff */
  74.  
  75. struct diff3_block {
  76.   enum diff_type correspond;    /* Type of diff */
  77.   int ranges[3][2];        /* Ranges are inclusive */
  78.   char **lines[3];        /* The actual lines (may contain nulls) */
  79.   size_t *lengths[3];        /* Line lengths (including newlines, if any) */
  80.   struct diff3_block *next;
  81. };
  82.  
  83. /*
  84.  * Access the ranges on a diff block.
  85.  */
  86. #define    D_LOWLINE(diff, filenum)    \
  87.   ((diff)->ranges[filenum][START])
  88. #define    D_HIGHLINE(diff, filenum)    \
  89.   ((diff)->ranges[filenum][END])
  90. #define    D_NUMLINES(diff, filenum)    \
  91.   (D_HIGHLINE (diff, filenum) - D_LOWLINE (diff, filenum) + 1)
  92.  
  93. /*
  94.  * Access the line numbers in a file in a diff by relative line
  95.  * numbers (i.e. line number within the diff itself).  Note that these
  96.  * are lvalues and can be used for assignment.
  97.  */
  98. #define    D_RELNUM(diff, filenum, linenum)    \
  99.   ((diff)->lines[filenum][linenum])
  100. #define    D_RELLEN(diff, filenum, linenum)    \
  101.   ((diff)->lengths[filenum][linenum])
  102.  
  103. /*
  104.  * And get at them directly, when that should be necessary.
  105.  */
  106. #define    D_LINEARRAY(diff, filenum)    \
  107.   ((diff)->lines[filenum])
  108. #define    D_LENARRAY(diff, filenum)    \
  109.   ((diff)->lengths[filenum])
  110.  
  111. /*
  112.  * Next block.
  113.  */
  114. #define    D_NEXT(diff)    ((diff)->next)
  115.  
  116. /*
  117.  * Access the type of a diff3 block.
  118.  */
  119. #define    D3_TYPE(diff)    ((diff)->correspond)
  120.  
  121. /*
  122.  * Line mappings based on diffs.  The first maps off the top of the
  123.  * diff, the second off of the bottom.
  124.  */
  125. #define    D_HIGH_MAPLINE(diff, fromfile, tofile, lineno)    \
  126.   ((lineno)                        \
  127.    - D_HIGHLINE ((diff), (fromfile))            \
  128.    + D_HIGHLINE ((diff), (tofile)))
  129.  
  130. #define    D_LOW_MAPLINE(diff, fromfile, tofile, lineno)    \
  131.   ((lineno)                        \
  132.    - D_LOWLINE ((diff), (fromfile))            \
  133.    + D_LOWLINE ((diff), (tofile)))
  134.  
  135. /*
  136.  * General memory allocation function.
  137.  */
  138. #define    ALLOCATE(number, type)    \
  139.   (type *) xmalloc ((number) * sizeof (type))
  140.  
  141. /* Options variables for flags set on command line.  */
  142.  
  143. /* If nonzero, treat all files as text files, never as binary.  */
  144. static int always_text;
  145.  
  146. /* If nonzero, write out an ed script instead of the standard diff3 format.  */
  147. static int edscript;
  148.  
  149. /* If nonzero, in the case of overlapping diffs (type DIFF_ALL),
  150.    preserve the lines which would normally be deleted from
  151.    file 1 with a special flagging mechanism.  */
  152. static int flagging;
  153.  
  154. /* Number of lines to keep in identical prefix and suffix.  */
  155. static int horizon_lines = 10;
  156.  
  157. /* Use a tab to align output lines (-T).  */
  158. static int tab_align_flag;
  159.  
  160. /* If nonzero, do not output information for overlapping diffs.  */
  161. static int simple_only;
  162.  
  163. /* If nonzero, do not output information for non-overlapping diffs.  */
  164. static int overlap_only;
  165.  
  166. /* If nonzero, show information for DIFF_2ND diffs.  */
  167. static int show_2nd;
  168.  
  169. /* If nonzero, include `:wq' at the end of the script
  170.    to write out the file being edited.   */
  171. static int finalwrite;
  172.  
  173. /* If nonzero, output a merged file.  */
  174. static int merge;
  175.  
  176. static char *argv0;
  177.  
  178. static VOID *xmalloc PARAMS((size_t));
  179. static VOID *xrealloc PARAMS((VOID *, size_t));
  180.  
  181. static char *read_diff PARAMS((char const *, char const *, char **));
  182. static char *scan_diff_line PARAMS((char *, char **, size_t *, char *, int));
  183. static enum diff_type process_diff_control PARAMS((char **, struct diff_block *));
  184. static int compare_line_list PARAMS((char * const[], size_t const[], char * const[], size_t const[], int));
  185. static int copy_stringlist PARAMS((char * const[], size_t const[], char *[], size_t[], int));
  186. static int dotlines PARAMS((FILE *, struct diff3_block *, int));
  187. static int output_diff3_edscript PARAMS((FILE *, struct diff3_block *, int const[3], int const[3], char const *, char const *, char const *));
  188. static int output_diff3_merge PARAMS((FILE *, FILE *, struct diff3_block *, int const[3], int const[3], char const *, char const *, char const *));
  189. static size_t myread PARAMS((int, char *, size_t));
  190. static struct diff3_block *create_diff3_block PARAMS((int, int, int, int, int, int));
  191. static struct diff3_block *make_3way_diff PARAMS((struct diff_block *, struct diff_block *));
  192. static struct diff3_block *reverse_diff3_blocklist PARAMS((struct diff3_block *));
  193. static struct diff3_block *using_to_diff3_block PARAMS((struct diff_block *[2], struct diff_block *[2], int, int, struct diff3_block const *));
  194. static struct diff_block *process_diff PARAMS((char const *, char const *, struct diff_block **));
  195. static void fatal PARAMS((char const *));
  196. static void output_diff3 PARAMS((FILE *, struct diff3_block *, int const[3], int const[3]));
  197. static void perror_with_exit PARAMS((char const *));
  198. static void undotlines PARAMS((FILE *, int, int, int));
  199. static void usage PARAMS((int));
  200.  
  201. static char const diff_program[] = DIFF_PROGRAM;
  202.  
  203. static struct option const longopts[] =
  204. {
  205.   {"text", 0, 0, 'a'},
  206.   {"show-all", 0, 0, 'A'},
  207.   {"ed", 0, 0, 'e'},
  208.   {"show-overlap", 0, 0, 'E'},
  209.   {"label", 1, 0, 'L'},
  210.   {"merge", 0, 0, 'm'},
  211.   {"initial-tab", 0, 0, 'T'},
  212.   {"overlap-only", 0, 0, 'x'},
  213.   {"easy-only", 0, 0, '3'},
  214.   {"version", 0, 0, 'v'},
  215.   {"help", 0, 0, 129},
  216.   {0, 0, 0, 0}
  217. };
  218.  
  219. /*
  220.  * Main program.  Calls diff twice on two pairs of input files,
  221.  * combines the two diffs, and outputs them.
  222.  */
  223. int
  224. main (argc, argv)
  225.      int argc;
  226.      char **argv;
  227. {
  228.   int c, i;
  229.   int mapping[3];
  230.   int rev_mapping[3];
  231.   int incompat;
  232.   int conflicts_found;
  233.   struct diff_block *thread0, *thread1, *last_block;
  234.   struct diff3_block *diff3;
  235.   int tag_count = 0;
  236.   char *tag_strings[3];
  237.   char *commonname;
  238.   char **file;
  239.   struct stat statb;
  240.  
  241.   incompat = 0;
  242.  
  243.   argv0 = argv[0];
  244.  
  245.   while ((c = getopt_long (argc, argv, "aeimvx3AEL:TX", longopts, 0)) != EOF)
  246.     {
  247.       switch (c)
  248.     {
  249.     case 'a':
  250.       always_text = 1;
  251.       break;
  252.     case 'A':
  253.       show_2nd = 1;
  254.       flagging = 1;
  255.       incompat++;
  256.       break;
  257.     case 'x':
  258.       overlap_only = 1;
  259.       incompat++;
  260.       break;
  261.     case '3':
  262.       simple_only = 1;
  263.       incompat++;
  264.       break;
  265.     case 'i':
  266.       finalwrite = 1;
  267.       break;
  268.     case 'm':
  269.       merge = 1;
  270.       break;
  271.     case 'X':
  272.       overlap_only = 1;
  273.       /* Falls through */
  274.     case 'E':
  275.       flagging = 1;
  276.       /* Falls through */
  277.     case 'e':
  278.       incompat++;
  279.       break;
  280.     case 'T':
  281.       tab_align_flag = 1;
  282.       break;
  283.     case 'v':
  284.       printf ("GNU diff3 version %s\n", version_string);
  285.       exit (0);
  286.     case 129:
  287.       usage (0);
  288.     case 'L':
  289.       /* Handle up to three -L options.  */
  290.       if (tag_count < 3)
  291.         {
  292.           tag_strings[tag_count++] = optarg;
  293.           break;
  294.         }
  295.       /* Falls through */
  296.     default:
  297.       usage (2);
  298.     }
  299.     }
  300.  
  301.   edscript = incompat & ~merge;  /* -AeExX3 without -m implies ed script.  */
  302.   show_2nd |= ~incompat & merge;  /* -m without -AeExX3 implies -A.  */
  303.   flagging |= ~incompat & merge;
  304.  
  305.   if (incompat > 1  /* Ensure at most one of -AeExX3.  */
  306.       || finalwrite & merge /* -i -m would rewrite input file.  */
  307.       || (tag_count && ! flagging) /* -L requires one of -AEX.  */
  308.       || argc - optind != 3)
  309.     usage (2);
  310.  
  311.   file = &argv[optind];
  312.  
  313.   for (i = tag_count; i < 3; i++)
  314.     tag_strings[i] = file[i];
  315.  
  316.   /* Always compare file1 to file2, even if file2 is "-".
  317.      This is needed for -mAeExX3.  Using the file0 as
  318.      the common file would produce wrong results, because if the
  319.      file0-file1 diffs didn't line up with the file0-file2 diffs
  320.      (which is entirely possible since we don't use diff's -n option),
  321.      diff3 might report phantom changes from file1 to file2.  */
  322.  
  323.   if (strcmp (file[2], "-") == 0)
  324.     {
  325.       /* Sigh.  We've got standard input as the last arg.  We can't
  326.      call diff twice on stdin.  Use the middle arg as the common
  327.      file instead.  */
  328.       if (strcmp (file[0], "-") == 0 || strcmp (file[1], "-") == 0)
  329.     fatal ("`-' specified for more than one input file");
  330.       mapping[0] = 0;
  331.       mapping[1] = 2;
  332.       mapping[2] = 1;
  333.     }
  334.   else
  335.     {
  336.       /* Normal, what you'd expect */
  337.       mapping[0] = 0;
  338.       mapping[1] = 1;
  339.       mapping[2] = 2;
  340.     }
  341.  
  342.   for (i = 0; i < 3; i++)
  343.     rev_mapping[mapping[i]] = i;
  344.  
  345.   for (i = 0; i < 3; i++)
  346.     if (strcmp (file[i], "-") != 0)
  347.       {
  348.     if (stat (file[i], &statb) < 0)
  349.       perror_with_exit (file[i]);
  350.     else if (S_ISDIR(statb.st_mode))
  351.       {
  352.         fprintf (stderr, "%s: %s: Is a directory\n", argv0, file[i]);
  353.         exit (2);
  354.       }
  355.       }
  356.  
  357.   commonname = file[rev_mapping[FILEC]];
  358.   thread1 = process_diff (file[rev_mapping[FILE1]], commonname, &last_block);
  359.   if (thread1)
  360.     for (i = 0; i < 2; i++)
  361.       {
  362.     horizon_lines = max (horizon_lines, D_NUMLINES (thread1, i));
  363.     horizon_lines = max (horizon_lines, D_NUMLINES (last_block, i));
  364.       }
  365.   thread0 = process_diff (file[rev_mapping[FILE0]], commonname, &last_block);
  366.   diff3 = make_3way_diff (thread0, thread1);
  367.   if (edscript)
  368.     conflicts_found
  369.       = output_diff3_edscript (stdout, diff3, mapping, rev_mapping,
  370.                    tag_strings[0], tag_strings[1], tag_strings[2]);
  371.   else if (merge)
  372.     {
  373.       if (! freopen (file[rev_mapping[FILE0]], "r", stdin))
  374.     perror_with_exit (file[rev_mapping[FILE0]]);
  375.       conflicts_found
  376.     = output_diff3_merge (stdin, stdout, diff3, mapping, rev_mapping,
  377.                   tag_strings[0], tag_strings[1], tag_strings[2]);
  378.       if (ferror (stdin))
  379.     fatal ("read error");
  380.     }
  381.   else
  382.     {
  383.       output_diff3 (stdout, diff3, mapping, rev_mapping);
  384.       conflicts_found = 0;
  385.     }
  386.  
  387.   if (ferror (stdout) || fclose (stdout) != 0)
  388.     fatal ("write error");
  389.   exit (conflicts_found);
  390.   return conflicts_found;
  391. }
  392.  
  393. /*
  394.  * Explain, patiently and kindly, how to use this program.  Then exit.
  395.  */
  396. static void
  397. usage (status)
  398.      int status;
  399. {
  400.   fflush (stderr);
  401.   printf ("\
  402. Usage: %s [options] my-file older-file your-file\n\
  403. Options:\n\
  404.     [-exAEX3aTv] [-i|-m] [-L label1 [-L label2 [-L label3]]]\n\
  405.     [--easy-only] [--ed] [--help] [--initial-tab]\n\
  406.     [--label=label1 [--label=label2 [--label=label3]]] [--merge]\n\
  407.     [--overlap-only] [--show-all] [--show-overlap] [--text] [--version]\n\
  408.     Only one of [exAEX3] is allowed\n", argv0);
  409.   exit (status);
  410. }
  411.  
  412. /*
  413.  * Routines that combine the two diffs together into one.  The
  414.  * algorithm used follows:
  415.  *
  416.  *   File2 is shared in common between the two diffs.
  417.  *   Diff02 is the diff between 0 and 2.
  418.  *   Diff12 is the diff between 1 and 2.
  419.  *
  420.  *    1) Find the range for the first block in File2.
  421.  *        a) Take the lowest of the two ranges (in File2) in the two
  422.  *           current blocks (one from each diff) as being the low
  423.  *           water mark.  Assign the upper end of this block as
  424.  *           being the high water mark and move the current block up
  425.  *           one.  Mark the block just moved over as to be used.
  426.  *        b) Check the next block in the diff that the high water
  427.  *           mark is *not* from.
  428.  *
  429.  *           *If* the high water mark is above
  430.  *           the low end of the range in that block,
  431.  *
  432.  *           mark that block as to be used and move the current
  433.  *           block up.  Set the high water mark to the max of
  434.  *           the high end of this block and the current.  Repeat b.
  435.  *
  436.  *     2) Find the corresponding ranges in File0 (from the blocks
  437.  *        in diff02; line per line outside of diffs) and in File1.
  438.  *        Create a diff3_block, reserving space as indicated by the ranges.
  439.  *
  440.  *     3) Copy all of the pointers for file2 in.  At least for now,
  441.  *        do memcmp's between corresponding strings in the two diffs.
  442.  *
  443.  *     4) Copy all of the pointers for file0 and 1 in.  Get what you
  444.  *        need from file2 (when there isn't a diff block, it's
  445.  *        identical to file2 within the range between diff blocks).
  446.  *
  447.  *     5) If the diff blocks you used came from only one of the two
  448.  *        strings of diffs, then that file (i.e. the one other than
  449.  *        the common file in that diff) is the odd person out.  If you used
  450.  *        diff blocks from both sets, check to see if files 0 and 1 match:
  451.  *
  452.  *        Same number of lines?  If so, do a set of memcmp's (if a
  453.  *        memcmp matches; copy the pointer over; it'll be easier later
  454.  *        if you have to do any compares).  If they match, 0 & 1 are
  455.  *        the same.  If not, all three different.
  456.  *
  457.  *   Then you do it again, until you run out of blocks.
  458.  *
  459.  */
  460.  
  461. /*
  462.  * This routine makes a three way diff (chain of diff3_block's) from two
  463.  * two way diffs (chains of diff_block's).  It is assumed that each of
  464.  * the two diffs passed are onto the same file (i.e. that each of the
  465.  * diffs were made "to" the same file).  The three way diff pointer
  466.  * returned will have numbering FILE0--the other file in diff02,
  467.  * FILE1--the other file in diff12, and FILEC--the common file.
  468.  */
  469. static struct diff3_block *
  470. make_3way_diff (thread0, thread1)
  471.      struct diff_block *thread0, *thread1;
  472. {
  473. /*
  474.  * This routine works on the two diffs passed to it as threads.
  475.  * Thread number 0 is diff02, thread number 1 is diff12.  The USING
  476.  * array is set to the base of the list of blocks to be used to
  477.  * construct each block of the three way diff; if no blocks from a
  478.  * particular thread are to be used, that element of the using array
  479.  * is set to 0.  The elements LAST_USING array are set to the last
  480.  * elements on each of the using lists.
  481.  *
  482.  * The HIGH_WATER_MARK is set to the highest line number in the common file
  483.  * described in any of the diffs in either of the USING lists.  The
  484.  * HIGH_WATER_THREAD names the thread.  Similarly the BASE_WATER_MARK
  485.  * and BASE_WATER_THREAD describe the lowest line number in the common file
  486.  * described in any of the diffs in either of the USING lists.  The
  487.  * HIGH_WATER_DIFF is the diff from which the HIGH_WATER_MARK was
  488.  * taken.
  489.  *
  490.  * The HIGH_WATER_DIFF should always be equal to LAST_USING
  491.  * [HIGH_WATER_THREAD].  The OTHER_DIFF is the next diff to check for
  492.  * higher water, and should always be equal to
  493.  * CURRENT[HIGH_WATER_THREAD ^ 0x1].  The OTHER_THREAD is the thread
  494.  * in which the OTHER_DIFF is, and hence should always be equal to
  495.  * HIGH_WATER_THREAD ^ 0x1.
  496.  *
  497.  * The variable LAST_DIFF is kept set to the last diff block produced
  498.  * by this routine, for line correspondence purposes between that diff
  499.  * and the one currently being worked on.  It is initialized to
  500.  * ZERO_DIFF before any blocks have been created.
  501.  */
  502.  
  503.   struct diff_block
  504.     *using[2],
  505.     *last_using[2],
  506.     *current[2];
  507.  
  508.   int
  509.     high_water_mark;
  510.  
  511.   int
  512.     high_water_thread,
  513.     base_water_thread,
  514.     other_thread;
  515.  
  516.   struct diff_block
  517.     *high_water_diff,
  518.     *other_diff;
  519.  
  520.   struct diff3_block
  521.     *result,
  522.     *tmpblock,
  523.     **result_end;
  524.  
  525.   struct diff3_block const *last_diff3;
  526.  
  527.   static struct diff3_block const zero_diff3;
  528.  
  529.   /* Initialization */
  530.   result = 0;
  531.   result_end = &result;
  532.   current[0] = thread0; current[1] = thread1;
  533.   last_diff3 = &zero_diff3;
  534.  
  535.   /* Sniff up the threads until we reach the end */
  536.  
  537.   while (current[0] || current[1])
  538.     {
  539.       using[0] = using[1] = last_using[0] = last_using[1] = 0;
  540.  
  541.       /* Setup low and high water threads, diffs, and marks.  */
  542.       if (!current[0])
  543.     base_water_thread = 1;
  544.       else if (!current[1])
  545.     base_water_thread = 0;
  546.       else
  547.     base_water_thread =
  548.       (D_LOWLINE (current[0], FC) > D_LOWLINE (current[1], FC));
  549.  
  550.       high_water_thread = base_water_thread;
  551.  
  552.       high_water_diff = current[high_water_thread];
  553.  
  554. #if 0
  555.       /* low and high waters start off same diff */
  556.       base_water_mark = D_LOWLINE (high_water_diff, FC);
  557. #endif
  558.  
  559.       high_water_mark = D_HIGHLINE (high_water_diff, FC);
  560.  
  561.       /* Make the diff you just got info from into the using class */
  562.       using[high_water_thread]
  563.     = last_using[high_water_thread]
  564.     = high_water_diff;
  565.       current[high_water_thread] = high_water_diff->next;
  566.       last_using[high_water_thread]->next = 0;
  567.  
  568.       /* And mark the other diff */
  569.       other_thread = high_water_thread ^ 0x1;
  570.       other_diff = current[other_thread];
  571.  
  572.       /* Shuffle up the ladder, checking the other diff to see if it
  573.      needs to be incorporated.  */
  574.       while (other_diff
  575.          && D_LOWLINE (other_diff, FC) <= high_water_mark + 1)
  576.     {
  577.  
  578.       /* Incorporate this diff into the using list.  Note that
  579.          this doesn't take it off the current list */
  580.       if (using[other_thread])
  581.         last_using[other_thread]->next = other_diff;
  582.       else
  583.         using[other_thread] = other_diff;
  584.       last_using[other_thread] = other_diff;
  585.  
  586.       /* Take it off the current list.  Note that this following
  587.          code assumes that other_diff enters it equal to
  588.          current[high_water_thread ^ 0x1] */
  589.       current[other_thread] = current[other_thread]->next;
  590.       other_diff->next = 0;
  591.  
  592.       /* Set the high_water stuff
  593.          If this comparison is equal, then this is the last pass
  594.          through this loop; since diff blocks within a given
  595.          thread cannot overlap, the high_water_mark will be
  596.          *below* the range_start of either of the next diffs.  */
  597.  
  598.       if (high_water_mark < D_HIGHLINE (other_diff, FC))
  599.         {
  600.           high_water_thread ^= 1;
  601.           high_water_diff = other_diff;
  602.           high_water_mark = D_HIGHLINE (other_diff, FC);
  603.         }
  604.  
  605.       /* Set the other diff */
  606.       other_thread = high_water_thread ^ 0x1;
  607.       other_diff = current[other_thread];
  608.     }
  609.  
  610.       /* The using lists contain a list of all of the blocks to be
  611.      included in this diff3_block.  Create it.  */
  612.  
  613.       tmpblock = using_to_diff3_block (using, last_using,
  614.                        base_water_thread, high_water_thread,
  615.                        last_diff3);
  616.  
  617.       if (!tmpblock)
  618.     fatal ("internal error: screwup in format of diff blocks");
  619.  
  620.       /* Put it on the list.  */
  621.       *result_end = tmpblock;
  622.       result_end = &tmpblock->next;
  623.  
  624.       /* Set up corresponding lines correctly.  */
  625.       last_diff3 = tmpblock;
  626.     }
  627.   return result;
  628. }
  629.  
  630. /*
  631.  * using_to_diff3_block:
  632.  *   This routine takes two lists of blocks (from two separate diff
  633.  * threads) and puts them together into one diff3 block.
  634.  * It then returns a pointer to this diff3 block or 0 for failure.
  635.  *
  636.  * All arguments besides using are for the convenience of the routine;
  637.  * they could be derived from the using array.
  638.  * LAST_USING is a pair of pointers to the last blocks in the using
  639.  * structure.
  640.  * LOW_THREAD and HIGH_THREAD tell which threads contain the lowest
  641.  * and highest line numbers for File0.
  642.  * last_diff3 contains the last diff produced in the calling routine.
  643.  * This is used for lines mappings which would still be identical to
  644.  * the state that diff ended in.
  645.  *
  646.  * A distinction should be made in this routine between the two diffs
  647.  * that are part of a normal two diff block, and the three diffs that
  648.  * are part of a diff3_block.
  649.  */
  650. static struct diff3_block *
  651. using_to_diff3_block (using, last_using, low_thread, high_thread, last_diff3)
  652.      struct diff_block
  653.        *using[2],
  654.        *last_using[2];
  655.      int low_thread, high_thread;
  656.      struct diff3_block const *last_diff3;
  657. {
  658.   int low[2], high[2];
  659.   struct diff3_block *result;
  660.   struct diff_block *ptr;
  661.   int d, i;
  662.  
  663.   /* Find the range in the common file.  */
  664.   int lowc = D_LOWLINE (using[low_thread], FC);
  665.   int highc = D_HIGHLINE (last_using[high_thread], FC);
  666.  
  667.   /* Find the ranges in the other files.
  668.      If using[d] is null, that means that the file to which that diff
  669.      refers is equivalent to the common file over this range.  */
  670.  
  671.   for (d = 0; d < 2; d++)
  672.     if (using[d])
  673.       {
  674.     low[d] = D_LOW_MAPLINE (using[d], FC, FO, lowc);
  675.     high[d] = D_HIGH_MAPLINE (last_using[d], FC, FO, highc);
  676.       }
  677.     else
  678.       {
  679.     low[d] = D_HIGH_MAPLINE (last_diff3, FILEC, FILE0 + d, lowc);
  680.     high[d] = D_HIGH_MAPLINE (last_diff3, FILEC, FILE0 + d, highc);
  681.       }
  682.  
  683.   /* Create a block with the appropriate sizes */
  684.   result = create_diff3_block (low[0], high[0], low[1], high[1], lowc, highc);
  685.  
  686.   /* Copy information for the common file.
  687.      Return with a zero if any of the compares failed.  */
  688.  
  689.   for (d = 0; d < 2; d++)
  690.     for (ptr = using[d]; ptr; ptr = D_NEXT (ptr))
  691.       {
  692.     int result_offset = D_LOWLINE (ptr, FC) - lowc;
  693.  
  694.     if (!copy_stringlist (D_LINEARRAY (ptr, FC),
  695.                   D_LENARRAY (ptr, FC),
  696.                   D_LINEARRAY (result, FILEC) + result_offset,
  697.                   D_LENARRAY (result, FILEC) + result_offset,
  698.                   D_NUMLINES (ptr, FC)))
  699.       return 0;
  700.       }
  701.  
  702.   /* Copy information for file d.  First deal with anything that might be
  703.      before the first diff.  */
  704.  
  705.   for (d = 0; d < 2; d++)
  706.     {
  707.       struct diff_block *u = using[d];
  708.       int lo = low[d], hi = high[d];
  709.  
  710.       for (i = 0;
  711.        i + lo < (u ? D_LOWLINE (u, FO) : hi + 1);
  712.        i++)
  713.     {
  714.       D_RELNUM (result, FILE0 + d, i) = D_RELNUM (result, FILEC, i);
  715.       D_RELLEN (result, FILE0 + d, i) = D_RELLEN (result, FILEC, i);
  716.     }
  717.  
  718.       for (ptr = u; ptr; ptr = D_NEXT (ptr))
  719.     {
  720.       int result_offset = D_LOWLINE (ptr, FO) - lo;
  721.       int linec;
  722.  
  723.       if (!copy_stringlist (D_LINEARRAY (ptr, FO),
  724.                 D_LENARRAY (ptr, FO),
  725.                 D_LINEARRAY (result, FILE0 + d) + result_offset,
  726.                 D_LENARRAY (result, FILE0 + d) + result_offset,
  727.                 D_NUMLINES (ptr, FO)))
  728.         return 0;
  729.  
  730.       /* Catch the lines between here and the next diff */
  731.       linec = D_HIGHLINE (ptr, FC) + 1 - lowc;
  732.       for (i = D_HIGHLINE (ptr, FO) + 1 - lo;
  733.            i < (D_NEXT (ptr) ? D_LOWLINE (D_NEXT (ptr), FO) : hi + 1) - lo;
  734.            i++)
  735.         {
  736.           D_RELNUM (result, FILE0 + d, i) = D_RELNUM (result, FILEC, linec);
  737.           D_RELLEN (result, FILE0 + d, i) = D_RELLEN (result, FILEC, linec);
  738.           linec++;
  739.         }
  740.     }
  741.     }
  742.  
  743.   /* Set correspond */
  744.   if (!using[0])
  745.     D3_TYPE (result) = DIFF_2ND;
  746.   else if (!using[1])
  747.     D3_TYPE (result) = DIFF_1ST;
  748.   else
  749.     {
  750.       int nl0 = D_NUMLINES (result, FILE0);
  751.       int nl1 = D_NUMLINES (result, FILE1);
  752.  
  753.       if (nl0 != nl1
  754.       || !compare_line_list (D_LINEARRAY (result, FILE0),
  755.                  D_LENARRAY (result, FILE0),
  756.                  D_LINEARRAY (result, FILE1),
  757.                  D_LENARRAY (result, FILE1),
  758.                  nl0))
  759.     D3_TYPE (result) = DIFF_ALL;
  760.       else
  761.     D3_TYPE (result) = DIFF_3RD;
  762.     }
  763.  
  764.   return result;
  765. }
  766.  
  767. /*
  768.  * This routine copies pointers from a list of strings to a different list
  769.  * of strings.  If a spot in the second list is already filled, it
  770.  * makes sure that it is filled with the same string; if not it
  771.  * returns 0, the copy incomplete.
  772.  * Upon successful completion of the copy, it returns 1.
  773.  */
  774. static int
  775. copy_stringlist (fromptrs, fromlengths, toptrs, tolengths, copynum)
  776.      char * const fromptrs[];
  777.      char *toptrs[];
  778.      size_t const fromlengths[];
  779.      size_t tolengths[];
  780.      int copynum;
  781. {
  782.   register char * const *f = fromptrs;
  783.   register char **t = toptrs;
  784.   register size_t const *fl = fromlengths;
  785.   register size_t *tl = tolengths;
  786.  
  787.   while (copynum--)
  788.     {
  789.       if (*t)
  790.     { if (*fl != *tl || memcmp (*f, *t, *fl)) return 0; }
  791.       else
  792.     { *t = *f ; *tl = *fl; }
  793.  
  794.       t++; f++; tl++; fl++;
  795.     }
  796.   return 1;
  797. }
  798.  
  799. /*
  800.  * Create a diff3_block, with ranges as specified in the arguments.
  801.  * Allocate the arrays for the various pointers (and zero them) based
  802.  * on the arguments passed.  Return the block as a result.
  803.  */
  804. static struct diff3_block *
  805. create_diff3_block (low0, high0, low1, high1, low2, high2)
  806.      register int low0, high0, low1, high1, low2, high2;
  807. {
  808.   struct diff3_block *result = ALLOCATE (1, struct diff3_block);
  809.   int numlines;
  810.  
  811.   D3_TYPE (result) = ERROR;
  812.   D_NEXT (result) = 0;
  813.  
  814.   /* Assign ranges */
  815.   D_LOWLINE (result, FILE0) = low0;
  816.   D_HIGHLINE (result, FILE0) = high0;
  817.   D_LOWLINE (result, FILE1) = low1;
  818.   D_HIGHLINE (result, FILE1) = high1;
  819.   D_LOWLINE (result, FILE2) = low2;
  820.   D_HIGHLINE (result, FILE2) = high2;
  821.  
  822.   /* Allocate and zero space */
  823.   numlines = D_NUMLINES (result, FILE0);
  824.   if (numlines)
  825.     {
  826.       D_LINEARRAY (result, FILE0) = ALLOCATE (numlines, char *);
  827.       D_LENARRAY (result, FILE0) = ALLOCATE (numlines, size_t);
  828.       bzero (D_LINEARRAY (result, FILE0), (numlines * sizeof (char *)));
  829.       bzero (D_LENARRAY (result, FILE0), (numlines * sizeof (size_t)));
  830.     }
  831.   else
  832.     {
  833.       D_LINEARRAY (result, FILE0) = 0;
  834.       D_LENARRAY (result, FILE0) = 0;
  835.     }
  836.  
  837.   numlines = D_NUMLINES (result, FILE1);
  838.   if (numlines)
  839.     {
  840.       D_LINEARRAY (result, FILE1) = ALLOCATE (numlines, char *);
  841.       D_LENARRAY (result, FILE1) = ALLOCATE (numlines, size_t);
  842.       bzero (D_LINEARRAY (result, FILE1), (numlines * sizeof (char *)));
  843.       bzero (D_LENARRAY (result, FILE1), (numlines * sizeof (size_t)));
  844.     }
  845.   else
  846.     {
  847.       D_LINEARRAY (result, FILE1) = 0;
  848.       D_LENARRAY (result, FILE1) = 0;
  849.     }
  850.  
  851.   numlines = D_NUMLINES (result, FILE2);
  852.   if (numlines)
  853.     {
  854.       D_LINEARRAY (result, FILE2) = ALLOCATE (numlines, char *);
  855.       D_LENARRAY (result, FILE2) = ALLOCATE (numlines, size_t);
  856.       bzero (D_LINEARRAY (result, FILE2), (numlines * sizeof (char *)));
  857.       bzero (D_LENARRAY (result, FILE2), (numlines * sizeof (size_t)));
  858.     }
  859.   else
  860.     {
  861.       D_LINEARRAY (result, FILE2) = 0;
  862.       D_LENARRAY (result, FILE2) = 0;
  863.     }
  864.  
  865.   /* Return */
  866.   return result;
  867. }
  868.  
  869. /*
  870.  * Compare two lists of lines of text.
  871.  * Return 1 if they are equivalent, 0 if not.
  872.  */
  873. static int
  874. compare_line_list (list1, lengths1, list2, lengths2, nl)
  875.      char * const list1[], * const list2[];
  876.      size_t const lengths1[], lengths2[];
  877.      int nl;
  878. {
  879.   char
  880.     * const *l1 = list1,
  881.     * const *l2 = list2;
  882.   size_t const
  883.     *lgths1 = lengths1,
  884.     *lgths2 = lengths2;
  885.  
  886.   while (nl--)
  887.     if (!*l1 || !*l2 || *lgths1 != *lgths2++
  888.     || memcmp (*l1++, *l2++, *lgths1++))
  889.       return 0;
  890.   return 1;
  891. }
  892.  
  893. /*
  894.  * Routines to input and parse two way diffs.
  895.  */
  896.  
  897. extern char **environ;
  898.  
  899. #define    DIFF_CHUNK_SIZE    10000
  900.  
  901. static struct diff_block *
  902. process_diff (filea, fileb, last_block)
  903.      char const *filea, *fileb;
  904.      struct diff_block **last_block;
  905. {
  906.   char *diff_contents;
  907.   char *diff_limit;
  908.   char *scan_diff;
  909.   enum diff_type dt;
  910.   int i;
  911.   struct diff_block *block_list, **block_list_end, *bptr;
  912.  
  913.   diff_limit = read_diff (filea, fileb, &diff_contents);
  914.   scan_diff = diff_contents;
  915.   block_list_end = &block_list;
  916.   bptr = 0; /* Pacify `gcc -W'.  */
  917.  
  918.   while (scan_diff < diff_limit)
  919.     {
  920.       bptr = ALLOCATE (1, struct diff_block);
  921.       bptr->lines[0] = bptr->lines[1] = 0;
  922.       bptr->lengths[0] = bptr->lengths[1] = 0;
  923.  
  924.       dt = process_diff_control (&scan_diff, bptr);
  925.       if (dt == ERROR || *scan_diff != '\n')
  926.     {
  927.       fprintf (stderr, "%s: diff error: ", argv0);
  928.       do
  929.         {
  930.           putc (*scan_diff, stderr);
  931.         }
  932.       while (*scan_diff++ != '\n');
  933.       exit (2);
  934.     }
  935.       scan_diff++;
  936.  
  937.       /* Force appropriate ranges to be null, if necessary */
  938.       switch (dt)
  939.     {
  940.     case ADD:
  941.       bptr->ranges[0][0]++;
  942.       break;
  943.     case DELETE:
  944.       bptr->ranges[1][0]++;
  945.       break;
  946.     case CHANGE:
  947.       break;
  948.     default:
  949.       fatal ("internal error: invalid diff type in process_diff");
  950.       break;
  951.     }
  952.  
  953.       /* Allocate space for the pointers for the lines from filea, and
  954.      parcel them out among these pointers */
  955.       if (dt != ADD)
  956.     {
  957.       int numlines = D_NUMLINES (bptr, 0);
  958.       bptr->lines[0] = ALLOCATE (numlines, char *);
  959.       bptr->lengths[0] = ALLOCATE (numlines, size_t);
  960.       for (i = 0; i < numlines; i++)
  961.         scan_diff = scan_diff_line (scan_diff,
  962.                     &(bptr->lines[0][i]),
  963.                     &(bptr->lengths[0][i]),
  964.                     diff_limit,
  965.                     '<');
  966.     }
  967.  
  968.       /* Get past the separator for changes */
  969.       if (dt == CHANGE)
  970.     {
  971.       if (strncmp (scan_diff, "---\n", 4))
  972.         fatal ("invalid diff format; invalid change separator");
  973.       scan_diff += 4;
  974.     }
  975.  
  976.       /* Allocate space for the pointers for the lines from fileb, and
  977.      parcel them out among these pointers */
  978.       if (dt != DELETE)
  979.     {
  980.       int numlines = D_NUMLINES (bptr, 1);
  981.       bptr->lines[1] = ALLOCATE (numlines, char *);
  982.       bptr->lengths[1] = ALLOCATE (numlines, size_t);
  983.       for (i = 0; i < numlines; i++)
  984.         scan_diff = scan_diff_line (scan_diff,
  985.                     &(bptr->lines[1][i]),
  986.                     &(bptr->lengths[1][i]),
  987.                     diff_limit,
  988.                     '>');
  989.     }
  990.  
  991.       /* Place this block on the blocklist.  */
  992.       *block_list_end = bptr;
  993.       block_list_end = &bptr->next;
  994.     }
  995.  
  996.   *block_list_end = 0;
  997.   *last_block = bptr;
  998.   return block_list;
  999. }
  1000.  
  1001. /*
  1002.  * This routine will parse a normal format diff control string.  It
  1003.  * returns the type of the diff (ERROR if the format is bad).  All of
  1004.  * the other important information is filled into to the structure
  1005.  * pointed to by db, and the string pointer (whose location is passed
  1006.  * to this routine) is updated to point beyond the end of the string
  1007.  * parsed.  Note that only the ranges in the diff_block will be set by
  1008.  * this routine.
  1009.  *
  1010.  * If some specific pair of numbers has been reduced to a single
  1011.  * number, then both corresponding numbers in the diff block are set
  1012.  * to that number.  In general these numbers are interpetted as ranges
  1013.  * inclusive, unless being used by the ADD or DELETE commands.  It is
  1014.  * assumed that these will be special cased in a superior routine.
  1015.  */
  1016.  
  1017. static enum diff_type
  1018. process_diff_control (string, db)
  1019.      char **string;
  1020.      struct diff_block *db;
  1021. {
  1022.   char *s = *string;
  1023.   int holdnum;
  1024.   enum diff_type type;
  1025.  
  1026. /* These macros are defined here because they can use variables
  1027.    defined in this function.  Don't try this at home kids, we're
  1028.    trained professionals!
  1029.  
  1030.    Also note that SKIPWHITE only recognizes tabs and spaces, and
  1031.    that READNUM can only read positive, integral numbers */
  1032.  
  1033. #define    SKIPWHITE(s)    { while (*s == ' ' || *s == '\t') s++; }
  1034. #define    READNUM(s, num)    \
  1035.     { unsigned char c = *s; if (!isdigit (c)) return ERROR; holdnum = 0; \
  1036.       do { holdnum = (c - '0' + holdnum * 10); }    \
  1037.       while (isdigit (c = *++s)); (num) = holdnum; }
  1038.  
  1039.   /* Read first set of digits */
  1040.   SKIPWHITE (s);
  1041.   READNUM (s, db->ranges[0][START]);
  1042.  
  1043.   /* Was that the only digit? */
  1044.   SKIPWHITE (s);
  1045.   if (*s == ',')
  1046.     {
  1047.       /* Get the next digit */
  1048.       s++;
  1049.       READNUM (s, db->ranges[0][END]);
  1050.     }
  1051.   else
  1052.     db->ranges[0][END] = db->ranges[0][START];
  1053.  
  1054.   /* Get the letter */
  1055.   SKIPWHITE (s);
  1056.   switch (*s)
  1057.     {
  1058.     case 'a':
  1059.       type = ADD;
  1060.       break;
  1061.     case 'c':
  1062.       type = CHANGE;
  1063.       break;
  1064.     case 'd':
  1065.       type = DELETE;
  1066.       break;
  1067.     default:
  1068.       return ERROR;            /* Bad format */
  1069.     }
  1070.   s++;                /* Past letter */
  1071.  
  1072.   /* Read second set of digits */
  1073.   SKIPWHITE (s);
  1074.   READNUM (s, db->ranges[1][START]);
  1075.  
  1076.   /* Was that the only digit? */
  1077.   SKIPWHITE (s);
  1078.   if (*s == ',')
  1079.     {
  1080.       /* Get the next digit */
  1081.       s++;
  1082.       READNUM (s, db->ranges[1][END]);
  1083.       SKIPWHITE (s);        /* To move to end */
  1084.     }
  1085.   else
  1086.     db->ranges[1][END] = db->ranges[1][START];
  1087.  
  1088.   *string = s;
  1089.   return type;
  1090. }
  1091.  
  1092. static char *
  1093. read_diff (filea, fileb, output_placement)
  1094.      char const *filea, *fileb;
  1095.      char **output_placement;
  1096. {
  1097.   char *diff_result;
  1098.   size_t bytes, current_chunk_size, total;
  1099.   char const *argv[7];
  1100.   char horizon_arg[256];
  1101.   char const **ap;
  1102.   int fds[2];
  1103.   pid_t pid;
  1104.   int wstatus;
  1105.  
  1106.   ap = argv;
  1107.   *ap++ = diff_program;
  1108.   if (always_text)
  1109.     *ap++ = "-a";
  1110.   sprintf (horizon_arg, "--horizon-lines=%d", horizon_lines);
  1111.   *ap++ = horizon_arg;
  1112.   *ap++ = "--";
  1113.   *ap++ = filea;
  1114.   *ap++ = fileb;
  1115.   *ap = 0;
  1116.  
  1117.   if (pipe (fds) < 0)
  1118.     perror_with_exit ("pipe failed");
  1119.  
  1120.   pid = vfork ();
  1121.   if (pid == 0)
  1122.     {
  1123.       /* Child */
  1124.       close (fds[0]);
  1125.       if (fds[1] != STDOUT_FILENO)
  1126.     {
  1127.       dup2 (fds[1], STDOUT_FILENO);
  1128.       close (fds[1]);
  1129.     }
  1130.       execve (diff_program, (char **) argv, environ);
  1131.       /* Avoid stdio, because the parent process's buffers are inherited.  */
  1132.       write (STDERR_FILENO, diff_program, strlen (diff_program));
  1133.       write (STDERR_FILENO, ": not found\n", 12);
  1134.       _exit (2);
  1135.     }
  1136.  
  1137.   if (pid == -1)
  1138.     perror_with_exit ("fork failed");
  1139.  
  1140.   close (fds[1]);        /* Prevent erroneous lack of EOF */
  1141.   current_chunk_size = DIFF_CHUNK_SIZE;
  1142.   diff_result = xmalloc (current_chunk_size);
  1143.   total = 0;
  1144.   do {
  1145.     bytes = myread (fds[0],
  1146.             diff_result + total,
  1147.             current_chunk_size - total);
  1148.     total += bytes;
  1149.     if (total == current_chunk_size)
  1150.       {
  1151.     if (current_chunk_size < 2 * current_chunk_size)
  1152.       current_chunk_size = 2 * current_chunk_size;
  1153.     else if (current_chunk_size < (size_t) -1)
  1154.       current_chunk_size = (size_t) -1;
  1155.     else
  1156.       fatal ("files are too large to fit into memory");
  1157.     diff_result = xrealloc (diff_result, (current_chunk_size *= 2));
  1158.       }
  1159.   } while (bytes);
  1160.  
  1161.   if (total != 0 && diff_result[total-1] != '\n')
  1162.     fatal ("invalid diff format; incomplete last line");
  1163.  
  1164.   *output_placement = diff_result;
  1165.  
  1166. #if HAVE_WAITPID
  1167.   if (waitpid (pid, &wstatus, 0) < 0)
  1168.     perror_with_exit ("waitpid failed");
  1169. #else
  1170.   for (;;) {
  1171.     pid_t w = wait (&wstatus);
  1172.     if (w < 0)
  1173.       perror_with_exit ("wait failed");
  1174.     if (w == pid)
  1175.       break;
  1176.   }
  1177. #endif
  1178.  
  1179.   if (! (WIFEXITED (wstatus) && WEXITSTATUS (wstatus) < 2))
  1180.     fatal ("subsidiary diff failed");
  1181.  
  1182.   return diff_result + total;
  1183. }
  1184.  
  1185.  
  1186. /*
  1187.  * Scan a regular diff line (consisting of > or <, followed by a
  1188.  * space, followed by text (including nulls) up to a newline.
  1189.  *
  1190.  * This next routine began life as a macro and many parameters in it
  1191.  * are used as call-by-reference values.
  1192.  */
  1193. static char *
  1194. scan_diff_line (scan_ptr, set_start, set_length, limit, firstchar)
  1195.      char *scan_ptr, **set_start;
  1196.      size_t *set_length;
  1197.      char *limit;
  1198.      char firstchar;
  1199. {
  1200.   char *line_ptr;
  1201.  
  1202.   if (!(scan_ptr[0] == (firstchar)
  1203.     && scan_ptr[1] == ' '))
  1204.     fatal ("invalid diff format; incorrect leading line chars");
  1205.  
  1206.   *set_start = line_ptr = scan_ptr + 2;
  1207.   while (*line_ptr++ != '\n')
  1208.     ;
  1209.  
  1210.   /* Include newline if the original line ended in a newline,
  1211.      or if an edit script is being generated.
  1212.      Copy any missing newline message to stderr if an edit script is being
  1213.      generated, because edit scripts cannot handle missing newlines.
  1214.      Return the beginning of the next line.  */
  1215.   *set_length = line_ptr - *set_start;
  1216.   if (line_ptr < limit && *line_ptr == '\\')
  1217.     {
  1218.       if (edscript)
  1219.     fprintf (stderr, "%s:", argv0);
  1220.       else
  1221.     --*set_length;
  1222.       line_ptr++;
  1223.       do
  1224.     {
  1225.       if (edscript)
  1226.         putc (*line_ptr, stderr);
  1227.     }
  1228.       while (*line_ptr++ != '\n');
  1229.     }
  1230.  
  1231.   return line_ptr;
  1232. }
  1233.  
  1234. /*
  1235.  * This routine outputs a three way diff passed as a list of
  1236.  * diff3_block's.
  1237.  * The argument MAPPING is indexed by external file number (in the
  1238.  * argument list) and contains the internal file number (from the
  1239.  * diff passed).  This is important because the user expects his
  1240.  * outputs in terms of the argument list number, and the diff passed
  1241.  * may have been done slightly differently (if the last argument
  1242.  * was "-", for example).
  1243.  * REV_MAPPING is the inverse of MAPPING.
  1244.  */
  1245. static void
  1246. output_diff3 (outputfile, diff, mapping, rev_mapping)
  1247.      FILE *outputfile;
  1248.      struct diff3_block *diff;
  1249.      int const mapping[3], rev_mapping[3];
  1250. {
  1251.   int i;
  1252.   int oddoneout;
  1253.   char *cp;
  1254.   struct diff3_block *ptr;
  1255.   int line;
  1256.   size_t length;
  1257.   int dontprint;
  1258.   static int skew_increment[3] = { 2, 3, 1 }; /* 0==>2==>1==>3 */
  1259.   char const *line_prefix = tab_align_flag ? "\t" : "  ";
  1260.  
  1261.   for (ptr = diff; ptr; ptr = D_NEXT (ptr))
  1262.     {
  1263.       char x[2];
  1264.  
  1265.       switch (ptr->correspond)
  1266.     {
  1267.     case DIFF_ALL:
  1268.       x[0] = '\0';
  1269.       dontprint = 3;    /* Print them all */
  1270.       oddoneout = 3;    /* Nobody's odder than anyone else */
  1271.       break;
  1272.     case DIFF_1ST:
  1273.     case DIFF_2ND:
  1274.     case DIFF_3RD:
  1275.       oddoneout = rev_mapping[(int) ptr->correspond - (int) DIFF_1ST];
  1276.  
  1277.       x[0] = oddoneout + '1';
  1278.       x[1] = '\0';
  1279.       dontprint = oddoneout==0;
  1280.       break;
  1281.     default:
  1282.       fatal ("internal error: invalid diff type passed to output");
  1283.     }
  1284.       fprintf (outputfile, "====%s\n", x);
  1285.  
  1286.       /* Go 0, 2, 1 if the first and third outputs are equivalent.  */
  1287.       for (i = 0; i < 3;
  1288.        i = (oddoneout == 1 ? skew_increment[i] : i + 1))
  1289.     {
  1290.       int realfile = mapping[i];
  1291.       int
  1292.         lowt = D_LOWLINE (ptr, realfile),
  1293.         hight = D_HIGHLINE (ptr, realfile);
  1294.  
  1295.       fprintf (outputfile, "%d:", i + 1);
  1296.       switch (lowt - hight)
  1297.         {
  1298.         case 1:
  1299.           fprintf (outputfile, "%da\n", lowt - 1);
  1300.           break;
  1301.         case 0:
  1302.           fprintf (outputfile, "%dc\n", lowt);
  1303.           break;
  1304.         default:
  1305.           fprintf (outputfile, "%d,%dc\n", lowt, hight);
  1306.           break;
  1307.         }
  1308.  
  1309.       if (i == dontprint) continue;
  1310.  
  1311.       if (lowt <= hight)
  1312.         {
  1313.           line = 0;
  1314.           do
  1315.         {
  1316.           fprintf (outputfile, line_prefix);
  1317.           cp = D_RELNUM (ptr, realfile, line);
  1318.           length = D_RELLEN (ptr, realfile, line);
  1319.           fwrite (cp, sizeof (char), length, outputfile);
  1320.         }
  1321.           while (++line < hight - lowt + 1);
  1322.           if (cp[length - 1] != '\n')
  1323.         fprintf (outputfile, "\n\\ No newline at end of file\n");
  1324.         }
  1325.     }
  1326.     }
  1327. }
  1328.  
  1329.  
  1330. /*
  1331.  * Output to OUTPUTFILE the lines of B taken from FILENUM.
  1332.  * Double any initial '.'s; yield nonzero if any initial '.'s were doubled.
  1333.  */
  1334. static int
  1335. dotlines (outputfile, b, filenum)
  1336.      FILE *outputfile;
  1337.      struct diff3_block *b;
  1338.      int filenum;
  1339. {
  1340.   int i;
  1341.   int leading_dot = 0;
  1342.  
  1343.   for (i = 0;
  1344.        i < D_NUMLINES (b, filenum);
  1345.        i++)
  1346.     {
  1347.       char *line = D_RELNUM (b, filenum, i);
  1348.       if (line[0] == '.')
  1349.     {
  1350.       leading_dot = 1;
  1351.       fprintf (outputfile, ".");
  1352.     }
  1353.       fwrite (line, sizeof (char),
  1354.           D_RELLEN (b, filenum, i), outputfile);
  1355.     }
  1356.  
  1357.   return leading_dot;
  1358. }
  1359.  
  1360. /*
  1361.  * Output to OUTPUTFILE a '.' line.  If LEADING_DOT is nonzero,
  1362.  * also output a command that removes initial '.'s
  1363.  * starting with line START and continuing for NUM lines.
  1364.  */
  1365. static void
  1366. undotlines (outputfile, leading_dot, start, num)
  1367.      FILE *outputfile;
  1368.      int leading_dot, start, num;
  1369. {
  1370.   fprintf (outputfile, ".\n");
  1371.   if (leading_dot)
  1372.     if (num == 1)
  1373.       fprintf (outputfile, "%ds/^\\.//\n", start);
  1374.     else
  1375.       fprintf (outputfile, "%d,%ds/^\\.//\n", start, start + num - 1);
  1376. }
  1377.  
  1378. /*
  1379.  * This routine outputs a diff3 set of blocks as an ed script.  This
  1380.  * script applies the changes between file's 2 & 3 to file 1.  It
  1381.  * takes the precise format of the ed script to be output from global
  1382.  * variables set during options processing.  Note that it does
  1383.  * destructive things to the set of diff3 blocks it is passed; it
  1384.  * reverses their order (this gets around the problems involved with
  1385.  * changing line numbers in an ed script).
  1386.  *
  1387.  * Note that this routine has the same problem of mapping as the last
  1388.  * one did; the variable MAPPING maps from file number according to
  1389.  * the argument list to file number according to the diff passed.  All
  1390.  * files listed below are in terms of the argument list.
  1391.  * REV_MAPPING is the inverse of MAPPING.
  1392.  *
  1393.  * The arguments FILE0, FILE1 and FILE2 are the strings to print
  1394.  * as the names of the three files.  These may be the actual names,
  1395.  * or may be the arguments specified with -L.
  1396.  *
  1397.  * Returns 1 if conflicts were found.
  1398.  */
  1399.  
  1400. static int
  1401. output_diff3_edscript (outputfile, diff, mapping, rev_mapping,
  1402.                file0, file1, file2)
  1403.      FILE *outputfile;
  1404.      struct diff3_block *diff;
  1405.      int const mapping[3], rev_mapping[3];
  1406.      char const *file0, *file1, *file2;
  1407. {
  1408.   int leading_dot;
  1409.   int conflicts_found = 0, conflict;
  1410.   struct diff3_block *b;
  1411.  
  1412.   for (b = reverse_diff3_blocklist (diff); b; b = b->next)
  1413.     {
  1414.       /* Must do mapping correctly.  */
  1415.       enum diff_type type
  1416.     = ((b->correspond == DIFF_ALL) ?
  1417.        DIFF_ALL :
  1418.        ((enum diff_type)
  1419.         (((int) DIFF_1ST)
  1420.          + rev_mapping[(int) b->correspond - (int) DIFF_1ST])));
  1421.  
  1422.       /* If we aren't supposed to do this output block, skip it.  */
  1423.       switch (type)
  1424.     {
  1425.     default: continue;
  1426.     case DIFF_2ND: if (!show_2nd) continue; conflict = 1; break;
  1427.     case DIFF_3RD: if (overlap_only) continue; conflict = 0; break;
  1428.     case DIFF_ALL: if (simple_only) continue; conflict = flagging; break;
  1429.     }
  1430.  
  1431.       if (conflict)
  1432.     {
  1433.       conflicts_found = 1;
  1434.  
  1435.  
  1436.       /* Mark end of conflict.  */
  1437.  
  1438.       fprintf (outputfile, "%da\n", D_HIGHLINE (b, mapping[FILE0]));
  1439.       leading_dot = 0;
  1440.       if (type == DIFF_ALL)
  1441.         {
  1442.           if (show_2nd)
  1443.         {
  1444.           /* Append lines from FILE1.  */
  1445.           fprintf (outputfile, "||||||| %s\n", file1);
  1446.           leading_dot = dotlines (outputfile, b, mapping[FILE1]);
  1447.         }
  1448.           /* Append lines from FILE2.  */
  1449.           fprintf (outputfile, "=======\n");
  1450.           leading_dot |= dotlines (outputfile, b, mapping[FILE2]);
  1451.         }
  1452.       fprintf (outputfile, ">>>>>>> %s\n", file2);
  1453.       undotlines (outputfile, leading_dot,
  1454.               D_HIGHLINE (b, mapping[FILE0]) + 2,
  1455.               (D_NUMLINES (b, mapping[FILE1])
  1456.                + D_NUMLINES (b, mapping[FILE2]) + 1));
  1457.  
  1458.  
  1459.       /* Mark start of conflict.  */
  1460.  
  1461.       fprintf (outputfile, "%da\n<<<<<<< %s\n",
  1462.            D_LOWLINE (b, mapping[FILE0]) - 1,
  1463.            type == DIFF_ALL ? file0 : file1);
  1464.       leading_dot = 0;
  1465.       if (type == DIFF_2ND)
  1466.         {
  1467.           /* Prepend lines from FILE1.  */
  1468.           leading_dot = dotlines (outputfile, b, mapping[FILE1]);
  1469.           fprintf (outputfile, "=======\n");
  1470.         }
  1471.       undotlines (outputfile, leading_dot,
  1472.               D_LOWLINE (b, mapping[FILE0]) + 1,
  1473.               D_NUMLINES (b, mapping[FILE1]));
  1474.     }
  1475.       else if (D_NUMLINES (b, mapping[FILE2]) == 0)
  1476.     /* Write out a delete */
  1477.     {
  1478.       if (D_NUMLINES (b, mapping[FILE0]) == 1)
  1479.         fprintf (outputfile, "%dd\n",
  1480.              D_LOWLINE (b, mapping[FILE0]));
  1481.       else
  1482.         fprintf (outputfile, "%d,%dd\n",
  1483.              D_LOWLINE (b, mapping[FILE0]),
  1484.              D_HIGHLINE (b, mapping[FILE0]));
  1485.     }
  1486.       else
  1487.     /* Write out an add or change */
  1488.     {
  1489.       switch (D_NUMLINES (b, mapping[FILE0]))
  1490.         {
  1491.         case 0:
  1492.           fprintf (outputfile, "%da\n",
  1493.                D_HIGHLINE (b, mapping[FILE0]));
  1494.           break;
  1495.         case 1:
  1496.           fprintf (outputfile, "%dc\n",
  1497.                D_HIGHLINE (b, mapping[FILE0]));
  1498.           break;
  1499.         default:
  1500.           fprintf (outputfile, "%d,%dc\n",
  1501.                D_LOWLINE (b, mapping[FILE0]),
  1502.                D_HIGHLINE (b, mapping[FILE0]));
  1503.           break;
  1504.         }
  1505.  
  1506.       undotlines (outputfile, dotlines (outputfile, b, mapping[FILE2]),
  1507.               D_LOWLINE (b, mapping[FILE0]),
  1508.               D_NUMLINES (b, mapping[FILE2]));
  1509.     }
  1510.     }
  1511.   if (finalwrite) fprintf (outputfile, "w\nq\n");
  1512.   return conflicts_found;
  1513. }
  1514.  
  1515. /*
  1516.  * Read from INFILE and output to OUTPUTFILE a set of diff3_ blocks DIFF
  1517.  * as a merged file.  This acts like 'ed file0 <[output_diff3_edscript]',
  1518.  * except that it works even for binary data or incomplete lines.
  1519.  *
  1520.  * As before, MAPPING maps from arg list file number to diff file number,
  1521.  * REV_MAPPING is its inverse,
  1522.  * and FILE0, FILE1, and FILE2 are the names of the files.
  1523.  *
  1524.  * Returns 1 if conflicts were found.
  1525.  */
  1526.  
  1527. static int
  1528. output_diff3_merge (infile, outputfile, diff, mapping, rev_mapping,
  1529.             file0, file1, file2)
  1530.      FILE *infile, *outputfile;
  1531.      struct diff3_block *diff;
  1532.      int const mapping[3], rev_mapping[3];
  1533.      char const *file0, *file1, *file2;
  1534. {
  1535.   int c, i;
  1536.   int conflicts_found = 0, conflict;
  1537.   struct diff3_block *b;
  1538.   int linesread = 0;
  1539.  
  1540.   for (b = diff; b; b = b->next)
  1541.     {
  1542.       /* Must do mapping correctly.  */
  1543.       enum diff_type type
  1544.     = ((b->correspond == DIFF_ALL) ?
  1545.        DIFF_ALL :
  1546.        ((enum diff_type)
  1547.         (((int) DIFF_1ST)
  1548.          + rev_mapping[(int) b->correspond - (int) DIFF_1ST])));
  1549.       char const *format_2nd = "<<<<<<< %s\n";
  1550.  
  1551.       /* If we aren't supposed to do this output block, skip it.  */
  1552.       switch (type)
  1553.     {
  1554.     default: continue;
  1555.     case DIFF_2ND: if (!show_2nd) continue; conflict = 1; break;
  1556.     case DIFF_3RD: if (overlap_only) continue; conflict = 0; break;
  1557.     case DIFF_ALL: if (simple_only) continue; conflict = flagging;
  1558.       format_2nd = "||||||| %s\n";
  1559.       break;
  1560.     }
  1561.  
  1562.       /* Copy I lines from file 0.  */
  1563.       i = D_LOWLINE (b, FILE0) - linesread - 1;
  1564.       linesread += i;
  1565.       while (0 <= --i)
  1566.     do
  1567.       {
  1568.         c = getc (infile);
  1569.         if (c == EOF)
  1570.           if (ferror (infile))
  1571.         perror_with_exit ("input file");
  1572.           else if (feof (infile))
  1573.         fatal ("input file shrank");
  1574.         putc (c, outputfile);
  1575.       }
  1576.     while (c != '\n');
  1577.  
  1578.       if (conflict)
  1579.     {
  1580.       conflicts_found = 1;
  1581.  
  1582.       if (type == DIFF_ALL)
  1583.         {
  1584.           /* Put in lines from FILE0 with bracket.  */
  1585.           fprintf (outputfile, "<<<<<<< %s\n", file0);
  1586.           for (i = 0;
  1587.            i < D_NUMLINES (b, mapping[FILE0]);
  1588.            i++)
  1589.         fwrite (D_RELNUM (b, mapping[FILE0], i), sizeof (char),
  1590.             D_RELLEN (b, mapping[FILE0], i), outputfile);
  1591.         }
  1592.  
  1593.       if (show_2nd)
  1594.         {
  1595.           /* Put in lines from FILE1 with bracket.  */
  1596.           fprintf (outputfile, format_2nd, file1);
  1597.           for (i = 0;
  1598.            i < D_NUMLINES (b, mapping[FILE1]);
  1599.            i++)
  1600.         fwrite (D_RELNUM (b, mapping[FILE1], i), sizeof (char),
  1601.             D_RELLEN (b, mapping[FILE1], i), outputfile);
  1602.         }
  1603.  
  1604.       fprintf (outputfile, "=======\n");
  1605.     }
  1606.  
  1607.       /* Put in lines from FILE2.  */
  1608.       for (i = 0;
  1609.        i < D_NUMLINES (b, mapping[FILE2]);
  1610.        i++)
  1611.     fwrite (D_RELNUM (b, mapping[FILE2], i), sizeof (char),
  1612.         D_RELLEN (b, mapping[FILE2], i), outputfile);
  1613.  
  1614.       if (conflict)
  1615.     fprintf (outputfile, ">>>>>>> %s\n", file2);
  1616.  
  1617.       /* Skip I lines in file 0.  */
  1618.       i = D_NUMLINES (b, FILE0);
  1619.       linesread += i;
  1620.       while (0 <= --i)
  1621.     while ((c = getc (infile)) != '\n')
  1622.       if (c == EOF)
  1623.         if (ferror (infile))
  1624.           perror_with_exit ("input file");
  1625.         else if (feof (infile))
  1626.           {
  1627.         if (i || b->next)
  1628.           fatal ("input file shrank");
  1629.         return conflicts_found;
  1630.           }
  1631.     }
  1632.   /* Copy rest of common file.  */
  1633.   while ((c = getc (infile)) != EOF || !(ferror (infile) | feof (infile)))
  1634.     putc (c, outputfile);
  1635.   return conflicts_found;
  1636. }
  1637.  
  1638. /*
  1639.  * Reverse the order of the list of diff3 blocks.
  1640.  */
  1641. static struct diff3_block *
  1642. reverse_diff3_blocklist (diff)
  1643.      struct diff3_block *diff;
  1644. {
  1645.   register struct diff3_block *tmp, *next, *prev;
  1646.  
  1647.   for (tmp = diff, prev = 0;  tmp;  tmp = next)
  1648.     {
  1649.       next = tmp->next;
  1650.       tmp->next = prev;
  1651.       prev = tmp;
  1652.     }
  1653.  
  1654.   return prev;
  1655. }
  1656.  
  1657. static size_t
  1658. myread (fd, ptr, size)
  1659.      int fd;
  1660.      char *ptr;
  1661.      size_t size;
  1662. {
  1663.   size_t result = read (fd, ptr, size);
  1664.   if (result == -1)
  1665.     perror_with_exit ("read failed");
  1666.   return result;
  1667. }
  1668.  
  1669. static VOID *
  1670. xmalloc (size)
  1671.      size_t size;
  1672. {
  1673.   VOID *result = (VOID *) malloc (size ? size : 1);
  1674.   if (!result)
  1675.     fatal ("memory exhausted");
  1676.   return result;
  1677. }
  1678.  
  1679. static VOID *
  1680. xrealloc (ptr, size)
  1681.      VOID *ptr;
  1682.      size_t size;
  1683. {
  1684.   VOID *result = (VOID *) realloc (ptr, size ? size : 1);
  1685.   if (!result)
  1686.     fatal ("memory exhausted");
  1687.   return result;
  1688. }
  1689.  
  1690. static void
  1691. fatal (string)
  1692.      char const *string;
  1693. {
  1694.   fprintf (stderr, "%s: %s\n", argv0, string);
  1695.   exit (2);
  1696. }
  1697.  
  1698. static void
  1699. perror_with_exit (string)
  1700.      char const *string;
  1701. {
  1702.   int e = errno;
  1703.   fprintf (stderr, "%s: ", argv0);
  1704.   errno = e;
  1705.   perror (string);
  1706.   exit (2);
  1707. }
  1708.