home *** CD-ROM | disk | FTP | other *** search
/ Gold Fish 3 / goldfish_volume_3.bin / files / dev / c / cweb / common.w < prev    next >
Encoding:
Text File  |  1994-12-05  |  50.9 KB  |  1,416 lines

  1. % This file is part of CWEB.
  2. % This program by Silvio Levy and Donald E. Knuth
  3. % is based on a program by Knuth.
  4. % It is distributed WITHOUT ANY WARRANTY, express or implied.
  5. % Version 3.3 --- December 1994 (works with later versions too)
  6.  
  7. % Copyright (C) 1987,1990,1993 Silvio Levy and Donald E. Knuth
  8.  
  9. % Permission is granted to make and distribute verbatim copies of this
  10. % document provided that the copyright notice and this permission notice
  11. % are preserved on all copies.
  12.  
  13. % Permission is granted to copy and distribute modified versions of this
  14. % document under the conditions for verbatim copying, provided that the
  15. % entire resulting derived work is given a different name and distributed
  16. % under the terms of a permission notice identical to this one.
  17.  
  18. \def\v{\char'174} % vertical (|) in typewriter font
  19.  
  20. \def\title{Common code for CTANGLE and CWEAVE (Version 3.3)}
  21. \def\topofcontents{\null\vfill
  22.   \centerline{\titlefont Common code for {\ttitlefont CTANGLE} and
  23.     {\ttitlefont CWEAVE}}
  24.   \vskip 15pt
  25.   \centerline{(Version 3.3)}
  26.   \vfill}
  27. \def\botofcontents{\vfill
  28. \noindent
  29. Copyright \copyright\ 1987, 1990, 1993 Silvio Levy and Donald E. Knuth
  30. \bigskip\noindent
  31. Permission is granted to make and distribute verbatim copies of this
  32. document provided that the copyright notice and this permission notice
  33. are preserved on all copies.
  34.  
  35. \smallskip\noindent
  36. Permission is granted to copy and distribute modified versions of this
  37. document under the conditions for verbatim copying, provided that the
  38. entire resulting derived work is given a different name and distributed
  39. under the terms of a permission notice identical to this one.
  40. }
  41.  
  42. \pageno=\contentspagenumber \advance\pageno by 1
  43. \let\maybe=\iftrue
  44.  
  45. @** Introduction.  This file contains code common
  46. to both \.{CTANGLE} and \.{CWEAVE}, which roughly concerns the following
  47. problems: character uniformity, input routines, error handling and
  48. parsing of command line.  We have tried to concentrate in this file
  49. all the system dependencies, so as to maximize portability.
  50.  
  51. In the texts below we will
  52. sometimes use \.{CWEB} to refer to either of the two component
  53. programs, if no confusion can arise.
  54.  
  55. The file begins with a few basic definitions.
  56.  
  57. @c
  58. @<Include files@>@/
  59. @h
  60. @<Definitions that should agree with \.{CTANGLE} and \.{CWEAVE}@>@/
  61. @<Other definitions@>@/
  62. @<Predeclaration of procedures@>@/
  63.  
  64. @ In certain cases \.{CTANGLE} and \.{CWEAVE} should do almost, but not
  65. quite, the same thing.  In these cases we've written common code for
  66. both, differentiating between the two by means of the global variable
  67. |program|.
  68.  
  69. @d ctangle 0
  70. @d cweave 1
  71.  
  72. @<Definitions...@>=
  73. typedef short boolean;
  74. boolean program; /* \.{CWEAVE} or \.{CTANGLE}? */
  75.  
  76. @ \.{CWEAVE} operates in three phases: first it inputs the source
  77. file and stores cross-reference data, then it inputs the source once again and
  78. produces the \TEX/ output file, and finally it sorts and outputs the index.
  79. Similarly, \.{CTANGLE} operates in two phases.
  80. The global variable |phase| tells which phase we are in.
  81.  
  82. @<Other...@>= int phase; /* which phase are we in? */
  83.  
  84. @ There's an initialization procedure that gets both \.{CTANGLE} and
  85. \.{CWEAVE} off to a good start. We will fill in the details of this
  86. procedure later.
  87.  
  88. @c
  89. void
  90. common_init()
  91. {
  92.   @<Initialize pointers@>;
  93.   @<Set the default options common to \.{CTANGLE} and \.{CWEAVE}@>;
  94.   @<Scan arguments and open output files@>;
  95. }
  96.  
  97. @*1 The character set.
  98. \.{CWEB} uses the conventions of \CEE/ programs found in the standard
  99. \.{ctype.h} header file.
  100.  
  101. @<Include files@>=
  102. #include <ctype.h>
  103.  
  104. @ A few character pairs are encoded internally as single characters,
  105. using the definitions below. These definitions are consistent with
  106. an extension of ASCII code originally developed at MIT and explained in
  107. Appendix~C of {\sl The \TEX/book\/}; thus, users who have such a
  108. character set can type things like \.{\char'32} and \.{\char'4} instead
  109. of \.{!=} and \.{\&\&}. (However, their files will not be too portable
  110. until more people adopt the extended code.)
  111.  
  112. If the character set is not ASCII, the definitions given here may conflict
  113. with existing characters; in such cases, other arbitrary codes should be
  114. substituted. The indexes to \.{CTANGLE} and \.{CWEAVE} mention every
  115. case where similar codes may have to be changed in order to
  116. avoid character conflicts. Look for the entry ``ASCII code dependencies''
  117. in those indexes.
  118.  
  119. @^ASCII code dependencies@>
  120. @^system dependencies@>
  121.  
  122. @d and_and 04 /* `\.{\&\&}'\,; corresponds to MIT's {\tentex\char'4} */
  123. @d lt_lt 020 /* `\.{<<}'\,;  corresponds to MIT's {\tentex\char'20} */
  124. @d gt_gt 021 /* `\.{>>}'\,;  corresponds to MIT's {\tentex\char'21} */
  125. @d plus_plus 013 /* `\.{++}'\,;  corresponds to MIT's {\tentex\char'13} */
  126. @d minus_minus 01 /* `\.{--}'\,;  corresponds to MIT's {\tentex\char'1} */
  127. @d minus_gt 031 /* `\.{->}'\,;  corresponds to MIT's {\tentex\char'31} */
  128. @d not_eq 032 /* `\.{!=}'\,;  corresponds to MIT's {\tentex\char'32} */
  129. @d lt_eq 034 /* `\.{<=}'\,;  corresponds to MIT's {\tentex\char'34} */
  130. @d gt_eq 035 /* `\.{>=}'\,;  corresponds to MIT's {\tentex\char'35} */
  131. @d eq_eq 036 /* `\.{==}'\,;  corresponds to MIT's {\tentex\char'36} */
  132. @d or_or 037 /* `\.{\v\v}'\,;  corresponds to MIT's {\tentex\char'37} */
  133. @d dot_dot_dot 016 /* `\.{...}'\,;  corresponds to MIT's {\tentex\char'16} */
  134. @d colon_colon 06 /* `\.{::}'\,;  corresponds to MIT's {\tentex\char'6} */
  135. @d period_ast 026 /* `\.{.*}'\,;  corresponds to MIT's {\tentex\char'26} */
  136. @d minus_gt_ast 027 /* `\.{->*}'\,;  corresponds to MIT's {\tentex\char'27} */
  137.  
  138. @** Input routines.  The lowest level of input to the \.{CWEB} programs
  139. is performed by |input_ln|, which must be told which file to read from.
  140. The return value of |input_ln| is 1 if the read is successful and 0 if
  141. not (generally this means the file has ended). The conventions
  142. of \TEX/ are followed; i.e., the characters of the next line of the file
  143. are copied into the |buffer| array,
  144. and the global variable |limit| is set to the first unoccupied position.
  145. Trailing blanks are ignored. The value of |limit| must be strictly less
  146. than |buf_size|, so that |buffer[buf_size-1]| is never filled.
  147.  
  148. Since |buf_size| is strictly less than |long_buf_size|,
  149. some of \.{CWEB}'s routines use the fact that it is safe to refer to
  150. |*(limit+2)| without overstepping the bounds of the array.
  151.  
  152. @d buf_size 100 /* for \.{CWEAVE} and \.{CTANGLE} */
  153. @d longest_name 1000
  154. @d long_buf_size (buf_size+longest_name) /* for \.{CWEAVE} */
  155. @d xisspace(c) (isspace(c)&&((unsigned char)c<0200))
  156. @d xisupper(c) (isupper(c)&&((unsigned char)c<0200))
  157.  
  158. @<Definitions...@>=
  159. char buffer[long_buf_size]; /* where each line of input goes */
  160. char *buffer_end=buffer+buf_size-2; /* end of |buffer| */
  161. char *limit=buffer; /* points to the last character in the buffer */
  162. char *loc=buffer; /* points to the next character to be read from the buffer */
  163.  
  164. @ @<Include files@>=
  165. #include <stdio.h>
  166.  
  167. @ In the unlikely event that your standard I/O library does not
  168. support |feof|, |getc| and |ungetc| you may have to change things here.
  169. @^system dependencies@>
  170.  
  171. @c
  172. int input_ln(fp) /* copies a line into |buffer| or returns 0 */
  173. FILE *fp; /* what file to read from */
  174. {
  175.   register int  c=EOF; /* character read; initialized so some compilers won't complain */
  176.   register char *k;  /* where next character goes */
  177.   if (feof(fp)) return(0);  /* we have hit end-of-file */
  178.   limit = k = buffer;  /* beginning of buffer */
  179.   while (k<=buffer_end && (c=getc(fp)) != EOF && c!='\n')
  180.     if ((*(k++) = c) != ' ') limit = k;
  181.   if (k>buffer_end)
  182.     if ((c=getc(fp))!=EOF && c!='\n') {
  183.       ungetc(c,fp); loc=buffer; err_print("! Input line too long");
  184. @.Input line too long@>
  185.   }
  186.   if (c==EOF && limit==buffer) return(0);  /* there was nothing after
  187.     the last newline */
  188.   return(1);
  189. }
  190.  
  191. @ Now comes the problem of deciding which file to read from next.
  192. Recall that the actual text that \.{CWEB} should process comes from two
  193. streams: a |web_file|, which can contain possibly nested include
  194. commands \.{@@i}, and a |change_file|, which might also contain
  195. includes.  The |web_file| together with the currently open include
  196. files form a stack |file|, whose names are stored in a parallel stack
  197. |file_name|.  The boolean |changing| tells whether or not we're reading
  198. from the |change_file|.
  199.  
  200. The line number of each open file is also kept for error reporting and
  201. for the benefit of \.{CTANGLE}.
  202.  
  203. @f line x /* make |line| an unreserved word */
  204. @d max_include_depth 10 /* maximum number of source files open
  205.   simultaneously, not counting the change file */
  206. @d max_file_name_length 60
  207. @d cur_file file[include_depth] /* current file */
  208. @d cur_file_name file_name[include_depth] /* current file name */
  209. @d cur_line line[include_depth] /* number of current line in current file */
  210. @d web_file file[0] /* main source file */
  211. @d web_file_name file_name[0] /* main source file name */
  212.  
  213. @<Definitions...@>=
  214. int include_depth; /* current level of nesting */
  215. FILE *file[max_include_depth]; /* stack of non-change files */
  216. FILE *change_file; /* change file */
  217. char file_name[max_include_depth][max_file_name_length];
  218.   /* stack of non-change file names */
  219. char change_file_name[max_file_name_length]; /* name of change file */
  220. char alt_web_file_name[max_file_name_length]; /* alternate name to try */
  221. int line[max_include_depth]; /* number of current line in the stacked files */
  222. int change_line; /* number of current line in change file */
  223. int change_depth; /* where \.{@@y} originated during a change */
  224. boolean input_has_ended; /* if there is no more input */
  225. boolean changing; /* if the current line is from |change_file| */
  226. boolean web_file_open=0; /* if the web file is being read */
  227.  
  228. @ When |changing==0|, the next line of |change_file| is kept in
  229. |change_buffer|, for purposes of comparison with the next
  230. line of |cur_file|. After the change file has been completely input, we
  231. set |change_limit=change_buffer|,
  232. so that no further matches will be made.
  233.  
  234. Here's a shorthand expression for inequality between the two lines:
  235.  
  236. @d lines_dont_match (change_limit-change_buffer != limit-buffer ||
  237.   strncmp(buffer, change_buffer, limit-buffer))
  238.  
  239. @<Other...@>=
  240. char change_buffer[buf_size]; /* next line of |change_file| */
  241. char *change_limit; /* points to the last character in |change_buffer| */
  242.  
  243. @ Procedure |prime_the_change_buffer|
  244. sets |change_buffer| in preparation for the next matching operation.
  245. Since blank lines in the change file are not used for matching, we have
  246. |(change_limit==change_buffer && !changing)| if and only if
  247. the change file is exhausted. This procedure is called only when
  248. |changing| is 1; hence error messages will be reported correctly.
  249.  
  250. @c
  251. void
  252. prime_the_change_buffer()
  253. {
  254.   change_limit=change_buffer; /* this value is used if the change file ends */
  255.   @<Skip over comment lines in the change file; |return| if end of file@>;
  256.   @<Skip to the next nonblank line; |return| if end of file@>;
  257.   @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>;
  258. }
  259.  
  260. @ While looking for a line that begins with \.{@@x} in the change file, we
  261. allow lines that begin with \.{@@}, as long as they don't begin with \.{@@y},
  262. \.{@@z} or \.{@@i} (which would probably mean that the change file is fouled up).
  263.  
  264. @<Skip over comment lines in the change file...@>=
  265. while(1) {
  266.   change_line++;
  267.   if (!input_ln(change_file)) return;
  268.   if (limit<buffer+2) continue;
  269.   if (buffer[0]!='@@') continue;
  270.   if (xisupper(buffer[1])) buffer[1]=tolower(buffer[1]);
  271.   if (buffer[1]=='x') break;
  272.   if (buffer[1]=='y' || buffer[1]=='z' || buffer[1]=='i') {
  273.     loc=buffer+2;
  274.     err_print("! Missing @@x in change file");
  275. @.Missing @@x...@>
  276.   }
  277. }
  278.  
  279. @ Here we are looking at lines following the \.{@@x}.
  280.  
  281. @<Skip to the next nonblank line...@>=
  282. do {
  283.   change_line++;
  284.   if (!input_ln(change_file)) {
  285.     err_print("! Change file ended after @@x");
  286. @.Change file ended...@>
  287.     return;
  288.   }
  289. } while (limit==buffer);
  290.  
  291. @ @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>=
  292. {
  293.   change_limit=change_buffer-buffer+limit;
  294.   strncpy(change_buffer,buffer,limit-buffer+1);
  295. }
  296.  
  297. @ The following procedure is used to see if the next change entry should
  298. go into effect; it is called only when |changing| is 0.
  299. The idea is to test whether or not the current
  300. contents of |buffer| matches the current contents of |change_buffer|.
  301. If not, there's nothing more to do; but if so, a change is called for:
  302. All of the text down to the \.{@@y} is supposed to match. An error
  303. message is issued if any discrepancy is found. Then the procedure
  304. prepares to read the next line from |change_file|.
  305.  
  306. When a match is found, the current section is marked as changed unless
  307. the first line after the \.{@@x} and after the \.{@@y} both start with
  308. either |'@@*'| or |'@@ '| (possibly preceded by whitespace).
  309.  
  310. This procedure is called only when |buffer<limit|, i.e., when the
  311. current line is nonempty.
  312.  
  313. @d if_section_start_make_pending(b) {@+*limit='!';
  314.   for (loc=buffer;xisspace(*loc);loc++) ;
  315.   *limit=' ';
  316.   if (*loc=='@@' && (xisspace(*(loc+1)) || *(loc+1)=='*')) change_pending=b;
  317. }
  318.  
  319. @c
  320. void
  321. check_change() /* switches to |change_file| if the buffers match */
  322. {
  323.   int n=0; /* the number of discrepancies found */
  324.   if (lines_dont_match) return;
  325.   change_pending=0;
  326.   if (!changed_section[section_count]) {
  327.     if_section_start_make_pending(1);
  328.     if (!change_pending) changed_section[section_count]=1;
  329.   }
  330.   while (1) {
  331.     changing=1; print_where=1; change_line++;
  332.     if (!input_ln(change_file)) {
  333.       err_print("! Change file ended before @@y");
  334. @.Change file ended...@>
  335.       change_limit=change_buffer; changing=0;
  336.       return;
  337.     }
  338.     if (limit>buffer+1 && buffer[0]=='@@') {
  339.       if (xisupper(buffer[1])) buffer[1]=tolower(buffer[1]);
  340.       @<If the current line starts with \.{@@y},
  341.         report any discrepancies and |return|@>;
  342.     }
  343.     @<Move |buffer| and |limit|...@>;
  344.     changing=0; cur_line++;
  345.     while (!input_ln(cur_file)) { /* pop the stack or quit */
  346.       if (include_depth==0) {
  347.         err_print("! CWEB file ended during a change");
  348. @.CWEB file ended...@>
  349.         input_has_ended=1; return;
  350.       }
  351.       include_depth--; cur_line++;
  352.     }
  353.     if (lines_dont_match) n++;
  354.   }
  355. }
  356.  
  357. @ @<If the current line starts with \.{@@y}...@>=
  358. if (buffer[1]=='x' || buffer[1]=='z') {
  359.   loc=buffer+2; err_print("! Where is the matching @@y?");
  360. @.Where is the match...@>
  361.   }
  362. else if (buffer[1]=='y') {
  363.   if (n>0) {
  364.     loc=buffer+2;
  365.     printf("\n! Hmm... %d ",n);
  366.     err_print("of the preceding lines failed to match");
  367. @.Hmm... n of the preceding...@>
  368.   }
  369.   change_depth=include_depth;
  370.   return;
  371. }
  372.  
  373. @ The |reset_input| procedure, which gets \.{CWEB} ready to read the
  374. user's \.{CWEB} input, is used at the beginning of phase one of \.{CTANGLE},
  375. phases one and two of \.{CWEAVE}.
  376.  
  377. @c
  378. void
  379. reset_input()
  380. {
  381.   limit=buffer; loc=buffer+1; buffer[0]=' ';
  382.   @<Open input files@>;
  383.   include_depth=0; cur_line=0; change_line=0;
  384.   change_depth=include_depth;
  385.   changing=1; prime_the_change_buffer(); changing=!changing;
  386.   limit=buffer; loc=buffer+1; buffer[0]=' '; input_has_ended=0;
  387. }
  388.  
  389. @ The following code opens the input files.
  390. @^system dependencies@>
  391.  
  392. @<Open input files@>=
  393. if ((web_file=fopen(web_file_name,"r"))==NULL) {
  394.   strcpy(web_file_name,alt_web_file_name);
  395.   if ((web_file=fopen(web_file_name,"r"))==NULL)
  396.        fatal("! Cannot open input file ", web_file_name);
  397. }
  398. @.Cannot open input file@>
  399. @.Cannot open change file@>
  400. web_file_open=1;
  401. if ((change_file=fopen(change_file_name,"r"))==NULL)
  402.        fatal("! Cannot open change file ", change_file_name);
  403.  
  404. @ The |get_line| procedure is called when |loc>limit|; it puts the next
  405. line of merged input into the buffer and updates the other variables
  406. appropriately. A space is placed at the right end of the line.
  407. This procedure returns |!input_has_ended| because we often want to
  408. check the value of that variable after calling the procedure.
  409.  
  410. If we've just changed from the |cur_file| to the |change_file|, or if
  411. the |cur_file| has changed, we tell \.{CTANGLE} to print this
  412. information in the \CEE/ file by means of the |print_where| flag.
  413.  
  414. @d max_sections 2000 /* number of identifiers, strings, section names;
  415.   must be less than 10240 */
  416.  
  417. @<Defin...@>=
  418. typedef unsigned short sixteen_bits;
  419. sixteen_bits section_count; /* the current section number */
  420. boolean changed_section[max_sections]; /* is the section changed? */
  421. boolean change_pending; /* if the current change is not yet recorded in
  422.   |changed_section[section_count]| */
  423. boolean print_where=0; /* should \.{CTANGLE} print line and file info? */
  424.  
  425. @ @c
  426. int get_line() /* inputs the next line */
  427. {
  428.   restart:
  429.   if (changing && include_depth==change_depth)
  430.    @<Read from |change_file| and maybe turn off |changing|@>;
  431.   if (! changing || include_depth>change_depth) {
  432.     @<Read from |cur_file| and maybe turn on |changing|@>;
  433.     if (changing && include_depth==change_depth) goto restart;
  434.   }
  435.   loc=buffer; *limit=' ';
  436.   if (*buffer=='@@' && (*(buffer+1)=='i' || *(buffer+1)=='I')) {
  437.     loc=buffer+2;
  438.     while (loc<=limit && (*loc==' '||*loc=='\t'||*loc=='"')) loc++;
  439.     if (loc>=limit) {
  440.       err_print("! Include file name not given");
  441. @.Include file name ...@>
  442.       goto restart;
  443.     }
  444.     if (include_depth>=max_include_depth-1) {
  445.       err_print("! Too many nested includes");
  446. @.Too many nested includes@>
  447.       goto restart;
  448.     }
  449.     include_depth++; /* push input stack */
  450.     @<Try to open include file, abort push if unsuccessful, go to |restart|@>;
  451.   }
  452.   return (!input_has_ended);
  453. }
  454.  
  455. @ When an \.{@@i} line is found in the |cur_file|, we must temporarily
  456. stop reading it and start reading from the named include file.  The
  457. \.{@@i} line should give a complete file name with or without
  458. double quotes.
  459. If the environment variable \.{CWEBINPUTS} is set, or if the compiler flag
  460. of the same name was defined at compile time,
  461. \.{CWEB} will look for include files in the directory thus named, if
  462. it cannot find them in the current directory.
  463. (Colon-separated paths are not supported.)
  464. The remainder of the \.{@@i} line after the file name is ignored.
  465.  
  466. @d too_long() {include_depth--;
  467.         err_print("! Include file name too long"); goto restart;}
  468.  
  469. @<Include...@>=
  470. #include <stdlib.h> /* declaration of |getenv| and |exit| */
  471.  
  472. @ @<Try to open...@>= {
  473.   char temp_file_name[max_file_name_length];
  474.   char *cur_file_name_end=cur_file_name+max_file_name_length-1;
  475.   char *k=cur_file_name, *kk;
  476.   int l; /* length of file name */
  477.  
  478.   while (*loc!=' '&&*loc!='\t'&&*loc!='"'&&k<=cur_file_name_end) *k++=*loc++;
  479.   if (k>cur_file_name_end) too_long();
  480. @.Include file name ...@>
  481.   *k='\0';
  482.   if ((cur_file=fopen(cur_file_name,"r"))!=NULL) {
  483.     cur_line=0; print_where=1;
  484.     goto restart; /* success */
  485.   }
  486.   kk=getenv("CWEBINPUTS");
  487.   if (kk!=NULL) {
  488.     if ((l=strlen(kk))>max_file_name_length-2) too_long();
  489.     strcpy(temp_file_name,kk);
  490.   }
  491.   else {
  492. #ifdef CWEBINPUTS
  493.     if ((l=strlen(CWEBINPUTS))>max_file_name_length-2) too_long();
  494.     strcpy(temp_file_name,CWEBINPUTS);
  495. #else
  496.     l=0;
  497. #endif /* |CWEBINPUTS| */
  498.   }
  499.   if (l>0) {
  500.     if (k+l+2>=cur_file_name_end)  too_long();
  501. @.Include file name ...@>
  502.     for (; k>= cur_file_name; k--) *(k+l+1)=*k;
  503.     strcpy(cur_file_name,temp_file_name);
  504.     cur_file_name[l]='/'; /* \UNIX/ pathname separator */
  505.     if ((cur_file=fopen(cur_file_name,"r"))!=NULL) {
  506.       cur_line=0; print_where=1;
  507.       goto restart; /* success */
  508.     }
  509.   }
  510.   include_depth--; err_print("! Cannot open include file"); goto restart;
  511. }
  512.  
  513. @ @<Read from |cur_file|...@>= {
  514.   cur_line++;
  515.   while (!input_ln(cur_file)) { /* pop the stack or quit */
  516.     print_where=1;
  517.     if (include_depth==0) {input_has_ended=1; break;}
  518.     else {
  519.       fclose(cur_file); include_depth--;
  520.       if (changing && include_depth==change_depth) break;
  521.       cur_line++;
  522.     }
  523.   }
  524.   if (!changing && !input_has_ended)
  525.    if (limit-buffer==change_limit-change_buffer)
  526.     if (buffer[0]==change_buffer[0])
  527.       if (change_limit>change_buffer) check_change();
  528. }
  529.  
  530. @ @<Read from |change_file|...@>= {
  531.   change_line++;
  532.   if (!input_ln(change_file)) {
  533.     err_print("! Change file ended without @@z");
  534. @.Change file ended...@>
  535.     buffer[0]='@@'; buffer[1]='z'; limit=buffer+2;
  536.   }
  537.   if (limit>buffer) { /* check if the change has ended */
  538.     if (change_pending) {
  539.       if_section_start_make_pending(0);
  540.       if (change_pending) {
  541.         changed_section[section_count]=1; change_pending=0;
  542.       }
  543.     }
  544.     *limit=' ';
  545.     if (buffer[0]=='@@') {
  546.       if (xisupper(buffer[1])) buffer[1]=tolower(buffer[1]);
  547.       if (buffer[1]=='x' || buffer[1]=='y') {
  548.         loc=buffer+2;
  549.         err_print("! Where is the matching @@z?");
  550. @.Where is the match...@>
  551.       }
  552.       else if (buffer[1]=='z') {
  553.         prime_the_change_buffer(); changing=!changing; print_where=1;
  554.       }
  555.     }
  556.   }
  557. }
  558.  
  559. @ At the end of the program, we will tell the user if the change file
  560. had a line that didn't match any relevant line in |web_file|.
  561.  
  562. @c
  563. void
  564. check_complete(){
  565.   if (change_limit!=change_buffer) { /* |changing| is 0 */
  566.     strncpy(buffer,change_buffer,change_limit-change_buffer+1);
  567.     limit=buffer+(int)(change_limit-change_buffer);
  568.     changing=1; change_depth=include_depth; loc=buffer;
  569.     err_print("! Change file entry did not match");
  570. @.Change file entry did not match@>
  571.   }
  572. }
  573.  
  574. @** Storage of names and strings.
  575. Both \.{CWEAVE} and \.{CTANGLE} store identifiers, section names and
  576. other strings in a large array of |char|s, called |byte_mem|.
  577. Information about the names is kept in the array |name_dir|, whose
  578. elements are structures of type |name_info|, containing a pointer into
  579. the |byte_mem| array (the address where the name begins) and other data.
  580. A |name_pointer| variable is a pointer into |name_dir|.
  581.  
  582. @d max_bytes 90000 /* the number of bytes in identifiers,
  583.   index entries, and section names; must be less than $2^{24}$ */
  584. @d max_names 4000 /* number of identifiers, strings, section names;
  585.   must be less than 10240 */
  586.  
  587. @<Definitions that...@>=
  588. typedef struct name_info {
  589.   char *byte_start; /* beginning of the name in |byte_mem| */
  590.   @<More elements of |name_info| structure@>@;
  591. } name_info; /* contains information about an identifier or section name */
  592. typedef name_info *name_pointer; /* pointer into array of |name_info|s */
  593. char byte_mem[max_bytes]; /* characters of names */
  594. char *byte_mem_end = byte_mem+max_bytes-1; /* end of |byte_mem| */
  595. name_info name_dir[max_names]; /* information about names */
  596. name_pointer name_dir_end = name_dir+max_names-1; /* end of |name_dir| */
  597.  
  598. @ The actual sequence of characters in the name pointed to by a |name_pointer
  599. p| appears in positions |p->byte_start| to |(p+1)->byte_start-1|, inclusive.
  600. The |print_id| macro prints this text on the user's terminal.
  601.  
  602. @d length(c) (c+1)->byte_start-(c)->byte_start /* the length of a name */
  603. @d print_id(c) term_write((c)->byte_start,length((c))) /* print identifier */
  604.  
  605. @ The first unused position in |byte_mem| and |name_dir| is
  606. kept in |byte_ptr| and |name_ptr|, respectively.  Thus we
  607. usually have |name_ptr->byte_start==byte_ptr|, and certainly
  608. we want to keep |name_ptr<=name_dir_end| and |byte_ptr<=byte_mem_end|.
  609.  
  610. @<Defini...@>=
  611. name_pointer name_ptr; /* first unused position in |byte_start| */
  612. char *byte_ptr; /* first unused position in |byte_mem| */
  613.  
  614. @ @<Init...@>=
  615. name_dir->byte_start=byte_ptr=byte_mem; /* position zero in both arrays */
  616. name_ptr=name_dir+1; /* |name_dir[0]| will be used only for error recovery */
  617. name_ptr->byte_start=byte_mem; /* this makes name 0 of length zero */
  618.  
  619. @ The names of identifiers are found by computing a hash address |h| and
  620. then looking at strings of bytes signified by the |name_pointer|s
  621. |hash[h]|, |hash[h]->link|, |hash[h]->link->link|, \dots,
  622. until either finding the desired name or encountering the null pointer.
  623.  
  624. @<More elements of |name...@>=
  625. struct name_info *link;
  626.  
  627. @ The hash table itself
  628. consists of |hash_size| entries of type |name_pointer|, and is
  629. updated by the |id_lookup| procedure, which finds a given identifier
  630. and returns the appropriate |name_pointer|. The matching is done by the
  631. function |names_match|, which is slightly different in
  632. \.{CWEAVE} and \.{CTANGLE}.  If there is no match for the identifier,
  633. it is inserted into the table.
  634.  
  635. @d hash_size 353 /* should be prime */
  636.  
  637. @<Defini...@>=
  638. typedef name_pointer *hash_pointer;
  639. name_pointer hash[hash_size]; /* heads of hash lists */
  640. hash_pointer hash_end = hash+hash_size-1; /* end of |hash| */
  641. hash_pointer h; /* index into hash-head array */
  642.  
  643. @ @<Predec...@>=
  644. extern int names_match();
  645.  
  646. @ Initially all the hash lists are empty.
  647.  
  648. @<Init...@>=
  649. for (h=hash; h<=hash_end; *h++=NULL) ;
  650.  
  651. @ Here is the main procedure for finding identifiers:
  652.  
  653. @c
  654. name_pointer
  655. id_lookup(first,last,t) /* looks up a string in the identifier table */
  656. char *first; /* first character of string */
  657. char *last; /* last character of string plus one */
  658. char t; /* the |ilk|; used by \.{CWEAVE} only */
  659. {
  660.   char *i=first; /* position in |buffer| */
  661.   int h; /* hash code */
  662.   int l; /* length of the given identifier */
  663.   name_pointer p; /* where the identifier is being sought */
  664.   if (last==NULL) for (last=first; *last!='\0'; last++);
  665.   l=last-first; /* compute the length */
  666.   @<Compute the hash code |h|@>;
  667.   @<Compute the name location |p|@>;
  668.   if (p==name_ptr) @<Enter a new name into the table at position |p|@>;
  669.   return(p);
  670. }
  671.  
  672. @ A simple hash code is used: If the sequence of
  673. character codes is $c_1c_2\ldots c_n$, its hash value will be
  674. $$(2^{n-1}c_1+2^{n-2}c_2+\cdots+c_n)\,\bmod\,|hash_size|.$$
  675.  
  676. @<Compute the hash...@>=
  677. h=(unsigned char)*i;
  678. while (++i<last) h=(h+h+(int)((unsigned char)*i)) % hash_size;
  679. @^high-bit character handling@>
  680.  
  681. @ If the identifier is new, it will be placed in position |p=name_ptr|,
  682. otherwise |p| will point to its existing location.
  683.  
  684. @<Compute the name location...@>=
  685. p=hash[h];
  686. while (p && !names_match(p,first,l,t)) p=p->link;
  687. if (p==NULL) {
  688.   p=name_ptr; /* the current identifier is new */
  689.   p->link=hash[h]; hash[h]=p; /* insert |p| at beginning of hash list */
  690. }
  691.  
  692. @ The information associated with a new identifier must be initialized
  693. in a slightly different way in \.{CWEAVE} than in \.{CTANGLE}; hence the
  694. |init_p| procedure.
  695.  
  696. @<Pred...@>=
  697. void init_p();
  698.  
  699. @ @<Enter a new name...@>= {
  700.   if (byte_ptr+l>byte_mem_end) overflow("byte memory");
  701.   if (name_ptr>=name_dir_end) overflow("name");
  702.   strncpy(byte_ptr,first,l);
  703.   (++name_ptr)->byte_start=byte_ptr+=l;
  704.   if (program==cweave) init_p(p,t);
  705. }
  706.  
  707. @ The names of sections are stored in |byte_mem| together
  708. with the identifier names, but a hash table is not used for them because
  709. \.{CTANGLE} needs to be able to recognize a section name when given a prefix of
  710. that name. A conventional binary search tree is used to retrieve section names,
  711. with fields called |llink| and |rlink| (where |llink| takes the place
  712. of |link|).  The root of this tree is stored in |name_dir->rlink|;
  713. this will be the only information in |name_dir[0]|.
  714.  
  715. Since the space used by |rlink| has a different function for
  716. identifiers than for section names, we declare it as a |union|.
  717.  
  718. @d llink link /* left link in binary search tree for section names */
  719. @d rlink dummy.Rlink /* right link in binary search tree for section names */
  720. @d root name_dir->rlink /* the root of the binary search tree
  721.   for section names */
  722.  
  723. @<More elements of |name...@>=
  724. union {
  725.   struct name_info *Rlink; /* right link in binary search tree for section
  726.     names */
  727.   char Ilk; /* used by identifiers in \.{CWEAVE} only */
  728. } dummy;
  729.  
  730. @ @<Init...@>=
  731. root=NULL; /* the binary search tree starts out with nothing in it */
  732.  
  733. @ If |p| is a |name_pointer| variable, as we have seen,
  734. |p->byte_start| is the beginning of the area where the name
  735. corresponding to |p| is stored.  However, if |p| refers to a section
  736. name, the name may need to be stored in chunks, because it may
  737. ``grow'': a prefix of the section name may be encountered before
  738. the full name.  Furthermore we need to know the length of the shortest
  739. prefix of the name that was ever encountered.
  740.  
  741. We solve this problem by inserting two extra bytes at |p->byte_start|,
  742. representing the length of the shortest prefix, when |p| is a
  743. section name. Furthermore, the last byte of the name will be a blank
  744. space if |p| is a prefix. In the latter case, the name pointer
  745. |p+1| will allow us to access additional chunks of the name:
  746. The second chunk will begin at the name pointer |(p+1)->link|,
  747. and if it too is a prefix (ending with blank) its |link| will point
  748. to additional chunks in the same way. Null links are represented by
  749. |name_dir|.
  750.  
  751. @d first_chunk(p)  ((p)->byte_start+2)
  752. @d prefix_length(p) (int)((unsigned char)*((p)->byte_start)*256 +
  753.                 (unsigned char)*((p)->byte_start+1))
  754. @d set_prefix_length(p,m) (*((p)->byte_start)=(m)/256,
  755.                  *((p)->byte_start+1)=(m)%256)
  756.  
  757. @c
  758. void
  759. print_section_name(p)
  760. name_pointer p;
  761. {
  762.   char *ss, *s = first_chunk(p);
  763.   name_pointer q = p+1;
  764.   while (p!=name_dir) {
  765.     ss = (p+1)->byte_start-1;
  766.     if (*ss==' ' && ss>=s) {
  767.       term_write(s,ss-s); p=q->link; q=p;
  768.     } else {
  769.       term_write(s,ss+1-s); p=name_dir; q=NULL;
  770.     }
  771.     s = p->byte_start;
  772.   }
  773.   if (q) term_write("...",3); /* complete name not yet known */
  774. }
  775.  
  776. @ @c
  777. void
  778. sprint_section_name(dest,p)
  779.   char*dest;
  780.   name_pointer p;
  781. {
  782.   char *ss, *s = first_chunk(p);
  783.   name_pointer q = p+1;
  784.   while (p!=name_dir) {
  785.     ss = (p+1)->byte_start-1;
  786.     if (*ss==' ' && ss>=s) {
  787.       p=q->link; q=p;
  788.     } else {
  789.       ss++; p=name_dir;
  790.     }
  791.     strncpy(dest,s,ss-s), dest+=ss-s;
  792.     s = p->byte_start;
  793.   }
  794.   *dest='\0';
  795. }
  796.  
  797. @ @c
  798. void
  799. print_prefix_name(p)
  800. name_pointer p;
  801. {
  802.   char *s = first_chunk(p);
  803.   int l = prefix_length(p);
  804.   term_write(s,l);
  805.   if (s+l<(p+1)->byte_start) term_write("...",3);
  806. }
  807.  
  808. @ When we compare two section names, we'll need a function analogous to
  809. |strcmp|. But we do not assume the strings
  810. are null-terminated, and we keep an eye open for prefixes and extensions.
  811.  
  812. @d less 0 /* the first name is lexicographically less than the second */
  813. @d equal 1 /* the first name is equal to the second */
  814. @d greater 2 /* the first name is lexicographically greater than the second */
  815. @d prefix 3 /* the first name is a proper prefix of the second */
  816. @d extension 4 /* the first name is a proper extension of the second */
  817.  
  818. @c
  819. int web_strcmp(j,j_len,k,k_len) /* fuller comparison than |strcmp| */
  820.   char *j, *k; /* beginning of first and second strings */
  821.   int j_len, k_len; /* length of strings */
  822. {
  823.   char *j1=j+j_len, *k1=k+k_len;
  824.   while (k<k1 && j<j1 && *j==*k) k++, j++;
  825.   if (k==k1) if (j==j1) return equal;
  826.     else return extension;
  827.   else if (j==j1) return prefix;
  828.   else if (*j<*k) return less;
  829.   else return greater;
  830. }
  831.  
  832. @ Adding a section name to the tree is straightforward if we know its
  833. parent and whether it's the |rlink| or |llink| of the parent.  As a
  834. special case, when the name is the first section being added, we set the
  835. ``parent'' to |NULL|.  When a section name is created, it has only one
  836. chunk, which however may be just a prefix: the full name will
  837. hopefully be unveiled later.  Obviously, |prefix_length| starts
  838. out as the length of the first chunk, though it may decrease later.
  839.  
  840. The information associated with a new node must be initialized
  841. differently in \.{CWEAVE} and \.{CTANGLE}; hence the
  842. |init_node| procedure, which is defined differently in \.{cweave.w}
  843. and \.{ctangle.w}.
  844.  
  845. @<Prede...@>=
  846. extern void init_node();
  847.  
  848. @ @c
  849. name_pointer
  850. add_section_name(par,c,first,last,ispref) /* install a new node in the tree */
  851. name_pointer par; /* parent of new node */
  852. int c; /* right or left? */
  853. char *first; /* first character of section name */
  854. char *last; /* last character of section name, plus one */
  855. int ispref; /* are we adding a prefix or a full name? */
  856. {
  857.   name_pointer p=name_ptr; /* new node */
  858.   char *s=first_chunk(p);
  859.   int name_len=last-first+ispref; /* length of section name */
  860.   if (s+name_len>byte_mem_end) overflow("byte memory");
  861.   if (name_ptr+1>=name_dir_end) overflow("name");
  862.   (++name_ptr)->byte_start=byte_ptr=s+name_len;
  863.   if (ispref) {
  864.     *(byte_ptr-1)=' ';
  865.     name_len--;
  866.     name_ptr->link=name_dir;
  867.     (++name_ptr)->byte_start=byte_ptr;
  868.   }
  869.   set_prefix_length(p,name_len);
  870.   strncpy(s,first,name_len);
  871.   p->llink=NULL;
  872.   p->rlink=NULL;
  873.   init_node(p);
  874.   return par==NULL ? (root=p) : c==less ? (par->llink=p) : (par->rlink=p);
  875. }
  876.  
  877. @ @c
  878. void
  879. extend_section_name(p,first,last,ispref)
  880. name_pointer p; /* name to be extended */
  881. char *first; /* beginning of extension text */
  882. char *last; /* one beyond end of extension text */
  883. int ispref; /* are we adding a prefix or a full name? */
  884. {
  885.   char *s;
  886.   name_pointer q=p+1;
  887.   int name_len=last-first+ispref;
  888.   if (name_ptr>=name_dir_end) overflow("name");
  889.   while (q->link!=name_dir) q=q->link;
  890.   q->link=name_ptr;
  891.   s=name_ptr->byte_start;
  892.   name_ptr->link=name_dir;
  893.   if (s+name_len>byte_mem_end) overflow("byte memory");
  894.   (++name_ptr)->byte_start=byte_ptr=s+name_len;
  895.   strncpy(s,first,name_len);
  896.   if (ispref) *(byte_ptr-1)=' ';
  897. }
  898.  
  899. @ The |section_lookup| procedure is supposed to find a
  900. section name that matches a new name, installing the new name if
  901. it doesn't match an existing one. The new name is the string
  902. between |first| and |last|; a ``match'' means that the new name
  903. exactly equals or is a prefix or extension of a name in the tree.
  904.  
  905. @c
  906. name_pointer
  907. section_lookup(first,last,ispref) /* find or install section name in tree */
  908. char *first, *last; /* first and last characters of new name */
  909. int ispref; /* is the new name a prefix or a full name? */
  910. {
  911.   int c=0; /* comparison between two names; initialized so some compilers won't complain */
  912.   name_pointer p=root; /* current node of the search tree */
  913.   name_pointer q=NULL; /* another place to look in the tree */
  914.   name_pointer r=NULL; /* where a match has been found */
  915.   name_pointer par=NULL; /* parent of |p|, if |r| is |NULL|;
  916.             otherwise parent of |r| */
  917.   int name_len=last-first+1;
  918.   @<Look for matches for new name among shortest prefixes, complaining
  919.         if more than one is found@>;
  920.   @<If no match found, add new name to tree@>;
  921.   @<If one match found, check for compatibility and return match@>;
  922. }
  923.  
  924. @ A legal new name matches an existing section name if and only if it
  925. matches the shortest prefix of that section name.  Therefore we can
  926. limit our search for matches to shortest prefixes, which eliminates
  927. the need for chunk-chasing at this stage.
  928.  
  929. @<Look for matches for new name among...@>=
  930. while (p) { /* compare shortest prefix of |p| with new name */
  931.   c=web_strcmp(first,name_len,first_chunk(p),prefix_length(p));
  932.   if (c==less || c==greater) { /* new name does not match |p| */
  933.     if (r==NULL) /* no previous matches have been found */
  934.       par=p;
  935.     p=(c==less?p->llink:p->rlink);
  936.   } else { /* new name matches |p| */
  937.     if (r!=NULL) {  /* and also |r|: illegal */
  938.       printf("\n! Ambiguous prefix: matches <");
  939. @.Ambiguous prefix ... @>
  940.       print_prefix_name(p);
  941.       printf(">\n and <");
  942.       print_prefix_name(r);
  943.       err_print(">");
  944.       return name_dir; /* the unsection */
  945.     }
  946.     r=p; /* remember match */
  947.     p=p->llink; /* try another */
  948.     q=r->rlink; /* we'll get back here if the new |p| doesn't match */
  949.   }
  950.   if (p==NULL)
  951.     p=q, q=NULL; /* |q| held the other branch of |r| */
  952. }
  953.  
  954. @ @<If no match ...@>=
  955.   if (r==NULL) /* no matches were found */
  956.     return add_section_name(par,c,first,last+1,ispref);
  957.  
  958. @ Although error messages are given in anomalous cases, we do return the
  959. unique best match when a discrepancy is found, because users often
  960. change a title in one place while forgetting to change it elsewhere.
  961.  
  962. @<If one match found, check for compatibility and return match@>=
  963. switch(section_name_cmp(&first,name_len,r)) {
  964.               /* compare all of |r| with new name */
  965.   case prefix:
  966.     if (!ispref) {
  967.       printf("\n! New name is a prefix of <");
  968. @.New name is a prefix...@>
  969.       print_section_name(r);
  970.       err_print(">");
  971.     }
  972.     else if (name_len<prefix_length(r)) set_prefix_length(r,name_len);
  973.     /* fall through */
  974.   case equal: return r;
  975.   case extension: if (!ispref || first<=last)
  976.         extend_section_name(r,first,last+1,ispref);
  977.       return r;
  978.   case bad_extension:
  979.       printf("\n! New name extends <");
  980. @.New name extends...@>
  981.       print_section_name(r);
  982.       err_print(">");
  983.     return r;
  984.   default: /* no match: illegal */
  985.     printf("\n! Section name incompatible with <");
  986. @.Section name incompatible...@>
  987.     print_prefix_name(r);
  988.     printf(">,\n which abbreviates <");
  989.     print_section_name(r);
  990.     err_print(">");
  991.     return r;
  992. }
  993.  
  994. @ The return codes of |section_name_cmp|, which compares a string with
  995. the full name of a section, are those of |web_strcmp| plus
  996. |bad_extension|, used when the string is an extension of a
  997. supposedly already complete section name.  This function has a side
  998. effect when the comparison string is an extension: it advances the
  999. address of the first character of the string by an amount equal to
  1000. the length of the known part of the section name.
  1001.  
  1002. The name \.{@@<foo...@@>} should be an acceptable ``abbreviation''
  1003. for \.{@@<foo@@>}. If such an abbreviation comes after the complete
  1004. name, there's no trouble recognizing it. If it comes before the
  1005. complete name, we simply append a null chunk. This logic requires
  1006. us to regard \.{@@<foo...@@>} as an ``extension'' of itself.
  1007.  
  1008. @d bad_extension 5
  1009.  
  1010. @<Predec...@>=
  1011. int section_name_cmp();
  1012.  
  1013. @ @c
  1014. int section_name_cmp(pfirst,len,r)
  1015. char **pfirst; /* pointer to beginning of comparison string */
  1016. int len; /* length of string */
  1017. name_pointer r; /* section name being compared */
  1018. {
  1019.   char *first=*pfirst; /* beginning of comparison string */
  1020.   name_pointer q=r+1; /* access to subsequent chunks */
  1021.   char *ss, *s=first_chunk(r);
  1022.   int c; /* comparison */
  1023.   int ispref; /* is chunk |r| a prefix? */
  1024.   while (1) {
  1025.     ss=(r+1)->byte_start-1;
  1026.     if (*ss==' ' && ss>=r->byte_start) ispref=1,q=q->link;
  1027.     else ispref=0,ss++,q=name_dir;
  1028.     switch(c=web_strcmp(first,len,s,ss-s)) {
  1029.     case equal: if (q==name_dir)
  1030.         if (ispref) {
  1031.           *pfirst=first+(ss-s);
  1032.           return extension; /* null extension */
  1033.         } else return equal;
  1034.       else return (q->byte_start==(q+1)->byte_start)? equal: prefix;
  1035.     case extension:
  1036.       if (!ispref) return bad_extension;
  1037.       first += ss-s;
  1038.       if (q!=name_dir) {len -= ss-s; s=q->byte_start; r=q; continue;}
  1039.       *pfirst=first; return extension;
  1040.     default: return c;
  1041.     }
  1042.   }
  1043. }
  1044.  
  1045. @ The last component of |name_info| is different for \.{CTANGLE} and
  1046. \.{CWEAVE}.  In \.{CTANGLE}, if |p| is a pointer to a section name,
  1047. |p->equiv| is a pointer to its replacement text, an element of the
  1048. array |text_info|.  In \.{CWEAVE}, on the other hand, if
  1049. |p| points to an identifier, |p->xref| is a pointer to its
  1050. list of cross-references, an element of the array |xmem|.  The make-up
  1051. of |text_info| and |xmem| is discussed in the \.{CTANGLE} and \.{CWEAVE}
  1052. source files, respectively; here we just declare a common field
  1053. |equiv_or_xref| as a pointer to a |char|.
  1054.  
  1055. @<More elements of |name...@>=
  1056. char *equiv_or_xref; /* info corresponding to names */
  1057.  
  1058. @** Reporting errors to the user.
  1059. A global variable called |history| will contain one of four values
  1060. at the end of every run: |spotless| means that no unusual messages were
  1061. printed; |harmless_message| means that a message of possible interest
  1062. was printed but no serious errors were detected; |error_message| means that
  1063. at least one error was found; |fatal_message| means that the program
  1064. terminated abnormally. The value of |history| does not influence the
  1065. behavior of the program; it is simply computed for the convenience
  1066. of systems that might want to use such information.
  1067.  
  1068. @d spotless 0 /* |history| value for normal jobs */
  1069. @d harmless_message 1 /* |history| value when non-serious info was printed */
  1070. @d error_message 2 /* |history| value when an error was noted */
  1071. @d fatal_message 3 /* |history| value when we had to stop prematurely */
  1072. @d mark_harmless {if (history==spotless) history=harmless_message;}
  1073. @d mark_error history=error_message
  1074.  
  1075. @<Definit...@>=
  1076. int history=spotless; /* indicates how bad this run was */
  1077.  
  1078. @ The command `|err_print("! Error message")|' will report a syntax error to
  1079. the user, by printing the error message at the beginning of a new line and
  1080. then giving an indication of where the error was spotted in the source file.
  1081. Note that no period follows the error message, since the error routine
  1082. will automatically supply a period. A newline is automatically supplied
  1083. if the string begins with |"!"|.
  1084.  
  1085. @<Predecl...@>=
  1086. void  err_print();
  1087.  
  1088. @ @c
  1089. void
  1090. err_print(s) /* prints `\..' and location of error message */
  1091. char *s;
  1092. {
  1093.   char *k,*l; /* pointers into |buffer| */
  1094.   printf(*s=='!'? "\n%s" : "%s",s);
  1095.   if(web_file_open) @<Print error location based on input buffer@>;
  1096.   update_terminal; mark_error;
  1097. }
  1098.  
  1099. @ The error locations can be indicated by using the global variables
  1100. |loc|, |cur_line|, |cur_file_name| and |changing|,
  1101. which tell respectively the first
  1102. unlooked-at position in |buffer|, the current line number, the current
  1103. file, and whether the current line is from |change_file| or |cur_file|.
  1104. This routine should be modified on systems whose standard text editor
  1105. has special line-numbering conventions.
  1106. @^system dependencies@>
  1107.  
  1108. @<Print error location based on input buffer@>=
  1109. {if (changing && include_depth==change_depth)
  1110.   printf(". (l. %d of change file)\n", change_line);
  1111. else if (include_depth==0) printf(". (l. %d)\n", cur_line);
  1112.   else printf(". (l. %d of include file %s)\n", cur_line, cur_file_name);
  1113. l= (loc>=limit? limit: loc);
  1114. if (l>buffer) {
  1115.   for (k=buffer; k<l; k++)
  1116.     if (*k=='\t') putchar(' ');
  1117.     else putchar(*k); /* print the characters already read */
  1118.   putchar('\n');
  1119.   for (k=buffer; k<l; k++) putchar(' '); /* space out the next line */
  1120. }
  1121. for (k=l; k<limit; k++) putchar(*k); /* print the part not yet read */
  1122. if (*limit=='|') putchar('|'); /* end of \CEE/ text in section names */
  1123. putchar(' '); /* to separate the message from future asterisks */
  1124. }
  1125.  
  1126. @ When no recovery from some error has been provided, we have to wrap
  1127. up and quit as graciously as possible.  This is done by calling the
  1128. function |wrap_up| at the end of the code.
  1129.  
  1130. \.{CTANGLE} and \.{CWEAVE} have their own notions about how to
  1131. print the job statistics.
  1132.  
  1133. @<Prede...@>=
  1134. int wrap_up();
  1135. extern void print_stats();
  1136.  
  1137. @ Some implementations may wish to pass the |history| value to the
  1138. operating system so that it can be used to govern whether or not other
  1139. programs are started. Here, for instance, we pass the operating system
  1140. a status of 0 if and only if only harmless messages were printed.
  1141. @^system dependencies@>
  1142.  
  1143. @c
  1144. int wrap_up() {
  1145.   putchar('\n');
  1146.   if (show_stats)
  1147.     print_stats(); /* print statistics about memory usage */
  1148.   @<Print the job |history|@>;
  1149.   if (history > harmless_message) return(1);
  1150.   else return(0);
  1151. }
  1152.  
  1153. @ @<Print the job |history|@>=
  1154. switch (history) {
  1155. case spotless: if (show_happiness) printf("(No errors were found.)\n"); break;
  1156. case harmless_message:
  1157.   printf("(Did you see the warning message above?)\n"); break;
  1158. case error_message:
  1159.   printf("(Pardon me, but I think I spotted something wrong.)\n"); break;
  1160. case fatal_message: printf("(That was a fatal error, my friend.)\n");
  1161. } /* there are no other cases */
  1162.  
  1163. @ When there is no way to recover from an error, the |fatal| subroutine is
  1164. invoked. This happens most often when |overflow| occurs.
  1165.  
  1166. @<Predec...@>=
  1167. void fatal(), overflow();
  1168.  
  1169. @ The two parameters to |fatal| are strings that are essentially
  1170. concatenated to print the final error message.
  1171.  
  1172. @c void
  1173. fatal(s,t)
  1174.   char *s,*t;
  1175. {
  1176.   if (*s) printf(s);
  1177.   err_print(t);
  1178.   history=fatal_message; exit(wrap_up());
  1179. }
  1180.  
  1181. @ An overflow stop occurs if \.{CWEB}'s tables aren't large enough.
  1182.  
  1183. @c void
  1184. overflow(t)
  1185.   char *t;
  1186. {
  1187.   printf("\n! Sorry, %s capacity exceeded",t); fatal("","");
  1188. }
  1189. @.Sorry, capacity exceeded@>
  1190.  
  1191. @ Sometimes the program's behavior is far different from what it should be,
  1192. and \.{CWEB} prints an error message that is really for the \.{CWEB}
  1193. maintenance person, not the user. In such cases the program says
  1194. |confusion("indication of where we are")|.
  1195.  
  1196. @d confusion(s) fatal("! This can't happen: ",s)
  1197. @.This can't happen@>
  1198.  
  1199. @** Command line arguments.
  1200. The user calls \.{CWEAVE} and \.{CTANGLE} with arguments on the command line.
  1201. These are either file names or flags to be turned off (beginning with |"-"|)
  1202. or flags to be turned on (beginning with |"+"|.
  1203. The following globals are for communicating the user's desires to the rest
  1204. of the program. The various file name variables contain strings with
  1205. the names of those files. Most of the 128 flags are undefined but available
  1206. for future extensions.
  1207.  
  1208. @d show_banner flags['b'] /* should the banner line be printed? */
  1209. @d show_progress flags['p'] /* should progress reports be printed? */
  1210. @d show_stats flags['s'] /* should statistics be printed at end of run? */
  1211. @d show_happiness flags['h'] /* should lack of errors be announced? */
  1212.  
  1213. @<Defin...@>=
  1214. int argc; /* copy of |ac| parameter to |main| */
  1215. char **argv; /* copy of |av| parameter to |main| */
  1216. char C_file_name[max_file_name_length]; /* name of |C_file| */
  1217. char tex_file_name[max_file_name_length]; /* name of |tex_file| */
  1218. char idx_file_name[max_file_name_length]; /* name of |idx_file| */
  1219. char scn_file_name[max_file_name_length]; /* name of |scn_file| */
  1220. boolean flags[128]; /* an option for each 7-bit code */
  1221.  
  1222. @ The |flags| will be initially zero. Some of them are set to~1 before
  1223. scanning the arguments; if additional flags are 1 by default they
  1224. should be set before calling |common_init|.
  1225.  
  1226. @<Set the default options common to \.{CTANGLE} and \.{CWEAVE}@>=
  1227. show_banner=show_happiness=show_progress=1;
  1228.  
  1229. @ We now must look at the command line arguments and set the file names
  1230. accordingly.  At least one file name must be present: the \.{CWEB}
  1231. file.  It may have an extension, or it may omit the extension to get |".w"| or
  1232. |".web"| added.  The \TEX/ output file name is formed by replacing the \.{CWEB}
  1233. file name extension by |".tex"|, and the \CEE/ file name by replacing
  1234. the extension by |".c"|, after removing the directory name (if any).
  1235.  
  1236. If there is a second file name present among the arguments, it is the
  1237. change file, again either with an extension or without one to get |".ch"|.
  1238. An omitted change file argument means that |"/dev/null"| should be used,
  1239. when no changes are desired.
  1240. @^system dependencies@>
  1241.  
  1242. If there's a third file name, it will be the output file.
  1243.  
  1244. @<Pred...@>=
  1245. void scan_args();
  1246.  
  1247. @ @c
  1248. void
  1249. scan_args()
  1250. {
  1251.   char *dot_pos; /* position of |'.'| in the argument */
  1252.   char *name_pos; /* file name beginning, sans directory */
  1253.   register char *s; /* register for scanning strings */
  1254.   boolean found_web=0,found_change=0,found_out=0;
  1255.              /* have these names have been seen? */
  1256.   boolean flag_change;
  1257.  
  1258.   while (--argc > 0) {
  1259.     if ((**(++argv)=='-'||**argv=='+')&&*(*argv+1)) @<Handle flag argument@>@;
  1260.     else {
  1261.       s=name_pos=*argv;@+dot_pos=NULL;
  1262.       while (*s) {
  1263.         if (*s=='.') dot_pos=s++;
  1264.         else if (*s=='/') dot_pos=NULL,name_pos=++s;
  1265.         else s++;
  1266.       }
  1267.       if (!found_web) @<Make
  1268.        |web_file_name|, |tex_file_name| and |C_file_name|@>@;
  1269.       else if (!found_change) @<Make |change_file_name| from |fname|@>@;
  1270.       else if (!found_out) @<Override |tex_file_name| and |C_file_name|@>@;
  1271.         else @<Print usage error message and quit@>;
  1272.     }
  1273.   }
  1274.   if (!found_web) @<Print usage error message and quit@>;
  1275.   if (found_change<=0) strcpy(change_file_name,"/dev/null");
  1276. }
  1277.  
  1278. @ We use all of |*argv| for the |web_file_name| if there is a |'.'| in it,
  1279. otherwise we add |".w"|. If this file can't be opened, we prepare an
  1280. |alt_web_file_name| by adding |"web"| after the dot.
  1281. The other file names come from adding other things
  1282. after the dot.  We must check that there is enough room in
  1283. |web_file_name| and the other arrays for the argument.
  1284.  
  1285. @<Make |web_file_name|...@>=
  1286. {
  1287.   if (s-*argv > max_file_name_length-5)
  1288.     @<Complain about argument length@>;
  1289.   if (dot_pos==NULL)
  1290.     sprintf(web_file_name,"%s.w",*argv);
  1291.   else {
  1292.     strcpy(web_file_name,*argv);
  1293.     *dot_pos=0; /* string now ends where the dot was */
  1294.   }
  1295.   sprintf(alt_web_file_name,"%s.web",*argv);
  1296.   sprintf(tex_file_name,"%s.tex",name_pos); /* strip off directory name */
  1297.   sprintf(idx_file_name,"%s.idx",name_pos);
  1298.   sprintf(scn_file_name,"%s.scn",name_pos);
  1299.   sprintf(C_file_name,"%s.c",name_pos);
  1300.   found_web=1;
  1301. }
  1302.  
  1303. @ @<Make |change_file_name|...@>=
  1304. {
  1305.   if (strcmp(*argv,"-")==0) found_change=-1;
  1306.   else {
  1307.     if (s-*argv > max_file_name_length-4)
  1308.       @<Complain about argument length@>;
  1309.     if (dot_pos==NULL)
  1310.       sprintf(change_file_name,"%s.ch",*argv);
  1311.     else strcpy(change_file_name,*argv);
  1312.     found_change=1;
  1313.   }
  1314. }
  1315.  
  1316. @ @<Override...@>=
  1317. {
  1318.   if (s-*argv > max_file_name_length-5)
  1319.     @<Complain about argument length@>;
  1320.   if (dot_pos==NULL) {
  1321.     sprintf(tex_file_name,"%s.tex",*argv);
  1322.     sprintf(idx_file_name,"%s.idx",*argv);
  1323.     sprintf(scn_file_name,"%s.scn",*argv);
  1324.     sprintf(C_file_name,"%s.c",*argv);
  1325.   } else {
  1326.     strcpy(tex_file_name,*argv);
  1327.     if (flags['x']) { /* indexes will be generated */
  1328.       if (program==cweave && strcmp(*argv+strlen(*argv)-4,".tex")!=0)
  1329.         fatal("! Output file name should end with .tex\n",*argv);
  1330. @.Output file name...tex@>
  1331.       strcpy(idx_file_name,*argv);
  1332.       strcpy(idx_file_name+strlen(*argv)-4,".idx");
  1333.       strcpy(scn_file_name,*argv);
  1334.       strcpy(scn_file_name+strlen(*argv)-4,".scn");
  1335.     }
  1336.     strcpy(C_file_name,*argv);
  1337.   }
  1338.   found_out=1;
  1339. }
  1340.  
  1341. @ @<Handle flag...@>=
  1342. {
  1343.   if (**argv=='-') flag_change=0;
  1344.   else flag_change=1;
  1345.   for(dot_pos=*argv+1;*dot_pos>'\0';dot_pos++)
  1346.     flags[*dot_pos]=flag_change;
  1347. }
  1348.  
  1349. @ @<Print usage error message and quit@>=
  1350. {
  1351. if (program==ctangle)
  1352.   fatal(
  1353. "! Usage: ctangle [options] webfile[.w] [{changefile[.ch]|-} [outfile[.c]]]\n"
  1354.    ,"");
  1355. @.Usage:@>
  1356. else fatal(
  1357. "! Usage: cweave [options] webfile[.w] [{changefile[.ch]|-} [outfile[.tex]]]\n"
  1358.    ,"");
  1359. }
  1360.  
  1361. @ @<Complain about arg...@>= fatal("! Filename too long\n", *argv);
  1362. @.Filename too long@>
  1363.  
  1364. @** Output. Here is the code that opens the output file:
  1365. @^system dependencies@>
  1366.  
  1367. @<Defin...@>=
  1368. FILE *C_file; /* where output of \.{CTANGLE} goes */
  1369. FILE *tex_file; /* where output of \.{CWEAVE} goes */
  1370. FILE *idx_file; /* where index from \.{CWEAVE} goes */
  1371. FILE *scn_file; /* where list of sections from \.{CWEAVE} goes */
  1372. FILE *active_file; /* currently active file for \.{CWEAVE} output */
  1373.  
  1374. @ @<Scan arguments and open output files@>=
  1375. scan_args();
  1376. if (program==ctangle) {
  1377.   if ((C_file=fopen(C_file_name,"w"))==NULL)
  1378.     fatal("! Cannot open output file ", C_file_name);
  1379. @.Cannot open output file@>
  1380. }
  1381. else {
  1382.   if ((tex_file=fopen(tex_file_name,"w"))==NULL)
  1383.     fatal("! Cannot open output file ", tex_file_name);
  1384. }
  1385.  
  1386. @ The |update_terminal| procedure is called when we want
  1387. to make sure that everything we have output to the terminal so far has
  1388. actually left the computer's internal buffers and been sent.
  1389. @^system dependencies@>
  1390.  
  1391. @d update_terminal fflush(stdout) /* empty the terminal output buffer */
  1392.  
  1393. @ Terminal output uses |putchar| and |putc| when we have to
  1394. translate from \.{CWEB}'s code into the external character code,
  1395. and |printf| when we just want to print strings.
  1396. Several macros make other kinds of output convenient.
  1397. @^system dependencies@>
  1398. @d new_line putchar('\n') @d putxchar putchar
  1399. @d term_write(a,b) fflush(stdout),fwrite(a,sizeof(char),b,stdout)
  1400. @d C_printf(c,a) fprintf(C_file,c,a)
  1401. @d C_putc(c) putc(c,C_file) /* isn't \CEE/ wonderfully consistent? */
  1402.  
  1403. @ We predeclare several standard system functions here instead of including
  1404. their system header files, because the names of the header files are not as
  1405. standard as the names of the functions. (For example, some \CEE/ environments
  1406. have \.{<string.h>} where others have \.{<strings.h>}.)
  1407.  
  1408. @<Predecl...@>=
  1409. extern int strlen(); /* length of string */
  1410. extern int strcmp(); /* compare strings lexicographically */
  1411. extern char* strcpy(); /* copy one string to another */
  1412. extern int strncmp(); /* compare up to $n$ string characters */
  1413. extern char* strncpy(); /* copy up to $n$ string characters */
  1414.  
  1415. @** Index.
  1416.