home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / programming / cweb / cwebsrc / CWEB / src / w / common next >
Encoding:
Text File  |  1996-11-22  |  51.1 KB  |  1,419 lines

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