home *** CD-ROM | disk | FTP | other *** search
/ Frozen Fish 1: Amiga / FrozenFish-Apr94.iso / bbs / alib / d5xx / d551 / cweb.lha / CWeb / cweb2.lzh / cweb / common.w < prev    next >
Text File  |  1990-12-14  |  40KB  |  1,068 lines

  1. % This file is part of CWEB.
  2. % This program by Silvio Levy is based on a program by D. E. Knuth.
  3. % It is distributed WITHOUT ANY WARRANTY, express or implied.
  4. % $Revision: 2.0$ % Don Knuth, July 1990
  5.  
  6. % Copyright (C) 1987,1990 Silvio Levy and Donald E. Knuth
  7.  
  8. % Permission is granted to make and distribute verbatim copies of this
  9. % document provided that the copyright notice and this permission notice
  10. % are preserved on all copies.
  11.  
  12. % Permission is granted to copy and distribute modified versions of this
  13. % document under the conditions for verbatim copying, provided that the
  14. % entire resulting derived work is distributed under the terms of a
  15. % permission notice identical to this one.
  16.  
  17. \def\v{\char'174} % vertical (|) in typewriter font
  18.  
  19. \def\title{Common code for CTANGLE and CWEAVE $
  20.   ($Revision: 2.0$)
  21.   $}
  22. \def\topofcontents{\null\vfill
  23.   \centerline{\titlefont Common code for {\ttitlefont CTANGLE} and
  24.     {\ttitlefont CWEAVE}}
  25.   \vskip 15pt
  26.   \centerline{$
  27.     ($Revision: 2.0$)
  28.     $}}
  29. \def\botofcontents{\vfill
  30. \noindent
  31. Copyright \copyright\ 1987,\thinspace1990 Silvio Levy and Donald E. Knuth
  32. \bigskip\noindent
  33. Permission is granted to make and distribute verbatim copies of this
  34. document provided that the copyright notice and this permission notice
  35. are preserved on all copies.
  36.  
  37. \smallskip\noindent
  38. Permission is granted to copy and distribute modified versions of this
  39. document under the conditions for verbatim copying, provided that the
  40. entire resulting derived work is distributed under the terms of a
  41. permission notice identical to this one.
  42. }
  43.  
  44. \pageno=\contentspagenumber \advance\pageno by 1
  45. \let\maybe=\iftrue
  46.  
  47. @* Introduction.  This file contains code common
  48. to both \.{TANGLE} and \.{WEAVE}, that roughly concerns the following
  49. problems: character uniformity, input routines, error handling and
  50. parsing of command line.  We have tried to concentrate in this file
  51. all the system dependencies, so as to maximize portability.
  52.  
  53. In the texts below we will
  54. sometimes use \.{WEB} to refer to either of the two component
  55. programs, if no confusion can arise.
  56.  
  57. Here is the overall appearance of this file:
  58.  
  59. @c
  60. @<Include files@>@/
  61. @<Definitions that should agree with \.{TANGLE} and \.{WEAVE}@>@;
  62. @<Other definitions@>@;
  63. @<Functions@>;
  64.  
  65. @ In certain cases \.{TANGLE} and \.{WEAVE} 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 tangle 0
  71. @d weave 1
  72.  
  73. @<Definitions...@>=
  74. typedef short boolean;
  75. boolean program; /* \.{WEAVE} or \.{TANGLE}? */
  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. @<Functions...@>=
  90. common_init()
  91. {
  92.   @<Initialize pointers@>;
  93.   @<Set the default options common to \.{TANGLE} and \.{WEAVE}@>;
  94.   @<Scan arguments and open output files@>;
  95. }
  96.  
  97. @* The character set.
  98. \.{CWEB} uses the conventions of \Cee\ programs found in the standard
  99. \.{ctype.h} header file.
  100.  
  101. @<Include files@>=
  102. #include <ctype.h>
  103.  
  104. @ A few character pairs are encoded internally as single characters,
  105. using the definitions below. These definitions are consistent with
  106. an extension of ASCII code originally developed at MIT and explained in
  107. Appendix~C of {\sl The \TeX book\/}; thus, users who have such a
  108. character set can type things like \.{\char'32} and \.{char'4} instead
  109. of \.{!=} and \.{\&\&}. (However, their files will not be too portable
  110. until more people adopt the extended code.)
  111.  
  112. If the character set is not ASCII, the definitions given here may conflict
  113. with existing characters; in such cases, other arbitrary codes should be
  114. substituted. The indexes to \.{CTANGLE} and \.{CWEAVE} mention every
  115. case where similar codes may have to be changed in order to
  116. avoid character conflicts. Look for the entry ``ASCII code dependencies''
  117. in those indexes.
  118.  
  119. @^ASCII code dependencies@>
  120. @^system dependencies@>
  121.  
  122. @d and_and 04 /* `\.{\&\&}'; this corresponds to MIT's {\tentex\char'4} */
  123. @d lt_lt 020 /* `\.{<<}';  this corresponds to MIT's {\tentex\char'20} */
  124. @d gt_gt 021 /* `\.{>>}';  this corresponds to MIT's {\tentex\char'21} */
  125. @d plus_plus 013 /* `\.{++}';  this corresponds to MIT's {\tentex\char'13} */
  126. @d minus_minus 01 /* `\.{--}';  this corresponds to MIT's {\tentex\char'1} */
  127. @d minus_gt 031 /* `\.{->}';  this corresponds to MIT's {\tentex\char'31} */
  128. @d not_eq 032 /* `\.{!=}';  this corresponds to MIT's {\tentex\char'32} */
  129. @d lt_eq 034 /* `\.{<=}';  this corresponds to MIT's {\tentex\char'34} */
  130. @d gt_eq 035 /* `\.{>=}';  this corresponds to MIT's {\tentex\char'35} */
  131. @d eq_eq 036 /* `\.{==}';  this corresponds to MIT's {\tentex\char'36} */
  132. @d or_or 037 /* `\.{\v\v}';  this corresponds to MIT's {\tentex\char'37} */
  133.  
  134. @* Input routines.  The lowest level of input to the \.{WEB} programs
  135. is performed by |input_ln|, which must be told which file to read from.
  136. The return value of |input_ln| is 1 if the read is successful and 0 if
  137. not (generally this means the file has ended). The conventions
  138. of \TeX\ are followed; i.e., the characters of the next line of the file
  139. are copied into the |buffer| array,
  140. and the global variable |limit| is set to the first unoccupied position.
  141. Trailing blanks are ignored. The value of |limit| must be strictly less
  142. than |buf_size|, so that |buffer[buf_size-1]| is never filled.
  143.  
  144. Since |buf_size| is strictly less than |long_buf_size|,
  145. some of \.{WEB}'s routines use the fact that it is safe to refer to
  146. |*(limit+2)| without overstepping the bounds of the array.
  147.  
  148. @d buf_size 100 /* for \.{WEAVE} and \.{TANGLE} */
  149. @d long_buf_size 500 /* for \.{WEAVE} */
  150.  
  151. @<Definitions...@>=
  152. char buffer[long_buf_size]; /* where each line of input goes */
  153. char *buffer_end=buffer+buf_size-2; /* end of |buffer| */
  154. char *limit=buffer; /* points to the last character in the buffer */
  155. char *loc=buffer; /* points to the next character to be read from the buffer */
  156.  
  157. @ @<Include files@>=
  158. #include <stdio.h>
  159.  
  160. @ In the unlikely event that your standard I/O library does not
  161. support |feof|, |getc| and |ungetc| you may have to change things here.
  162. @^system dependencies@>
  163.  
  164. @<Func...@>=
  165. input_ln(fp) /* copies a line into |buffer| or returns 0 */
  166. FILE *fp; /* what file to read from */
  167. {
  168.   register int  c; /* the character read */
  169.   register char *k;  /* where next character goes */
  170.   if (feof(fp)) return(0);  /* we have hit end-of-file */
  171.   limit = k = buffer;  /* beginning of buffer */
  172.   while (k<=buffer_end && (c=getc(fp)) != EOF && c!='\n')
  173.     if ((*(k++) = c) != ' ') limit = k;
  174.   if (k>buffer_end)
  175.     if ((c=getc(fp))!=EOF && c!='\n') {
  176.       ungetc(c,fp); loc=buffer; err_print("! Input line too long");
  177. @.Input line too long@>
  178.   }
  179.   if (c==EOF && limit==buffer) return(0);  /* there was nothing after
  180.     the last newline */
  181.   return(1);
  182. }
  183.  
  184. @ Now comes the problem of deciding which file to read from next.
  185. Recall that the actual text that \.{WEB} should process comes from two
  186. streams: a |web_file|, which can contain possibly nested include
  187. commands \.{@@i}, and a |change_file|, which should not contain
  188. includes.  The |web_file| together with the currently open include
  189. files form a stack |file|, whose names are stored in a parallel stack
  190. |file_name|.  The boolean |changing| tells whether or not we're reading
  191. form the |change_file|.
  192.  
  193. The line number of each open file is also kept for error reporting and
  194. for the benefit of \.{TANGLE}.
  195.  
  196. @f line x /* make |line| an unreserved word */
  197. @d max_include_depth 10 /* maximum number of source files open
  198.   simultaneously, not counting the change file */
  199. @d max_file_name_length 60
  200. @d cur_file file[include_depth] /* current file */
  201. @d cur_file_name file_name[include_depth] /* current file name */
  202. @d cur_line line[include_depth] /* number of current line in current file */
  203. @d web_file file[0] /* main source file */
  204. @d web_file_name file_name[0] /* main source file name */
  205.  
  206. @<Definitions...@>=
  207. int include_depth; /* current level of nesting */
  208. FILE *file[max_include_depth]; /* stack of non-change files */
  209. FILE *change_file; /* change file */
  210. char file_name[max_include_depth][max_file_name_length];
  211.   /* stack of non-change file names */
  212. char change_file_name[max_file_name_length]; /* name of change file */
  213. char alt_web_file_name[max_file_name_length]; /* alternate name to try */
  214. int line[max_include_depth]; /* number of current line in the stacked files */
  215. int change_line; /* number of current line in change file */
  216. boolean input_has_ended; /* if there is no more input */
  217. boolean changing; /* if the current line is from |change_file| */
  218. boolean web_file_open=0; /* if the web file is being read */
  219.  
  220. @ When |changing=0|, the next line of |change_file| is kept in
  221. |change_buffer|, for purposes of comparison with the next
  222. line of |cur_file|. After the change file has been completely input, we
  223. set |change_limit=change_buffer|,
  224. so that no further matches will be made.
  225.  
  226. Here's a shorthand expression for inequality between the two lines:
  227.  
  228. @d lines_dont_match (change_limit-change_buffer != limit-buffer ||
  229.   strncmp(buffer, change_buffer, limit-buffer))
  230.  
  231. @<Other...@>=
  232. char change_buffer[buf_size]; /* next line of |change_file| */
  233. char *change_limit; /* points to the last character in |change_buffer| */
  234.  
  235. @ Procedure |prime_the_change_buffer| sets |change_buffer| in preparation
  236. for the next matching operation. Since blank lines in the change file are
  237. not used for matching, we have |(change_limit==change_buffer && !changing)|
  238. if and only if the change file is exhausted. This procedure is called only
  239. when |changing| is 1; hence error messages will be reported correctly.
  240.  
  241. @<Func...@>=
  242. prime_the_change_buffer()
  243. {
  244.   change_limit=change_buffer; /* this value is used if the change file ends */
  245.   @<Skip over comment lines in the change file; |return| if end of file@>;
  246.   @<Skip to the next nonblank line; |return| if end of file@>;
  247.   @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>;
  248. }
  249.  
  250. @ While looking for a line that begins with \.{@@x} in the change file,
  251. we allow lines that begin with \.{@@}, as long as they don't begin with
  252. \.{@@y} or \.{@@z} (which would probably indicate that the change file is
  253. fouled up).
  254.  
  255. @<Skip over comment lines in the change file...@>=
  256. while(1) {
  257.   change_line++;
  258.   if (!input_ln(change_file)) return;
  259.   if (limit<buffer+2) continue;
  260.   if (buffer[0]!='@@') continue;
  261.   if (isupper(buffer[1])) buffer[1]=tolower(buffer[1]);
  262.   @<Check for erroneous \.{@@i}@>;
  263.   if (buffer[1]=='x') break;
  264.   if (buffer[1]=='y' || buffer[1]=='z') {
  265.     loc=buffer+2;
  266.     err_print("! Where is the matching @@x?");
  267. @.Where is the match...@>
  268.   }
  269. }
  270.  
  271. @ We do not allow includes in a change file, so as to avoid confusion.
  272.  
  273. @<Check for erron...@>= {
  274.   if (buffer[1]=='i') {
  275.     loc=buffer+2;
  276.     err_print("! No includes allowed in change file");
  277. @.No includes allowed...@>
  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. This procedure is called only when |buffer<limit|, i.e., when the
  309. current line is nonempty.
  310.  
  311. @<Func...@>=
  312. check_change() /* switches to |change_file| if the buffers match */
  313. {
  314.   int n=0; /* the number of discrepancies found */
  315.   if (lines_dont_match) return;
  316.   while (1) {
  317.     changing=1; print_where=1; change_line++;
  318.     if (!input_ln(change_file)) {
  319.       err_print("! Change file ended before @@y");
  320. @.Change file ended...@>
  321.       change_limit=change_buffer; changing=0;
  322.       return;
  323.     }
  324.     if (limit>buffer+1 && buffer[0]=='@@') {
  325.       if (isupper(buffer[1])) buffer[1]=tolower(buffer[1]);
  326.       @<Check for erron...@>;
  327.       @<If the current line starts with \.{@@y},
  328.         report any discrepancies and |return|@>;
  329.     }
  330.     @<Move |buffer| and |limit|...@>;
  331.     changing=0; cur_line++;
  332.     while (!input_ln(cur_file)) { /* pop the stack or quit */
  333.       if (include_depth==0) {
  334.         err_print("! WEB file ended during a change");
  335. @.WEB file ended...@>
  336.         input_has_ended=1; return;
  337.       }
  338.       include_depth--; cur_line++;
  339.     }
  340.     if (lines_dont_match) n++;
  341.   }
  342. }
  343.  
  344. @ @<If the current line starts with \.{@@y}...@>=
  345. if (buffer[1]=='x' || buffer[1]=='z') {
  346.   loc=buffer+2; err_print("! Where is the matching @@y?");
  347. @.Where is the match...@>
  348.   }
  349. else if (buffer[1]=='y') {
  350.   if (n>0) {
  351.     loc=buffer+2;
  352.     printf("\n! Hmm... %d ",n);
  353.     err_print("of the preceding lines failed to match");
  354. @.Hmm... n of the preceding...@>
  355.   }
  356.   return;
  357. }
  358.  
  359. @ The |reset_input| procedure, which gets \.{WEB} ready to read the
  360. user's \.{WEB} input, is used at the beginning of phase one of \.{TANGLE},
  361. phases one and two of \.{WEAVE}.
  362.  
  363. @<Func...@>=
  364. reset_input()
  365. {
  366.   limit=buffer; loc=buffer+1; buffer[0]=' ';
  367.   @<Open input files@>;
  368.   cur_line=0; change_line=0; include_depth=0;
  369.   changing=1; prime_the_change_buffer(); changing=!changing;
  370.   limit=buffer; loc=buffer+1; buffer[0]=' '; input_has_ended=0;
  371. }
  372.  
  373. @ The following code opens the input files.
  374. @^system dependencies@>
  375.  
  376. @<Open input files@>=
  377. if ((web_file=fopen(web_file_name,"r"))==NULL) {
  378.   strcpy(web_file_name,alt_web_file_name);
  379.   if ((web_file=fopen(web_file_name,"r"))==NULL)
  380.        fatal("! Cannot open input file ", web_file_name);
  381. }
  382. @.Cannot open input file@>
  383. @.Cannot open change file@>
  384. web_file_open=1;
  385. if ((change_file=fopen(change_file_name,"r"))==NULL)
  386.        fatal("! Cannot open change file ", change_file_name);
  387.  
  388. @ The |get_line| procedure is called when |loc>limit|; it puts the next
  389. line of merged input into the buffer and updates the other variables
  390. appropriately. A space is placed at the right end of the line.
  391. This procedure returns |!input_has_ended| because we often want to
  392. check the value of that variable after calling the procedure.
  393.  
  394. If we've just changed from the |cur_file| to the |change_file|, or if
  395. the |cur_file| has changed, we tell \.{TANGLE} to print this
  396. information in the \Cee\ file by means of the |print_where| flag.
  397.  
  398. @d max_modules 2000 /* number of identifiers, strings, module names;
  399.   must be less than 10240 */
  400.  
  401. @<Defin...@>=
  402. typedef unsigned short sixteen_bits;
  403. sixteen_bits module_count; /* the current module number */
  404. boolean changed_module[max_modules]; /* is the module changed? */
  405. boolean print_where=0; /* should \.{TANGLE} print line and file info? */
  406.  
  407. @ @<Fun...@>=
  408. get_line() /* inputs the next line */
  409. {
  410.   restart:
  411.   if (changing) changed_module[module_count]=1;
  412.   else @<Read from |cur_file| and maybe turn on |changing|@>;
  413.   if (changing) {
  414.     @<Read from |change_file| and maybe turn off |changing|@>;
  415.     if (! changing) {
  416.       changed_module[module_count]=1; goto restart;
  417.     }
  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. \.{WEB} will not look for include files in standard directories as the
  430. \Cee\ preprocessor does when a |
  431. #include <filename>
  432. | line is found.
  433.  
  434. @<Push stack and...@>= {
  435.   char *k, *j;
  436.   loc=buffer+2;
  437.   while (loc<=limit && (*loc==' '||*loc=='\t'||*loc=='"')) loc++;
  438.   if (loc>=limit) err_print("! Include file name not given");
  439. @.Include file name not given@>
  440.   else {
  441.     if (++include_depth<max_include_depth) {
  442.       k=cur_file_name; j=loc;
  443.       while (*loc!=' '&&*loc!='\t'&&*loc!='"') *k++=*loc++;
  444.       *k='\0';
  445.       if ((cur_file=fopen(cur_file_name,"r"))==NULL) {
  446.         include_depth--;
  447.         err_print("! Cannot open include file");
  448. @.Cannot open include file@>
  449.       }
  450.       else {cur_line=0; print_where=1;}
  451.     }
  452.     else {
  453.       include_depth--;
  454.       err_print("! Too many nested includes");
  455. @.Too many nested includes@>
  456.     }
  457.   }
  458.   goto restart;
  459. }
  460.  
  461. @ @<Read from |cur_file|...@>= {
  462.   cur_line++;
  463.   while (!input_ln(cur_file)) { /* pop the stack or quit */
  464.     print_where=1;
  465.     if (include_depth==0) {input_has_ended=1; break;}
  466.     else {fclose(cur_file); include_depth--; cur_line++;}
  467.   }
  468.   if (!input_has_ended)
  469.   if (limit==change_limit-change_buffer+buffer)
  470.     if (buffer[0]==change_buffer[0])
  471.       if (change_limit>change_buffer) check_change();
  472. }
  473.  
  474. @ @<Read from |change_file|...@>= {
  475.   change_line++;
  476.   if (!input_ln(change_file)) {
  477.     err_print("! Change file ended without @@z");
  478. @.Change file ended...@>
  479.     buffer[0]='@@'; buffer[1]='z'; limit=buffer+2;
  480.   }
  481.   if (limit>buffer+1) /* check if the change has ended */
  482.   if (buffer[0]=='@@') {
  483.     if (isupper(buffer[1])) buffer[1]=tolower(buffer[1]);
  484.     @<Check for erron...@>;
  485.     if (buffer[1]=='x' || buffer[1]=='y') {
  486.     loc=buffer+2; err_print("! Where is the matching @@z?");
  487. @.Where is the match...@>
  488.     }
  489.     else if (buffer[1]=='z') {
  490.       prime_the_change_buffer(); changing=!changing; print_where=1;
  491.     }
  492.   }
  493. }
  494.  
  495. @ At the end of the program, we will tell the user if the change file
  496. had a line that didn't match any relevant line in |web_file|.
  497.  
  498. @<Funct...@>=
  499. check_complete(){
  500.   if (change_limit!=change_buffer) { /* |changing| is 0 */
  501.     strncpy(buffer,change_buffer,change_limit-change_buffer+1);
  502.     limit=change_limit-change_buffer+buffer;
  503.     changing=1; loc=buffer;
  504.     err_print("! Change file entry did not match");
  505.   @.Change file entry did not match@>
  506.   }
  507. }
  508.  
  509. @* Storage of names and strings.
  510. Both \.{WEAVE} and \.{TANGLE} store identifiers, module names and
  511. other strings in a large array of |char|s, called |byte_mem|.
  512. Information about the names is kept in the array |name_dir|, whose
  513. elements are structures of type |name_info|, containing a pointer into
  514. the |byte_mem| array (the address where the name begins) and other data.
  515. A |name_pointer| variable is a pointer into |name_dir|.
  516.  
  517. @d max_bytes 90000 /* the number of bytes in identifiers,
  518.   index entries, and module names */
  519. @d max_names 4000 /* number of identifiers, strings, module names;
  520.   must be less than 10240 */
  521.  
  522. @<Definitions that...@>=
  523. typedef struct name_info {
  524.   char *byte_start; /* beginning of the name in |byte_mem| */
  525.   @<More elements of |name_info| structure@>@;
  526. } name_info; /* contains information about an identifier or module name */
  527. typedef name_info *name_pointer; /* pointer into array of |name_info|s */
  528. char byte_mem[max_bytes]; /* characters of names */
  529. char *byte_mem_end = byte_mem+max_bytes-1; /* end of |byte_mem| */
  530. name_info name_dir[max_names]; /* information about names */
  531. name_pointer name_dir_end = name_dir+max_names-1; /* end of |name_dir| */
  532.  
  533. @ The actual sequence of characters in the name pointed to by a |name_pointer
  534. p| appears in positions |p->byte_start| to |(p+1)->byte_start-1|, inclusive.
  535. The |print_id| macro prints this text on the user's terminal.
  536.  
  537. @d length(c) (c+1)->byte_start-(c)->byte_start /* the length of a name */
  538. @d print_id(c) term_write((c)->byte_start,length((c)))
  539.   /* print identifier or module name */
  540.  
  541. @ The first unused position in |byte_mem| and |name_dir| is
  542. kept in |byte_ptr| and |name_ptr|, respectively.  Thus we
  543. usually have |name_ptr->byte_start=byte_ptr|, and certainly
  544. we want to keep |name_ptr<=name_dir_end| and |byte_ptr<=byte_mem_end|.
  545.  
  546. @<Defini...@>=
  547. name_pointer name_ptr; /* first unused position in |byte_start| */
  548. char *byte_ptr; /* first unused position in |byte_mem| */
  549.  
  550. @ @<Init...@>=
  551. name_dir->byte_start=byte_ptr=byte_mem; /* position zero in both arrays */
  552. name_ptr=name_dir+1; /* |name_dir[0]| will be used only for error recovery */
  553. name_ptr->byte_start=byte_mem; /* this makes name 0 of length zero */
  554.  
  555. @ The names of identifiers are found by computing a hash address |h| and
  556. then looking at strings of bytes signified by the |name_pointer|s
  557. |hash[h]|, |hash[h]->link|, |hash[h]->link->link|, \dots,
  558. until either finding the desired name or encountering the null pointer.
  559.  
  560. @<More elements of |name...@>=
  561. struct name_info *link;
  562.  
  563. @ The hash table itself
  564. consists of |hash_size| entries of type |name_pointer|, and is
  565. updated by the |id_lookup| procedure, which finds a given identifier
  566. and returns the appropriate |name_pointer|. The matching is done by the
  567. function |names_match|, which is slightly different in
  568. \.{WEAVE} and \.{TANGLE}.  If there is no match for the identifier,
  569. it is inserted into the table.
  570.  
  571. @d hash_size 353 /* should be prime */
  572.  
  573. @<Defini...@>=
  574. typedef name_pointer *hash_pointer;
  575. name_pointer hash[hash_size]; /* heads of hash lists */
  576. hash_pointer hash_end = hash+hash_size-1; /* end of |hash| */
  577. hash_pointer h; /* index into hash-head array */
  578.  
  579. @ Initially all the hash lists are empty.
  580.  
  581. @<Init...@>=
  582. for (h=hash; h<=hash_end; *h++=NULL) ;
  583.  
  584. @ Here is the main procedure for finding identifiers:
  585.  
  586. @c name_pointer
  587. id_lookup(first,last,t) /* looks up a string in the identifier table */
  588. char *first; /* first character of string */
  589. char *last; /* last character of string plus one */
  590. sixteen_bits t; /* the |ilk|; used by \.{WEAVE} only */
  591. {
  592.   char *i=first; /* position in |buffer| */
  593.   int h; /* hash code */
  594.   int l; /* length of the given identifier */
  595.   name_pointer p; /* where the identifier is being sought */
  596.   if (last==NULL) for (last=first; *last!='\0'; last++);
  597.   l=last-first; /* compute the length */
  598.   @<Compute the hash code |h|@>;
  599.   @<Compute the name location |p|@>;
  600.   if (p==name_ptr) @<Enter a new name into the table at position |p|@>;
  601.   return(p);
  602. }
  603.  
  604. @ A simple hash code is used: If the sequence of
  605. character codes is $c_1c_2\ldots c_n$, its hash value will be
  606. $$(2^{n-1}c_1+2^{n-2}c_2+\cdots+c_n)\,\bmod\,|hash_size|.$$
  607.  
  608. @<Compute the hash...@>=
  609. h=*i; while (++i<last) h=(h+h+*i) % hash_size;
  610.  
  611. @ If the identifier is new, it will be placed in position |p=name_ptr|,
  612. otherwise |p| will point to its existing location.
  613.  
  614. @<Compute the name location...@>=
  615. p=hash[h];
  616. while (p && !names_match(p,first,l,t)) p=p->link;
  617. if (p==NULL) {
  618.   p=name_ptr; /* the current identifier is new */
  619.   p->link=hash[h]; hash[h]=p; /* insert |p| at beginning of hash list */
  620. }
  621.  
  622. @ The information associated with a new identifier must be initialized
  623. in a slightly different way in \.{WEAVE} than in \.{TANGLE}; hence the
  624. |init_p| procedure.
  625.  
  626. @<Enter a new name...@>= {
  627.   if (byte_ptr+l>byte_mem_end) overflow("byte memory");
  628.   if (name_ptr>=name_dir_end) overflow("name");
  629.   strncpy(byte_ptr,first,l);
  630.   (++name_ptr)->byte_start=byte_ptr+=l;
  631.   if (program==weave) init_p(p,t);
  632. }
  633.  
  634. @ The names of modules are stored in |byte_mem| together
  635. with the identifier names, but a hash table is not used for them because
  636. \.{TANGLE} needs to be able to recognize a module name when given a prefix of
  637. that name. A conventional binary search tree is used to retrieve module names,
  638. with fields called |llink| and |rlink| (where |llink| takes the place
  639. of |link|).  The root of this tree is stored in |name_dir->rlink|;
  640. this will be the only information in |name_dir[0]|.
  641.  
  642. Since the space used by |rlink| has a different function for
  643. identifiers than for module names, we declare it as a |union|.
  644.  
  645. @d llink link /* left link in binary search tree for module names */
  646. @d rlink dummy.Rlink /* right link in binary search tree for module names */
  647. @d root name_dir->rlink /* the root of the binary search tree
  648.   for module names */
  649.  
  650. @<More elements of |name...@>=
  651. union {
  652.   struct name_info *Rlink; /* right link in binary search tree for module
  653.     names */  
  654.   sixteen_bits Ilk; /* used by identifiers in \.{WEAVE} only */
  655. } dummy;
  656.  
  657. @ @<Init...@>=
  658. root=NULL; /* the binary search tree starts out with nothing in it */
  659.  
  660. @ The |mod_lookup| procedure finds a module name in the
  661. search tree, after inserting it if necessary, and returns a pointer to
  662. where it was found.
  663.  
  664. According to the rules of \.{WEB}, no module name should be a proper
  665. prefix of another, so a ``clean'' comparison should occur between any
  666. two names. The result of |mod_lookup| is |name_dir| (the location of
  667. a dummy module name) if this prefix condition
  668. is violated. An error message is printed when such violations are detected.
  669.  
  670. @d less 0 /* the first name is lexicographically less than the second */
  671. @d equal 1 /* the first name is equal to the second */
  672. @d greater 2 /* the first name is lexicographically greater than the second */
  673. @d prefix 3 /* the first name is a proper prefix of the second */
  674. @d extension 4 /* the first name is a proper extension of the second */
  675.  
  676. @<Other...@>=
  677. name_pointer install_node();
  678.  
  679. @ @c name_pointer
  680. mod_lookup(k,l) /* finds module name */
  681. char *k; /* first character of name */
  682. char *l; /* last character of name */
  683. {
  684.   short c = greater; /* comparison between two names */
  685.   name_pointer p = root; /* current node of the search tree */
  686.   name_pointer q = name_dir; /* father of node |p| */
  687.   while (p) {
  688.     c=web_strcmp(k,l+1,p->byte_start,(p+1)->byte_start);
  689.     q=p;
  690.     switch(c) {
  691.       case less: p=p->llink; continue;
  692.       case greater: p=p->rlink; continue;
  693.       case equal: return p;
  694.       default: err_print("! Incompatible section names"); return name_dir;
  695. @.Incompatible section names@>
  696.     }
  697.   }
  698.   return(install_node(q,c,k,l-k+1));
  699. }
  700.  
  701. @ This function is like |strcmp|, but it does not assume the strings
  702. are null-terminated.
  703.  
  704. @c
  705. web_strcmp(j,j1,k,k1) /* fuller comparison than |strcmp| */
  706. char *j; /* beginning of first string */
  707. char *j1; /* end of first string plus one */
  708. char *k; /* beginning of second string */
  709. char *k1; /* end of second string plus one */
  710. {
  711.   while (k<k1 && j<j1 && *j==*k) k++, j++;
  712.   if (k==k1) if (j==j1) return equal;
  713.     else return extension;
  714.   else if (j==j1) return prefix;
  715.   else if (*j<*k) return less;
  716.   else return greater;
  717. }
  718.  
  719. @ The reason we initialized |c| to |greater| is so that
  720. |name_pointer| will make |name_dir->rlink| point to the root of the tree 
  721. when |q=name_dir|, that is, the first time it is called.
  722.  
  723. The information associated with a new node must be initialized
  724. in a slightly different way in \.{WEAVE} than in \.{TANGLE}; hence the
  725. |init_node| procedure.
  726.  
  727. @c name_pointer
  728. install_node(parent,c,j,name_len) /* install a new node in the tree */
  729. name_pointer parent; /* parent of new node */
  730. int c; /* right or left? */
  731. char *j; /* where replacement text starts */
  732. int name_len; /* length of replacement text */
  733. {
  734.   name_pointer node=name_ptr; /* new node */
  735.   if (byte_ptr+name_len>byte_mem_end) overflow("byte memory");
  736.   if (name_ptr==name_dir_end) overflow("name");
  737.   if (c==less) parent->llink=node; else parent->rlink=node;
  738.   node->llink=NULL; node->rlink=NULL;
  739.   init_node(node);
  740.   strncpy(byte_ptr,j,name_len);
  741.   (++name_ptr)->byte_start=byte_ptr+=name_len;
  742.   return(node);
  743. }
  744.  
  745. @ The |prefix_lookup| procedure is supposed to find exactly one module
  746. name that has |k..l| as a prefix. Actually the algorithm
  747. silently accepts also the situation that some module name is a prefix of
  748. |k..l|, because the user who painstakingly typed in more than
  749. necessary probably doesn't want to be told about the wasted effort.
  750.  
  751. @c name_pointer
  752. prefix_lookup(k,l) /* finds module name given a prefix */
  753. char *k; /* first char of prefix */
  754. char *l; /* last char of prefix */
  755. {
  756.   short c = greater; /* comparison between two names */
  757.   short count = 0; /* the number of hits */
  758.   name_pointer p = root; /* current node of the search tree */
  759.   name_pointer q = NULL;
  760.     /* another place to resume the search after one is done */
  761.   name_pointer r = name_dir; /* extension found */
  762.   while (p) {
  763.     c=web_strcmp(k,l+1,p->byte_start,(p+1)->byte_start);
  764.     switch(c) {
  765.       case less: p=p->llink; break;
  766.       case greater: p=p->rlink; break;
  767.       default: r=p; count++; q=p->rlink; p=p->llink;
  768.     }
  769.     if (p==NULL) {
  770.       p=q; q=NULL;
  771.     }
  772.   }
  773.   if (count==0) err_print("! Name does not match");
  774. @.Name does not match@>
  775.   if (count>1) err_print("! Ambiguous prefix");
  776. @.Ambiguous prefix@>
  777.   return(r); /* the result will be |name_dir| if there was no match */
  778. }
  779.  
  780. @ The last component of |name_info| is different for \.{TANGLE} and
  781. \.{WEAVE}.  In \.{TANGLE}, if |p| is a pointer to a module name,
  782. |p->equiv| is a pointer to its replacement text, an element of the
  783. array |text_info|.  In \.{WEAVE}, on the other hand, if 
  784. |p| points to an identifier, |p->xref| is a pointer to its
  785. list of cross-references, an element of the array |xmem|.  The make-up
  786. of |text_info| and |xmem| is discussed in the \.{TANGLE} and \.{WEAVE}
  787. source files, respectively; here we just declare a common field
  788. |equiv_or_xref| as a pointer to a |char|.
  789.  
  790. @<More elements of |name...@>=
  791. char *equiv_or_xref; /* info corresponding to names */
  792.  
  793. @* Reporting errors to the user.
  794. A global variable called |history| will contain one of four values
  795. at the end of every run: |spotless| means that no unusual messages were
  796. printed; |harmless_message| means that a message of possible interest
  797. was printed but no serious errors were detected; |error_message| means that
  798. at least one error was found; |fatal_message| means that the program
  799. terminated abnormally. The value of |history| does not influence the
  800. behavior of the program; it is simply computed for the convenience
  801. of systems that might want to use such information.
  802.  
  803. @d spotless 0 /* |history| value for normal jobs */
  804. @d harmless_message 1 /* |history| value when non-serious info was printed */
  805. @d error_message 2 /* |history| value when an error was noted */
  806. @d fatal_message 3 /* |history| value when we had to stop prematurely */
  807. @d mark_harmless {if (history==spotless) history=harmless_message;}
  808. @d mark_error history=error_message
  809.  
  810. @<Definit...@>=
  811. int history=spotless; /* indicates how bad this run was */
  812.  
  813. @ The command `|err_print("! Error message")|' will report a syntax error to
  814. the user, by printing the error message at the beginning of a new line and
  815. then giving an indication of where the error was spotted in the source file.
  816. Note that no period follows the error message, since the error routine
  817. will automatically supply a period. A newline is automatically supplied
  818. if the string begins with |"|"|.
  819.  
  820. @<Functions...@>=
  821. err_print(s) /* prints `\..' and location of error message */
  822. char *s;
  823. {
  824.   char *k,*l; /* pointers into |buffer| */
  825.   printf(*s=='!'? "\n%s" : "%s",s);
  826.   if(web_file_open) @<Print error location based on input buffer@>;
  827.   update_terminal; mark_error;
  828. }
  829.  
  830. @ The error locations can be indicated by using the global variables
  831. |loc|, |cur_line|, |cur_file_name| and |changing|,
  832. which tell respectively the first
  833. unlooked-at position in |buffer|, the current line number, the current
  834. file, and whether the current line is from |change_file| or |cur_file|.
  835. This routine should be modified on systems whose standard text editor
  836. has special line-numbering conventions.
  837. @^system dependencies@>
  838.  
  839. @<Print error location based on input buffer@>=
  840. {if (changing) printf(". (l. %d of change file)\n", change_line);
  841. else if (include_depth==0) printf(". (l. %d)\n", cur_line);
  842.   else printf(". (l. %d of include file %s)\n", cur_line, cur_file_name);
  843. l= (loc>=limit? limit: loc);
  844. if (l>buffer) {
  845.   for (k=buffer; k<l; k++)
  846.     if (*k=='\t') putchar(' ');
  847.     else putchar(*k); /* print the characters already read */
  848.   putchar('\n');
  849.   for (k=buffer; k<l; k++) putchar(' '); /* space out the next line */
  850. }
  851. for (k=l; k<limit; k++) putchar(*k); /* print the part not yet read */
  852. if (*limit=='|') putchar('|'); /* end of \Cee\ text in module names */
  853. putchar(' '); /* to separate the message from future asterisks */
  854. }
  855.  
  856. @ When no recovery from some error has been provided, we have to wrap
  857. up and quit as graciously as possible.  This is done by calling the
  858. function |wrap_up| at the end of the code.
  859.  
  860. @d fatal(s,t) {
  861.   printf(s); err_print(t);
  862.   history=fatal_message; wrap_up();
  863. }
  864.  
  865. @ Sometimes the program's behavior is far different from what it should be,
  866. and \.{WEB} prints an error message that is really for the \.{WEB}
  867. maintenance person, not the user. In such cases the program says
  868. |confusion("indication of where we are")|.
  869.  
  870. @d confusion(s) fatal("! This can't happen: ",s)
  871. @.This can't happen@>
  872.  
  873. @ An overflow stop occurs if \.{WEB}'s tables aren't large enough.
  874.  
  875. @d overflow(t) {
  876.   printf("\n! Sorry, %s capacity exceeded",t); fatal("","");
  877. }
  878. @.Sorry, capacity exceeded@>
  879.  
  880. @ Some implementations may wish to pass the |history| value to the
  881. operating system so that it can be used to govern whether or not other
  882. programs are started. Here, for instance, we pass the operating system
  883. a status of 0 if and only if only harmless messages were printed.
  884. @^system dependencies@>
  885.  
  886. @<Func...@>=
  887. wrap_up() {
  888.   putchar('\n');
  889. #ifdef STAT
  890.   if (show_stats) print_stats(); /* print statistics about memory usage */
  891. #endif
  892.   @<Print the job |history|@>;
  893.   if (history > harmless_message) exit(1);
  894.   else exit(0);
  895. }
  896.  
  897. @ @<Print the job |history|@>=
  898. switch (history) {
  899. case spotless: if (show_happiness) printf("(No errors were found.)\n"); break;
  900. case harmless_message:
  901.   printf("(Did you see the warning message above?)\n"); break;
  902. case error_message:
  903.   printf("(Pardon me, but I think I spotted something wrong.)\n"); break;
  904. case fatal_message: printf("(That was a fatal error, my friend.)\n");
  905. } /* there are no other cases */
  906.  
  907. @* Command line arguments.
  908. The user calls \.{CWEAVE} and \.{CTANGLE} with arguments on the command line.
  909. These are either file names or flags to be turned off (beginning with |"-"|)
  910. or flags to be turned on (beginning with |"+"|.
  911. The following globals are for communicating the user's desires to the rest
  912. of the program. The various file name variables contain strings with
  913. the names of those files. Most of the 128 flags are undefined but available
  914. for future extensions.
  915.  
  916. @d show_banner flags['b'] /* should the banner line be printed? */
  917. @d show_progress flags['p'] /* should progress reports be printed? */
  918. @d show_stats flags['s'] /* should statistics be printed at end of run? */
  919. @d show_happiness flags['h'] /* should lack of errors be announced? */
  920.  
  921. @<Defin...@>=
  922. int argc; /* copy of |ac| parameter to |main| */
  923. char **argv; /* copy of |av| parameter to |main| */
  924. char C_file_name[max_file_name_length]; /* name of |C_file| */
  925. char tex_file_name[max_file_name_length]; /* name of |tex_file| */
  926. boolean flags[128]; /* an option for each 7-bit code */
  927.  
  928. @ The |flags| will be initially zero. Some of them are set to~1 before
  929. scanning the arguments; if additional flags are 1 by default they
  930. should be set before calling |common_init|.
  931.  
  932. @<Set the default options common to \.{TANGLE} and \.{WEAVE}@>=
  933. show_banner=show_happiness=show_progress=1;
  934.  
  935. @ We now must look at the command line arguments and set the file names
  936. accordingly.  At least one file name must be present: the \.{WEB}
  937. file.  It may have an extension, or it may omit the extension to get |".w"| or
  938. |".web"| added.  The \TeX\ output file name is formed by replacing the \.{WEB}
  939. file name extension by |".tex"|, and the \Cee\ file name by replacing
  940. the extension by |".c"|.
  941.  
  942. If there is another file name present among the arguments, it is the
  943. change file, again either with an extension or without one to get |".ch"|.
  944. An omitted change file argument means that |"/dev/null"| should be used,
  945. when no changes are desired.
  946. @^system dependencies@>
  947.  
  948. @<Function...@>=
  949. char *index(s,c) /* this is standard, but the name is not */
  950. char *s;
  951. char c;
  952. {
  953.   while (*s!=c && *s!='\0')
  954.     s++;
  955.   if (*s=='\0') return NULL;
  956.   return s;
  957. }
  958.  
  959. scan_args()
  960. {
  961.   char *dot_pos; /* position of |'.'| in the argument */
  962.   boolean found_web=0,found_change=0; /* have these names have been seen? */
  963.   boolean flag_change;
  964.  
  965.   while (--argc > 0) {
  966.     if (**(++argv)!='-' && **argv!='+') {
  967.       if (!found_web) @<Make
  968.        |web_file_name|, |tex_file_name| and |C_file_name|@>@;
  969.       else if (!found_change) @<Make |change_file_name| from |fname|@>@;
  970.         else @<Print usage error message and quit@>;
  971.     }
  972.     else @<Handle flag argument@>;
  973.   }
  974.   if (!found_web) @<Print usage error message and quit@>;
  975.   if (!found_change) @<Set up null change file@>;
  976. }
  977.  
  978. @ We use all of |*argv| for the |web_file_name| if there is a |'.'| in it,
  979. otherwise we add |".w"|. If this file can't be opened, we prepare an
  980. |alt_web_file_name| by adding |"web"| after the dot.
  981. The other file names come from adding other things
  982. after the dot.  We must check that there is enough room in
  983. |web_file_name| and the other arrays for the argument.
  984.  
  985. @<Make |web_file_name|...@>=
  986. {
  987.   if (strlen(*argv) > max_file_name_length-5)
  988.     @<Complain about argument length@>;
  989.   if ((dot_pos=index(*argv,'.'))==NULL)
  990.     sprintf(web_file_name,"%s.w",*argv);
  991.   else {
  992.     sprintf(web_file_name,"%s",*argv);
  993.     *dot_pos=0; /* string now ends where the dot was */
  994.   }
  995.   sprintf(alt_web_file_name,"%s.web",*argv);
  996.   sprintf(tex_file_name,"%s.tex",*argv);
  997.   sprintf(C_file_name,"%s.c",*argv);
  998.   found_web=1;
  999. }
  1000.  
  1001. @ @<Make |change_file_name|...@>=
  1002. {
  1003.   if (strlen(*argv) > max_file_name_length-5)
  1004.     @<Complain about argument length@>;
  1005.   if ((dot_pos=index(*argv,'.'))==NULL)
  1006.     sprintf(change_file_name,"%s.ch",*argv);
  1007.   else sprintf(change_file_name,"%s",*argv);
  1008.   found_change=1;
  1009. }
  1010.  
  1011. @ @<Set up null...@>= strcpy(change_file_name,"/dev/null");
  1012.  
  1013. @ @<Handle flag...@>=
  1014. {
  1015.   if (**argv=='-') flag_change=0;
  1016.   else flag_change=1;
  1017.   for(dot_pos=*argv+1;*dot_pos>'\0';dot_pos++)
  1018.     flags[*dot_pos]=flag_change;
  1019. }
  1020.  
  1021. @ @<Print usage error message and quit@>=
  1022. {
  1023. if (program==tangle)
  1024.   fatal("! Usage: tangle [options] webfile[.w] [changefile[.ch]]\n","")@;
  1025. else fatal("! Usage: weave [options] webfile[.w] [changefile[.ch]]\n","");
  1026. }
  1027.  
  1028. @ @<Complain about arg...@>= fatal("! Filename too long\n", *argv);
  1029.  
  1030. @* Output. Here is the code that opens the output file:
  1031. @^system dependencies@>
  1032.  
  1033. @<Defin...@>=
  1034. FILE *C_file; /* where output of \.{TANGLE} goes */
  1035. FILE *tex_file; /* where output of \.{WEAVE} goes */
  1036.  
  1037. @ @<Scan arguments and open output files@>=
  1038. scan_args();
  1039. if (program==tangle) {
  1040.   if ((C_file=fopen(C_file_name,"w"))==NULL)
  1041.     fatal("! Cannot open output file ", C_file_name);
  1042. @.Cannot open output file@>
  1043. }
  1044. else {
  1045.   if ((tex_file=fopen(tex_file_name,"w"))==NULL)
  1046.     fatal("! Cannot open output file ", tex_file_name);
  1047. }
  1048.  
  1049. @ The |update_terminal| procedure is called when we want
  1050. to make sure that everything we have output to the terminal so far has
  1051. actually left the computer's internal buffers and been sent.
  1052. @^system dependencies@>
  1053.  
  1054. @d update_terminal fflush(stdout) /* empty the terminal output buffer */
  1055.  
  1056. @ Terminal output uses |putchar| and |putc| when we have to
  1057. translate from \.{WEB}'s code into the external character code,
  1058. and |printf| when we just want to print strings.
  1059. Several macros make other kinds of output convenient.
  1060. @^system dependencies@>
  1061. @d new_line putchar('\n') @d putxchar putchar
  1062. @d term_write(a,b) fflush(stdout), write(1,a,b) /* write on the standard output */
  1063. @d line_write(c) write(fileno(C_file),c) /* write on the C output file */
  1064. @d C_printf(c,a) fprintf(C_file,c,a)
  1065. @d C_putc(c) putc(c,C_file) /* isn't \UNIX\ wonderfully consistent? */
  1066.  
  1067. @* Index.
  1068.