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