home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / cweb28.zip / cweave.w (.txt) < prev    next >
Texinfo Document  |  1992-10-01  |  142KB  |  3,125 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 --- September 1992
  6. % Copyright (C) 1987,1990,1991,1992 Silvio Levy and Donald E. Knuth
  7. % Permission is granted to make and distribute verbatim copies of this
  8. % document provided that the copyright notice and this permission notice
  9. % are preserved on all copies.
  10. % Permission is granted to copy and distribute modified versions of this
  11. % document under the conditions for verbatim copying, provided that the
  12. % entire resulting derived work is distributed under the terms of a
  13. % permission notice identical to this one.
  14. % Here is TeX material that gets inserted after \input webmac
  15. \def\hang{\hangindent 3em\indent\ignorespaces}
  16. \def\Pascal{Pascal}
  17. \def\pb{$\.|\ldots\.|$} % C brackets (|...|)
  18. \def\v{\char'174} % vertical (|) in typewriter font
  19. \def\dleft{[\![} \def\dright{]\!]} % double brackets
  20. \mathchardef\RA="3221 % right arrow
  21. \mathchardef\BA="3224 % double arrow
  22. \def\({} % kludge for alphabetizing certain section names
  23. \def\Ceeref{{\sl C Reference Manual\/}}
  24. \def\TeXxstring{\\{\TeX\_string}}
  25. \def\skipxTeX{\\{skip\_\TeX}}
  26. \def\copyxTeX{\\{copy\_\TeX}}
  27. \def\title{CWEAVE (Version 2.8)}
  28. \def\topofcontents{\null\vfill
  29.   \centerline{\titlefont The {\ttitlefont CWEAVE} processor}
  30.   \vskip 15pt
  31.   \centerline{(Version 2.8)}
  32.   \vfill}
  33. \def\botofcontents{\vfill
  34. \noindent
  35. Copyright \copyright\ 1987, 1990, 1991, 1992 Silvio Levy and Donald E. Knuth
  36. \bigskip\noindent
  37. Permission is granted to make and distribute verbatim copies of this
  38. document provided that the copyright notice and this permission notice
  39. are preserved on all copies.
  40. \smallskip\noindent
  41. Permission is granted to copy and distribute modified versions of this
  42. document under the conditions for verbatim copying, provided that the
  43. entire resulting derived work is distributed under the terms of a
  44. permission notice identical to this one.
  45. \pageno=\contentspagenumber \advance\pageno by 1
  46. \let\maybe=\iftrue
  47. @* Introduction.
  48. This is the \.{CWEAVE} program by Silvio Levy and Donald E. Knuth,
  49. based on \.{WEAVE} by Knuth.
  50. The ``banner line'' defined here should be changed whenever \.{CWEAVE}
  51. is modified.
  52. @d banner "This is CWEAVE (Version 2.8)\n"
  53. @ \.{CWEAVE} has a fairly straightforward outline.  It operates in
  54. three phases: First it inputs the source file and stores cross-reference
  55. data, then it inputs the source once again and produces the \TeX\ output
  56. file, finally it sorts and outputs the index.  It can be compiled
  57. with certain optional flags, |DEBUG| and |STAT|, the latter being used
  58. to keep track of how much of \.{WEAVE}'s resources were actually used.
  59. Please read the documentation for \.{common}, the set of routines common
  60. to \.{TANGLE} and \.{WEAVE}, before proceeding further.
  61. @c @<Include files@>@/
  62. @<Common code for \.{WEAVE} and \.{TANGLE}@>@/
  63. @<Typedef declarations@>@/
  64. @<Global variables@>@/
  65. main (ac, av)
  66. int ac; /* argument count */
  67. char **av; /* argument values */
  68.   argc=ac; argv=av;
  69.   program=weave;
  70.   make_xrefs=force_lines=1; /* controlled by command-line options */
  71.   common_init();
  72.   @<Set initial values@>;
  73.   if (show_banner) printf(banner); /* print a ``banner line'' */
  74.   @<Store all the reserved words@>;
  75.   phase_one(); /* read all the user's text and store the cross-references */
  76.   phase_two(); /* read all the text again and translate it to \TeX\ form */
  77.   phase_three(); /* output the cross-reference index */
  78.   wrap_up(); /* and exit gracefully */
  79. @ The following parameters were sufficient in the original \.{WEAVE} to
  80. handle \TeX, so they should be sufficient for most applications of \.{CWEAVE}.
  81. If you change |max_bytes|, |max_names|, |hash_size| or |buf_size|
  82. you have to change them also in the file |"common.w"|.
  83. @d max_bytes 90000 /* the number of bytes in identifiers,
  84.   index entries, and section names */
  85. @d max_names 4000 /* number of identifiers, strings, section names;
  86.   must be less than 10240; used in |"common.w"| */
  87. @d max_sections 2000 /* greater than the total number of sections */
  88. @d hash_size 353 /* should be prime */
  89. @d buf_size 100 /* maximum length of input line, plus one */
  90. @d longest_name 400 /* section names and strings shouldn't be longer than this */
  91. @d long_buf_size 500 /* |buf_size+longest_name| */
  92. @d line_length 80 /* lines of \TeX\ output have at most this many characters;
  93.   should be less than 256 */
  94. @d max_refs 20000 /* number of cross-references; must be less than 65536 */
  95. @d max_toks 20000 /* number of symbols in \Cee\ texts being parsed;
  96.   must be less than 65536 */
  97. @d max_texts 4000 /* number of phrases in \Cee\ texts being parsed;
  98.   must be less than 10240 */
  99. @d max_scraps 2000 /* number of tokens in \Cee\ texts being parsed */
  100. @d stack_size 400 /* number of simultaneous output levels */
  101. @ The next few sections contain stuff from the file |"common.w"| that has
  102. to be included in both |"tangle.w"| and |"weave.w"|. It appears in
  103. file |"common.h"|, which needs to be updated when |"common.w"| changes.
  104. @i common.h
  105. @* Data structures exclusive to {\tt WEAVE}.
  106. As explained in \.{common.w}, the field of a |name_info| structure
  107. that contains the |rlink| of a section name is used for a completely
  108. different purpose in the case of identifiers.  It is then called the
  109. |ilk| of the identifier, and it is used to
  110. distinguish between various types of identifiers, as follows:
  111. \yskip\hang |normal| identifiers are part of the \Cee\ program and
  112. will appear in italic type.
  113. \yskip\hang |roman| identifiers are index entries that appear after
  114. \.{@@\^} in the \.{WEB} file.
  115. \yskip\hang |wildcard| identifiers are index entries that appear after
  116. \.{@@:} in the \.{WEB} file.
  117. \yskip\hang |typewriter| identifiers are index entries that appear after
  118. \.{@@.} in the \.{WEB} file.
  119. \yskip\hang |case_like|, \dots, |typedef_like|
  120. identifiers are \Cee\ reserved words whose |ilk| explains how they are
  121. to be treated when \Cee\ code is being formatted.
  122. @d ilk dummy.Ilk
  123. @d normal 0 /* ordinary identifiers have |normal| ilk */
  124. @d roman 1 /* normal index entries have |roman| ilk */
  125. @d wildcard 2 /* user-formatted index entries have |wildcard| ilk */
  126. @d typewriter 3 /* `typewriter type' entries have |typewriter| ilk */
  127. @d reserved(a) (a->ilk>typewriter) /* tells if a name is a reserved word */
  128. @d custom 4 /* identifiers with |custom| ilk have user-given control sequence */
  129. @d unindexed(a) (a->ilk>custom) /* tells if uses of a name are to be indexed */
  130. @d quoted 5 /* \.{NULL} */
  131. @d do_like 46 /* \&{do} */
  132. @d if_like 47 /* \&{if}, \&{while}, \&{for}, \&{switch}, \&{ifdef},
  133. \&{ifndef}, \&{endif} */
  134. @d int_like 48 /* \&{int}, \&{char}, \&{extern}, \dots  */
  135. @d case_like 49 /* \&{return}, \&{goto}, \&{break}, \&{continue} */
  136. @d sizeof_like 50 /* \&{sizeof} */
  137. @d struct_like 51 /* \&{struct} */
  138. @d typedef_like 52 /* \&{typedef} */
  139. @d define_like 53 /* \&{define} */
  140. @d begin_arg 54 /* \.{@@[} */
  141. @d end_arg 55 /* \.{@@]} */
  142. @ We keep track of the current section number in |section_count|, which
  143. is the total number of sections that have started.  Sections which have
  144. been altered by a change file entry have their |changed_section| flag
  145. turned on during the first phase.
  146. @<Global...@>=
  147. boolean change_exists; /* has any section changed? */
  148. @ The other large memory area in \.{CWEAVE} keeps the cross-reference data.
  149. All uses of the name |p| are recorded in a linked list beginning at
  150. |p->xref|, which points into the |xmem| array. The elements of |xmem|
  151. are structures consisting of an integer, |num|, and a pointer |xlink|
  152. to another element of |xmem|.  If |x=p->xref| is a pointer into |xmem|,
  153. the value of |x->num| is either a section number where |p| is used,
  154. or |cite_flag| plus a section number where |p| is mentioned,
  155. or |def_flag| plus a section number where |p| is defined;
  156. and |x->xlink| points to the next such cross-reference for |p|,
  157. if any. This list of cross-references is in decreasing order by
  158. section number. The next unused slot in |xmem| is |xref_ptr|.
  159. The linked list ends at |&xmem[0]|.
  160. The global variable |xref_switch| is set either to |def_flag| or to zero,
  161. depending on whether the next cross-reference to an identifier is to be
  162. underlined or not in the index. This switch is set to |def_flag| when
  163. \.{@@!} or \.{@@d} is scanned, and it is cleared to zero when
  164. the next identifier or index entry cross-reference has been made.
  165. Similarly, the global variable |section_xref_switch| is either
  166. |def_flag| or |cite_flag| or zero, depending
  167. on whether a section name is being defined, cited or used in \Cee\ text.
  168. @<Type...@>=
  169. typedef struct xref_info {
  170.   sixteen_bits num; /* section number plus zero or |def_flag| */
  171.   struct xref_info *xlink; /* pointer to the previous cross-reference */
  172. } xref_info;
  173. typedef xref_info *xref_pointer;
  174. @ @<Global...@>=
  175. xref_info xmem[max_refs]; /* contains cross-reference information */
  176. xref_pointer xmem_end = xmem+max_refs-1;
  177. xref_pointer xref_ptr; /* the largest occupied position in |xmem| */
  178. sixteen_bits xref_switch,section_xref_switch; /* either zero or |def_flag| */
  179. @ A section that is used for multi-file output (with the \.{@@(} feature)
  180. has a special first cross-reference whose |num| field is |file_flag|.
  181. @d file_flag (3*cite_flag)
  182. @d def_flag (2*cite_flag)
  183. @d cite_flag 10240 /* must be strictly larger than |max_sections| */
  184. @d xref equiv_or_xref
  185. @<Set init...@>=
  186. xref_ptr=xmem; name_dir->xref=(char*)xmem; xref_switch=0; section_xref_switch=0;
  187. xmem->num=0; /* sentinel value */
  188. @ A new cross-reference for an identifier is formed by calling |new_xref|,
  189. which discards duplicate entries and ignores non-underlined references
  190. to one-letter identifiers or \Cee's reserved words.
  191. If the user has sent the |no_xref| flag (the \.{-x} option of the command line),
  192. it is unnecessary to keep track of cross-references for identifiers.
  193. If one were careful, one could probably make more changes around section
  194. 100 to avoid a lot of identifier looking up.
  195. @d append_xref(c) if (xref_ptr==xmem_end) overflow("cross-reference")@;
  196.   else (++xref_ptr)->num=c;
  197. @d no_xref (flags['x']==0)
  198. @d make_xrefs flags['x'] /* should cross references be output? */
  199. @d is_tiny(p) ((p+1)->byte_start==(p)->byte_start+1)
  200. @c new_xref(p)
  201. name_pointer p;
  202.   xref_pointer q; /* pointer to previous cross-reference */
  203.   sixteen_bits m, n; /* new and previous cross-reference value */
  204.   if (no_xref) return;
  205.   if ((unindexed(p) || is_tiny(p)) && xref_switch==0) return;
  206.   m=section_count+xref_switch; xref_switch=0; q=(xref_pointer)p->xref;
  207.   if (q != xmem) {
  208.     n=q->num;
  209.     if (n==m || n==m+def_flag) return;
  210.     else if (m==n+def_flag) {
  211.         q->num=m; return;
  212.     }
  213.   append_xref(m); xref_ptr->xlink=q; p->xref=(char*)xref_ptr;
  214. @ The cross-reference lists for section names are slightly different.
  215. Suppose that a section name is defined in sections $m_1$, \dots,
  216. $m_k$, cited in sections $n_1$, \dots, $n_l$, and used in sections
  217. $p_1$, \dots, $p_j$.  Then its list will contain $m_1+|def_flag|$,
  218. \dots, $m_k+|def_flag|$, $n_1+|cite_flag|$, \dots,
  219. $n_l+|cite_flag|$, $p_1$, \dots, $p_j$, in this order.
  220. Although this method of storage take quadratic time on the length of
  221. the list, under foreseeable uses of \.{WEAVE} this inefficiency is
  222. insignificant.
  223. @c new_section_xref(p)
  224. name_pointer p;
  225.   xref_pointer q,r; /* pointers to previous cross-references */
  226.   q=(xref_pointer)p->xref; r=xmem;
  227.   if (q>xmem)
  228.         while (q->num>section_xref_switch) {r=q; q=q->xlink;}
  229.   if (r->num==section_count+section_xref_switch)
  230.         return; /* don't duplicate entries */
  231.   append_xref(section_count+section_xref_switch);
  232.   xref_ptr->xlink=q; section_xref_switch=0;
  233.   if (r==xmem) p->xref=(char*)xref_ptr;
  234.   else r->xlink=xref_ptr;
  235. @ The cross-reference list for a section name may also begin with
  236. |file_flag|. Here's how that flag gets put~in.
  237. @c set_file_flag(p)
  238. name_pointer p;
  239.   xref_pointer q;
  240.   q=(xref_pointer)p->xref;
  241.   if (q->num==file_flag) return;
  242.   append_xref(file_flag);
  243.   xref_ptr->xlink = q;
  244.   p->xref = (char *)xref_ptr;
  245. @ A third large area of memory is used for sixteen-bit `tokens', which appear
  246. in short lists similar to the strings of characters in |byte_mem|. Token lists
  247. are used to contain the result of \Cee\ code translated into \TeX\ form;
  248. further details about them will be explained later. A |text_pointer| variable
  249. is an index into |tok_start|.
  250. @<Typed...@>=
  251. typedef sixteen_bits token;
  252. typedef token *token_pointer;
  253. typedef token_pointer *text_pointer;
  254. @ The first position of |tok_mem|
  255. that is unoccupied by replacement text is called |tok_ptr|, and the first
  256. unused location of |tok_start| is called |text_ptr|.
  257. Thus, we usually have |tok_start[text_ptr]=tok_ptr|.
  258. @<Global...@>=
  259. token tok_mem[max_toks]; /* tokens */
  260. token_pointer tok_mem_end = tok_mem+max_toks-1; /* end of |tok_mem| */
  261. token_pointer tok_start[max_texts]; /* directory into |tok_mem| */
  262. token_pointer tok_ptr; /* first unused position in |tok_mem| */
  263. text_pointer text_ptr; /* first unused position in |tok_start| */
  264. text_pointer tok_start_end = tok_start+max_texts-1; /* end of |tok_start| */
  265. #ifdef STAT
  266. token_pointer max_tok_ptr; /* largest value of |tok_ptr| */
  267. text_pointer max_text_ptr; /* largest value of |text_ptr| */
  268. #endif /* |STAT| */
  269. @ @<Set init...@>=
  270. tok_ptr=tok_mem+1; text_ptr=tok_start+1; tok_start[0]=tok_mem+1;
  271. tok_start[1]=tok_mem+1;
  272. #ifdef STAT
  273. max_tok_ptr=tok_mem+1; max_text_ptr=tok_start+1;
  274. #endif /* |STAT| */
  275. @ Here are the three procedures needed to complete |id_lookup|:
  276. @c names_match(p,first,l,t)
  277. name_pointer p; /* points to the proposed match */
  278. char *first; /* position of first character of string */
  279. int l; /* length of identifier */
  280. eight_bits t; /* desired ilk */
  281.   if (length(p)!=l) return 0;
  282.   if (p->ilk!=t && !(t==normal && reserved(p))) return 0;
  283.   return !strncmp(first,p->byte_start,l);
  284. init_p(p,t)
  285. name_pointer p;
  286. eight_bits t;
  287.   p->ilk=t; p->xref=(char*)xmem;
  288. init_node(p)
  289. name_pointer p;
  290.   p->xref=(char*)xmem;
  291. @ We have to get \Cee's
  292. reserved words into the hash table, and the simplest way to do this is
  293. to insert them every time \.{CWEAVE} is run.  Fortunately there are relatively
  294. few reserved words. (Some of these are not strictly ``reserved,'' but
  295. are defined in header files of the ISO Standard \Cee\ Library.)
  296. @^reserved words@>
  297. @<Store all the reserved words@>=
  298. id_lookup("auto",NULL,int_like);
  299. id_lookup("break",NULL,case_like);
  300. id_lookup("case",NULL,case_like);
  301. id_lookup("char",NULL,int_like);
  302. id_lookup("clock_t",NULL,int_like);
  303. id_lookup("const",NULL,int_like);
  304. id_lookup("continue",NULL,case_like);
  305. id_lookup("default",NULL,case_like);
  306. id_lookup("define",NULL,define_like);
  307. id_lookup("div_t",NULL,int_like);
  308. id_lookup("do",NULL,do_like);
  309. id_lookup("double",NULL,int_like);
  310. id_lookup("endif",NULL,if_like);
  311. id_lookup("else",NULL,else_like);
  312. id_lookup("enum",NULL,struct_like);
  313. id_lookup("extern",NULL,int_like);
  314. id_lookup("FILE",NULL,int_like);
  315. id_lookup("float",NULL,int_like);
  316. id_lookup("for",NULL,if_like);
  317. id_lookup("fpos_t",NULL,int_like);
  318. id_lookup("goto",NULL,case_like);
  319. id_lookup("if",NULL,if_like);
  320. id_lookup("ifdef",NULL,if_like);
  321. id_lookup("ifndef",NULL,if_like);
  322. id_lookup("int",NULL,int_like);
  323. id_lookup("jmp_buf",NULL,int_like);
  324. id_lookup("ldiv_t",NULL,int_like);
  325. id_lookup("long",NULL,int_like);
  326. id_lookup("line",NULL,if_like);
  327. id_lookup("include",NULL,if_like);
  328. id_lookup("offsetof",NULL,sizeof_like);
  329. id_lookup("ptrdiff_t",NULL,int_like);
  330. id_lookup("register",NULL,int_like);
  331. id_lookup("return",NULL,case_like);
  332. id_lookup("short",NULL,int_like);
  333. id_lookup("sig_atomic_t",NULL,int_like);
  334. id_lookup("sizeof",NULL,sizeof_like);
  335. id_lookup("size_t",NULL,int_like);
  336. id_lookup("static",NULL,int_like);
  337. id_lookup("struct",NULL,struct_like);
  338. id_lookup("switch",NULL,if_like);
  339. id_lookup("time_t",NULL,int_like);
  340. id_lookup("typedef",NULL,typedef_like);
  341. id_lookup("union",NULL,struct_like);
  342. id_lookup("undef",NULL,if_like);
  343. id_lookup("unsigned",NULL,int_like);
  344. id_lookup("while",NULL,if_like);
  345. id_lookup("void",NULL,int_like);
  346. id_lookup("va_dcl",NULL,decl); /* Berkeley's variable-arg-list convention */
  347. id_lookup("va_list",NULL,int_like); /* ditto */
  348. id_lookup("wchar_t",NULL,int_like);
  349. id_lookup("NULL",NULL,quoted);
  350. id_lookup("TeX",NULL,custom);
  351. @* Lexical scanning.
  352. Let us now consider the subroutines that read the \.{WEB} source file
  353. and break it into meaningful units. There are four such procedures:
  354. One simply skips to the next `\.{@@\ }' or `\.{@@*}' that begins a
  355. section; another passes over the \TeX\ text at the beginning of a
  356. section; the third passes over the \TeX\ text in a \Cee\ comment;
  357. and the last, which is the most interesting, gets the next token of
  358. a \Cee\ text.  They all use the pointers |limit| and |loc| into
  359. the line of input currently being studied.
  360. @ Control codes in \.{WEB}, which begin with `\.{@@}', are converted
  361. into a numeric code designed to simplify \.{CWEAVE}'s logic; for example,
  362. larger numbers are given to the control codes that denote more significant
  363. milestones, and the code of |new_section| should be the largest of
  364. all. Some of these numeric control codes take the place of |char|
  365. control codes that will not otherwise appear in the output of the
  366. scanning routines.
  367. @^ASCII code dependencies@>
  368. @d ignore 00 /* control code of no interest to \.{CWEAVE} */
  369. @d verbatim 02 /* takes the place of extended ASCII \.{\char2} */
  370. @d begin_comment '\t' /* tab marks will not appear */
  371. @d underline '\n' /* this code will be intercepted without confusion */
  372. @d noop 0177 /* takes the place of ASCII delete */
  373. @d xref_roman 0203 /* control code for `\.{@@\^}' */
  374. @d xref_wildcard 0204 /* control code for `\.{@@:}' */
  375. @d xref_typewriter 0205 /* control code for `\.{@@.}' */
  376. @d TeX_string 0206 /* control code for `\.{@@t}' */
  377. @f TeX_string TeX
  378. @d ord 0207 /* control code for `\.{@@'}' */
  379. @d join 0210 /* control code for `\.{@@\&}' */
  380. @d thin_space 0211 /* control code for `\.{@@,}' */
  381. @d math_break 0212 /* control code for `\.{@@\v}' */
  382. @d line_break 0213 /* control code for `\.{@@/}' */
  383. @d big_line_break 0214 /* control code for `\.{@@\#}' */
  384. @d no_line_break 0215 /* control code for `\.{@@+}' */
  385. @d pseudo_semi 0216 /* control code for `\.{@@;}' */
  386. @d macro_arg_open 0220 /* control code for `\.{@@[}' */
  387. @d macro_arg_close 0221 /* control code for `\.{@@]}' */
  388. @d trace 0222 /* control code for `\.{@@0}', `\.{@@1}' and `\.{@@2}' */
  389. @d format_code 0223 /* control code for `\.{@@f}' and `\.{@@s}' */
  390. @d definition 0224 /* control code for `\.{@@d}' */
  391. @d begin_C 0225 /* control code for `\.{@@c}' */
  392. @d section_name 0226 /* control code for `\.{@@<}' */
  393. @d new_section 0227 /* control code for `\.{@@\ }' and `\.{@@*}' */
  394. @ Control codes are converted to \.{CWEAVE}'s internal
  395. representation by means of the table |ccode|.
  396. @<Global...@>=
  397. eight_bits ccode[128]; /* meaning of a char following \.{@@} */
  398. @ @<Set ini...@>=
  399. {int c; for (c=0; c<=127; c++) ccode[c]=0;}
  400. ccode[' ']=ccode['\t']=ccode['\n']=ccode['\v']=ccode['\r']=ccode['\f']
  401.    =ccode['*']=new_section;
  402. ccode['@@']='@@'; /* `quoted' at sign */
  403. ccode['=']=verbatim;
  404. ccode['d']=ccode['D']=definition;
  405. ccode['f']=ccode['F']=ccode['s']=ccode['S']=format_code;
  406. ccode['c']=ccode['C']=ccode['p']=ccode['P']=begin_C;
  407. ccode['t']=ccode['T']=TeX_string;
  408. ccode['q']=ccode['Q']=noop;
  409. ccode['&']=join; ccode['<']=ccode['(']=section_name;
  410. ccode['!']=underline; ccode['^']=xref_roman;
  411. ccode[':']=xref_wildcard; ccode['.']=xref_typewriter; ccode[',']=thin_space;
  412. ccode['|']=math_break; ccode['/']=line_break; ccode['#']=big_line_break;
  413. ccode['+']=no_line_break; ccode[';']=pseudo_semi;
  414. ccode['[']=macro_arg_open; ccode[']']=macro_arg_close;
  415. ccode['\'']=ord;
  416. @<Special control codes allowed only when debugging@>@;
  417. @ If \.{CWEAVE} is compiled with debugging commands, one can write
  418. \.{@@2}, \.{@@1}, and \.{@@0} to turn tracing fully on, partly on,
  419. and off, respectively.
  420. @<Special control codes...@>=
  421. #ifdef DEBUG
  422. ccode['0']=ccode['1']=ccode['2']=trace;
  423. #endif /* |DEBUG| */
  424. @ The |skip_limbo| routine is used on the first pass to skip through
  425. portions of the input that are not in any sections, i.e., that precede
  426. the first section. After this procedure has been called, the value of
  427. |input_has_ended| will tell whether or not a section has actually been found.
  428. @c skip_limbo() {
  429.   while(1) {
  430.     if (loc>limit && get_line()==0) return;
  431.     *(limit+1)='@@';
  432.     while (*loc!='@@') loc++; /* look for '@@', then skip two chars */
  433.     if (loc++ <=limit) if (ccode[*loc++]==new_section) return;
  434. @ The |skip_TeX| routine is used on the first pass to skip through
  435. the \TeX\ code at the beginning of a section. It returns the next
  436. control code or `\.{\v}' found in the input. A |new_section| is
  437. assumed to exist at the very end of the file.
  438. @f skip_TeX TeX
  439. @c unsigned skip_TeX() /* skip past pure \TeX\ code */
  440.   while (1) {
  441.     if (loc>limit && get_line()==0) return(new_section);
  442.     *(limit+1)='@@';
  443.     while (*loc!='@@' && *loc!='|') loc++;
  444.     if (*loc++ =='|') return('|');
  445.     if (loc<=limit) return(ccode[*(loc++)]);
  446. @* Inputting the next token.
  447. As stated above, \.{WEAVE}'s most interesting lexical scanning routine is the
  448. |get_next| function that inputs the next token of \Cee\ input. However,
  449. |get_next| is not especially complicated.
  450. The result of |get_next| is either a |char| code for some special character,
  451. or it is a special code representing a pair of characters (e.g., `\.{!=}'),
  452. or it is the numeric value computed by the |ccode|
  453. table, or it is one of the following special codes:
  454. \yskip\hang |identifier|: In this case the global variables |id_first| and
  455. |id_loc| will have been set to the beginning and ending-plus-one locations
  456. in the buffer, as required by the |id_lookup| routine.
  457. \yskip\hang |string|: The string will have been copied into the array
  458. |section_text|; |id_first| and |id_loc| are set as above (now they are
  459. pointers into |section_text|).
  460. \yskip\hang |constant|: The constant is copied into |section_text|, with
  461. slight modifications; |id_first| and |id_loc| are set.
  462. \yskip\noindent Furthermore, some of the control codes cause
  463. |get_next| to take additional actions:
  464. \yskip\hang |xref_roman|, |xref_wildcard|, |xref_typewriter|, |TeX_string|,
  465. |verbatim|: The values of |id_first| and |id_loc| will have been set to
  466. the beginning and ending-plus-one locations in the buffer.
  467. \yskip\hang |section_name|: In this case the global variable |cur_section| will
  468. point to the |byte_start| entry for the section name that has just been scanned.
  469. The value of |cur_section_char| will be |'('| if the section name was
  470. preceded by \.{@@(} instead of \.{@@<}.
  471. \yskip\noindent If |get_next| sees `\.{@@!}'
  472. it sets |xref_switch| to |def_flag| and goes on to the next token.
  473. @d constant 0200 /* \Cee\ string or \.{WEB} precomputed string */
  474. @d string 0201 /* \Cee\ string or \.{WEB} precomputed string */
  475. @d identifier 0202 /* \Cee\ identifier or reserved word */
  476. @<Global...@>=
  477. name_pointer cur_section; /* name of section just scanned */
  478. char cur_section_char; /* the character just before that name */
  479. @ @<Include...@>=
  480. #include "ctype.h"
  481. @ As one might expect, |get_next| consists mostly of a big switch
  482. that branches to the various special cases that can arise.
  483. @d isxalpha(c) ((c)=='_') /* non-alpha character allowed in identifier */
  484. @c eight_bits get_next() /* produces the next input token */
  485. {@+eight_bits c; /* the current character */
  486.   while (1) {
  487.     @<Check if we're at the end of a preprocessor command@>;
  488.     if (loc>limit && get_line()==0) return(new_section);
  489.     c=*(loc++);
  490.     if (isdigit(c) || c=='\\' || c=='.') @<Get a constant@>@;
  491.     else if (isalpha(c) || isxalpha(c)) @<Get an identifier@>@;
  492.     else if (c=='\'' || c=='"' || (c=='<' && sharp_include_line==1)) @<Get a string@>@;
  493.     else if (c=='@@') @<Get control code and possible section name@>@;
  494.     else if (isspace(c)) continue; /* ignore spaces and tabs */
  495.     if (c=='#' && loc==buffer+1) @<Raise preprocessor flag@>;
  496.     mistake: @<Compress two-symbol operator@>@;
  497.     return(c);
  498. @ Because preprocessor commands do not fit in with the rest of the syntax of C,
  499. we have to deal with them separately.  One solution is to enclose such
  500. commands between special markers.  Thus, when a \.\# is seen as the
  501. first character of a line, |get_next| returns a special code
  502. \\{left\_preproc} and raises a flag |preprocessing|.
  503. @d left_preproc 0207 /* begins a preprocessor command */
  504. @d right_preproc 0217 /* ends a preprocessor command */
  505. @<Glob...@>=
  506. boolean preprocessing=0; /* are we scanning a preprocessor command? */
  507. @ @<Raise prep...@>= {
  508.   preprocessing=1;
  509.   @<Check if next token is |include|@>;
  510.   return (left_preproc);
  511. @ An additional complication is the freakish use of \.< and \.> to delimit
  512. a file name in lines that start with \.{\#include}.  We must treat this file
  513. name as a string.
  514. @<Glob...@>=
  515. boolean sharp_include_line=0; /* are we scanning a |#include| line? */
  516. @ @<Check if next token is |include|@>=
  517. while (loc<=buffer_end-7 && isspace(*loc)) loc++;
  518. if (loc<=buffer_end-6 && strncmp(loc,"include",7)==0) sharp_include_line=1;
  519. @ When we get to the end of a preprocessor line,
  520. we lower the flag and send a code \\{right\_preproc}, unless
  521. the last character was a \.\\.
  522. @<Check if we're at...@>=
  523.   while (loc==limit-1 && preprocessing && *loc=='\\')
  524.     if (get_line()==0) return(new_section); /* still in preprocessor mode */
  525.   if (loc>=limit && preprocessing) {
  526.     preprocessing=sharp_include_line=0;
  527.     return(right_preproc);
  528. @ The following code assigns values to the combinations \.{++},
  529. \.{--}, \.{->}, \.{>=}, \.{<=}, \.{==}, \.{<<}, \.{>>}, \.{!=}, \.{\v\v}, and
  530. \.{\&\&}.  The compound assignment operators (e.g., \.{+=}) are
  531. separate tokens, according to the
  532. \Ceeref.
  533. @d compress(c) if (loc++<=limit) return(c)
  534. @<Compress tw...@>=
  535. switch(c) {
  536.   case '/': if (*loc=='*') compress(begin_comment); break;
  537.   case '+': if (*loc=='+') compress(plus_plus); break;
  538.   case '-': if (*loc=='-') {compress(minus_minus);}
  539.     else if (*loc=='>') compress(minus_gt); break;
  540.   case '=': if (*loc=='=') compress(eq_eq); break;
  541.   case '>': if (*loc=='=') {compress(gt_eq);}
  542.     else if (*loc=='>') compress(gt_gt); break;
  543.   case '<': if (*loc=='=') {compress(lt_eq);}
  544.     else if (*loc=='<') compress(lt_lt); break;
  545.   case '&': if (*loc=='&') compress(and_and); break;
  546.   case '|': if (*loc=='|') compress(or_or); break;
  547.   case '!': if (*loc=='=') compress(not_eq); break;
  548. @ @<Get an identifier@>= {
  549.   id_first=--loc;
  550.   while (isalpha(*++loc) || isdigit(*loc) || isxalpha(*loc));
  551.   id_loc=loc; return(identifier);
  552. @ Different conventions are followed by \TeX\ and \Cee\ to express octal
  553. and hexadecimal numbers; it is reasonable to stick to each convention
  554. within its realm.  Thus the \Cee\ part of a \.{WEB} file has octals
  555. introduced by \.0 and hexadecimals by \.{0x}, but \.{WEAVE} will print
  556. in italics or typewriter font, respectively, and introduced by single
  557. or double quotes.  In order to simplify the \TeX\ macro used to print
  558. such constants, we replace some of the characters.
  559. Notice that in this section and the next, |id_first| and |id_loc|
  560. are pointers into the array |section_text|, not into |buffer|.
  561. @<Get a constant@>= {
  562.   id_first=id_loc=section_text+1;
  563.   if (*(loc-1)=='\\') {*id_loc++='~';
  564.   while (isdigit(*loc)) *id_loc++=*loc++;} /* octal constant */
  565.   else if (*(loc-1)=='0') {
  566.     if (*loc=='x' || *loc=='X') {*id_loc++='^'; loc++;
  567.       while (isxdigit(*loc)) *id_loc++=*loc++;} /* hex constant */
  568.     else if (isdigit(*loc)) {*id_loc++='~';
  569.       while (isdigit(*loc)) *id_loc++=*loc++;} /* octal constant */
  570.     else goto dec; /* decimal constant */
  571.   else { /* decimal constant */
  572.     if (*(loc-1)=='.' && !isdigit(*loc)) goto mistake; /* not a constant */
  573.     dec: *id_loc++=*(loc-1);
  574.     while (isdigit(*loc) || *loc=='.') *id_loc++=*loc++;
  575.     if (*loc=='e' || *loc=='E') { /* float constant */
  576.       *id_loc++='_'; loc++;
  577.       if (*loc=='+' || *loc=='-') *id_loc++=*loc++;
  578.       while (isdigit(*loc)) *id_loc++=*loc++;
  579.     }
  580.   if (*loc=='l' || *loc=='L') {*id_loc++='$'; loc++;}
  581.   return(constant);
  582. @ \Cee\ strings and character constants, delimited by double and single
  583. quotes, respectively, can contain newlines or instances of their own
  584. delimiters if they are protected by a backslash.  We follow this
  585. convention, but do not allow the string to be longer than |longest_name|.
  586. @<Get a string@>= {
  587.   char delim = c; /* what started the string */
  588.   id_first = section_text+1;
  589.   id_loc = section_text;
  590.   if (delim=='\'' && *(loc-2)=='@@') {*++id_loc='@@'; *++id_loc='@@';}
  591.   *++id_loc=delim;
  592.   if (delim=='<') delim='>'; /* for file names in |#include| lines */
  593.   while (1) {
  594.     if (loc>=limit) {
  595.       if(*(limit-1)!='\\') {
  596.         err_print("! String didn't end"); loc=limit; break;
  597. @.String didn't end@>
  598.       }
  599.       if(get_line()==0) {
  600.         err_print("! Input ended in middle of string"); loc=buffer; break;
  601. @.Input ended in middle of string@>
  602.       }
  603.     }
  604.     if ((c=*loc++)==delim) {
  605.       if (++id_loc<=section_text_end) *id_loc=c;
  606.       break;
  607.     }
  608.     if (c=='\\') if (loc>=limit) continue;
  609.       else if (++id_loc<=section_text_end) {
  610.         *id_loc = '\\'; c=*loc++;
  611.       }
  612.     if (++id_loc<=section_text_end) *id_loc=c;
  613.   if (id_loc>=section_text_end) {
  614.     printf("\n! String too long: ");
  615. @.String too long@>
  616.     term_write(section_text+1,25);
  617.     printf("..."); mark_error;
  618.   id_loc++;
  619.   return(string);
  620. @ After an \.{@@} sign has been scanned, the next character tells us
  621. whether there is more work to do.
  622. @<Get control code and possible section name@>= {
  623.   c=*loc++;
  624.   switch(ccode[c]) {
  625.     case underline: xref_switch=def_flag; continue;
  626. #ifdef DEBUG
  627.     case trace: tracing=c-'0'; continue;
  628. #endif /* |DEBUG| */
  629.     case xref_roman: case xref_wildcard: case xref_typewriter:
  630.     case noop: case TeX_string: @<Scan to the next \.{@@>}@>;
  631.     case section_name:
  632.       @<Scan the section name and make |cur_section| point to it@>;
  633.     case verbatim: @<Scan a verbatim string@>;
  634.     case ord: @<Get a string@>;
  635.     default: return(ccode[c]);
  636. @ The occurrence of a section name sets |xref_switch| to zero,
  637. because the section name might (for example) follow \&{int}.
  638. @<Scan the section name...@>= {
  639.   char *k; /* pointer into |section_text| */
  640.   cur_section_char=*(loc-1);
  641.   @<Put section name into |section_text|@>;
  642.   if (k-section_text>3 && strncmp(k-2,"...",3)==0)
  643.         cur_section=section_lookup(section_text+1,k-3,1); /* 1 indicates a prefix */
  644.   else cur_section=section_lookup(section_text+1,k,0);
  645.   xref_switch=0; return(section_name);
  646. @ Section names are placed into the |section_text| array with consecutive spaces,
  647. tabs, and carriage-returns replaced by single spaces. There will be no
  648. spaces at the beginning or the end. (We set |section_text[0]=' '| to facilitate
  649. this, since the |section_lookup| routine uses |section_text[1]| as the first
  650. character of the name.)
  651. @<Set init...@>=section_text[0]=' ';
  652. @ @<Put section name...@>=
  653. k=section_text;
  654. while (1) {
  655.   if (loc>limit && get_line()==0) {
  656.     err_print("! Input ended in section name");
  657. @.Input ended in section name@>
  658.     loc=buffer+1; break;
  659.   c=*loc;
  660.   @<If end of name or erroneous nesting, |break|@>;
  661.   loc++; if (k<section_text_end) k++;
  662.   if (isspace(c)) {
  663.     c=' '; if (*(k-1)==' ') k--;
  664. *k=c;
  665. if (k>=section_text_end) {
  666.   printf("\n! Section name too long: ");
  667. @.Section name too long@>
  668.   term_write(section_text+1,25);
  669.   printf("..."); mark_harmless;
  670. if (*k==' ' && k>section_text) k--;
  671. @ @<If end of name...@>=
  672. if (c=='@@') {
  673.   c=*(loc+1);
  674.   if (c=='>') {
  675.     loc+=2; break;
  676.   if (ccode[c]==new_section) {
  677.     err_print("! Section name didn't end"); break;
  678. @.Section name didn't end@>
  679.   if (ccode[c]==section_name) {
  680.     err_print("! Nesting of section names not allowed"); break;
  681. @.Nesting of section names...@>
  682.   *(++k)='@@'; loc++; /* now |c==*loc| again */
  683. @ @<Scan to the next...@>= {
  684.   c=ccode[*(loc-1)]; id_first=loc; *(limit+1)='@@';
  685.   while (*loc!='@@') loc++;
  686.   id_loc=loc;
  687.   if (loc++>limit) {
  688.     err_print("! Control text didn't end"); loc=limit; return(c);
  689. @.Control text didn't end@>
  690.   if (*loc++!='>') err_print("! Control codes are forbidden in control text");
  691. @.Control codes are forbidden...@>
  692.   return(c);
  693. @ At the present point in the program we
  694. have |*(loc-1)=verbatim|; we set |id_first| to the beginning
  695. of the string itself, and |id_loc| to its ending-plus-one location in the
  696. buffer.  We also set |loc| to the position just after the ending delimiter.
  697. @<Scan a verbatim string@>= {
  698.   id_first=loc++; *(limit+1)='@@'; *(limit+2)='>';
  699.   while (*loc!='@@' || *(loc+1)!='>') loc++;
  700.   if (loc>=limit) err_print("! Verbatim string didn't end");
  701. @.Verbatim string didn't end@>
  702.   id_loc=loc; loc+=2;
  703.   return (verbatim);
  704. @* Phase one processing.
  705. We now have accumulated enough subroutines to make it possible to carry out
  706. \.{WEAVE}'s first pass over the source file. If everything works right,
  707. both phase one and phase two of \.{WEAVE} will assign the same numbers to
  708. sections, and these numbers will agree with what \.{TANGLE} does.
  709. The global variable |next_control| often contains the most recent output of
  710. |get_next|; in interesting cases, this will be the control code that
  711. ended a section or part of a section.
  712. @<Global...@>=
  713. eight_bits next_control; /* control code waiting to be acting upon */
  714. @ The overall processing strategy in phase one has the following
  715. straightforward outline.
  716. @c phase_one() {
  717. phase=1; reset_input(); section_count=0;
  718. skip_limbo(); change_exists=0;
  719. while (!input_has_ended)
  720.   @<Store cross-reference data for the current section@>;
  721. changed_section[section_count]=change_exists;
  722.   /* the index changes if anything does */
  723. phase=2; /* prepare for second phase */
  724. @<Print error messages about unused or undefined section names@>;
  725. @ @<Store cross-reference data...@>=
  726.   if (++section_count==max_sections) overflow("section number");
  727.   changed_section[section_count]=changing;
  728.      /* it will become 1 if any line changes */
  729.   if (*(loc-1)=='*' && show_progress) {
  730.     printf("*%d",section_count);
  731.     update_terminal; /* print a progress report */
  732.   @<Store cross-references in the \TeX\ part of a section@>;
  733.   @<Store cross-references in the definition part of a section@>;
  734.   @<Store cross-references in the \Cee\ part of a section@>;
  735.   if (changed_section[section_count]) change_exists=1;
  736. @ The |C_xref| subroutine stores references to identifiers in
  737. \Cee\ text material beginning with the current value of |next_control|
  738. and continuing until |next_control| is `\.\{' or `\.{\v}', or until the next
  739. ``milestone'' is passed (i.e., |next_control>=format_code|). If
  740. |next_control>=format_code| when |C_xref| is called, nothing will happen;
  741. but if |next_control=='|'| upon entry, the procedure assumes that this is
  742. the `\.{\v}' preceding \Cee\ text that is to be processed.
  743. The parameter |spec_ctrl| is used to change this behavior. In most cases
  744. |C_xref| is called with |spec_ctrl==ignore|, which triggers the default
  745. processing described above. If |spec_ctrl==section_name|, section names will
  746. be gobbled. This is used when \Cee\ text in the \TeX\ part or inside comments
  747. is parsed: It allows for section names to appear in \pb, but these
  748. strings will not be entered into the cross reference lists since they are not
  749. definitions of section names.
  750. The program uses the fact that our internal code numbers satisfy
  751. the relations |xref_roman=identifier+roman| and |xref_wildcard=identifier
  752. +wildcard| and |xref_typewriter=identifier+typewriter| and |normal=0|.
  753. @c C_xref( spec_ctrl ) /* makes cross-references for \Cee\ identifiers */
  754.   eight_bits spec_ctrl;
  755.   name_pointer p; /* a referenced name */
  756.   while (next_control<format_code || next_control==spec_ctrl) {
  757.     if (next_control>=identifier && next_control<=xref_typewriter) {
  758.       p=id_lookup(id_first, id_loc,next_control-identifier); new_xref(p);
  759.     }
  760.     if (next_control==section_name) {
  761.       section_xref_switch=cite_flag;
  762.       new_section_xref(cur_section);
  763.     }
  764.     next_control=get_next();
  765.     if (next_control=='|' || next_control==begin_comment) return;
  766. @ The |outer_xref| subroutine is like |C_xref| except that it begins
  767. with |next_control!='|'| and ends with |next_control>=format_code|. Thus, it
  768. handles \Cee\ text with embedded comments.
  769. @c outer_xref() /* extension of |C_xref| */
  770.   int bal; /* brace level in comment */
  771.   while (next_control<format_code)
  772.     if (next_control!=begin_comment) C_xref(ignore);
  773.     else {
  774.       bal=copy_comment(1); next_control='|';
  775.       while (bal>0) {
  776.         C_xref(section_name); /* do not reference section names in comments */
  777.         if (next_control=='|') bal=copy_comment(bal);
  778.         else bal=0; /* an error message will occur in phase two */
  779.       }
  780.     }
  781. @ In the \TeX\ part of a section, cross-reference entries are made only for
  782. the identifiers in \Cee\ texts enclosed in \pb, or for control texts
  783. enclosed in \.{@@\^}$\,\ldots\,$\.{@@>} or \.{@@.}$\,\ldots\,$\.{@@>}
  784. or \.{@@:}$\,\ldots\,$\.{@@>}.
  785. @<Store cross-references in the \T...@>=
  786. while (1) {
  787.   switch (next_control=skip_TeX()) {
  788.     case underline: xref_switch=def_flag; continue;
  789. #ifdef DEBUG
  790.     case trace: tracing=*(loc-1)-'0'; continue;
  791. #endif /* |DEBUG| */
  792.     case '|': C_xref(section_name); break;
  793.     case xref_roman: case xref_wildcard: case xref_typewriter:
  794.     case noop: case section_name:
  795.       loc-=2; next_control=get_next(); /* scan to \.{@@>} */
  796.       if (next_control!=section_name && next_control!=noop)
  797.         new_xref(id_lookup(id_first, id_loc,next_control-identifier));
  798.       break;
  799.   if (next_control>=format_code) break;
  800. @ During the definition and \Cee\ parts of a section, cross-references
  801. are made for all identifiers except reserved words. However, the right
  802. identifier in a format definition is not referenced, and the left
  803. identifier is referenced only if it has been explicitly
  804. underlined (preceded by \.{@@!}).
  805. The \TeX\ code in comments is, of course, ignored, except for
  806. \Cee\ portions enclosed in \pb; the text of a section name is skipped
  807. entirely, even if it contains \pb\ constructions.
  808. The variables |lhs| and |rhs| point to the respective identifiers involved
  809. in a format definition.
  810. @<Global...@>=
  811. name_pointer lhs, rhs; /* pointers to |byte_start| for format identifiers */
  812. @ When we get to the following code we have |next_control>=format_code|.
  813. @<Store cross-references in the d...@>=
  814. while (next_control<=definition) { /* |format_code| or |definition| */
  815.   if (next_control==definition) {
  816.     xref_switch=def_flag; /* implied \.{@@!} */
  817.     next_control=get_next();
  818.   } else @<Process a format definition@>;
  819.   outer_xref();
  820. @ Error messages for improper format definitions will be issued in phase
  821. two. Our job in phase one is to define the |ilk| of a properly formatted
  822. identifier, and to remove cross-references to identifiers that we now
  823. discover should be unindexed.
  824. @<Process a form...@>= {
  825.   next_control=get_next();
  826.   if (next_control==identifier) {
  827.     lhs=id_lookup(id_first, id_loc,normal); lhs->ilk=normal;
  828.     if (xref_switch) new_xref(lhs);
  829.     next_control=get_next();
  830.     if (next_control==identifier) {
  831.       rhs=id_lookup(id_first, id_loc,normal);
  832.       lhs->ilk=rhs->ilk;
  833.       if (unindexed(lhs)) { /* retain only underlined entries */
  834.         xref_pointer q,r=NULL;
  835.         for (q=(xref_pointer)lhs->xref;q>xmem;q=q->xlink)
  836.           if (q->num<def_flag)
  837.             if (r) r->xlink=q->xlink;
  838.             else lhs->xref=(char*)q->xlink;
  839.           else r=q;
  840.       }
  841.       next_control=get_next();
  842.     }
  843. @ Finally, when the \TeX\ and definition parts have been treated, we have
  844. |next_control>=begin_C|.
  845. @<Store cross-references in the \Cee...@>=
  846. if (next_control<=section_name) {  /* |begin_C| or |section_name| */
  847.   if (next_control==begin_C) section_xref_switch=0;
  848.   else {
  849.     section_xref_switch=def_flag;
  850.     if(cur_section_char=='(' && cur_section!=name_dir)
  851.       set_file_flag(cur_section);
  852.   do {
  853.     if (next_control==section_name && cur_section!=name_dir)
  854.       new_section_xref(cur_section);
  855.     next_control=get_next(); outer_xref();
  856.   } while ( next_control<=section_name);
  857. @ After phase one has looked at everything, we want to check that each
  858. section name was both defined and used.  The variable |cur_xref| will point
  859. to cross-references for the current section name of interest.
  860. @<Global...@>=
  861. xref_pointer cur_xref; /* temporary cross-reference pointer */
  862. boolean an_output; /* did |file_flag| precede |cur_xref|? */
  863. @ The following recursive procedure
  864. walks through the tree of section names and prints out anomalies.
  865. @^recursion@>
  866. @c section_check(p) name_pointer p; /* print anomalies in subtree |p| */
  867.   if (p) {
  868.     section_check(p->llink);
  869.     cur_xref=(xref_pointer)p->xref;
  870.     if (cur_xref->num==file_flag) {an_output=1; cur_xref=cur_xref->xlink;}
  871.     else an_output=0;
  872.     if (cur_xref->num <def_flag) {
  873.       printf("\n! Never defined: <"); print_section_name(p); putchar('>'); mark_harmless;
  874. @.Never defined: <section name>@>
  875.     }
  876.     while (cur_xref->num >=cite_flag) cur_xref=cur_xref->xlink;
  877.     if (cur_xref==xmem && !an_output) {
  878.       printf("\n! Never used: <"); print_section_name(p); putchar('>'); mark_harmless;
  879. @.Never used: <section name>@>
  880.     }
  881.     section_check(p->rlink);
  882. @ @<Print error messages about un...@>=section_check(root)
  883. @* Low-level output routines.
  884. The \TeX\ output is supposed to appear in lines at most |line_length|
  885. characters long, so we place it into an output buffer. During the output
  886. process, |out_line| will hold the current line number of the line about to
  887. be output.
  888. @<Global...@>=
  889. char out_buf[line_length+1]; /* assembled characters */
  890. char *out_ptr; /* just after last character in |out_buf| */
  891. char *out_buf_end = out_buf+line_length; /* end of |out_buf| */
  892. int out_line; /* number of next line to be output */
  893. @ The |flush_buffer| routine empties the buffer up to a given breakpoint,
  894. and moves any remaining characters to the beginning of the next line.
  895. If the |per_cent| parameter is 1 a |'%'| is appended to the line
  896. that is being output; in this case the breakpoint |b| should be strictly
  897. less than |out_buf_end|. If the |per_cent| parameter is |0|,
  898. trailing blanks are suppressed.
  899. The characters emptied from the buffer form a new line of output;
  900. if the |carryover| parameter is true, a |"%"| in that line will be
  901. carried over to the next line (so that \TeX\ will ignore the completion
  902. of commented-out text).
  903. The same caveat that applies to |term_write| applies to |c_line_write|.
  904. @d c_line_write(c) fflush(tex_file),write(fileno(tex_file),out_buf+1,c)
  905. @d tex_putc(c) putc(c,tex_file)
  906. @d tex_new_line putc('\n',tex_file)
  907. @d tex_printf(c) fprintf(tex_file,c)
  908. @c flush_buffer(b,per_cent,carryover)
  909. char *b;  /* outputs from |out_buf+1| to |b|,where |b<=out_ptr| */
  910. boolean per_cent,carryover;
  911.   char *j; j=b; /* pointer into |out_buf| */
  912.   if (! per_cent) /* remove trailing blanks */
  913.     while (j>out_buf && *j==' ') j--;
  914.   c_line_write(j-out_buf);
  915.   if (per_cent) tex_putc('%');
  916.   tex_new_line; out_line++;
  917.   if (carryover)
  918.     while (j>out_buf)
  919.       if (*j--=='%' && (j==out_buf || *j!='\\')) {
  920.         *b--='%'; break;
  921.       }
  922.   if (b<out_ptr) strncpy(out_buf+1,b+1,out_ptr-b);
  923.   out_ptr-=b-out_buf;
  924. @ When we are copying \TeX\ source material, we retain line breaks
  925. that occur in the input, except that an empty line is not
  926. output when the \TeX\ source line was nonempty. For example, a line
  927. of the \TeX\ file that contains only an index cross-reference entry
  928. will not be copied. The |finish_line| routine is called just before
  929. |get_line| inputs a new line, and just after a line break token has
  930. been emitted during the output of translated \Cee\ text.
  931. @c finish_line() /* do this at the end of a line */
  932.   char *k; /* pointer into |buffer| */
  933.   if (out_ptr>out_buf) flush_buffer(out_ptr,0,0);
  934.   else {
  935.     for (k=buffer; k<=limit; k++)
  936.       if (!(isspace(*k))) return;
  937.     flush_buffer(out_buf,0,0);
  938. @ In particular, the |finish_line| procedure is called near the very
  939. beginning of phase two. We initialize the output variables in a slightly
  940. tricky way so that the first line of the output file will be
  941. `\.{\\input cwebmac}'.
  942. @<Set init...@>=
  943. out_ptr=out_buf+1; out_line=1; *out_ptr='c'; tex_printf("\\input cwebma");
  944. @ When we wish to append one character |c| to the output buffer, we write
  945. `|out(c)|'; this will cause the buffer to be emptied if it was already
  946. full.  If we want to append more than one character at once, we say
  947. |out_str(s)|, where |s| is a string containing the characters,
  948. or |out_str_del(s,t)|, where |s| and |t| point to the same array of
  949. characters; characters from |s| to |t-1|, inclusive, are output.
  950. A line break will occur at a space or after a single-nonletter
  951. \TeX\ control sequence.
  952. @d out(c) {if (out_ptr>=out_buf_end) break_out(); *(++out_ptr)=c;}
  953. @c out_str_del(s,t) /* output characters from |s| to |t-1| */
  954. char *s, *t;
  955.   while (s<t) out(*s++);
  956. out_str(s) /* output characters from |s| to end of string */
  957. char *s;
  958.   while (*s) out(*s++);
  959. @ The |break_out| routine is called just before the output buffer is about
  960. to overflow. To make this routine a little faster, we initialize position
  961. 0 of the output buffer to `\.\\'; this character isn't really output.
  962. @<Set init...@>=
  963. out_buf[0]='\\';
  964. @ A long line is broken at a blank space or just before a backslash that isn't
  965. preceded by another backslash. In the latter case, a |'%'| is output at
  966. the break.
  967. @c break_out() /* finds a way to break the output line */
  968.   char *k=out_ptr; /* pointer into |out_buf| */
  969.   while (1) {
  970.     if (k==out_buf) @<Print warning message, break the line, |return|@>;
  971.     if (*k==' ') {
  972.       flush_buffer(k,0,1); return;
  973.     }
  974.     if (*(k--)=='\\' && *k!='\\') { /* we've decreased |k| */
  975.       flush_buffer(k,1,1); return;
  976.     }
  977. @ We get to this section only in the unusual case that the entire output line
  978. consists of a string of backslashes followed by a string of nonblank
  979. non-backslashes. In such cases it is almost always safe to break the
  980. line by putting a |'%'| just before the last character.
  981. @<Print warning message...@>=
  982.   printf("\n! Line had to be broken (output l. %d):\n",out_line);
  983. @.Line had to be broken@>
  984.   term_write(out_buf+1, out_ptr-out_buf-1);
  985.   new_line; mark_harmless;
  986.   flush_buffer(out_ptr-1,1,1); return;
  987. @ Here is a macro that outputs a section number in decimal notation.
  988. The number to be converted by |out_section| is known to be less than
  989. |def_flag|, so it cannot have more than five decimal digits.  If
  990. the section is changed, we output `\.{\\*}' just after the number.
  991. @c out_section(n) sixteen_bits n;
  992.   char s[6];
  993.   sprintf(s,"%d",n); out_str(s);
  994.   if(changed_section[n]) out_str ("\\*");
  995. @.\\*@>
  996. @ The |out_name| procedure is used to output an identifier or index
  997. entry, enclosing it in braces.
  998. @c out_name(p) name_pointer p; {
  999.   char *k, *k_end=(p+1)->byte_start; /* pointers into |byte_mem| */
  1000.   out('{');
  1001.   for (k=p->byte_start; k<k_end; k++) {
  1002.     if (isxalpha(*k)) out('\\');
  1003.     out(*k);
  1004.   out('}');
  1005. @* Routines that copy \TeX\ material.
  1006. During phase two, we use subroutines |copy_limbo|, |copy_TeX|, and
  1007. |copy_comment| in place of the analogous |skip_limbo|, |skip_TeX|, and
  1008. |skip_comment| that were used in phase one. (Well, |copy_comment|
  1009. was actually written in such a way that it functions as a |skip_comment| routine
  1010. in phase one.)
  1011. The |copy_limbo| routine, for example, takes \TeX\ material that is not
  1012. part of any section and transcribes it almost verbatim to the output file.
  1013. No `\.{@@}' signs should occur in such material except in `\.{@@@@}'
  1014. pairs; such pairs are replaced by singletons.
  1015. @c copy_limbo()
  1016.   char c;
  1017.   while (1) {
  1018.     if (loc>limit && (finish_line(), get_line()==0)) return;
  1019.     *(limit+1)='@@';
  1020.     while (*loc!='@@') out(*(loc++));
  1021.     if (loc++<=limit) {
  1022.       c=*loc++;
  1023.       if (ccode[c]==new_section) break;
  1024.       if (c!='z' && c!='Z') {
  1025.         out('@@');
  1026.         if (c!='@@') err_print("! Double @@ required outside of sections");
  1027. @.Double {\AT} required...@>
  1028.       }
  1029.     }
  1030. @ The |copy_TeX| routine processes the \TeX\ code at the beginning of a
  1031. section; for example, the words you are now reading were copied in this
  1032. way. It returns the next control code or `\.{\v}' found in the input.
  1033. We don't copy spaces or tab marks into the beginning of a line. This
  1034. makes the test for empty lines in |finish_line| work.
  1035. @ @f copy_TeX TeX
  1036. @c eight_bits copy_TeX()
  1037.   char c; /* current character being copied */
  1038.   while (1) {
  1039.     if (loc>limit && (finish_line(), get_line()==0)) return(new_section);
  1040.     *(limit+1)='@@';
  1041.     while ((c=*(loc++))!='|' && c!='@@') {
  1042.       out(c);
  1043.       if (out_ptr==out_buf+1 && (isspace(c))) out_ptr--;
  1044.     }
  1045.     if (c=='|') return('|');
  1046.     if (loc<=limit) return(ccode[*(loc++)]);
  1047. @ The |copy_comment| function issues a warning if more braces are opened than
  1048. closed, and in the case of a more serious error it supplies enough
  1049. braces to keep \TeX\ from complaining about unbalanced braces.
  1050. Instead of copying the \TeX\ material
  1051. into the output buffer, this function copies it into the token memory
  1052. (in phase two only).
  1053. The abbreviation |app_tok(t)| is used to append token |t| to the current
  1054. token list, and it also makes sure that it is possible to append at least
  1055. one further token without overflow.
  1056. @d app_tok(c) {if (tok_ptr+2>tok_mem_end) overflow("token"); *(tok_ptr++)=c;}
  1057. @c copy_comment(bal) /* copies \TeX\ code in comments */
  1058. int bal; /* brace balance */
  1059.   char c; /* current character being copied */
  1060.   while (1) {
  1061.     if (loc>limit) if (get_line()==0) {
  1062.         err_print("! Input ended in mid-comment");
  1063. @.Input ended in mid-comment@>
  1064.         loc=buffer+1; goto done;
  1065.       }
  1066.     c=*(loc++);
  1067.     if (c=='|') return(bal);
  1068.     @<Check for end of comment@>;
  1069.     if (phase==2) app_tok(c);
  1070.     @<Copy special things when |c=='@@', '\\'|@>;
  1071.     if (c=='{') bal++;
  1072.     else if (c=='}') {
  1073.       if(bal>1) bal--;
  1074.       else {err_print("! Extra } in comment");
  1075. @.Extra \} in comment@>
  1076.         if (phase==2) tok_ptr--;
  1077.       }
  1078.     }
  1079. done:@<Clear |bal| and |return|@>;
  1080. @ @<Check for end of comment@>=
  1081. if (c=='*' && *loc=='/') {
  1082.   loc++;
  1083.   if (bal>1) err_print("! Missing } in comment");
  1084. @.Missing \} in comment@>
  1085.   goto done;
  1086. @ @<Copy special things when |c=='@@'...@>=
  1087. if (c=='@@') {
  1088.   if (*(loc++)!='@@') {
  1089.     err_print("! Illegal use of @@ in comment");
  1090. @.Illegal use of {\AT}...@>
  1091.     loc-=2; if (phase==2) *(tok_ptr-1)=' '; goto done;
  1092. else if (c=='\\' && *loc!='@@')
  1093.   if (phase==2) app_tok(*(loc++)) else loc++;
  1094. @ We output
  1095. enough right braces to keep \TeX\ happy.
  1096. @<Clear |bal|...@>=
  1097. if (phase==2) while (bal-- >0) app_tok('}');
  1098. return(0);
  1099. @* Parsing.
  1100. The most intricate part of \.{WEAVE} is its mechanism for converting
  1101. \Cee-like code into \TeX\ code, and we might as well plunge into this
  1102. aspect of the program now. A ``bottom up'' approach is used to parse the
  1103. \Cee-like material, since \.{WEAVE} must deal with fragmentary
  1104. constructions whose overall ``part of speech'' is not known.
  1105. At the lowest level, the input is represented as a sequence of entities
  1106. that we shall call {\it scraps}, where each scrap of information consists
  1107. of two parts, its {\it category} and its {\it translation}. The category
  1108. is essentially a syntactic class, and the translation is a token list that
  1109. represents \TeX\ code. Rules of syntax and semantics tell us how to
  1110. combine adjacent scraps into larger ones, and if we are lucky an entire
  1111. \Cee\ text that starts out as hundreds of small scraps will join
  1112. together into one gigantic scrap whose translation is the desired \TeX\
  1113. code. If we are unlucky, we will be left with several scraps that don't
  1114. combine; their translations will simply be output, one by one.
  1115. The combination rules are given as context-sensitive productions that are
  1116. applied from left to right. Suppose that we are currently working on the
  1117. sequence of scraps $s_1\,s_2\ldots s_n$. We try first to find the longest
  1118. production that applies to an initial substring $s_1\,s_2\ldots\,$; but if
  1119. no such productions exist, we find to find the longest production
  1120. applicable to the next substring $s_2\,s_3\ldots\,$; and if that fails, we
  1121. try to match $s_3\,s_4\ldots\,$, etc.
  1122. A production applies if the category codes have a given pattern. For
  1123. example, one of the productions (see rule~3) is
  1124. $$\hbox{|exp| |binop| |exp| $\RA$ |exp|}$$
  1125. and it means that three consecutive scraps whose respective categories are
  1126. |exp|, |binop|, and |exp| are converted to one scrap whose category
  1127. is |exp|.  The translations of the original
  1128. scraps are simply concatenated.  The case of
  1129. $$\hbox{|exp| |comma| |exp| $\RA$ |exp|} \hskip4emE_1C\,\\{opt}9\,E_2$$
  1130. (rule 4) is only slightly more complicated: here the resulting |exp| translation
  1131. consists not only of the three original translations, but also of the
  1132. tokens |opt| and 9 between the translations of the
  1133. |comma| and the following |exp|.
  1134. In the \TeX\ file, this will specify an optional line break after the
  1135. comma, with penalty 90.
  1136. At each opportunity the longest possible production is applied.
  1137. For example, if the current sequence of scraps is |struct_like|
  1138. |exp| |lbrace| this is transformed into a |struct_head| by rule
  1139. 33, but if the sequence is
  1140. |struct_like| |exp| followed by anything other than |lbrace| only
  1141. two scraps are used (by rule 34) to form an |int_like|.
  1142. Translation rules such as `$E_1C\,\\{opt}9\,E_2$' above use subscripts
  1143. to distinguish between translations of scraps whose categories have the
  1144. same initial letter; these subscripts are assigned from left to right.
  1145. @ Here is a list of the category codes that scraps can have.
  1146. @d exp 1 /* denotes an expression, including perhaps a single identifier */
  1147. @d unop 2 /* denotes a unary operator */
  1148. @d binop 3 /* denotes a binary operator */
  1149. @d unorbinop 4
  1150.   /* denotes an operator that can be unary or binary, depending on context */
  1151. @d cast 5 /* denotes a cast */
  1152. @d question 6 /* denotes a question mark and possibly the expressions flanking it */
  1153. @d lbrace 7 /* denotes a left brace */
  1154. @d rbrace 8 /* denotes a right brace */
  1155. @d decl_head 9 /* denotes an incomplete declaration */
  1156. @d comma 10 /* denotes a comma */
  1157. @d lpar 11 /* denotes a left parenthesis or left bracket */
  1158. @d rpar 12 /* denotes a right parenthesis or right bracket */
  1159. @d struct_head 21 /* denotes the beginning of a structure specifier */
  1160. @d decl 20 /* denotes a complete declaration */
  1161. @d stmt 23 /* denotes a complete statement */
  1162. @d function 24 /* denotes a complete function */
  1163. @d fn_decl 25 /* denotes a function declarator */
  1164. @d else_like 26 /* denotes the beginning of a conditional */
  1165. @d if_head 30 /* denotes the beginning of a conditional */
  1166. @d semi 27 /* denotes a semicolon */
  1167. @d colon 28 /* denotes a colon */
  1168. @d tag 29 /* denotes a statement label */
  1169. @d lproc 35 /* begins a preprocessor command */
  1170. @d rproc 36 /* ends a preprocessor command */
  1171. @d insert 37 /* a scrap that gets combined with its predecessor */
  1172. @d section_scrap 38 /* section name */
  1173. @d dead 39 /* scrap that won't combine */
  1174. @<Glo...@>=
  1175. #ifdef DEBUG
  1176. char cat_name[256][12];
  1177. eight_bits cat_index;
  1178. #endif /* |DEBUG| */
  1179. @ @<Set in...@>=
  1180. #ifdef DEBUG
  1181.     for (cat_index=0;cat_index<255;cat_index++)
  1182.       strcpy(cat_name[cat_index],"UNKNOWN");
  1183.     strcpy(cat_name[exp],"exp");
  1184.     strcpy(cat_name[stmt],"stmt");
  1185.     strcpy(cat_name[decl],"decl");
  1186.     strcpy(cat_name[decl_head],"decl_head");
  1187.     strcpy(cat_name[struct_head],"struct_head");
  1188.     strcpy(cat_name[function],"function");
  1189.     strcpy(cat_name[fn_decl],"fn_decl");
  1190.     strcpy(cat_name[else_like],"else_like");
  1191.     strcpy(cat_name[if_head],"if_head");
  1192.     strcpy(cat_name[unop],"unop");
  1193.     strcpy(cat_name[binop],"binop");
  1194.     strcpy(cat_name[unorbinop],"unorbinop");
  1195.     strcpy(cat_name[semi],";");
  1196.     strcpy(cat_name[colon],":");
  1197.     strcpy(cat_name[comma],",");
  1198.     strcpy(cat_name[question],"?");
  1199.     strcpy(cat_name[tag],"tag");
  1200.     strcpy(cat_name[cast],"cast");
  1201.     strcpy(cat_name[lpar],"(");
  1202.     strcpy(cat_name[rpar],")");
  1203.     strcpy(cat_name[lbrace],"{");
  1204.     strcpy(cat_name[rbrace],"}");
  1205.     strcpy(cat_name[lproc],"#{");
  1206.     strcpy(cat_name[rproc],"#}");
  1207.     strcpy(cat_name[insert],"insert");
  1208.     strcpy(cat_name[define_like],"define");
  1209.     strcpy(cat_name[do_like],"do");
  1210.     strcpy(cat_name[if_like],"if");
  1211.     strcpy(cat_name[int_like],"int");
  1212.     strcpy(cat_name[case_like],"case");
  1213.     strcpy(cat_name[sizeof_like],"sizeof");
  1214.     strcpy(cat_name[struct_like],"struct");
  1215.     strcpy(cat_name[typedef_like],"typedef");
  1216.     strcpy(cat_name[section_scrap],"section");
  1217.     strcpy(cat_name[dead],"@@d");
  1218.     strcpy(cat_name[begin_arg],"@@[");
  1219.     strcpy(cat_name[end_arg],"@@]");
  1220.     strcpy(cat_name[0],"zero");
  1221. #endif /* |DEBUG| */
  1222. @ When \.{CWEAVE} is compiled with the |DEBUG| switch, it can display its
  1223. parsing steps.
  1224. #ifdef DEBUG
  1225. print_cat(c) /* symbolic printout of a category */
  1226. eight_bits c;
  1227.   printf(cat_name[c]);
  1228. #endif /* |DEBUG| */
  1229. @ The token lists for translated \TeX\ output contain some special control
  1230. symbols as well as ordinary characters. These control symbols are
  1231. interpreted by \.{WEAVE} before they are written to the output file.
  1232. \yskip\hang |break_space| denotes an optional line break or an en space;
  1233. \yskip\hang |force| denotes a line break;
  1234. \yskip\hang |big_force| denotes a line break with additional vertical space;
  1235. \yskip\hang |preproc_line| denotes that the line will be printed flush left;
  1236. \yskip\hang |opt| denotes an optional line break (with the continuation
  1237. line indented two ems with respect to the normal starting position)---this
  1238. code is followed by an integer |n|, and the break will occur with penalty
  1239. $10n$;
  1240. \yskip\hang |backup| denotes a backspace of one em;
  1241. \yskip\hang |cancel| obliterates any |break_space|, |opt|, |force|, or
  1242. |big_force| tokens that immediately precede or follow it and also cancels any
  1243. |backup| tokens that follow it;
  1244. \yskip\hang |indent| causes future lines to be indented one more em;
  1245. \yskip\hang |outdent| causes future lines to be indented one less em.
  1246. \yskip\noindent All of these tokens are removed from the \TeX\ output that
  1247. comes from \Cee\ text between \pb\ signs; |break_space| and |force| and
  1248. |big_force| become single spaces in this mode. The translation of other
  1249. \Cee\ texts results in \TeX\ control sequences \.{\\1}, \.{\\2},
  1250. \.{\\3}, \.{\\4}, \.{\\5}, \.{\\6}, \.{\\7}, \.{\\8}
  1251. corresponding respectively to
  1252. |indent|, |outdent|, |opt|, |backup|, |break_space|, |force|,
  1253. |big_force| and |preproc_line|.
  1254. However, a sequence of consecutive `\.\ ', |break_space|,
  1255. |force|, and/or |big_force| tokens is first replaced by a single token
  1256. (the maximum of the given ones).
  1257. The token |math_rel| will be translated into
  1258. \.{\\mathrel\{}, and it will get a matching \.\} later.
  1259. Other control sequences in the \TeX\ output will be `\.{\\\\\{}$\,\ldots\,$\.\}'
  1260. surrounding identifiers, `\.{\\\&\{}$\,\ldots\,$\.\}' surrounding
  1261. reserved words, `\.{\\.\{}$\,\ldots\,$\.\}' surrounding strings,
  1262. `\.{\\C\{}$\,\ldots\,$\.\}$\,$|force|' surrounding comments, and
  1263. `\.{\\X$n$:}$\,\ldots\,$\.{\\X}' surrounding section names, where
  1264. |n| is the section number.
  1265. @d math_rel 0206
  1266. @d big_cancel 0210 /* like |cancel|, also overrides spaces */
  1267. @d cancel 0211 /* overrides |backup|, |break_space|, |force|, |big_force| */
  1268. @d indent 0212 /* one more tab (\.{\\1}) */
  1269. @d outdent 0213 /* one less tab (\.{\\2}) */
  1270. @d opt 0214 /* optional break in mid-statement (\.{\\3}) */
  1271. @d backup 0215 /* stick out one unit to the left (\.{\\4}) */
  1272. @d break_space 0216 /* optional break between statements (\.{\\5}) */
  1273. @d force 0217 /* forced break between statements (\.{\\6}) */
  1274. @d big_force 0220 /* forced break with additional space (\.{\\7}) */
  1275. @d preproc_line 0221 /* forced break with additional space (\.{\\8}) */
  1276. @d end_translation 0222 /* special sentinel token at end of list */
  1277. @ The raw input is converted into scraps according to the following table,
  1278. which gives category codes followed by the translations.
  1279. \def\stars {\.{**}}%
  1280. The symbol `\stars' stands for `\.{\\\&\{{\rm identifier}\}}',
  1281. i.e., the identifier itself treated as a reserved word.
  1282. The right-hand column is the so-called |mathness|, which is explained
  1283. further below.
  1284. An identifier |c| of length 1 is translated as \.{\\\v c} instead of
  1285. as \.{\\\\\{c\}}. An identifier \.{CAPS} in all caps is translated as
  1286. \.{\\.\{CAPS\}} instead of as \.{\\\\\{CAPS\}}. An identifier that has
  1287. become a reserved word via |typedef| is translated with \.{\\\&} replacing
  1288. \.{\\\\} and |int_like| replacing |exp|.
  1289. A string of length greater than 20 is broken into pieces of size at most~20
  1290. with discretionary breaks in between.
  1291. \yskip\halign{\quad#\hfil&\quad#\hfil&\quad\hfil#\hfil\cr
  1292. \.{!=}&|binop|: \.{\\I}&yes\cr
  1293. \.{<=}&|binop|: \.{\\le}&yes\cr
  1294. \.{>=}&|binop|: \.{\\G}&yes\cr
  1295. \.{==}&|binop|: \.{\\E}&yes\cr
  1296. \.{\&\&}&|binop|: \.{\\W}&yes\cr
  1297. \.{\v\v}&|binop|: \.{\\V}&yes\cr
  1298. \.{++}&|binop|: \.{\\PP}&yes\cr
  1299. \.{--}&|binop|: \.{\\MM}&yes\cr
  1300. \.{->}&|binop|: \.{\\MG}&yes\cr
  1301. \.{>>}&|binop|: \.{\\GG}&yes\cr
  1302. \.{<<}&|binop|: \.{\\LL}&yes\cr
  1303. \."string\."&|exp|: \.{\\.\{}string with special characters quoted\.\}&maybe\cr
  1304. \.{@@=}string\.{@@>}&|exp|: \.{\\vb\{}string with special characters
  1305.   quoted\.\}&maybe\cr
  1306. \.{@@'7'}&|exp|: \.{\\.\{@@'7'\}}&maybe\cr
  1307. \.{077} or \.{\\77}&|exp|: \.{\\T\{\\\~77\}}&maybe\cr
  1308. \.{0x7f}&|exp|: \.{\\T\{\\\^7f\}}&maybe\cr
  1309. \.{77}&|exp|: \.{\\T\{77\}}&maybe\cr
  1310. \.{77L}&|exp|: \.{\\T\{77\\\$\}}&maybe\cr
  1311. \.{0.1E5}&|exp|: \.{\\T\{0.1\\\_5\}}&maybe\cr
  1312. \.+&|unorbinop|: \.+&yes\cr
  1313. \.-&|unorbinop|: \.-&yes\cr
  1314. \.*&|unorbinop|: \.*&yes\cr
  1315. \./&|binop|: \./&yes\cr
  1316. \.<&|binop|: \.<&yes\cr
  1317. \.=&|binop|: \.{\\K}&yes\cr
  1318. \.>&|binop|: \.>&yes\cr
  1319. \..&|binop|: \..&yes\cr
  1320. \.{\v}&|binop|: \.{\\OR}&yes\cr
  1321. \.\^&|binop|: \.{\\XOR}&yes\cr
  1322. \.\%&|binop|: \.{\\MOD}&yes\cr
  1323. \.?&|question|: \.{\\?}&yes\cr
  1324. \.!&|unop|: \.{\\R}&yes\cr
  1325. \.\~&|unop|: \.{\\CM}&yes\cr
  1326. \.\&&|unorbinop|: \.{\\AND}&yes\cr
  1327. \.(&|lpar|: \.(&maybe\cr
  1328. \.[&|lpar|: \.[&maybe\cr
  1329. \.)&|rpar|: \.)&maybe\cr
  1330. \.]&|rpar|: \.]&maybe\cr
  1331. \.\{&|lbrace|: \.\{&yes\cr
  1332. \.\}&|lbrace|: \.\}&yes\cr
  1333. \.,&|comma|: \.,&yes\cr
  1334. \.;&|semi|: \.;&maybe\cr
  1335. \.:&|colon|: \.:&maybe\cr
  1336. \.\# (within line)&|insert|: \.{\\\#}&maybe\cr
  1337. \.\# (at beginning)&|lproc|:  |force| |preproc_line| \.{\\\#}&no\cr
  1338. end of \.\# line&|rproc|:  |force|&no\cr
  1339. identifier&|exp|: \.{\\\\\{}identifier with underlines quoted\.\}&maybe\cr
  1340. \.{auto}&|int_like|: \stars&maybe\cr
  1341. \.{break}&|case_like|: \stars&maybe\cr
  1342. \.{case}&|case_like|: \stars&maybe\cr
  1343. \.{char}&|int_like|: \stars&maybe\cr
  1344. \.{continue}&|case_like|: \stars&maybe\cr
  1345. \.{default}&|case_like|: \stars&maybe\cr
  1346. \.{define}&|define_like|: \stars&maybe\cr
  1347. \.{do}&|do_like|: \stars&maybe\cr
  1348. \.{double}&|int_like|: \stars&maybe\cr
  1349. \.{endif}&|if_like|: \stars&maybe\cr
  1350. \.{else}&|else_like|: \stars&maybe\cr
  1351. \.{enum}&|struct_like|: \stars&maybe\cr
  1352. \.{extern}&|int_like|: \stars&maybe\cr
  1353. \.{FILE}&|int_like|: \stars&maybe\cr
  1354. \.{float}&|int_like|: \stars&maybe\cr
  1355. \.{for}&|if_like|: \stars&maybe\cr
  1356. \.{goto}&|case_like|: \stars&maybe\cr
  1357. \.{if}&|if_like|: \stars&maybe\cr
  1358. \.{ifdef}&|if_like|: \stars&maybe\cr
  1359. \.{ifndef}&|if_like|: \stars&maybe\cr
  1360. \.{include}&|if_like|: \stars&maybe\cr
  1361. \.{int}&|int_like|: \stars&maybe\cr
  1362. \.{long}&|int_like|: \stars&maybe\cr
  1363. \.{line}&|if_like|: \stars&maybe\cr
  1364. \.{NULL}&|exp|: \.{\\NULL}&yes\cr
  1365. \.{register}&|int_like|: \stars&maybe\cr
  1366. \.{return}&|case_like|: \stars&maybe\cr
  1367. \.{short}&|int_like|: \stars&maybe\cr
  1368. \.{sizeof}&|sizeof_like|: \stars&maybe\cr
  1369. \.{static}&|int_like|: \stars&maybe\cr
  1370. \.{struct}&|struct_like|: \stars&maybe\cr
  1371. \.{switch}&|if_like|: \stars&maybe\cr
  1372. \.{TeX}&|exp|: \.{\\TeX}&yes\cr
  1373. \.{typedef}&|typedef_like|: \stars&maybe\cr
  1374. \.{union}&|struct_like|: \stars&maybe\cr
  1375. \.{undef}&|if_like|: \stars&maybe\cr
  1376. \.{unsigned}&|int_like|: \stars&maybe\cr
  1377. \.{va\_dcl}&|decl|: \stars&maybe\cr
  1378. \.{va\_list}&|int_like|: \stars&maybe\cr
  1379. \.{while}&|if_like|: \stars&maybe\cr
  1380. \.{void}&|int_like|: \stars&maybe\cr
  1381. \.{@@,}&|insert|: \.{\\,}&maybe\cr
  1382. \.{@@\v}&|insert|:  |opt| \.0&maybe\cr
  1383. \.{@@/}&|insert|:  |force|&no\cr
  1384. \.{@@\#}&|insert|:  |big_force|&no\cr
  1385. \.{@@+}&|insert|:  |big_cancel| \.{\{\}} |break_space|
  1386.   \.{\{\}} |big_cancel|&no\cr
  1387. \.{@@;}&|semi|: &maybe\cr
  1388. \.{@@[}&|begin_arg|: &maybe\cr
  1389. \.{@@]}&|end_arg|: &maybe\cr
  1390. \.{@@\&}&|insert|: \.{\\J}&maybe\cr
  1391. \.{@@t}\thinspace stuff\/\thinspace\.{@@>}&|exp|: \.{\\hbox\{}\thinspace
  1392.  stuff\/\thinspace\.\}&maybe\cr
  1393. \.{@@<}\thinspace section name\thinspace\.{@@>}&|section_scrap|:
  1394.  \.{\\X}$n$\.:translated section name\.{\\X}&maybe\cr
  1395. \.{@@(}\thinspace section name\thinspace\.{@@>}&|section_scrap|:
  1396.  \.{\\X}$n$\.{:\\.\{}section name with special characters
  1397.       quoted\.{\ \}\\X}&maybe\cr
  1398. \.{/*}comment\.{*/}&|insert|: \.{\\C\{}translated comment\.\} |force|&no\cr
  1399. @i prod.w
  1400. @* Implementing the productions.
  1401. More specifically, a scrap is a structure consisting of a category
  1402. |cat| and a |text_pointer| |trans|, which points to the translation in
  1403. |tok_start|.  When \Cee\ text is to be processed with the grammar above,
  1404. we form an array |scrap_info| containing the initial scraps.
  1405. Our production rules have the nice property that the right-hand side is never
  1406. longer than the left-hand side. Therefore it is convenient to use sequential
  1407. allocation for the current sequence of scraps. Five pointers are used to
  1408. manage the parsing:
  1409. \yskip\hang |pp| is a pointer into |scrap_info|.  We will try to match
  1410. the category codes |pp->cat,@,@,(pp+1)->cat|$,\,\,\ldots\,$
  1411. to the left-hand sides of productions.
  1412. \yskip\hang |scrap_base|, |lo_ptr|, |hi_ptr|, and |scrap_ptr| are such that
  1413. the current sequence of scraps appears in positions |scrap_base| through
  1414. |lo_ptr| and |hi_ptr| through |scrap_ptr|, inclusive, in the |cat| and
  1415. |trans| arrays. Scraps located between |scrap_base| and |lo_ptr| have
  1416. been examined, while those in positions |>=hi_ptr| have not yet been
  1417. looked at by the parsing process.
  1418. \yskip\noindent Initially |scrap_ptr| is set to the position of the final
  1419. scrap to be parsed, and it doesn't change its value. The parsing process
  1420. makes sure that |lo_ptr>=pp+3|, since productions have as many as four terms,
  1421. by moving scraps from |hi_ptr| to |lo_ptr|. If there are
  1422. fewer than |pp+3| scraps left, the positions up to |pp+3| are filled with
  1423. blanks that will not match in any productions. Parsing stops when
  1424. |pp=lo_ptr+1| and |hi_ptr=scrap_ptr+1|.
  1425. Since the |scrap| structure will later be used for other purposes, we
  1426. declare its second element as unions.
  1427. @<Type...@>=
  1428. typedef struct {
  1429.   eight_bits cat;
  1430.   eight_bits mathness;
  1431.   union {
  1432.     text_pointer Trans;
  1433.     @<Rest of |trans_plus| union@>@;
  1434.   } trans_plus;
  1435. } scrap;
  1436. typedef scrap *scrap_pointer;
  1437. @ @d trans trans_plus.Trans /* translation texts of scraps */
  1438. @<Global...@>=
  1439. scrap scrap_info[max_scraps]; /* memory array for scraps */
  1440. scrap_pointer scrap_info_end=scrap_info+max_scraps -1; /* end of |scrap_info| */
  1441. scrap_pointer pp; /* current position for reducing productions */
  1442. scrap_pointer scrap_base; /* beginning of the current scrap sequence */
  1443. scrap_pointer scrap_ptr; /* ending of the current scrap sequence */
  1444. scrap_pointer lo_ptr; /* last scrap that has been examined */
  1445. scrap_pointer hi_ptr; /* first scrap that has not been examined */
  1446. #ifdef STAT
  1447. scrap_pointer max_scr_ptr; /* largest value assumed by |scrap_ptr| */
  1448. #endif /* |STAT| */
  1449. @ @<Set init...@>=
  1450. scrap_base=scrap_info+1;
  1451. #ifdef STAT
  1452. max_scr_ptr=
  1453. #endif /* |STAT| */
  1454. scrap_ptr=scrap_info;
  1455. @ Token lists in |@!tok_mem| are composed of the following kinds of
  1456. items for \TeX\ output.
  1457. \yskip\item{$\bullet$}Character codes and special codes like |force| and
  1458. |math_rel| represent themselves;
  1459. \item{$\bullet$}|id_flag+p| represents \.{\\\\\{{\rm identifier $p$}\}};
  1460. \item{$\bullet$}|res_flag+p| represents \.{\\\&\{{\rm identifier $p$}\}};
  1461. \item{$\bullet$}|section_flag+p| represents section name |p|;
  1462. \item{$\bullet$}|tok_flag+p| represents token list number |p|;
  1463. \item{$\bullet$}|inner_tok_flag+p| represents token list number |p|, to be
  1464. translated without line-break controls.
  1465. @d id_flag 10240 /* signifies an identifier */
  1466. @d res_flag 2*id_flag /* signifies a reserved word */
  1467. @d section_flag 3*id_flag /* signifies a section name */
  1468. @d tok_flag 4*id_flag /* signifies a token list */
  1469. @d inner_tok_flag 5*id_flag /* signifies a token list in `\pb' */
  1470. #ifdef DEBUG
  1471. print_text(p) /* prints a token list for online debugging */
  1472. text_pointer p;
  1473.   token_pointer j; /* index into |tok_mem| */
  1474.   sixteen_bits r; /* remainder of token after the flag has been stripped off */
  1475.   if (p>=text_ptr) printf("BAD");
  1476.   else for (j=*p; j<*(p+1); j++) {
  1477.     r=*j%id_flag;
  1478.     switch (*j/id_flag) {
  1479.       case 1: printf("\\\\{"); print_id((name_dir+r)); printf("}"); break;
  1480.         /* |id_flag| */
  1481.       case 2: printf("\\&{"); print_id((name_dir+r)); printf("}"); break;
  1482.         /* |res_flag| */
  1483.       case 3: printf("<"); print_section_name((name_dir+r)); printf(">"); break;
  1484.         /* |section_flag| */
  1485.       case 4: printf("[[%d]]",r); break; /* |tok_flag| */
  1486.       case 5: printf("|[[%d]]|",r); break; /* |inner_tok_flag| */
  1487.       default: @<Print token |r| in symbolic form@>;
  1488.     }
  1489.   fflush(stdout);
  1490. #endif /* |DEBUG| */
  1491. @ @<Print token |r|...@>=
  1492. switch (r) {
  1493.   case math_rel: printf("\\mathrel{"); break;
  1494.   case big_cancel: printf("[ccancel]"); break;
  1495.   case cancel: printf("[cancel]"); break;
  1496.   case indent: printf("[indent]"); break;
  1497.   case outdent: printf("[outdent]"); break;
  1498.   case backup: printf("[backup]"); break;
  1499.   case opt: printf("[opt]"); break;
  1500.   case break_space: printf("[break]"); break;
  1501.   case force: printf("[force]"); break;
  1502.   case big_force: printf("[fforce]"); break;
  1503.   case end_translation: printf("[quit]"); break;
  1504.   default: putxchar(r);
  1505. @ The production rules listed above are embedded directly into the \.{WEAVE}
  1506. program, since it is easier to do this than to write an interpretive system
  1507. that would handle production systems in general. Several macros are defined
  1508. here so that the program for each production is fairly short.
  1509. All of our productions conform to the general notion that some |k|
  1510. consecutive scraps starting at some position |j| are to be replaced by a
  1511. single scrap of some category |c| whose translation is composed from the
  1512. translations of the disappearing scraps. After this production has been
  1513. applied, the production pointer |pp| should change by an amount |d|. Such
  1514. a production can be represented by the quadruple |(j,k,c,d)|. For example,
  1515. the production `|exp@,comma@,exp| $\RA$ |exp|' would be represented by
  1516. `|(pp,3,exp,-2)|'; in this case the pointer |pp| should decrease by 2
  1517. after the production has been applied, because some productions with
  1518. |exp| in their second or third positions might now match,
  1519. but no productions have
  1520. |exp| in the fourth position of their left-hand sides. Note that
  1521. the value of |d| is determined by the whole collection of productions, not
  1522. by an individual one.
  1523. The determination of |d| has been
  1524. done by hand in each case, based on the full set of productions but not on
  1525. the grammar of \Cee\ or on the rules for constructing the initial
  1526. scraps.
  1527. We also attach a serial number to each production, so that additional
  1528. information is available when debugging. For example, the program below
  1529. contains the statement `|reduce(pp,3,exp,-2,4)|' when it implements
  1530. the production just mentioned.
  1531. Before calling |reduce|, the program should have appended the tokens of
  1532. the new translation to the |tok_mem| array. We commonly want to append
  1533. copies of several existing translations, and macros are defined to
  1534. simplify these common cases. For example, \\{app2}|(pp)| will append the
  1535. translations of two consecutive scraps, |pp->trans| and |(pp+1)->trans|, to
  1536. the current token list. If the entire new translation is formed in this
  1537. way, we write `|squash(j,k,c,d,n)|' instead of `|reduce(j,k,c,d,n)|'. For
  1538. example, `|squash(pp,3,exp,-2,3)|' is an abbreviation for `\\{app3}|(pp);
  1539. reduce(pp,3,exp,-2,3)|'.
  1540. A couple more words of explanation:
  1541. both |big_app| and |app| append a token (while |big_app1| to |big_app4|
  1542. append the specified number of scrap translations) to the current token list.
  1543. The difference between |big_app| and |app| is simply that |big_app|
  1544. checks whether there can be a conflict between math and non-math
  1545. tokens, and intercalates a `\.{\$}' token if necessary.  When in
  1546. doubt what to use, use |big_app|.
  1547. The |mathness| is an attribute of scraps that says whether they are
  1548. to be printed in a math mode context or not.  It is separate from the
  1549. ``part of speech'' (the |cat|) because to make each |cat| have
  1550. a fixed |mathness| (as in the original \.{WEAVE}) would multiply the
  1551. number of necessary production rules.
  1552. The low two bits (i.e. |mathness % 4|) control the left boundary.
  1553. (We need two bits because we allow cases |yes_math|, |no_math| and
  1554. |maybe_math|, which can go either way.)
  1555. The next two bits (i.e. |mathness / 4|) control the right boundary.
  1556. If we combine two scraps and the right boundary of the first has
  1557. a different mathness from the left boundary of the second, we
  1558. insert a \.{\$} in between.  Similarly, if at printing time some
  1559. irreducible scrap has a |yes_math| boundary the scrap gets preceded
  1560. or followed by a \.{\$}. The left boundary is |maybe_math| if and
  1561. only if the right boundary is.
  1562. The code below is an exact translation of the production rules into
  1563. \Cee, using such macros, and the reader should have no difficulty
  1564. understanding the format by comparing the code with the symbolic
  1565. productions as they were listed earlier.
  1566. @d no_math 2 /* should be in horizontal mode */
  1567. @d yes_math 1 /* should be in math mode */
  1568. @d maybe_math 0 /* works in either horizontal or math mode */
  1569. @d big_app2(a) big_app1(a);big_app1(a+1)
  1570. @d big_app3(a) big_app2(a);big_app1(a+2)
  1571. @d big_app4(a) big_app3(a);big_app1(a+3)
  1572. @d app(a) *(tok_ptr++)=a
  1573. @d app1(a) *(tok_ptr++)=tok_flag+(a)->trans-tok_start
  1574. @<Global...@>=
  1575. int cur_mathness, init_mathness;
  1576. @ @c app_str(s)
  1577. char *s;
  1578.   while (*s) app_tok(*(s++));
  1579. big_app(a)
  1580. token a;
  1581.         if (a==' ' || a>=big_cancel && a<=big_force) /* non-math token */ {
  1582.                 if (cur_mathness==maybe_math) init_mathness=no_math;
  1583.                 else if (cur_mathness==yes_math) app_str("{}$");
  1584.                 cur_mathness=no_math;
  1585.         }
  1586.         else {
  1587.                 if (cur_mathness==maybe_math) init_mathness=yes_math;
  1588.                 else if (cur_mathness==no_math) app_str("${}");
  1589.                 cur_mathness=yes_math;
  1590.         }
  1591.         app(a);
  1592. big_app1(a)
  1593. scrap_pointer a;
  1594.   switch (a->mathness % 4) { /* left boundary */
  1595.   case (no_math):
  1596.     if (cur_mathness==maybe_math) init_mathness=no_math;
  1597.     else if (cur_mathness==yes_math) app_str("{}$");
  1598.     cur_mathness=a->mathness / 4; /* right boundary */
  1599.     break;
  1600.   case (yes_math):
  1601.     if (cur_mathness==maybe_math) init_mathness=yes_math;
  1602.     else if (cur_mathness==no_math) app_str("${}");
  1603.     cur_mathness=a->mathness / 4; /* right boundary */
  1604.     break;
  1605.   case (maybe_math): /* no changes */ break;
  1606.   app(tok_flag+(a)->trans-tok_start);
  1607. @ Let us consider the big switch for productions now, before looking
  1608. at its context. We want to design the program so that this switch
  1609. works, so we might as well not keep ourselves in suspense about exactly what
  1610. code needs to be provided with a proper environment.
  1611. @d cat1 (pp+1)->cat
  1612. @d cat2 (pp+2)->cat
  1613. @d cat3 (pp+3)->cat
  1614. @<Match a production at |pp|, or increase |pp| if there is no match@>= {
  1615.   if (cat1==end_arg)
  1616.     if (pp->cat==begin_arg) squash(pp,2,exp,-2,63);
  1617.     else squash(pp,2,end_arg,-1,64);
  1618.   else if (cat1==insert) squash(pp,2,pp->cat,-2,0);
  1619.   else if (cat2==insert) squash(pp+1,2,(pp+1)->cat,-1,0);
  1620.   else if (cat3==insert) squash(pp+2,2,(pp+2)->cat,0,0);
  1621.   else
  1622.   switch (pp->cat) {
  1623.     case exp: @<Cases for |exp|@>; @+break;
  1624.     case lpar: @<Cases for |lpar|@>; @+break;
  1625.     case question: @<Cases for |question|@>; @+break;
  1626.     case unop: @<Cases for |unop|@>; @+break;
  1627.     case unorbinop: @<Cases for |unorbinop|@>; @+break;
  1628.     case binop: @<Cases for |binop|@>; @+break;
  1629.     case cast: @<Cases for |cast|@>; @+break;
  1630.     case sizeof_like: @<Cases for |sizeof_like|@>; @+break;
  1631.     case int_like: @<Cases for |int_like|@>; @+break;
  1632.     case decl_head: @<Cases for |decl_head|@>; @+break;
  1633.     case decl: @<Cases for |decl|@>; @+break;
  1634.     case typedef_like: @<Cases for |typedef_like|@>; @+break;
  1635.     case struct_like: @<Cases for |struct_like|@>; @+break;
  1636.     case struct_head: @<Cases for |struct_head|@>; @+break;
  1637.     case fn_decl: @<Cases for |fn_decl|@>; @+break;
  1638.     case function: @<Cases for |function|@>; @+break;
  1639.     case lbrace: @<Cases for |lbrace|@>; @+break;
  1640.     case do_like: @<Cases for |do_like|@>; @+break;
  1641.     case if_like: @<Cases for |if_like|@>; @+break;
  1642.     case else_like: @<Cases for |else_like|@>; @+break;
  1643.     case if_head: @<Cases for |if_head|@>; @+break;
  1644.     case case_like: @<Cases for |case_like|@>; @+break;
  1645.     case stmt: @<Cases for |stmt|@>; @+break;
  1646.     case tag: @<Cases for |tag|@>; @+break;
  1647.     case semi: @<Cases for |semi|@>; @+break;
  1648.     case lproc: @<Cases for |lproc|@>; @+break;
  1649.     case section_scrap: @<Cases for |section_scrap|@>; @+break;
  1650.     case insert: @<Cases for |insert|@>; @+break;
  1651.   pp++; /* if no match was found, we move to the right */
  1652. @ In \Cee, new specifier names can be defined via |typedef|, and we want
  1653. to make the parser recognize future occurrences of the identifier thus
  1654. defined as specifiers.  This is done by the procedure |make_reserved|,
  1655. which changes the |ilk| of the relevant identifier.
  1656. We first need a procedure to recursively seek the first
  1657. identifier in a token list, because the identifier might
  1658. be enclosed in parentheses, as when one defines a function
  1659. returning a pointer.
  1660. @d no_ident_found 0 /* distinct from any identifier token */
  1661. @c token_pointer
  1662. find_first_ident(p)
  1663. text_pointer p;
  1664.   token_pointer q; /* token to be returned */
  1665.   token_pointer j; /* token being looked at */
  1666.   sixteen_bits r; /* remainder of token after the flag has been stripped off */
  1667.   if (p>=text_ptr) confusion("find_first_ident");
  1668.   for (j=*p; j<*(p+1); j++) {
  1669.     r=*j%id_flag;
  1670.     switch (*j/id_flag) {
  1671.       case 1: return j;
  1672.       case 4: case 5: /* |tok_flag| or |inner_tok_flag| */
  1673.         if ((q=find_first_ident(tok_start+r))!=no_ident_found)
  1674.           return q;
  1675.       default: ; /* |res_flag|, |section_flag|, |tok_flag|: move on to next token */
  1676.     }
  1677.   return no_ident_found;
  1678. @ The scraps currently being parsed must be inspected for any
  1679. occurrence of the identifier that we're making reserved; hence
  1680. the |for| loop below.
  1681. @c make_reserved(p) /* make the first identifier in |p->trans| like |int| */
  1682. scrap_pointer p;
  1683.   sixteen_bits tok_value; /* the name of this identifier, plus its flag*/
  1684.   token_pointer tok_loc; /* pointer to |tok_value| */
  1685.   if ((tok_loc=find_first_ident(p->trans))==no_ident_found)
  1686.     return; /* this should not happen */
  1687.   tok_value=*tok_loc;
  1688.   for (;p<=scrap_ptr; p==lo_ptr? p=hi_ptr: p++) {
  1689.     if (p->cat==exp) {
  1690.       if (**(p->trans)==tok_value) {
  1691.         p->cat=int_like;
  1692.         **(p->trans)+=res_flag-id_flag;
  1693.       }
  1694.     }
  1695.   (name_dir+tok_value-id_flag)->ilk=int_like;
  1696.   *tok_loc=tok_value-id_flag+res_flag;
  1697. @ In the following situations we want to mark the occurrence of
  1698. an identifier as a definition: when |make_reserved| has just been
  1699. used; after a specifier, as in |char **argv|;
  1700. before a colon, as in \\{found}:; and in the declaration of a function,
  1701. as in \\{main}()$\{\ldots;\}$.  This is accomplished by the invocation
  1702. of |make_underlined| at appropriate times.  Notice that, in the declaration
  1703. of a function, we only find out that the identifier is being defined after
  1704. it has been swallowed up by an |exp|.
  1705. @c make_underlined(p)
  1706. /* underline the entry for the first identifier in |p->trans| */
  1707. scrap_pointer p;
  1708.   token_pointer tok_loc; /* where the first identifier appears */
  1709.   if ((tok_loc=find_first_ident(p->trans))==no_ident_found)
  1710.     return; /* this happens after parsing the |()| in |double f();| */
  1711.   xref_switch=def_flag; underline_xref(*tok_loc-id_flag+name_dir);
  1712. @ We cannot use |new_xref| to underline a cross-reference at this point
  1713. because this would just make a new cross-reference at the end of the list.
  1714. We actually have to search through the list for the existing
  1715. cross-reference.
  1716. @c underline_xref(p)
  1717. name_pointer p;
  1718.   xref_pointer q=(xref_pointer)p->xref; /* pointer to cross-reference being examined */
  1719.   xref_pointer r; /* temporary pointer for permuting cross-references */
  1720.   sixteen_bits m; /* cross-reference value to be installed */
  1721.   sixteen_bits n; /* cross-reference value being examined */
  1722.   if (no_xref) return;
  1723.   xref_switch=def_flag;
  1724.   m=section_count+xref_switch;
  1725.   while (q != xmem) {
  1726.     n=q->num;
  1727.     if (n==m) return;
  1728.     else if (m==n+def_flag) {
  1729.         q->num=m; return;
  1730.     }
  1731.     else if (n>=def_flag && n<m) break;
  1732.     q=q->xlink;
  1733.   @<Insert new cross-reference at |q|, not at beginning of list@>;
  1734. @ We get to this section only when the identifier is one letter long,
  1735. so it didn't get a non-underlined entry during phase one.  But it may
  1736. have got some explicitly underlined entries in later sections, so in order
  1737. to preserve the numerical order of the entries in the index, we have
  1738. to insert the new cross-reference not at the beginning of the list
  1739. (namely, at |p->xref|), but rather right before |q|.
  1740. @<Insert new cross-reference at |q|...@>=
  1741.   append_xref(0); /* this number doesn't matter */
  1742.   xref_ptr->xlink=(xref_pointer)p->xref; r=xref_ptr;
  1743.   p->xref=(char*)xref_ptr;
  1744.   while (r->xlink!=q) {r->num=r->xlink->num; r=r->xlink;}
  1745.   r->num=m; /* everything from |q| on is left undisturbed */
  1746. @ Now comes the code that tries to match each production starting
  1747. with a particular type of scrap. Whenever a match is discovered,
  1748. the |squash| or |reduce| macro will cause the appropriate action
  1749. to be performed, followed by |goto found|.
  1750. @<Cases for |exp|@>=
  1751. if (cat1==lbrace || cat1==int_like || cat1==decl) {
  1752.   make_underlined(pp); big_app1(pp); big_app(indent); app(indent);
  1753.   reduce(pp,1,fn_decl,0,1);
  1754. else if (cat1==unop) squash(pp,2,exp,-2,2);
  1755. else if ((cat1==binop || cat1==unorbinop) && cat2==exp)
  1756.         squash(pp,3,exp,-2,3);
  1757. else if (cat1==comma && cat2==exp) {
  1758.   big_app2(pp);
  1759.   app(opt); app('9'); big_app1(pp+2); reduce(pp,3,exp,-2,4);
  1760. else if (cat1==exp) squash(pp,2,exp,-2,5);
  1761. else if (cat1==semi) squash(pp,2,stmt,-1,6);
  1762. else if (cat1==colon) {
  1763.   make_underlined (pp);  squash(pp,2,tag,0,7);
  1764. @ @<Cases for |lpar|@>=
  1765. if (cat1==exp && cat2==rpar) squash(pp,3,exp,-2,8);
  1766. else if (cat1==rpar) {
  1767.   big_app1(pp); app('\\'); app(','); big_app1(pp+1);
  1768.   reduce(pp,2,exp,-2,9);
  1769. else if ((cat1==decl_head || cat1==int_like) && cat2==rpar)
  1770.   squash(pp,3,cast,-1,10);
  1771. else if (cat1==stmt) {
  1772.   big_app2(pp); big_app(' '); reduce(pp,2,lpar,0,11);
  1773. @ @<Cases for |question|@>=
  1774. if (cat1==exp && cat2==colon) squash(pp,3,binop,-2,12);
  1775. @ @<Cases for |unop|@>=
  1776. if (cat1==exp) squash(pp,2,exp,-2,13);
  1777. @ @<Cases for |unorbinop|@>=
  1778. if (cat1==exp || cat1==int_like) {
  1779.   big_app('{'); big_app1(pp); big_app('}'); big_app1(pp+1);
  1780.   reduce(pp,2,exp,-2,14);
  1781. else if (cat1==binop) {
  1782.   big_app(math_rel); big_app1(pp); big_app('{'); big_app1(pp+1); big_app('}');
  1783.   big_app('}'); reduce(pp,2,binop,-1,15);
  1784. @ @<Cases for |binop|@>=
  1785. if (cat1==binop) {
  1786.   big_app(math_rel); big_app('{'); big_app1(pp); big_app('}');
  1787.   big_app('{'); big_app1(pp+1); big_app('}');
  1788.   big_app('}'); reduce(pp,2,binop,-1,16);
  1789. @ @<Cases for |cast|@>=
  1790. if (cat1==exp) {
  1791.   big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,exp,-2,17);
  1792. @ @<Cases for |sizeof_like|@>=
  1793. if (cat1==cast) squash(pp,2,exp,-2,18);
  1794. else if (cat1==exp) {
  1795.   big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,exp,-2,19);
  1796. @ @<Cases for |int_like|@>=
  1797. if (cat1==int_like|| cat1==struct_like) {
  1798.   big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,cat1,-1,20);
  1799. else if (cat1==exp || cat1==unorbinop || cat1==semi) {
  1800.   big_app1(pp);
  1801.   if (cat1!=semi) big_app(' ');
  1802.   reduce(pp,1,decl_head,-1,21);
  1803. else if (cat1==comma && cat2==exp) squash(pp,3,int_like,-1,65);
  1804. @ @<Cases for |decl_head|@>=
  1805. if (cat1==comma) {
  1806.   big_app2(pp); big_app(' '); reduce(pp,2,decl_head,-1,22);
  1807. else if (cat1==unorbinop) {
  1808.   big_app1(pp); big_app('{'); big_app1(pp+1); big_app('}');
  1809.   reduce(pp,2,decl_head,-1,23);
  1810. else if (cat1==exp && cat2!=lpar && cat2!=exp) {
  1811.   make_underlined(pp+1); squash(pp,2,decl_head,-1,24);
  1812. else if ((cat1==binop||cat1==colon) && cat2==exp && (cat3==comma || cat3==semi))
  1813.   squash(pp,3,decl_head,-1,25);
  1814. else if (cat1==lbrace || cat1==int_like || cat1==decl) {
  1815.   big_app1(pp); big_app(indent); app(indent); reduce(pp,1,fn_decl,0,26);
  1816. else if (cat1==semi) squash(pp,2,decl,-1,27);
  1817. @ @<Cases for |decl|@>=
  1818. if (cat1==decl) {
  1819.   big_app1(pp); big_app(force); big_app1(pp+1);
  1820.   reduce(pp,2,decl,-1,28);
  1821. else if (cat1==stmt || cat1==function) {
  1822.   big_app1(pp); big_app(big_force); big_app1(pp+1); reduce(pp,2,cat1,-1,29);
  1823. @ @<Cases for |typedef_like|@>=
  1824. if (cat1==decl_head)
  1825.   if ((cat2==exp&&cat3!=lpar&&cat3!=exp)||cat2==int_like) {
  1826.     make_underlined(pp+2); make_reserved(pp+2);
  1827.     big_app2(pp+1); reduce(pp+1,2,decl_head,0,30);
  1828.   else if (cat2==semi) {
  1829.     big_app1(pp); big_app(' '); big_app2(pp+1); reduce(pp,3,decl,-1,31);
  1830. @ @<Cases for |struct_like|@>=
  1831. if (cat1==lbrace) {
  1832.   big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,struct_head,0,32);
  1833. else if (cat1==exp||cat1==int_like) {
  1834.   if (cat2==lbrace) {
  1835.     make_underlined(pp+1);
  1836.     big_app1(pp); big_app(' '); big_app1(pp+1);
  1837.     big_app(' '); big_app1(pp+2);reduce(pp,3,struct_head,0,33);
  1838.   else {
  1839.     big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,int_like,-1,34);
  1840. @ @<Cases for |struct_head|@>=
  1841. if ((cat1==decl || cat1==stmt) && cat2==rbrace) {
  1842.   big_app1(pp); big_app(indent); big_app(force); big_app1(pp+1);
  1843.   big_app(outdent); big_app(force);  big_app1(pp+2);
  1844.   reduce(pp,3,int_like,-1,35);
  1845. @ @<Cases for |fn_decl|@>=
  1846. if (cat1==decl) {
  1847.   big_app1(pp); big_app(force); big_app1(pp+1); reduce(pp,2,fn_decl,0,36);
  1848. else if (cat1==stmt) {
  1849.   big_app1(pp); app(outdent); app(outdent); big_app(force);
  1850.   big_app1(pp+1); reduce(pp,2,function,-1,37);
  1851. @ @<Cases for |function|@>=
  1852. if (cat1==function || cat1==decl) {
  1853.   big_app1(pp); big_app(big_force); big_app1(pp+1); reduce(pp,2,cat1,0,38);
  1854. @ @<Cases for |lbrace|@>=
  1855. if (cat1==rbrace) {
  1856.   big_app1(pp); app('\\'); app(','); big_app1(pp+1);
  1857.   reduce(pp,2,stmt,-1,39);
  1858. else if (cat1==stmt && cat2==rbrace) {
  1859.   big_app(force); big_app1(pp);  big_app(indent); big_app(force);
  1860.   big_app1(pp+1); big_app(force); big_app(backup);  big_app1(pp+2);
  1861.   big_app(outdent); big_app(force); reduce(pp,3,stmt,-1,40);
  1862. else if (cat1==exp) {
  1863.   if (cat2==rbrace) squash(pp,3,exp,-2,41);
  1864.   else if (cat2==comma && cat3==rbrace) squash(pp,4,exp,-2,41);
  1865. @ @<Cases for |if_like|@>=
  1866. if (cat1==exp) {
  1867.   big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,else_like,-2,42);
  1868. @ @<Cases for |else_like|@>=
  1869. if (cat1==lbrace) squash(pp,1,if_head,0,43);
  1870. else if (cat1==stmt ||(cat1==exp && cat2==else_like)) {
  1871.   big_app(force); big_app1(pp); big_app(indent); big_app(break_space);
  1872.   big_app1(pp+1); big_app(outdent); big_app(force);
  1873.   if (cat2==else_like) {
  1874.     big_app1(pp+2); big_app(' '); big_app(cancel); reduce(pp,3,else_like,-2,44);
  1875.   else reduce(pp,2,stmt,-1,45);
  1876. @ @<Cases for |if_head|@>=
  1877. if (cat1==stmt ||(cat1==exp && cat2==else_like)) {
  1878.   big_app(force); big_app1(pp); big_app(break_space);
  1879.   app(noop); big_app(cancel); big_app1(pp+1);
  1880.   if (cat2==else_like) {
  1881.     big_app(break_space); big_app1(pp+2); big_app(' '); big_app(cancel);
  1882.     reduce(pp,3,else_like,-2,46);
  1883.   else {
  1884.     big_app(force); reduce(pp,2,stmt,-1,47);
  1885. @ @<Cases for |do_like|@>=
  1886. if (cat1==stmt && cat2==else_like && cat3==semi) {
  1887.   big_app1(pp); big_app(break_space); big_app1(pp+1);
  1888.   big_app(break_space); big_app1(pp+2); big_app1(pp+3);
  1889.   reduce(pp,4,stmt,-1,48);
  1890. @ @<Cases for |case_like|@>=
  1891. if (cat1==semi) squash(pp,2,stmt,-1,49);
  1892. else if (cat1==colon) squash(pp,2,tag,-1,51);
  1893. else if (cat1==exp) {
  1894.   if (cat2==semi) {
  1895.     big_app1(pp); big_app(' ');  big_app1(pp+1);  big_app1(pp+2);
  1896.     reduce(pp,3,stmt,-1,50);
  1897.   else if (cat2==colon) {
  1898.     big_app1(pp); big_app(' ');  big_app1(pp+1);  big_app1(pp+2);
  1899.     reduce(pp,3,tag,-1,52);
  1900. @ @<Cases for |tag|@>=
  1901. if (cat1==tag) {
  1902.   big_app1(pp); big_app(break_space); big_app1(pp+1); reduce(pp,2,tag,-1,53);
  1903. else if (cat1==stmt) {
  1904.   big_app(force); big_app(backup); big_app1(pp); big_app(break_space);
  1905.   big_app1(pp+1); reduce(pp,2,stmt,-1,54);
  1906. @ The user can decide at run-time whether short statements should be
  1907. grouped together on the same line.
  1908. @d force_lines flags['f'] /* should each statement be on its own line? */
  1909. @<Cases for |stmt|@>=
  1910. if (cat1==stmt) {
  1911.   big_app1(pp);
  1912.   if (force_lines) big_app(force);
  1913.   else big_app(break_space);
  1914.   big_app1(pp+1); reduce(pp,2,stmt,-1,55);
  1915. @ @<Cases for |semi|@>=
  1916. big_app(' '); big_app1(pp); reduce(pp,1,stmt,-1,56);
  1917. @ @<Cases for |lproc|@>=
  1918. if (cat1==define_like) make_underlined(pp+2);
  1919. if (cat1==else_like || cat1==if_like ||cat1==define_like)
  1920.   squash(pp,2,lproc,0,57);
  1921. else if (cat1==rproc) squash(pp,2,insert,-1,58);
  1922. else if (cat1==exp || cat1==function) {
  1923.   if (cat2==rproc) {
  1924.     big_app1(pp); big_app(' '); big_app2(pp+1);
  1925.     reduce(pp,3,insert,-1,59);
  1926.   else if (cat2==exp && cat3==rproc && cat1==exp) {
  1927.     big_app1(pp); big_app(' '); big_app1(pp+1); app_str(" \\5");
  1928.     big_app2(pp+2); reduce(pp,4,insert,-1,59);
  1929. @ @<Cases for |section_scrap|@>=
  1930. if (cat1==semi) {
  1931.   big_app2(pp); big_app(force); reduce(pp,2,stmt,-2,60);
  1932. else squash(pp,1,exp,-2,61);
  1933. @ @<Cases for |insert|@>=
  1934. if (cat1)
  1935.   squash(pp,2,cat1,0,62);
  1936. @ The `|freeze_text|' macro is used to give official status to a token list.
  1937. Before saying |freeze_text|, items are appended to the current token list,
  1938. and we know that the eventual number of this token list will be the current
  1939. value of |text_ptr|. But no list of that number really exists as yet,
  1940. because no ending point for the current list has been
  1941. stored in the |tok_start| array. After saying |freeze_text|, the
  1942. old current token list becomes legitimate, and its number is the current
  1943. value of |text_ptr-1| since |text_ptr| has been increased. The new
  1944. current token list is empty and ready to be appended to.
  1945. Note that |freeze_text| does not check to see that |text_ptr| hasn't gotten
  1946. too large, since it is assumed that this test was done beforehand.
  1947. @d freeze_text *(++text_ptr)=tok_ptr
  1948. @ Here's the |reduce| procedure used in our code for productions:
  1949. @c reduce(j,k,c,d,n)
  1950. scrap_pointer j;
  1951. eight_bits c;
  1952. short k, d, n;
  1953.   scrap_pointer i, i1; /* pointers into scrap memory */
  1954.   j->cat=c; j->trans=text_ptr;
  1955.   j->mathness=4*cur_mathness+init_mathness;
  1956.   freeze_text;
  1957.   if (k>1) {
  1958.     for (i=j+k, i1=j+1; i<=lo_ptr; i++, i1++) {
  1959.       i1->cat=i->cat; i1->trans=i->trans;
  1960.       i1->mathness=i->mathness;
  1961.     }
  1962.     lo_ptr=lo_ptr-k+1;
  1963.   @<Change |pp| to $\max(|scrap_base|,|pp+d|)$@>;
  1964.   @<Print a snapshot of the scrap list if debugging @>;
  1965.   pp--; /* we next say |pp++| */
  1966. @ @<Change |pp| to $\max...@>=
  1967. if (pp+d>=scrap_base) pp=pp+d;
  1968. else pp=scrap_base;
  1969. @ Here's the |squash| procedure, which
  1970. takes advantage of the simplification that occurs when |k=1|.
  1971. @c squash(j,k,c,d,n)
  1972. scrap_pointer j;
  1973. eight_bits c;
  1974. short k, d, n;
  1975.   scrap_pointer i; /* pointers into scrap memory */
  1976.   if (k==1) {
  1977.     j->cat=c; @<Change |pp|...@>;
  1978.     @<Print a snapshot...@>;
  1979.     pp--; /* we next say |pp++| */
  1980.     return;
  1981.   for (i=j; i<j+k; i++) big_app1(i);
  1982.   reduce(j,k,c,d,n);
  1983. @ Here now is the code that applies productions as long as possible.
  1984. Before applying the production mechanism, we must make sure
  1985. it has good input (at least four scraps, the length of the lhs of the
  1986. longest rules), and that there is enough room in the memory arrays
  1987. to hold the appended tokens and texts.  Here we use a very
  1988. conservative test: it's more important to make sure the program
  1989. will still work if we change the production rules (within reason)
  1990. than to squeeze the last bit of space from the memory arrays.
  1991. @d safe_tok_incr 20
  1992. @d safe_text_incr 10
  1993. @d safe_scrap_incr 10
  1994. @<Reduce the scraps using the productions until no more rules apply@>=
  1995. while (1) {
  1996.   @<Make sure the entries |pp| through |pp+3| of |cat| are defined@>;
  1997.   if (tok_ptr+safe_tok_incr>tok_mem_end) {
  1998. #ifdef STAT
  1999.     if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
  2000. #endif /* |STAT| */
  2001.     overflow("token");
  2002.   if (text_ptr+safe_text_incr>tok_start_end) {
  2003. #ifdef STAT
  2004.     if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
  2005. #endif /* |STAT| */
  2006.     overflow("text");
  2007.   if (pp>lo_ptr) break;
  2008.   init_mathness=cur_mathness=maybe_math;
  2009.   @<Match a production...@>;
  2010. @ If we get to the end of the scrap list, category codes equal to zero are
  2011. stored, since zero does not match anything in a production.
  2012. @<Make sure the entries...@>=
  2013. if (lo_ptr<pp+3) {
  2014.   while (hi_ptr<=scrap_ptr && lo_ptr!=pp+3) {
  2015.     (++lo_ptr)->cat=hi_ptr->cat; lo_ptr->mathness=(hi_ptr)->mathness;
  2016.     lo_ptr->trans=(hi_ptr++)->trans;
  2017.   for (i=lo_ptr+1;i<=pp+3;i++) i->cat=0;
  2018. @ If \.{WEAVE} is being run in debugging mode, the production numbers and
  2019. current stack categories will be printed out when |tracing| is set to 2;
  2020. a sequence of two or more irreducible scraps will be printed out when
  2021. |tracing| is set to 1.
  2022. @<Global...@>=
  2023. #ifdef DEBUG
  2024. int tracing; /* can be used to show parsing details */
  2025. #endif /* |DEBUG| */
  2026. @ @<Print a snapsh...@>=
  2027. #ifdef DEBUG
  2028. { scrap_pointer k; /* pointer into |scrap_info| */
  2029.   if (tracing==2) {
  2030.     printf("\n%d:",n);
  2031.     for (k=scrap_base; k<=lo_ptr; k++) {
  2032.       if (k==pp) putxchar('*'); else putxchar(' ');
  2033.       if (k->mathness %4 ==  yes_math) putchar('+');
  2034.       else if (k->mathness %4 ==  no_math) putchar('-');
  2035.       print_cat(k->cat);
  2036.       if (k->mathness /4 ==  yes_math) putchar('+');
  2037.       else if (k->mathness /4 ==  no_math) putchar('-');
  2038.     }
  2039.     if (hi_ptr<=scrap_ptr) printf("..."); /* indicate that more is coming */
  2040. #endif /* |DEBUG| */
  2041. @ The |translate| function assumes that scraps have been stored in
  2042. positions |scrap_base| through |scrap_ptr| of |cat| and |trans|. It
  2043. applies productions as much as
  2044. possible. The result is a token list containing the translation of
  2045. the given sequence of scraps.
  2046. After calling |translate|, we will have |text_ptr+3<=max_texts| and
  2047. |tok_ptr+6<=max_toks|, so it will be possible to create up to three token
  2048. lists with up to six tokens without checking for overflow. Before calling
  2049. |translate|, we should have |text_ptr<max_texts| and |scrap_ptr<max_scraps|,
  2050. since |translate| might add a new text and a new scrap before it checks
  2051. for overflow.
  2052. @c text_pointer translate() /* converts a sequence of scraps */
  2053.   scrap_pointer i, /* index into |cat| */
  2054.   j; /* runs through final scraps */
  2055.   pp=scrap_base; lo_ptr=pp-1; hi_ptr=pp;
  2056.   @<If tracing, print an indication of where we are@>;
  2057.   @<Reduce the scraps...@>;
  2058.   @<Combine the irreducible scraps that remain@>;
  2059. @ If the initial sequence of scraps does not reduce to a single scrap,
  2060. we concatenate the translations of all remaining scraps, separated by
  2061. blank spaces, with dollar signs surrounding the translations of scraps
  2062. where appropriate.
  2063. @<Combine the irreducible...@>= {
  2064.   @<If semi-tracing, show the irreducible scraps@>;
  2065.   for (j=scrap_base; j<=lo_ptr; j++) {
  2066.     if (j!=scrap_base) app(' ');
  2067.     if (j->mathness % 4 == yes_math) app('$');
  2068.     app1(j);
  2069.     if (j->mathness / 4 == yes_math) app('$');
  2070.     if (tok_ptr+6>tok_mem_end) overflow("token");
  2071.   freeze_text; return(text_ptr-1);
  2072. @ @<If semi-tracing, show the irreducible scraps@>=
  2073. #ifdef DEBUG
  2074. if (lo_ptr>scrap_base && tracing==1) {
  2075.   printf("\nIrreducible scrap sequence in section %d:",section_count);
  2076. @.Irreducible scrap sequence...@>
  2077.   mark_harmless;
  2078.   for (j=scrap_base; j<=lo_ptr; j++) {
  2079.     printf(" "); print_cat(j->cat);
  2080. #endif /* |DEBUG| */
  2081. @ @<If tracing,...@>=
  2082. #ifdef DEBUG
  2083. if (tracing==2) {
  2084.   printf("\nTracing after l. %d:\n",cur_line); mark_harmless;
  2085. @.Tracing after...@>
  2086.   if (loc>buffer+50) {
  2087.     printf("...");
  2088.     term_write(loc-51,51);
  2089.   else term_write(buffer,loc-buffer);
  2090. #endif /* |DEBUG| */
  2091. @* Initializing the scraps.
  2092. If we are going to use the powerful production mechanism just developed, we
  2093. must get the scraps set up in the first place, given a \Cee\ text. A table
  2094. of the initial scraps corresponding to \Cee\ tokens appeared above in the
  2095. section on parsing; our goal now is to implement that table. We shall do this
  2096. by implementing a subroutine called |C_parse| that is analogous to the
  2097. |C_xref| routine used during phase one.
  2098. Like |C_xref|, the |C_parse| procedure starts with the current
  2099. value of |next_control| and it uses the operation |next_control=get_next()|
  2100. repeatedly to read \Cee\ text until encountering the next `\.{\v}' or
  2101. `\.{/*}', or until |next_control>=format_code|. The scraps corresponding to what
  2102. it reads are appended into the |cat| and |trans| arrays, and |scrap_ptr|
  2103. is advanced.
  2104. @c C_parse(spec_ctrl) /* creates scraps from \Cee\ tokens */
  2105.   eight_bits spec_ctrl;
  2106.   name_pointer p; /* identifier designator */
  2107.   int count; /* characters remaining before string break */
  2108.   while (next_control<format_code || next_control==spec_ctrl) {
  2109.     @<Append the scrap appropriate to |next_control|@>;
  2110.     next_control=get_next();
  2111.     if (next_control=='|' || next_control==begin_comment) return;
  2112. @ The following macro is used to append a scrap whose tokens have just
  2113. been appended:
  2114. @d app_scrap(c,b) (++scrap_ptr)->cat=c; scrap_ptr->trans=text_ptr;
  2115. scrap_ptr->mathness=5*b; /* no no, yes yes, or maybe maybe */
  2116. freeze_text;
  2117. @ @<Append the scr...@>=
  2118. @<Make sure that there is room for the new scraps, tokens, and texts@>;
  2119. switch (next_control) {
  2120.   case section_name:
  2121.     app(section_flag+cur_section-name_dir);
  2122.     app_scrap(section_scrap,maybe_math);
  2123.     app_scrap(exp,yes_math);@+break;
  2124.   case string: case constant: case verbatim: @<Append a string or constant@>;
  2125.    @+break;
  2126.   case identifier: @<Append an identifier scrap@>;@+break;
  2127.   case TeX_string: @<Append a \TeX\ string scrap@>;@+break;
  2128.   case '/': case '<': case '>': case '.':
  2129.     app(next_control); app_scrap(binop,yes_math);@+break;
  2130.   case '=': app_str("\\K"); app_scrap(binop,yes_math);@+break;
  2131. @.\\K@>
  2132.   case '|': app_str("\\OR"); app_scrap(binop,yes_math);@+break;
  2133. @.\\OR@>
  2134.   case '^': app_str("\\XOR"); app_scrap(binop,yes_math);@+break;
  2135. @.\\XOR@>
  2136.   case '%': app_str("\\MOD"); app_scrap(binop,yes_math);@+break;
  2137. @.\\MOD@>
  2138.   case '!': app_str("\\R"); app_scrap(unop,yes_math);@+break;
  2139. @.\\R@>
  2140.   case '~': app_str("\\CM"); app_scrap(unop,yes_math);@+break;
  2141. @.\\CM@>
  2142.   case '+': case '-': case '*': app(next_control); app_scrap(unorbinop,yes_math);@+break;
  2143.   case '&': app_str("\\AND"); app_scrap(unorbinop,yes_math);@+break;
  2144. @.\\AND@>
  2145.   case '?': app_str("\\?"); app_scrap(question,yes_math);@+break;
  2146. @.\\\#@>
  2147.   case '#': app_str("\\#"); app_scrap(insert,maybe_math);@+break;
  2148.     /* this shouldn't happen in normal \Cee\ programs*/
  2149.   case ignore: case xref_roman: case xref_wildcard:
  2150.   case xref_typewriter: case noop:@+break;
  2151.   case '(': case '[': app(next_control); app_scrap(lpar,maybe_math);@+break;
  2152.   case ')': case ']': app(next_control); app_scrap(rpar,maybe_math);@+break;
  2153.   case '{': app_str("\\{"); app_scrap(lbrace,yes_math);@+break;
  2154.   case '}': app_str("\\}"); app_scrap(rbrace,yes_math);@+break;
  2155.   case ',': app(','); app_scrap(comma,yes_math);@+break;
  2156.   case ';': app(';'); app_scrap(semi,maybe_math);@+break;
  2157.   case ':': app(':'); app_scrap(colon,maybe_math);@+break;@/
  2158.   @t\4@>  @<Cases involving nonstandard characters@>@;
  2159.   case thin_space: app_str("\\,"); app_scrap(insert,maybe_math);@+break;
  2160. @.\\,@>
  2161.   case math_break: app(opt); app_str("0");
  2162.     app_scrap(insert,maybe_math);@+break;
  2163.   case line_break: app(force); app_scrap(insert,no_math);@+break;
  2164.   case left_preproc: app(force); app(preproc_line);
  2165.     app_str("\\#"); app_scrap(lproc,no_math);@+break;
  2166.   case right_preproc: app(force); app_scrap(rproc,no_math);@+break;
  2167.   case big_line_break: app(big_force); app_scrap(insert,no_math);@+break;
  2168.   case no_line_break: app(big_cancel); app(noop); app(break_space);
  2169.     app(noop); app(big_cancel);
  2170.     app_scrap(insert,no_math);@+break;
  2171.   case pseudo_semi: app_scrap(semi,maybe_math);@+break;
  2172.   case macro_arg_open: app_scrap(begin_arg,maybe_math);@+break;
  2173.   case macro_arg_close: app_scrap(end_arg,maybe_math);@+break;
  2174.   case join: app_str("\\J"); app_scrap(insert,no_math);@+break;
  2175. @.\\J@>
  2176.   default: app(next_control); app_scrap(insert,maybe_math);@+break;
  2177. @ @<Make sure that there is room for the new...@>=
  2178. if (scrap_ptr+safe_scrap_incr>scrap_info_end ||
  2179.   tok_ptr+safe_tok_incr>tok_mem_end @| ||
  2180.   text_ptr+safe_text_incr>tok_start_end) {
  2181. #ifdef STAT
  2182.   if (scrap_ptr>max_scr_ptr) max_scr_ptr=scrap_ptr;
  2183.   if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
  2184.   if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
  2185. #endif /* |STAT| */
  2186.   overflow("scrap/token/text");
  2187. @ Some nonstandard characters may have entered \.{WEAVE} by means of
  2188. standard ones. They are converted to \TeX\ control sequences so that it is
  2189. possible to keep \.{WEAVE} from outputting unusual |char| codes.
  2190. @<Cases involving nonstandard...@>=
  2191. case not_eq: app_str("\\I");@+app_scrap(binop,yes_math);@+break;
  2192. @.\\I@>
  2193. case lt_eq: app_str("\\le");@+app_scrap(binop,yes_math);@+break;
  2194. @.\\le@>
  2195. case gt_eq: app_str("\\G");@+app_scrap(binop,yes_math);@+break;
  2196. @.\\G@>
  2197. case eq_eq: app_str("\\E");@+app_scrap(binop,yes_math);@+break;
  2198. @.\\E@>
  2199. case and_and: app_str("\\W");@+app_scrap(binop,yes_math);@+break;
  2200. @.\\W@>
  2201. case or_or: app_str("\\V");@+app_scrap(binop,yes_math);@+break;
  2202. @.\\V@>
  2203. case plus_plus: app_str("\\PP");@+app_scrap(unop,yes_math);@+break;
  2204. @.\\PP@>
  2205. case minus_minus: app_str("\\MM");@+app_scrap(unop,yes_math);@+break;
  2206. @.\\MM@>
  2207. case minus_gt: app_str("\\MG");@+app_scrap(binop,yes_math);@+break;
  2208. @.\\MG@>
  2209. case gt_gt: app_str("\\GG");@+app_scrap(binop,yes_math);@+break;
  2210. @.\\GG@>
  2211. case lt_lt: app_str("\\LL");@+app_scrap(binop,yes_math);@+break;
  2212. @.\\LL@>
  2213. @ The following code must use |app_tok| instead of |app| in order to
  2214. protect against overflow. Note that |tok_ptr+1<=max_toks| after |app_tok|
  2215. has been used, so another |app| is legitimate before testing again.
  2216. Many of the special characters in a string must be prefixed by `\.\\' so that
  2217. \TeX\ will print them properly.
  2218. @^special string characters@>
  2219. @<Append a string or...@>=
  2220. count= -1;
  2221. if (next_control==constant) app_str("\\T{");
  2222. @.\\T@>
  2223. else if (next_control==string) {
  2224.   count=20; app_str("\\.{");
  2225. @.\\.@>
  2226. else app_str("\\vb{");
  2227. @.\\vb@>
  2228. while (id_first<id_loc) {
  2229.   if (count==0) { /* insert a discretionary break in a long string */
  2230.      app_str("}\\)\\.{"); count=20;
  2231. @.\\)@>
  2232.   switch (*id_first) {
  2233.     case  ' ':case '\\':case '#':case '%':case '$':case '^':
  2234.     case '{': case '}': case '~': case '&': case '_': app('\\'); break;
  2235.     case '@@': if (*(id_first+1)=='@@') id_first++;
  2236.       else err_print("! Double @@ should be used in strings");
  2237. @.Double {\AT} should be used...@>
  2238.   app_tok(*id_first++); count--;
  2239. app('}');
  2240. app_scrap(exp,maybe_math);
  2241. @ @<Append a \TeX\ string scrap@>=
  2242. app_str("\\hbox{"); while (id_first<id_loc) app_tok(*id_first++);
  2243. app('}'); app_scrap(exp,maybe_math);
  2244. @ @<Append an identifier scrap@>=
  2245. p=id_lookup(id_first, id_loc,normal);
  2246. if (!(reserved(p))) {
  2247.   app(id_flag+p-name_dir); app_scrap(exp,maybe_math); /* not a reserved word */
  2248. else if (p->ilk<=quoted) { /* |custom| or |quoted| */
  2249.   app('\\');
  2250.   while (id_first++<id_loc) {
  2251.     if (isxalpha(*(id_first-1))) app_tok('x')
  2252.     else app_tok(*(id_first-1));
  2253.   app_scrap(exp,yes_math);
  2254. @.\\NULL@>
  2255. else {
  2256.   app(res_flag+p-name_dir);
  2257.   app_scrap(p->ilk,maybe_math);
  2258. @ When the `\.{\v}' that introduces \Cee\ text is sensed, a call on
  2259. |C_translate| will return a pointer to the \TeX\ translation of
  2260. that text. If scraps exist in |scrap_info|, they are
  2261. unaffected by this translation process.
  2262. @c text_pointer C_translate()
  2263.   text_pointer p; /* points to the translation */
  2264.   scrap_pointer save_base; /* holds original value of |scrap_base| */
  2265.   save_base=scrap_base; scrap_base=scrap_ptr+1;
  2266.   C_parse(section_name); /* get the scraps together */
  2267.   if (next_control!='|') err_print("! Missing '|' after C text");
  2268. @.Missing '|'...@>
  2269.   app_tok(cancel); app_scrap(insert,maybe_math);
  2270.         /* place a |cancel| token as a final ``comment'' */
  2271.   p=translate(); /* make the translation */
  2272. #ifdef STAT
  2273.  if (scrap_ptr>max_scr_ptr) max_scr_ptr=scrap_ptr;
  2274. #endif /* |STAT| */
  2275.   scrap_ptr=scrap_base-1; scrap_base=save_base; /* scrap the scraps */
  2276.   return(p);
  2277. @ The |outer_parse| routine is to |C_parse| as |outer_xref|
  2278. is to |C_xref|: it constructs a sequence of scraps for \Cee\ text
  2279. until |next_control>=format_code|. Thus, it takes care of embedded comments.
  2280. @c outer_parse() /* makes scraps from \Cee\ tokens and comments */
  2281.   int bal; /* brace level in comment */
  2282.   text_pointer p, q; /* partial comments */
  2283.   while (next_control<format_code)
  2284.     if (next_control!=begin_comment) C_parse(ignore);
  2285.     else {
  2286.       @<Make sure that there is room for the new...@>;
  2287.       app(cancel); app_str("\\C{");
  2288. @.\\C@>
  2289.       bal=copy_comment(1); next_control=ignore;
  2290.       while (bal>0) {
  2291.         p=text_ptr; freeze_text; q=C_translate();
  2292.          /* at this point we have |tok_ptr+6<=max_toks| */
  2293.         app(tok_flag+p-tok_start); app(inner_tok_flag+q-tok_start);
  2294.         if (next_control=='|') {
  2295.           bal=copy_comment(bal);
  2296.           next_control=ignore;
  2297.         }
  2298.         else bal=0; /* an error has been reported */
  2299.       }
  2300.       app(force); app_scrap(insert,no_math);
  2301.         /* the full comment becomes a scrap */
  2302.     }
  2303. @* Output of tokens.
  2304. So far our programs have only built up multi-layered token lists in
  2305. \.{WEAVE}'s internal memory; we have to figure out how to get them into
  2306. the desired final form. The job of converting token lists to characters in
  2307. the \TeX\ output file is not difficult, although it is an implicitly
  2308. recursive process. Four main considerations had to be kept in mind when
  2309. this part of \.{WEAVE} was designed.  (a) There are two modes of output:
  2310. |outer| mode, which translates tokens like |force| into line-breaking
  2311. control sequences, and |inner| mode, which ignores them except that blank
  2312. spaces take the place of line breaks. (b) The |cancel| instruction applies
  2313. to adjacent token or tokens that are output, and this cuts across levels
  2314. of recursion since `|cancel|' occurs at the beginning or end of a token
  2315. list on one level. (c) The \TeX\ output file will be semi-readable if line
  2316. breaks are inserted after the result of tokens like |break_space| and
  2317. |force|.  (d) The final line break should be suppressed, and there should
  2318. be no |force| token output immediately after `\.{\\Y\\B}'.
  2319. @ The output process uses a stack to keep track of what is going on at
  2320. different ``levels'' as the token lists are being written out. Entries on
  2321. this stack have three parts:
  2322. \yskip\hang |end_field| is the |tok_mem| location where the token list of a
  2323. particular level will end;
  2324. \yskip\hang |tok_field| is the |tok_mem| location from which the next token
  2325. on a particular level will be read;
  2326. \yskip\hang |mode_field| is the current mode, either |inner| or |outer|.
  2327. \yskip\noindent The current values of these quantities are referred to
  2328. quite frequently, so they are stored in a separate place instead of in the
  2329. |stack| array. We call the current values |cur_end|, |cur_tok|, and
  2330. |cur_mode|.
  2331. The global variable |stack_ptr| tells how many levels of output are
  2332. currently in progress. The end of output occurs when an |end_translation|
  2333. token is found, so the stack is never empty except when we first begin the
  2334. output process.
  2335. @d inner 0 /* value of |mode| for \Cee\ texts within \TeX\ texts */
  2336. @d outer 1 /* value of |mode| for \Cee\ texts in sections */
  2337. @<Typed...@>= typedef int mode;
  2338. typedef struct {
  2339.   token_pointer end_field; /* ending location of token list */
  2340.   token_pointer tok_field; /* present location within token list */
  2341.   boolean mode_field; /* interpretation of control tokens */
  2342. } output_state;
  2343. typedef output_state *stack_pointer;
  2344. @ @d cur_end cur_state.end_field /* current ending location in |tok_mem| */
  2345. @d cur_tok cur_state.tok_field /* location of next output token in |tok_mem| */
  2346. @d cur_mode cur_state.mode_field /* current mode of interpretation */
  2347. @d init_stack stack_ptr=stack;cur_mode=outer /* initialize the stack */
  2348. @<Global...@>=
  2349. output_state cur_state; /* |cur_end|, |cur_tok|, |cur_mode| */
  2350. output_state stack[stack_size]; /* info for non-current levels */
  2351. stack_pointer stack_ptr; /* first unused location in the output state stack */
  2352. stack_pointer stack_end=stack+stack_size-1; /* end of |stack| */
  2353. #ifdef STAT
  2354. stack_pointer max_stack_ptr; /* largest value assumed by |stack_ptr| */
  2355. #endif /* |STAT| */
  2356. @ @<Set init...@>=
  2357. #ifdef STAT
  2358. max_stack_ptr=stack;
  2359. #endif /* |STAT| */
  2360. @ To insert token-list |p| into the output, the |push_level| subroutine
  2361. is called; it saves the old level of output and gets a new one going.
  2362. The value of |cur_mode| is not changed.
  2363. @c push_level(p) /* suspends the current level */
  2364. text_pointer p;
  2365.   if (stack_ptr==stack_end) overflow("stack");
  2366.   if (stack_ptr>stack) { /* save current state */
  2367.     stack_ptr->end_field=cur_end;
  2368.     stack_ptr->tok_field=cur_tok;
  2369.     stack_ptr->mode_field=cur_mode;
  2370.   stack_ptr++;
  2371. #ifdef STAT
  2372.   if (stack_ptr>max_stack_ptr) max_stack_ptr=stack_ptr;
  2373. #endif /* |STAT| */
  2374.   cur_tok=*p; cur_end=*(p+1);
  2375. @ Conversely, the |pop_level| routine restores the conditions that were in
  2376. force when the current level was begun. This subroutine will never be
  2377. called when |stack_ptr=1|.
  2378. @c pop_level()
  2379.   cur_end=(--stack_ptr)->end_field;
  2380.   cur_tok=stack_ptr->tok_field; cur_mode=stack_ptr->mode_field;
  2381. @ The |get_output| function returns the next byte of output that is not a
  2382. reference to a token list. It returns the values |identifier| or |res_word|
  2383. or |section_code| if the next token is to be an identifier (typeset in
  2384. italics), a reserved word (typeset in boldface) or a section name (typeset
  2385. by a complex routine that might generate additional levels of output).
  2386. In these cases |cur_name| points to the identifier or section name in
  2387. question.
  2388. @<Global...@>=
  2389. name_pointer cur_name;
  2390. @ @d res_word 0201 /* returned by |get_output| for reserved words */
  2391. @d section_code 0200 /* returned by |get_output| for section names */
  2392. @c eight_bits get_output() /* returns the next token of output */
  2393.   sixteen_bits a; /* current item read from |tok_mem| */
  2394.   restart: while (cur_tok==cur_end) pop_level();
  2395.   a=*(cur_tok++);
  2396.   if (a>=0400) {
  2397.     cur_name=a % id_flag + name_dir;
  2398.     switch (a / id_flag) {
  2399.       case 2: return(res_word); /* |a==res_flag+cur_name| */
  2400.       case 3: return(section_code); /* |a==section_flag+cur_name| */
  2401.       case 4: push_level(a % id_flag + tok_start); goto restart;
  2402.         /* |a==tok_flag+cur_name| */
  2403.       case 5: push_level(a % id_flag + tok_start); cur_mode=inner; goto restart;
  2404.         /* |a==inner_tok_flag+cur_name| */
  2405.       default: return(identifier); /* |a==id_flag+cur_name| */
  2406.     }
  2407.   return(a);
  2408. @ The real work associated with token output is done by |make_output|.
  2409. This procedure appends an |end_translation| token to the current token list,
  2410. and then it repeatedly calls |get_output| and feeds characters to the output
  2411. buffer until reaching the |end_translation| sentinel. It is possible for
  2412. |make_output| to be called recursively, since a section name may include
  2413. embedded \Cee\ text; however, the depth of recursion never exceeds one
  2414. level, since section names cannot be inside of section names.
  2415. A procedure called |output_C| does the scanning, translation, and
  2416. output of \Cee\ text within `\pb' brackets, and this procedure uses
  2417. |make_output| to output the current token list. Thus, the recursive call
  2418. of |make_output| actually occurs when |make_output| calls |output_C|
  2419. while outputting the name of a section.
  2420. @^recursion@>
  2421. output_C() /* outputs the current token list */
  2422.   token_pointer save_tok_ptr;
  2423.   text_pointer save_text_ptr;
  2424.   sixteen_bits save_next_control; /* values to be restored */
  2425.   text_pointer p; /* translation of the \Cee\ text */
  2426.   save_tok_ptr=tok_ptr; save_text_ptr=text_ptr;
  2427.   save_next_control=next_control; next_control=ignore; p=C_translate();
  2428.   app(p-tok_start+inner_tok_flag);
  2429.   make_output(); /* output the list */
  2430. #ifdef STAT
  2431.   if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
  2432.   if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
  2433. #endif /* |STAT| */
  2434.   text_ptr=save_text_ptr; tok_ptr=save_tok_ptr; /* forget the tokens */
  2435.   next_control=save_next_control; /* restore |next_control| to original state */
  2436. @ Here is \.{WEAVE}'s major output handler.
  2437. @c make_output() /* outputs the equivalents of tokens */
  2438.   eight_bits a, /* current output byte */
  2439.   b; /* next output byte */
  2440.   int c; /* count of |indent| and |outdent| tokens */
  2441.   char *k, *k_limit; /* indices into |byte_mem| */
  2442.   char *j; /* index into |buffer| */
  2443.   char delim; /* first and last character of string being copied */
  2444.   char *save_loc, *save_limit; /* |loc| and |limit| to be restored */
  2445.   char scratch[longest_name]; /* scratch area for section names */
  2446.   name_pointer cur_section_name; /* name of section being output */
  2447.   boolean save_mode; /* value of |cur_mode| before a sequence of breaks */
  2448.   app(end_translation); /* append a sentinel */
  2449.   freeze_text; push_level(text_ptr-1);
  2450.   while (1) {
  2451.     a=get_output();
  2452.     reswitch: switch(a) {
  2453.       case end_translation: return;
  2454.       case identifier: case res_word: @<Output an identifier@>; break;
  2455.       case section_code: @<Output a section name@>; break;
  2456.       case math_rel: out_str("\\mathrel{");
  2457.       case noop: break;
  2458.       case cancel: case big_cancel: c=0; b=a;
  2459.         while (((a=get_output())>=indent ||(b==big_cancel&&a==' '))@|
  2460.               && a<=big_force) {
  2461.           if (a==indent) c++; else if (a==outdent) c--;
  2462.           else if (a==opt) a=get_output();
  2463.         }
  2464.         @<Output saved |indent| or |outdent| tokens@>;
  2465.         goto reswitch;
  2466.       case indent: case outdent: case opt: case backup: case break_space:
  2467.       case force: case big_force: case preproc_line: @<Output a control,
  2468.         look ahead in case of line breaks, possibly |goto reswitch|@>; break;
  2469.       default: out(a); /* otherwise |a| is an ordinary character */
  2470.     }
  2471. @ An identifier of length one does not have to be enclosed in braces, and it
  2472. looks slightly better if set in a math-italic font instead of a (slightly
  2473. narrower) text-italic font. Thus we output `\.{\\\v}\.{a}' but
  2474. `\.{\\\\\{aa\}}'.
  2475. @<Output an identifier@>=
  2476. out('\\');
  2477. if (a==identifier) {
  2478.   if (is_tiny(cur_name)) out('|')
  2479. @.\\|@>
  2480.   else { delim='.';
  2481.     for (j=cur_name->byte_start;j<(cur_name+1)->byte_start;j++)
  2482.       if (islower(*j)) { /* not entirely uppercase */
  2483.          delim='\\'; break;
  2484.       }
  2485.   out(delim);
  2486. @.\\\\@>
  2487. @.\\.@>
  2488. else out('&') /* |a==res_word| */
  2489. @.\\\&@>
  2490. if (is_tiny(cur_name)) {
  2491.   if (isxalpha((cur_name->byte_start)[0]))
  2492.     out('\\');
  2493.   out((cur_name->byte_start)[0]);
  2494. else out_name(cur_name);
  2495. @ The current mode does not affect the behavior of \.{WEAVE}'s output routine
  2496. except when we are outputting control tokens.
  2497. @<Output a control...@>=
  2498. if (a<break_space || a==preproc_line) {
  2499.   if (cur_mode==outer) {
  2500.     out('\\'); out(a-cancel+'0');
  2501. @.\\1@>
  2502. @.\\2@>
  2503. @.\\3@>
  2504. @.\\4@>
  2505. @.\\8@>
  2506.     if (a==opt) out(get_output()); /* |opt| is followed by a digit */
  2507.     }
  2508.   else if (a==opt) b=get_output(); /* ignore digit following |opt| */
  2509. else @<Look ahead for strongest line break, |goto reswitch|@>
  2510. @ If several of the tokens |break_space|, |force|, |big_force| occur in a
  2511. row, possibly mixed with blank spaces (which are ignored),
  2512. the largest one is used. A line break also occurs in the output file,
  2513. except at the very end of the translation. The very first line break
  2514. is suppressed (i.e., a line break that follows `\.{\\Y\\B}').
  2515. @<Look ahead for st...@>= {
  2516.   b=a; save_mode=cur_mode; c=0;
  2517.   while (1) {
  2518.     a=get_output();
  2519.     if (a==cancel || a==big_cancel) {
  2520.       @<Output saved |indent| or |outdent| tokens@>;
  2521.       goto reswitch; /* |cancel| overrides everything */
  2522.     }
  2523.     if ((a!=' ' && a<indent) || a==backup || a>big_force) {
  2524.       if (save_mode==outer) {
  2525.         if (out_ptr>out_buf+3 && strncmp(out_ptr-3,"\\Y\\B",4)==0)
  2526.           goto reswitch;
  2527.         @<Output saved |indent| or |outdent| tokens@>;
  2528.         out('\\'); out(b-cancel+'0');
  2529. @.\\5@>
  2530. @.\\6@>
  2531. @.\\7@>
  2532.         if (a!=end_translation) finish_line();
  2533.       }
  2534.       else if (a!=end_translation && cur_mode==inner) out(' ');
  2535.       goto reswitch;
  2536.     }
  2537.     if (a==indent) c++;
  2538.     else if (a==outdent) c--;
  2539.     else if (a==opt) a=get_output();
  2540.     else if (a>b) b=a; /* if |a==' '| we have |a<b| */
  2541. @ @<Output saved...@>=
  2542.   for (;c>0;c--) out_str("\\1");
  2543. @.\\1@>
  2544.   for (;c<0;c++) out_str("\\2");
  2545. @.\\2@>
  2546. @ The remaining part of |make_output| is somewhat more complicated. When we
  2547. output a section name, we may need to enter the parsing and translation
  2548. routines, since the name may contain \Cee\ code embedded in
  2549. \pb\ constructions. This \Cee\ code is placed at the end of the active
  2550. input buffer and the translation process uses the end of the active
  2551. |tok_mem| area.
  2552. @<Output a section name@>= {
  2553.   out_str("\\X");
  2554. @.\\X@>
  2555.   cur_xref=(xref_pointer)cur_name->xref;
  2556.   if (cur_xref->num==file_flag) {an_output=1; cur_xref=cur_xref->xlink;}
  2557.   else an_output=0;
  2558.   if (cur_xref->num>=def_flag) {
  2559.     out_section(cur_xref->num-def_flag);
  2560.     if (phase==3) {
  2561.       cur_xref=cur_xref->xlink;
  2562.       while (cur_xref->num>=def_flag) {
  2563.         out_str(", ");
  2564.         out_section(cur_xref->num-def_flag);
  2565.       cur_xref=cur_xref->xlink;
  2566.       }
  2567.     }
  2568.   else out('0'); /* output the section number, or zero if it was undefined */
  2569.   out(':');
  2570.   if (an_output) out_str("\\.{");
  2571. @.\\.@>
  2572.   @<Output the text of the section name@>;
  2573.   if (an_output) out_str(" }");
  2574.   out_str("\\X");
  2575. @ @<Output the text...@>=
  2576. sprint_section_name(scratch,cur_name);
  2577. k=scratch;
  2578. k_limit=scratch+strlen(scratch);
  2579. cur_section_name=cur_name;
  2580. while (k<k_limit) {
  2581.   b=*(k++);
  2582.   if (b=='@@') @<Skip next character, give error if not `\.{@@}'@>;
  2583.   if (an_output)
  2584.     switch (b) {
  2585.  case  ' ':case '\\':case '#':case '%':case '$':case '^':
  2586.  case '{': case '}': case '~': case '&': case '_':
  2587.     out('\\'); /* falls through */
  2588.  default: out(b);
  2589.     }
  2590.   else if (b!='|') out(b)
  2591.   else {
  2592.     @<Copy the \Cee\ text into the |buffer| array@>;
  2593.     save_loc=loc; save_limit=limit; loc=limit+2; limit=j+1;
  2594.     *limit='|'; output_C();
  2595.     loc=save_loc; limit=save_limit;
  2596. @ @<Skip next char...@>=
  2597. if (*k++!='@@') {
  2598.   printf("\n! Illegal control code in section name: <");
  2599. @.Illegal control code...@>
  2600.   print_section_name(cur_section_name); printf("> "); mark_error;
  2601. @ The \Cee\ text enclosed in \pb\ should not contain `\.{\v}' characters,
  2602. except within strings. We put a `\.{\v}' at the front of the buffer, so that an
  2603. error message that displays the whole buffer will look a little bit sensible.
  2604. The variable |delim| is zero outside of strings, otherwise it
  2605. equals the delimiter that began the string being copied.
  2606. @<Copy the \Cee\ text into...@>=
  2607. j=limit+1; *j='|'; delim=0;
  2608. while (1) {
  2609.   if (k>=k_limit) {
  2610.     printf("\n! C text in section name didn't end: <");
  2611. @.C text...didn't end@>
  2612.     print_section_name(cur_section_name); printf("> "); mark_error; break;
  2613.   b=*(k++);
  2614.   if (b=='@@') @<Copy a control code into the buffer@>
  2615.   else {
  2616.     if (b=='\'' || b=='"')
  2617.       if (delim==0) delim=b;
  2618.       else if (delim==b) delim=0;
  2619.     if (b!='|' || delim!=0) {
  2620.       if (j>buffer+long_buf_size-3) overflow("buffer");
  2621.       *(++j)=b;
  2622.     }
  2623.     else break;
  2624. @ @<Copy a control code into the buffer@>= {
  2625.   if (j>buffer+long_buf_size-4) overflow("buffer");
  2626.   *(++j)='@@'; *(++j)=*(k++);
  2627. @* Phase two processing.
  2628. We have assembled enough pieces of the puzzle in order to be ready to specify
  2629. the processing in \.{WEAVE}'s main pass over the source file. Phase two
  2630. is analogous to phase one, except that more work is involved because we must
  2631. actually output the \TeX\ material instead of merely looking at the
  2632. \.{WEB} specifications.
  2633. @c phase_two() {
  2634. reset_input(); if (show_progress) printf("\nWriting the output file...");
  2635. @.Writing the output file...@>
  2636. section_count=0; format_visible=1; copy_limbo();
  2637. finish_line(); flush_buffer(out_buf,0,0); /* insert a blank line, it looks nice */
  2638. while (!input_has_ended) @<Translate the current section@>;
  2639. @ The output file will contain the control sequence \.{\\Y} between non-null
  2640. sections of a section, e.g., between the \TeX\ and definition parts if both
  2641. are nonempty. This puts a little white space between the parts when they are
  2642. printed. However, we don't want \.{\\Y} to occur between two definitions
  2643. within a single section. The variables |out_line| or |out_ptr| will
  2644. change if a section is non-null, so the following macros `|save_position|'
  2645. and `|emit_space_if_needed|' are able to handle the situation:
  2646. @d save_position save_line=out_line; save_place=out_ptr
  2647. @d emit_space_if_needed if (save_line!=out_line || save_place!=out_ptr)
  2648.   out_str("\\Y");
  2649.   space_checked=1
  2650. @.\\Y@>
  2651. @<Global...@>=
  2652. int save_line; /* former value of |out_line| */
  2653. char *save_place; /* former value of |out_ptr| */
  2654. boolean space_checked; /* have we done |emit_space_if_needed|? */
  2655. boolean format_visible; /* should the next format declaration be output? */
  2656. @ @<Translate the current section@>= {
  2657.   section_count++;
  2658.   @<Output the code for the beginning of a new section@>;
  2659.   save_position;
  2660.   @<Translate the \TeX\ part of the current section@>;
  2661.   @<Translate the definition part of the current section@>;
  2662.   @<Translate the \Cee\ part of the current section@>;
  2663.   @<Show cross-references to this section@>;
  2664.   @<Output the code for the end of a section@>;
  2665. @ Sections beginning with the \.{WEB} control sequence `\.{@@\ }' start in the
  2666. output with the \TeX\ control sequence `\.{\\M}', followed by the section
  2667. number. Similarly, `\.{@@*}' sections lead to the control sequence `\.{\\N}'.
  2668. If this is a changed section, we put \.{*} just before the section number.
  2669. @<Output the code for the beginning...@>=
  2670. if (*(loc-1)!='*') out_str("\\M");
  2671. @.\\M@>
  2672. else {
  2673.   out_str("\\N");
  2674. @.\\N@>
  2675.   if (show_progress)
  2676.   printf("*%d",section_count); update_terminal; /* print a progress report */
  2677. out_section(section_count); out_str(". ");
  2678. @ In the \TeX\ part of a section, we simply copy the source text, except that
  2679. index entries are not copied and \Cee\ text within \pb\ is translated.
  2680. @<Translate the \T...@>= do {
  2681.   next_control=copy_TeX();
  2682.   switch (next_control) {
  2683.     case '|': init_stack; output_C(); break;
  2684.     case '@@': out('@@'); break;
  2685.     case TeX_string: case noop:
  2686.     case xref_roman: case xref_wildcard: case xref_typewriter:
  2687.     case section_name: loc-=2; next_control=get_next(); /* skip to \.{@@>} */
  2688.       if (next_control==TeX_string)
  2689.         err_print("! TeX string should be in C text only"); break;
  2690. @.TeX string should be...@>
  2691.     case thin_space: case math_break: case ord:
  2692.     case line_break: case big_line_break: case no_line_break: case join:
  2693.     case pseudo_semi: case macro_arg_open: case macro_arg_close:
  2694.         err_print("! You can't do that in TeX text"); break;
  2695. @.You can't do that...@>
  2696. } while (next_control<format_code);
  2697. @ When we get to the following code we have |next_control>=format_code|, and
  2698. the token memory is in its initial empty state.
  2699. @<Translate the d...@>=
  2700. space_checked=0;
  2701. while (next_control<=definition) { /* |format_code| or |definition| */
  2702.   init_stack;
  2703.   if (next_control==definition) @<Start a macro definition@>@;
  2704.   else @<Start a format definition@>;
  2705.   outer_parse(); finish_C(format_visible); format_visible=1;
  2706. @ The |finish_C| procedure outputs the translation of the current
  2707. scraps, preceded by the control sequence `\.{\\B}' and followed by the
  2708. control sequence `\.{\\par}'. It also restores the token and scrap
  2709. memories to their initial empty state.
  2710. A |force| token is appended to the current scraps before translation
  2711. takes place, so that the translation will normally end with \.{\\6} or
  2712. \.{\\7} (the \TeX\ macros for |force| and |big_force|). This \.{\\6} or
  2713. \.{\\7} is replaced by the concluding \.{\\par} or by \.{\\Y\\par}.
  2714. @c finish_C(visible) /* finishes a definition or a \Cee\ part */
  2715.   boolean visible; /* nonzero if we should produce \TeX\ output */
  2716.   text_pointer p; /* translation of the scraps */
  2717.   if (visible) {
  2718.     out_str("\\B"); app_tok(force); app_scrap(insert,no_math);
  2719.     p=translate();
  2720. @.\\B@>
  2721.     app(p-tok_start+tok_flag); make_output(); /* output the list */
  2722.     if (out_ptr>out_buf+1)
  2723.       if (*(out_ptr-1)=='\\')
  2724. @.\\6@>
  2725. @.\\7@>
  2726. @.\\Y@>
  2727.         if (*out_ptr=='6') out_ptr-=2;
  2728.         else if (*out_ptr=='7') *out_ptr='Y';
  2729.     out_str("\\par"); finish_line();
  2730. #ifdef STAT
  2731.   if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
  2732.   if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
  2733.   if (scrap_ptr>max_scr_ptr) max_scr_ptr=scrap_ptr;
  2734. #endif /* |STAT| */
  2735.   tok_ptr=tok_mem+1; text_ptr=tok_start+1; scrap_ptr=scrap_info;
  2736.     /* forget the tokens and the scraps */
  2737. @ Keeping in line with the conventions of the \Cee\ preprocessor (and
  2738. otherwise contrary to the rules of \.{WEB}) we distinguish here
  2739. between the case that `\.(' immediately follows an identifier and the
  2740. case that the two are separated by a space.  In the latter case, and
  2741. if the identifier is not followed by `\.(' at all, the replacement
  2742. text starts immediately after the identifier.  In the former case,
  2743. it starts after we scan the matching `\.)'.
  2744. @<Start a macro...@>= {
  2745.   if (save_line!=out_line || save_place!=out_ptr)  app(backup);
  2746.   if(!space_checked){emit_space_if_needed;save_position;}
  2747.   app_str("\\D"); /* this will produce `\&{define }' */
  2748. @.\\D@>
  2749.   if ((next_control=get_next())!=identifier)
  2750.     err_print("! Improper macro definition");
  2751. @.Improper macro definition@>
  2752.   else {
  2753.     app('$'); app(id_flag+id_lookup(id_first, id_loc,normal)-name_dir);
  2754.     if (*loc=='(')
  2755.   reswitch: switch (next_control=get_next()) {
  2756.       case '(': case ',': app(next_control); goto reswitch;
  2757.       case identifier: app(id_flag+id_lookup(id_first, id_loc,normal)-name_dir); goto reswitch;
  2758.       case ')': app(next_control); next_control=get_next(); break;
  2759.       default: err_print("! Improper macro definition"); break;
  2760.     }
  2761.     else next_control=get_next();
  2762.     app_str("$ "); app(break_space);
  2763.     app_scrap(dead,no_math); /* scrap won't take part in the parsing */
  2764. @ @<Start a format...@>= {
  2765.   if(*(loc-1)=='s' || *(loc-1)=='S') format_visible=0;
  2766.   if(!space_checked){emit_space_if_needed;save_position;}
  2767.   app_str("\\F"); /* this will produce `\&{format }' */
  2768. @.\\F@>
  2769.   next_control=get_next();
  2770.   if (next_control==identifier) {
  2771.     app(id_flag+id_lookup(id_first, id_loc,normal)-name_dir);
  2772.     app(' ');
  2773.     app(break_space); /* this is syntactically separate from what follows */
  2774.     next_control=get_next();
  2775.     if (next_control==identifier) {
  2776.       app(id_flag+id_lookup(id_first, id_loc,normal)-name_dir);
  2777.       app_scrap(exp,maybe_math); app_scrap(semi,maybe_math);
  2778.       next_control=get_next();
  2779.     }
  2780.   if (scrap_ptr!=scrap_info+2) err_print("! Improper format definition");
  2781. @.Improper format definition@>
  2782. @ Finally, when the \TeX\ and definition parts have been treated, we have
  2783. |next_control>=begin_C|. We will make the global variable |this_section|
  2784. point to the current section name, if it has a name.
  2785. @<Global...@>=
  2786. name_pointer this_section; /* the current section name, or zero */
  2787. @ @<Translate the \Cee...@>=
  2788. this_section=name_dir;
  2789. if (next_control<=section_name) {
  2790.   emit_space_if_needed; init_stack;
  2791.   if (next_control==begin_C) next_control=get_next();
  2792.   else {
  2793.     this_section=cur_section;
  2794.     @<Check that |=| or |==| follows this section name, and
  2795.       emit the scraps to start the section definition@>;
  2796.   while  (next_control<=section_name) {
  2797.     outer_parse();
  2798.     @<Emit the scrap for a section name if present@>;
  2799.   finish_C(1);
  2800. @ @<Check that |=|...@>=
  2801. do next_control=get_next();
  2802.   while (next_control=='+'); /* allow optional `\.{+=}' */
  2803. if (next_control!='=' && next_control!=eq_eq)
  2804.   err_print("! You need an = sign after the section name");
  2805. @.You need an = sign...@>
  2806.   else next_control=get_next();
  2807. if (out_ptr>out_buf+1 && *out_ptr=='Y' && *(out_ptr-1)=='\\') app(backup);
  2808.     /* the section name will be flush left */
  2809. @.\\Y@>
  2810. app(section_flag+this_section-name_dir);
  2811. cur_xref=(xref_pointer)this_section->xref;
  2812. if(cur_xref->num==file_flag) cur_xref=cur_xref->xlink;
  2813. app_str("${}");
  2814. if (cur_xref->num!=section_count+def_flag) {
  2815.   app_str("\\mathrel+"); /*section name is multiply defined*/
  2816.   this_section=name_dir; /*so we won't give cross-reference info here*/
  2817. app_str("\\E"); /* output an equivalence sign */
  2818. @.\\E@>
  2819. app_str("{}$");
  2820. app(force); app_scrap(stmt,no_math);
  2821.  /* this forces a line break unless `\.{@@+}' follows */
  2822. @ @<Emit the scrap...@>=
  2823. if (next_control<section_name) {
  2824.   err_print("! You can't do that in C text");
  2825. @.You can't do that...@>
  2826.   next_control=get_next();
  2827. else if (next_control==section_name) {
  2828.   app(section_flag+cur_section-name_dir); app_scrap(section_scrap,maybe_math);
  2829.   next_control=get_next();
  2830. @ Cross references relating to a named section are given
  2831. after the section ends.
  2832. @<Show cross...@>=
  2833. if (this_section>name_dir) {
  2834.   cur_xref=(xref_pointer)this_section->xref;
  2835.   if (cur_xref->num==file_flag){an_output=1;cur_xref=cur_xref->xlink;}
  2836.   else an_output=0;
  2837.   if (cur_xref->num>def_flag)
  2838.     cur_xref=cur_xref->xlink; /* bypass current section number */
  2839.   footnote(def_flag); footnote(cite_flag); footnote(0);
  2840. @ The |footnote| procedure gives cross-reference information about
  2841. multiply defined section names (if the |flag| parameter is
  2842. |def_flag|), or about references to a section name
  2843. (if |flag==cite_flag|), or to its uses (if |flag==0|). It assumes that
  2844. |cur_xref| points to the first cross-reference entry of interest, and it
  2845. leaves |cur_xref| pointing to the first element not printed.  Typical outputs:
  2846. `\.{\\A101.}'; `\.{\\Us 370\\ET1009.}';
  2847. `\.{\\As 8, 27\\*\\ETs64.}'.
  2848. Note that the output of \.{CWEAVE} is not English-specific; users may
  2849. supply new definitions for the macros \.{\\A}, \.{\\As}, etc.
  2850. @c footnote(flag) /* outputs section cross-references */
  2851. sixteen_bits flag;
  2852.   xref_pointer q; /* cross-reference pointer variable */
  2853.   if (cur_xref->num<=flag) return;
  2854.   finish_line(); out('\\');
  2855. @.\\A@>
  2856. @.\\Q@>
  2857. @.\\U@>
  2858.   out(flag==0? 'U': flag==cite_flag? 'Q': 'A');
  2859.   @<Output all the section numbers on the reference list |cur_xref|@>;
  2860.   out('.');
  2861. @ The following code distinguishes three cases, according as the number
  2862. of cross-references is one, two, or more than two. Variable |q| points
  2863. to the first cross-reference, and the last link is a zero.
  2864. @<Output all the section numbers...@>=
  2865. q=cur_xref; if (q->xlink->num>flag) out('s'); /* plural */
  2866. while (1) {
  2867.   out_section(cur_xref->num-flag);
  2868.   cur_xref=cur_xref->xlink; /* point to the next cross-reference to output */
  2869.   if (cur_xref->num<=flag) break;
  2870.   if (cur_xref->xlink->num>flag) out_str(", "); /* not the last */
  2871.   else {out_str("\\ET"); /* the last */
  2872.   if (cur_xref != q->xlink) out('s'); /* the last of more than two */
  2873. @ @<Output the code for the end of a section@>=
  2874. out_str("\\fi"); finish_line();
  2875. @.\\fi@>
  2876. flush_buffer(out_buf,0,0); /* insert a blank line, it looks nice */
  2877. @* Phase three processing.
  2878. We are nearly finished! \.{WEAVE}'s only remaining task is to write out the
  2879. index, after sorting the identifiers and index entries.
  2880. If the user has set the |no_xref| flag (the |-x| option on the command line),
  2881. just finish off the page, omitting the index, section name list, and table of
  2882. contents.
  2883. @c phase_three() {
  2884. if (no_xref) {
  2885.   finish_line();
  2886.   out_str("\\vfill\\end");
  2887.   finish_line();
  2888. else {
  2889.   phase=3; if (show_progress) printf("\nWriting the index...");
  2890. @.Writing the index...@>
  2891.   if (change_exists) {
  2892.     finish_line(); @<Tell about changed sections@>;
  2893.   finish_line(); out_str("\\inx"); finish_line();
  2894. @.\\inx@>
  2895.   @<Do the first pass of sorting@>;
  2896.   @<Sort and output the index@>;
  2897.   out_str("\\fin"); finish_line();
  2898. @.\\fin@>
  2899.   @<Output all the section names@>;
  2900.   out_str("\\con"); finish_line();
  2901. @.\\con@>
  2902. if (show_happiness) printf("\nDone.");
  2903. check_complete(); /* was all of the change file used? */
  2904. @ Just before the index comes a list of all the changed sections, including
  2905. the index section itself.
  2906. @<Global...@>=
  2907. sixteen_bits k_section; /* runs through the sections */
  2908. @ @<Tell about changed sections@>= {
  2909.   /* remember that the index is already marked as changed */
  2910.   k_section=0;
  2911.   while (!changed_section[++k_section]);
  2912.   out_str("\\ch ");
  2913.   out_section(k_section);
  2914.   while (1) {
  2915.     while (!changed_section[++k_section]);
  2916.     out_str(", "); out_section(k_section);
  2917.     if (k_section==section_count) break;
  2918.   out('.');
  2919. @ A left-to-right radix sorting method is used, since this makes it easy to
  2920. adjust the collating sequence and since the running time will be at worst
  2921. proportional to the total length of all entries in the index. We put the
  2922. identifiers into 102 different lists based on their first characters.
  2923. (Uppercase letters are put into the same list as the corresponding lowercase
  2924. letters, since we want to have `$t<\\{TeX}<\&{to}$'.) The
  2925. list for character |c| begins at location |bucket[c]| and continues through
  2926. the |blink| array.
  2927. @<Global...@>=
  2928. name_pointer bucket[128];
  2929. name_pointer next_name; /* successor of |cur_name| when sorting */
  2930. hash_pointer h; /* index into |hash| */
  2931. name_pointer blink[max_names]; /* links in the buckets */
  2932. @ To begin the sorting, we go through all the hash lists and put each entry
  2933. having a nonempty cross-reference list into the proper bucket.
  2934. @<Do the first pass...@>= {
  2935. int c;
  2936. for (c=0; c<=127; c++) bucket[c]=NULL;
  2937. for (h=hash; h<=hash_end; h++) {
  2938.   next_name=*h;
  2939.   while (next_name) {
  2940.     cur_name=next_name; next_name=cur_name->link;
  2941.     if (cur_name->xref!=(char*)xmem) {
  2942.       c=(cur_name->byte_start)[0];
  2943.       if (isupper(c)) c=tolower(c);
  2944.       blink[cur_name-name_dir]=bucket[c]; bucket[c]=cur_name;
  2945.     }
  2946. @ During the sorting phase we shall use the |cat| and |trans| arrays from
  2947. \.{WEAVE}'s parsing algorithm and rename them |depth| and |head|. They now
  2948. represent a stack of identifier lists for all the index entries that have
  2949. not yet been output. The variable |sort_ptr| tells how many such lists are
  2950. present; the lists are output in reverse order (first |sort_ptr|, then
  2951. |sort_ptr-1|, etc.). The |j|th list starts at |head[j]|, and if the first
  2952. |k| characters of all entries on this list are known to be equal we have
  2953. |depth[j]=k|.
  2954. @ @<Rest of |trans_plus| union@>=
  2955. name_pointer Head;
  2956. @d depth cat /* reclaims memory that is no longer needed for parsing */
  2957. @d head trans_plus.Head /* ditto */
  2958. @f sort_pointer int
  2959. @d sort_pointer scrap_pointer /* ditto */
  2960. @d sort_ptr scrap_ptr /* ditto */
  2961. @d max_sorts max_scraps /* ditto */
  2962. @<Global...@>=
  2963. eight_bits cur_depth; /* depth of current buckets */
  2964. char *cur_byte; /* index into |byte_mem| */
  2965. sixteen_bits cur_val; /* current cross-reference number */
  2966. #ifdef STAT
  2967. sort_pointer max_sort_ptr; /* largest value of |sort_ptr| */
  2968. #endif /* |STAT| */
  2969. @ @<Set init...@>=
  2970. #ifdef STAT
  2971. max_sort_ptr=scrap_info;
  2972. #endif /* |STAT| */
  2973. @ The desired alphabetic order is specified by the |collate| array; namely,
  2974. |collate[0]<collate[1]<@t$\cdots$@><collate[100]|.
  2975. @<Global...@>=
  2976. char collate[102]; /* collation order */
  2977. @ We use the order $\hbox{null}<\.\ <\hbox{other characters}<{}$\.\_${}<
  2978. \.A=\.a<\cdots<\.Z=\.z<\.0<\cdots<\.9.$ Warning: The collation mapping
  2979. needs to be changed if ASCII code is not being used.
  2980. @^ASCII code dependencies@>
  2981. @<Set init...@>=
  2982. collate[0]=0; strcpy(collate+1," \1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\
  2983. \20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37\
  2984. !\42#$%&'()*+,-./:;<=>?@@[\\]^`{|}~_\
  2985. abcdefghijklmnopqrstuvwxyz0123456789");
  2986. @ Procedure |unbucket| goes through the buckets and adds nonempty lists
  2987. to the stack, using the collating sequence specified in the |collate| array.
  2988. The parameter to |unbucket| tells the current depth in the buckets.
  2989. Any two sequences that agree in their first 255 character positions are
  2990. regarded as identical.
  2991. @d infinity 255 /* $\infty$ (approximately) */
  2992. @c unbucket(d) /* empties buckets having depth |d| */
  2993. eight_bits d;
  2994.   int c;  /* index into |bucket|; cannot be a simple |char| because of sign
  2995.     comparison below*/
  2996.   for (c=100; c>= 0; c--) if (bucket[collate[c]]) {
  2997.     if (sort_ptr>=scrap_info_end) overflow("sorting");
  2998.     sort_ptr++;
  2999. #ifdef STAT
  3000.     if (sort_ptr>max_sort_ptr) max_sort_ptr=sort_ptr;
  3001. #endif /* |STAT| */
  3002.     if (c==0) sort_ptr->depth=infinity;
  3003.     else sort_ptr->depth=d;
  3004.     sort_ptr->head=bucket[collate[c]]; bucket[collate[c]]=NULL;
  3005. @ @<Sort and output...@>=
  3006. sort_ptr=scrap_info; unbucket(1);
  3007. while (sort_ptr>scrap_info) {
  3008.   cur_depth=sort_ptr->depth;
  3009.   if (blink[sort_ptr->head-name_dir]==0 || cur_depth==infinity)
  3010.     @<Output index entries for the list at |sort_ptr|@>@;
  3011.   else @<Split the list at |sort_ptr| into further lists@>;
  3012. @ @<Split the list...@>= {
  3013.   char c;
  3014.   next_name=sort_ptr->head;
  3015.   do {
  3016.     cur_name=next_name; next_name=blink[cur_name-name_dir];
  3017.     cur_byte=cur_name->byte_start+cur_depth;
  3018.     if (cur_byte==(cur_name+1)->byte_start) c=0; /* hit end of the name */
  3019.     else {
  3020.       c=*cur_byte;
  3021.       if (isupper(c)) c=tolower(c);
  3022.     }
  3023.   blink[cur_name-name_dir]=bucket[c]; bucket[c]=cur_name;
  3024.   } while (next_name);
  3025.   --sort_ptr; unbucket(cur_depth+1);
  3026. @ @<Output index...@>= {
  3027.   cur_name=sort_ptr->head;
  3028.   do {
  3029.     out_str("\\I");
  3030. @.\\I@>
  3031.     @<Output the name at |cur_name|@>;
  3032.     @<Output the cross-references at |cur_name|@>;
  3033.     cur_name=blink[cur_name-name_dir];
  3034.   } while (cur_name);
  3035.   --sort_ptr;
  3036. @ @<Output the name...@>=
  3037. switch (cur_name->ilk) {
  3038.   case normal: if (is_tiny(cur_name)) out_str("\\|");
  3039.     else {char *j;
  3040.       for (j=cur_name->byte_start;j<(cur_name+1)->byte_start;j++)
  3041.         if (islower(*j)) goto lowcase;
  3042.       out_str("\\."); break;
  3043. lowcase: out_str("\\\\");
  3044.     }
  3045.   break;
  3046. @.\\|@>
  3047. @.\\.@>
  3048. @.\\\\@>
  3049.   case roman: break;
  3050.   case wildcard: out_str("\\9"); break;
  3051. @.\\9@>
  3052.   case typewriter: out_str("\\."); break;
  3053. @.\\.@>
  3054.   case custom: case quoted: {char *j; out_str("$\\");
  3055.     for (j=cur_name->byte_start;j<(cur_name+1)->byte_start;j++)
  3056.       out(isxalpha(*j)? 'x' : *j);
  3057.     out('$');
  3058.     goto name_done;
  3059.     }
  3060.   default: out_str("\\&");
  3061. @.\\\&@>
  3062. out_name(cur_name);
  3063. name_done:
  3064. @ Section numbers that are to be underlined are enclosed in
  3065. `\.{\\[}$\,\ldots\,$\.]'.
  3066. @<Output the cross-references...@>=
  3067. @<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>;
  3068.   out_str(", "); cur_val=cur_xref->num;
  3069.   if (cur_val<def_flag) out_section(cur_val);
  3070.   else {out_str("\\["); out_section(cur_val-def_flag); out(']');}
  3071. @.\\[@>
  3072.   cur_xref=cur_xref->xlink;
  3073. } while (cur_xref!=xmem);
  3074. out('.'); finish_line();
  3075. @ List inversion is best thought of as popping elements off one stack and
  3076. pushing them onto another. In this case |cur_xref| will be the head of
  3077. the stack that we push things onto.
  3078. @<Global...@>=
  3079. xref_pointer next_xref, this_xref;
  3080.   /* pointer variables for rearranging a list */
  3081. @ @<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>=
  3082. this_xref=(xref_pointer)cur_name->xref; cur_xref=xmem;
  3083.   next_xref=this_xref->xlink; this_xref->xlink=cur_xref;
  3084.   cur_xref=this_xref; this_xref=next_xref;
  3085. } while (this_xref!=xmem);
  3086. @ The following recursive procedure walks through the tree of section names and
  3087. prints them.
  3088. @^recursion@>
  3089. @c section_print(p) /* print all section names in subtree |p| */
  3090. name_pointer p;
  3091.   if (p) {
  3092.     section_print(p->llink); out_str("\\I");
  3093. @.\\I@>
  3094.     tok_ptr=tok_mem+1; text_ptr=tok_start+1; scrap_ptr=scrap_info; init_stack;
  3095.     app(p-name_dir+section_flag); make_output();
  3096.     footnote(cite_flag);
  3097.     footnote(0); /* |cur_xref| was set by |make_output| */
  3098.     finish_line();@/
  3099.     section_print(p->rlink);
  3100. @ @<Output all the section names@>=section_print(root)
  3101. #ifdef STAT
  3102. print_stats() {
  3103.   printf("\nMemory usage statistics:\n");
  3104. @.Memory usage statistics:@>
  3105.   printf("%d names (out of %d)\n",name_ptr-name_dir,max_names);
  3106.   printf("%d cross-references (out of %d)\n",xref_ptr-xmem,max_refs);
  3107.   printf("%d bytes (out of %d)\n",byte_ptr-byte_mem,max_bytes);
  3108.   printf("Parsing:\n");
  3109.   printf("%d scraps (out of %d)\n",max_scr_ptr-scrap_info,max_scraps);
  3110.   printf("%d texts (out of %d)\n",max_text_ptr-tok_start,max_texts);
  3111.   printf("%d tokens (out of %d)\n",max_tok_ptr-tok_mem,max_toks);
  3112.   printf("%d levels (out of %d)\n",max_stack_ptr-stack,stack_size);
  3113.   printf("Sorting:\n");
  3114.   printf("%d levels (out of %d)\n",max_sort_ptr-scrap_info,max_scraps);
  3115. #endif /* |STAT| */
  3116. @* Index.
  3117. If you have read and understood the code for Phase III above, you know what
  3118. is in this index and how it got here. All sections in which an identifier is
  3119. used are listed with that identifier, except that reserved words are
  3120. indexed only when they appear in format definitions, and the appearances
  3121. of identifiers in section names are not indexed. Underlined entries
  3122. correspond to where the identifier was declared. Error messages, control
  3123. sequences put into the output, and a few
  3124. other things like ``recursion'' are indexed here too.
  3125.