home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / unixtex-6.1b-src.tgz / tar.out / contrib / unixtex / web2c / web / weave.web (.txt) < prev   
Encoding:
Texinfo Document  |  1996-09-28  |  182.9 KB  |  4,253 lines

  1. % This program by D. E. Knuth is not copyrighted and can be used freely.
  2. % Version 0 was released in December, 1981.
  3. % Version 1 was released in September, 1982, with version 0 of TeX.
  4. % Slight changes were made in October, 1982, for version 0.6 of TeX.
  5. % Version 1.1 changed "_" to "\_" if not within an identifier (November, 1982).
  6. % Version 1.2 added @@= and @@\ and marked changed modules (December, 1982).
  7. % Version 1.3 marked and indexed changed modules better (January, 1983).
  8. % Version 1.4 added "history" (February, 1983).
  9. % Version 1.5 conformed to TeX version 0.96 (March, 1983).
  10. % Version 1.6 conformed to TeX version 0.98 (May, 1983).
  11. % Version 1.7 introduced the new change file format (June, 1983).
  12. % Version 2 was released in July, 1983, with version 0.999 of TeX.
  13. % Version 2.1 corrected a bug in changed_module reckoning (August, 1983).
  14. % Version 2.2 corrected it better (August, 1983).
  15. % Version 2.3 starts the output with \input webmac (August, 1983).
  16. % Version 2.4 fixed a bug in compress(#) (September, 1983).
  17. % Version 2.5 cleared xrefswitch after module names (November, 1983).
  18. % Version 2.6 fixed a bug in declaration of trans array (January, 1984).
  19. % Version 2.7 fixed a bug in real constants (August, 1984).
  20. % Version 2.8 fixed a bug in change_buffer movement (August, 1985).
  21. % Version 2.9 increased max_refs and max_toks to 30000 each (January, 1987).
  22. % Version 3, for Sewell's book, fixed long-line bug in input_ln (March, 1989).
  23. % Version 3.1 fixed a bug for programs with only one module (April, 1989).
  24. % Version 4 was major change to allow 8-bit input (September, 1989).
  25. % Version 4.1, for Breitenlohner, avoids English-only output (March, 1990).
  26. % Version 4.2 conforms to ANSI standard for-loop rules (September, 1990).
  27. % Version 4.3 catches extra } in input (Breitenlohner, September, 1991).
  28. % Version 4.4 corrects changed_module logic, %-overflow (January, 1992).
  29. % Here is TeX material that gets inserted after \input webmac
  30. \def\hang{\hangindent 3em\indent\ignorespaces}
  31. \font\ninerm=cmr9
  32. \let\mc=\ninerm % medium caps for names like SAIL
  33. \def\PASCAL{Pascal}
  34. \def\pb{$\.|\ldots\.|$} % Pascal brackets (|...|)
  35. \def\v{\.{\char'174}} % vertical (|) in typewriter font
  36. \def\dleft{[\![} \def\dright{]\!]} % double brackets
  37. \mathchardef\RA="3221 % right arrow
  38. \mathchardef\BA="3224 % double arrow
  39. \def\({} % kludge for alphabetizing certain module names
  40. \def\title{WEAVE}
  41. \def\contentspagenumber{15} % should be odd
  42. \def\topofcontents{\null\vfill
  43.   \titlefalse % include headline on the contents page
  44.   \def\rheader{\mainfont Appendix D\hfil \contentspagenumber}
  45.   \centerline{\titlefont The {\ttitlefont WEAVE} processor}
  46.   \vskip 15pt
  47.   \centerline{(Version 4.4)}
  48.   \vfill}
  49. \pageno=\contentspagenumber \advance\pageno by 1
  50. @* Introduction.
  51. This program converts a \.{WEB} file to a \TeX\ file. It was written
  52. by D. E. Knuth in October, 1981; a somewhat similar {\mc SAIL} program had
  53. been developed in March, 1979, although the earlier program used a top-down
  54. parsing method that is quite different from the present scheme.
  55. The code uses a few features of the local \PASCAL\ compiler that may need
  56. to be changed in other installations:
  57. \yskip\item{1)} Case statements have a default.
  58. \item{2)} Input-output routines may need to be adapted for use with a particular
  59. character set and/or for printing messages on the user's terminal.
  60. \yskip\noindent
  61. These features are also present in the \PASCAL\ version of \TeX, where they
  62. are used in a similar (but more complex) way. System-dependent portions
  63. of \.{WEAVE} can be identified by looking at the entries for `system
  64. dependencies' in the index below.
  65. @!@^system dependencies@>
  66. The ``banner line'' defined here should be changed whenever \.{WEAVE}
  67. is modified.
  68. @d banner=='This is WEAVE, Version 4.4'
  69. @ The program begins with a fairly normal header, made up of pieces that
  70. @^system dependencies@>
  71. will mostly be filled in later. The \.{WEB} input comes from files |web_file|
  72. and |change_file|, and the \TeX\ output goes to file |tex_file|.
  73. If it is necessary to abort the job because of a fatal error, the program
  74. calls the `|jump_out|' procedure, which goes to the label |end_of_WEAVE|.
  75. @d end_of_WEAVE = 9999 {go here to wrap it up}
  76. @p @t\4@>@<Compiler directives@>@/
  77. program WEAVE(@!web_file,@!change_file,@!tex_file);
  78. label end_of_WEAVE; {go here to finish}
  79. const @<Constants in the outer block@>@/
  80. type @<Types in the outer block@>@/
  81. var @<Globals in the outer block@>@/
  82. @<Error handling procedures@>@/
  83. procedure initialize;
  84.   var @<Local variables for initialization@>@/
  85.   begin @<Set initial values@>@/
  86.   end;
  87. @ Some of this code is optional for use when debugging only;
  88. such material is enclosed between the delimiters |debug| and $|gubed|$.
  89. Other parts, delimited by |stat| and $|tats|$, are optionally included
  90. if statistics about \.{WEAVE}'s memory usage are desired.
  91. @d debug==@{ {change this to `$\\{debug}\equiv\null$' when debugging}
  92. @d gubed==@t@>@} {change this to `$\\{gubed}\equiv\null$' when debugging}
  93. @f debug==begin
  94. @f gubed==end
  95. @d stat==@{ {change this to `$\\{stat}\equiv\null$'
  96.   when gathering usage statistics}
  97. @d tats==@t@>@} {change this to `$\\{tats}\equiv\null$'
  98.   when gathering usage statistics}
  99. @f stat==begin
  100. @f tats==end
  101. @ The \PASCAL\ compiler used to develop this system has ``compiler
  102. directives'' that can appear in comments whose first character is a dollar sign.
  103. In production versions of \.{WEAVE} these directives tell the compiler that
  104. @^system dependencies@>
  105. it is safe to avoid range checks and to leave out the extra code it inserts
  106. for the \PASCAL\ debugger's benefit, although interrupts will occur if
  107. there is arithmetic overflow.
  108. @<Compiler directives@>=
  109. @{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
  110. @!debug @{@&$C+,D+@}@+ gubed {but turn everything on when debugging}
  111. @ Labels are given symbolic names by the following definitions. We insert
  112. the label `|exit|:' just before the `\ignorespaces|end|\unskip' of a
  113. procedure in which we have used the `|return|' statement defined below;
  114. the label `|restart|' is occasionally used at the very beginning of a
  115. procedure; and the label `|reswitch|' is occasionally used just prior to
  116. a \&{case} statement in which some cases change the conditions and we wish to
  117. branch to the newly applicable case.
  118. Loops that are set up with the \&{loop} construction defined below are
  119. commonly exited by going to `|done|' or to `|found|' or to `|not_found|',
  120. and they are sometimes repeated by going to `|continue|'.
  121. @d exit=10 {go here to leave a procedure}
  122. @d restart=20 {go here to start a procedure again}
  123. @d reswitch=21 {go here to start a case statement again}
  124. @d continue=22 {go here to resume a loop}
  125. @d done=30 {go here to exit a loop}
  126. @d found=31 {go here when you've found it}
  127. @d not_found=32 {go here when you've found something else}
  128. @ Here are some macros for common programming idioms.
  129. @d incr(#) == #:=#+1 {increase a variable by unity}
  130. @d decr(#) == #:=#-1 {decrease a variable by unity}
  131. @d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
  132. @d do_nothing == {empty statement}
  133. @d return == goto exit {terminate a procedure call}
  134. @f return == nil
  135. @f loop == xclause
  136. @ We assume that |case| statements may include a default case that applies
  137. if no matching label is found. Thus, we shall use constructions like
  138. @^system dependencies@>
  139. $$\vbox{\halign{#\hfil\cr
  140. |case x of|\cr
  141. 1: $\langle\,$code for $x=1\,\rangle$;\cr
  142. 3: $\langle\,$code for $x=3\,\rangle$;\cr
  143. |othercases| $\langle\,$code for |x<>1| and |x<>3|$\,\rangle$\cr
  144. |endcases|\cr}}$$
  145. since most \PASCAL\ compilers have plugged this hole in the language by
  146. incorporating some sort of default mechanism. For example, the compiler
  147. used to develop \.{WEB} and \TeX\ allows `|others|:' as a default label,
  148. and other \PASCAL s allow syntaxes like `\ignorespaces|else|\unskip' or
  149. `\&{otherwise}' or `\\{otherwise}:', etc. The definitions of |othercases|
  150. and |endcases| should be changed to agree with local conventions.
  151. (Of course, if no default mechanism is available, the |case| statements of
  152. this program must be extended by listing all remaining cases.)
  153. @d othercases == others: {default for cases not listed explicitly}
  154. @d endcases == @+end {follows the default case in an extended |case| statement}
  155. @f othercases == else
  156. @f endcases == end
  157. @ The following parameters are set big enough to handle \TeX, so they
  158. should be sufficient for most applications of \.{WEAVE}.
  159. @<Constants...@>=
  160. @!max_bytes=45000; {|1/ww| times the number of bytes in identifiers,
  161.   index entries, and module names; must be less than 65536}
  162. @!max_names=5000; {number of identifiers, index entries, and module names;
  163.   must be less than 10240}
  164. @!max_modules=2000;{greater than the total number of modules}
  165. @!hash_size=353; {should be prime}
  166. @!buf_size=100; {maximum length of input line}
  167. @!longest_name=400; {module names shouldn't be longer than this}
  168. @!long_buf_size=500; {|buf_size+longest_name|}
  169. @!line_length=80; {lines of \TeX\ output have at most this many characters,
  170.   should be less than 256}
  171. @!max_refs=30000; {number of cross references; must be less than 65536}
  172. @!max_toks=30000; {number of symbols in \PASCAL\ texts being parsed;
  173.   must be less than 65536}
  174. @!max_texts=2000; {number of phrases in \PASCAL\ texts being parsed;
  175.   must be less than 10240}
  176. @!max_scraps=1000; {number of tokens in \PASCAL\ texts being parsed}
  177. @!stack_size=200; {number of simultaneous output levels}
  178. @ A global variable called |history| will contain one of four values
  179. at the end of every run: |spotless| means that no unusual messages were
  180. printed; |harmless_message| means that a message of possible interest
  181. was printed but no serious errors were detected; |error_message| means that
  182. at least one error was found; |fatal_message| means that the program
  183. terminated abnormally. The value of |history| does not influence the
  184. behavior of the program; it is simply computed for the convenience
  185. of systems that might want to use such information.
  186. @d spotless=0 {|history| value for normal jobs}
  187. @d harmless_message=1 {|history| value when non-serious info was printed}
  188. @d error_message=2 {|history| value when an error was noted}
  189. @d fatal_message=3 {|history| value when we had to stop prematurely}
  190. @d mark_harmless==@t@>@+if history=spotless then history:=harmless_message
  191. @d mark_error==history:=error_message
  192. @d mark_fatal==history:=fatal_message
  193. @<Glob...@>=@!history:spotless..fatal_message; {how bad was this run?}
  194. @ @<Set init...@>=history:=spotless;
  195. @* The character set.
  196. One of the main goals in the design of \.{WEB} has been to make it readily
  197. portable between a wide variety of computers. Yet \.{WEB} by its very
  198. nature must use a greater variety of characters than most computer
  199. programs deal with, and character encoding is one of the areas in which
  200. existing machines differ most widely from each other.
  201. To resolve this problem, all input to \.{WEAVE} and \.{TANGLE} is
  202. converted to an internal eight-bit code that is essentially standard
  203. ASCII, the ``American Standard Code for Information Interchange.''
  204. The conversion is done immediately when each character is read in.
  205. Conversely, characters are converted from ASCII to the user's external
  206. representation just before they are output. (The original ASCII code
  207. was seven bits only; \.{WEB} now allows eight bits in an attempt to
  208. keep up with modern times.)
  209. Such an internal code is relevant to users of \.{WEB} only because it is
  210. the code used for preprocessed constants like \.{"A"}. If you are writing
  211. a program in \.{WEB} that makes use of such one-character constants, you
  212. should convert your input to ASCII form, like \.{WEAVE} and \.{TANGLE} do.
  213. Otherwise \.{WEB}'s internal coding scheme does not affect you.
  214. @^ASCII code@>
  215. Here is a table of the standard visible ASCII codes:
  216. $$\def\:{\char\count255\global\advance\count255 by 1}
  217. \count255='40
  218. \vbox{
  219. \hbox{\hbox to 40pt{\it\hfill0\/\hfill}%
  220. \hbox to 40pt{\it\hfill1\/\hfill}%
  221. \hbox to 40pt{\it\hfill2\/\hfill}%
  222. \hbox to 40pt{\it\hfill3\/\hfill}%
  223. \hbox to 40pt{\it\hfill4\/\hfill}%
  224. \hbox to 40pt{\it\hfill5\/\hfill}%
  225. \hbox to 40pt{\it\hfill6\/\hfill}%
  226. \hbox to 40pt{\it\hfill7\/\hfill}}
  227. \vskip 4pt
  228. \hrule
  229. \def\^{\vrule height 10.5pt depth 4.5pt}
  230. \halign{\hbox to 0pt{\hskip -24pt\O{#0}\hfill}&\^
  231. \hbox to 40pt{\tt\hfill#\hfill\^}&
  232. &\hbox to 40pt{\tt\hfill#\hfill\^}\cr
  233. 04&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  234. 05&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  235. 06&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  236. 07&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  237. 10&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  238. 11&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  239. 12&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  240. 13&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  241. 14&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  242. 15&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  243. 16&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  244. 17&\:&\:&\:&\:&\:&\:&\:\cr}
  245. \hrule width 280pt}$$
  246. (Actually, of course, code @'040 is an invisible blank space.)  Code @'136
  247. was once an upward arrow (\.{\char'13}), and code @'137 was
  248. once a left arrow (\.^^X), in olden times when the first draft
  249. of ASCII code was prepared; but \.{WEB} works with today's standard
  250. ASCII in which those codes represent circumflex and underline as shown.
  251. @<Types...@>=
  252. @!ASCII_code=0..255; {eight-bit numbers, a subrange of the integers}
  253. @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
  254. character sets were common, so it did not make provision for lowercase
  255. letters. Nowadays, of course, we need to deal with both capital and small
  256. letters in a convenient way, so \.{WEB} assumes that it is being used
  257. with a \PASCAL\ whose character set contains at least the characters of
  258. standard ASCII as listed above. Some \PASCAL\ compilers use the original
  259. name |char| for the data type associated with the characters in text files,
  260. while other \PASCAL s consider |char| to be a 64-element subrange of a larger
  261. data type that has some other name.
  262. In order to accommodate this difference, we shall use the name |text_char|
  263. to stand for the data type of the characters in the input and output
  264. files.  We shall also assume that |text_char| consists of the elements
  265. |chr(first_text_char)| through |chr(last_text_char)|, inclusive. The
  266. following definitions should be adjusted if necessary.
  267. @^system dependencies@>
  268. @d text_char == char {the data type of characters in text files}
  269. @d first_text_char=0 {ordinal number of the smallest element of |text_char|}
  270. @d last_text_char=255 {ordinal number of the largest element of |text_char|}
  271. @<Types...@>=
  272. @!text_file=packed file of text_char;
  273. @ The \.{WEAVE} and \.{TANGLE} processors convert between ASCII code and
  274. the user's external character set by means of arrays |xord| and |xchr|
  275. that are analogous to \PASCAL's |ord| and |chr| functions.
  276. @<Globals...@>=
  277. @!xord: array [text_char] of ASCII_code;
  278.   {specifies conversion of input characters}
  279. @!xchr: array [ASCII_code] of text_char;
  280.   {specifies conversion of output characters}
  281. @ If we assume that every system using \.{WEB} is able to read and write the
  282. visible characters of standard ASCII (although not necessarily using the
  283. ASCII codes to represent them), the following assignment statements initialize
  284. most of the |xchr| array properly, without needing any system-dependent
  285. changes. For example, the statement \.{xchr[@@\'101]:=\'A\'} that appears
  286. in the present \.{WEB} file might be encoded in, say, {\mc EBCDIC} code
  287. on the external medium on which it resides, but \.{TANGLE} will convert from
  288. this external code to ASCII and back again. Therefore the assignment
  289. statement \.{XCHR[65]:=\'A\'} will appear in the corresponding \PASCAL\ file,
  290. and \PASCAL\ will compile this statement so that |xchr[65]| receives the
  291. character \.A in the external (|char|) code. Note that it would be quite
  292. incorrect to say \.{xchr[@@\'101]:="A"}, because |"A"| is a constant of
  293. type |integer|, not |char|, and because we have $|"A"|=65$ regardless of
  294. the external character set.
  295. @<Set init...@>=
  296. xchr[@'40]:=' ';
  297. xchr[@'41]:='!';
  298. xchr[@'42]:='"';
  299. xchr[@'43]:='#';
  300. xchr[@'44]:='$';
  301. xchr[@'45]:='%';
  302. xchr[@'46]:='&';
  303. xchr[@'47]:='''';@/
  304. xchr[@'50]:='(';
  305. xchr[@'51]:=')';
  306. xchr[@'52]:='*';
  307. xchr[@'53]:='+';
  308. xchr[@'54]:=',';
  309. xchr[@'55]:='-';
  310. xchr[@'56]:='.';
  311. xchr[@'57]:='/';@/
  312. xchr[@'60]:='0';
  313. xchr[@'61]:='1';
  314. xchr[@'62]:='2';
  315. xchr[@'63]:='3';
  316. xchr[@'64]:='4';
  317. xchr[@'65]:='5';
  318. xchr[@'66]:='6';
  319. xchr[@'67]:='7';@/
  320. xchr[@'70]:='8';
  321. xchr[@'71]:='9';
  322. xchr[@'72]:=':';
  323. xchr[@'73]:=';';
  324. xchr[@'74]:='<';
  325. xchr[@'75]:='=';
  326. xchr[@'76]:='>';
  327. xchr[@'77]:='?';@/
  328. xchr[@'100]:='@@';
  329. xchr[@'101]:='A';
  330. xchr[@'102]:='B';
  331. xchr[@'103]:='C';
  332. xchr[@'104]:='D';
  333. xchr[@'105]:='E';
  334. xchr[@'106]:='F';
  335. xchr[@'107]:='G';@/
  336. xchr[@'110]:='H';
  337. xchr[@'111]:='I';
  338. xchr[@'112]:='J';
  339. xchr[@'113]:='K';
  340. xchr[@'114]:='L';
  341. xchr[@'115]:='M';
  342. xchr[@'116]:='N';
  343. xchr[@'117]:='O';@/
  344. xchr[@'120]:='P';
  345. xchr[@'121]:='Q';
  346. xchr[@'122]:='R';
  347. xchr[@'123]:='S';
  348. xchr[@'124]:='T';
  349. xchr[@'125]:='U';
  350. xchr[@'126]:='V';
  351. xchr[@'127]:='W';@/
  352. xchr[@'130]:='X';
  353. xchr[@'131]:='Y';
  354. xchr[@'132]:='Z';
  355. xchr[@'133]:='[';
  356. xchr[@'134]:='\';
  357. xchr[@'135]:=']';
  358. xchr[@'136]:='^';
  359. xchr[@'137]:='_';@/
  360. xchr[@'140]:='`';
  361. xchr[@'141]:='a';
  362. xchr[@'142]:='b';
  363. xchr[@'143]:='c';
  364. xchr[@'144]:='d';
  365. xchr[@'145]:='e';
  366. xchr[@'146]:='f';
  367. xchr[@'147]:='g';@/
  368. xchr[@'150]:='h';
  369. xchr[@'151]:='i';
  370. xchr[@'152]:='j';
  371. xchr[@'153]:='k';
  372. xchr[@'154]:='l';
  373. xchr[@'155]:='m';
  374. xchr[@'156]:='n';
  375. xchr[@'157]:='o';@/
  376. xchr[@'160]:='p';
  377. xchr[@'161]:='q';
  378. xchr[@'162]:='r';
  379. xchr[@'163]:='s';
  380. xchr[@'164]:='t';
  381. xchr[@'165]:='u';
  382. xchr[@'166]:='v';
  383. xchr[@'167]:='w';@/
  384. xchr[@'170]:='x';
  385. xchr[@'171]:='y';
  386. xchr[@'172]:='z';
  387. xchr[@'173]:='{';
  388. xchr[@'174]:='|';
  389. xchr[@'175]:='}';
  390. xchr[@'176]:='~';@/
  391. xchr[0]:=' '; xchr[@'177]:=' '; {these ASCII codes are not used}
  392. @ Some of the ASCII codes below @'40 have been given symbolic names in
  393. \.{WEAVE} and \.{TANGLE} because they are used with a special meaning.
  394. @d and_sign=@'4 {equivalent to `\.{and}'}
  395. @d not_sign=@'5 {equivalent to `\.{not}'}
  396. @d set_element_sign=@'6 {equivalent to `\.{in}'}
  397. @d tab_mark=@'11 {ASCII code used as tab-skip}
  398. @d line_feed=@'12 {ASCII code thrown away at end of line}
  399. @d form_feed=@'14 {ASCII code used at end of page}
  400. @d carriage_return=@'15 {ASCII code used at end of line}
  401. @d left_arrow=@'30 {equivalent to `\.{:=}'}
  402. @d not_equal=@'32 {equivalent to `\.{<>}'}
  403. @d less_or_equal=@'34 {equivalent to `\.{<=}'}
  404. @d greater_or_equal=@'35 {equivalent to `\.{>=}'}
  405. @d equivalence_sign=@'36 {equivalent to `\.{==}'}
  406. @d or_sign=@'37 {equivalent to `\.{or}'}
  407. @ When we initialize the |xord| array and the remaining parts of |xchr|,
  408. it will be convenient to make use of an index variable, |i|.
  409. @<Local variables for init...@>=
  410. @!i:0..255;
  411. @ Here now is the system-dependent part of the character set.
  412. If \.{WEB} is being implemented on a garden-variety \PASCAL\ for which
  413. only standard ASCII codes will appear in the input and output files, you
  414. don't need to make any changes here. But if you have, for example, an extended
  415. character set like the one in Appendix~C of {\sl The \TeX book}, the first
  416. line of code in this module should be changed to
  417. $$\hbox{|for i:=1 to @'37 do xchr[i]:=chr(i);|}$$
  418. \.{WEB}'s character set is essentially identical to \TeX's, even with respect to
  419. characters less than @'40.
  420. @^system dependencies@>
  421. Changes to the present module will make \.{WEB} more friendly on computers
  422. that have an extended character set, so that one can type things like
  423. \.^^Z\ instead of \.{<>}. If you have an extended set of characters that
  424. are easily incorporated into text files, you can assign codes arbitrarily
  425. here, giving an |xchr| equivalent to whatever characters the users of
  426. \.{WEB} are allowed to have in their input files, provided that unsuitable
  427. characters do not correspond to special codes like |carriage_return|
  428. that are listed above.
  429. (The present file \.{WEAVE.WEB} does not contain any of the non-ASCII
  430. characters, because it is intended to be used with all implementations of
  431. \.{WEB}.  It was originally created on a Stanford system that has a
  432. convenient extended character set, then ``sanitized'' by applying another
  433. program that transliterated all of the non-standard characters into
  434. standard equivalents.)
  435. @<Set init...@>=
  436. for i:=1 to @'37 do xchr[i]:=' ';
  437. for i:=@'200 to @'377 do xchr[i]:=' ';
  438. @ The following system-independent code makes the |xord| array contain a
  439. suitable inverse to the information in |xchr|.
  440. @<Set init...@>=
  441. for i:=first_text_char to last_text_char do xord[chr(i)]:=" ";
  442. for i:=1 to @'377 do xord[xchr[i]]:=i;
  443. xord[' ']:=" ";
  444. @* Input and output.
  445. The input conventions of this program are intended to be very much like those
  446. of \TeX\ (except, of course, that they are much simpler, because much less
  447. needs to be done). Furthermore they are identical to those of \.{TANGLE}.
  448. Therefore people who need to make modifications to all three systems
  449. should be able to do so without too many headaches.
  450. We use the standard \PASCAL\ input/output procedures in several places that
  451. \TeX\ cannot, since \.{WEAVE} does not have to deal with files that are named
  452. dynamically by the user, and since there is no input from the terminal.
  453. @ Terminal output is done by writing on file |term_out|, which is assumed to
  454. consist of characters of type |text_char|:
  455. @^system dependencies@>
  456. @d print(#)==write(term_out,#) {`|print|' means write on the terminal}
  457. @d print_ln(#)==write_ln(term_out,#) {`|print|' and then start new line}
  458. @d new_line==write_ln(term_out) {start new line}
  459. @d print_nl(#)==  {print information starting on a new line}
  460.   begin new_line; print(#);
  461.   end
  462. @<Globals...@>=
  463. @!term_out:text_file; {the terminal as an output file}
  464. @ Different systems have different ways of specifying that the output on a
  465. certain file will appear on the user's terminal. Here is one way to do this
  466. on the \PASCAL\ system that was used in \.{TANGLE}'s initial development:
  467. @^system dependencies@>
  468. @<Set init...@>=
  469. rewrite(term_out,'TTY:'); {send |term_out| output to the terminal}
  470. @ The |update_terminal| procedure is called when we want
  471. to make sure that everything we have output to the terminal so far has
  472. actually left the computer's internal buffers and been sent.
  473. @^system dependencies@>
  474. @d update_terminal == break(term_out) {empty the terminal output buffer}
  475. @ The main input comes from |web_file|; this input may be overridden
  476. by changes in |change_file|. (If |change_file| is empty, there are no changes.)
  477. @<Globals...@>=
  478. @!web_file:text_file; {primary input}
  479. @!change_file:text_file; {updates}
  480. @ The following code opens the input files.  Since these files were listed
  481. in the program header, we assume that the \PASCAL\ runtime system has
  482. already checked that suitable file names have been given; therefore no
  483. additional error checking needs to be done. We will see below that
  484. \.{WEAVE} reads through the entire input twice.
  485. @^system dependencies@>
  486. @p procedure open_input; {prepare to read |web_file| and |change_file|}
  487. begin reset(web_file); reset(change_file);
  488. @ The main output goes to |tex_file|.
  489. @<Globals...@>=
  490. @!tex_file: text_file;
  491. @ The following code opens |tex_file|.
  492. Since this file was listed in the program header, we assume that the
  493. \PASCAL\ runtime system has checked that a suitable external file name has
  494. been given.
  495. @^system dependencies@>
  496. @<Set init...@>=
  497. rewrite(tex_file);
  498. @ Input goes into an array called |buffer|.
  499. @<Globals...@>=@!buffer: array[0..long_buf_size] of ASCII_code;
  500. @ The |input_ln| procedure brings the next line of input from the specified
  501. file into the |buffer| array and returns the value |true|, unless the file has
  502. already been entirely read, in which case it returns |false|. The conventions
  503. of \TeX\ are followed; i.e., |ASCII_code| numbers representing the next line
  504. of the file are input into |buffer[0]|, |buffer[1]|, \dots,
  505. |buffer[limit-1]|; trailing blanks are ignored;
  506. and the global variable |limit| is set to the length of the
  507. @^system dependencies@>
  508. line. The value of |limit| must be strictly less than |buf_size|.
  509. We assume that none of the |ASCII_code| values
  510. of |buffer[j]| for |0<=j<limit| is equal to 0, @'177, |line_feed|, |form_feed|,
  511. or |carriage_return|. Since |buf_size| is strictly less than |long_buf_size|,
  512. some of \.{WEAVE}'s routines use the fact that it is safe to refer to
  513. |buffer[limit+2]| without overstepping the bounds of the array.
  514. @p function input_ln(var f:text_file):boolean;
  515.   {inputs a line or returns |false|}
  516. var final_limit:0..buf_size; {|limit| without trailing blanks}
  517. begin limit:=0; final_limit:=0;
  518. if eof(f) then input_ln:=false
  519. else  begin while not eoln(f) do
  520.     begin buffer[limit]:=xord[f^]; get(f);
  521.     incr(limit);
  522.     if buffer[limit-1]<>" " then final_limit:=limit;
  523.     if limit=buf_size then
  524.       begin while not eoln(f) do get(f);
  525.       decr(limit); {keep |buffer[buf_size]| empty}
  526.       if final_limit>limit then final_limit:=limit;
  527.       print_nl('! Input line too long'); loc:=0; error;
  528. @.Input line too long@>
  529.       end;
  530.     end;
  531.   read_ln(f); limit:=final_limit; input_ln:=true;
  532.   end;
  533. @* Reporting errors to the user.
  534. The \.{WEAVE} processor operates in three phases: first it inputs the source
  535. file and stores cross-reference data, then it inputs the source once again and
  536. produces the \TeX\ output file, and finally it sorts and outputs the index.
  537. The global variables |phase_one| and |phase_three| tell which Phase we are in.
  538. @<Globals...@>=
  539. @!phase_one: boolean; {|true| in Phase I, |false| in Phases II and III}
  540. @!phase_three: boolean; {|true| in Phase III, |false| in Phases I and II}
  541. @ If an error is detected while we are debugging,
  542. we usually want to look at the contents of memory.
  543. A special procedure will be declared later for this purpose.
  544. @<Error handling...@>=
  545. @!debug@+ procedure debug_help; forward;@+gubed
  546. @ The command `|err_print('! Error message')|' will report a syntax error to
  547. the user, by printing the error message at the beginning of a new line and
  548. then giving an indication of where the error was spotted in the source file.
  549. Note that no period follows the error message, since the error routine
  550. will automatically supply a period.
  551. The actual error indications are provided by a procedure called |error|.
  552. However, error messages are not actually reported during phase one,
  553. since errors detected on the first pass will be detected again
  554. during the second.
  555. @d err_print(#)==
  556.   begin if not phase_one then
  557.     begin new_line; print(#); error;
  558.     end;
  559.   end
  560. @<Error handling...@>=
  561. procedure error; {prints `\..' and location of error message}
  562. var@!k,@!l: 0..long_buf_size; {indices into |buffer|}
  563. begin @<Print error location based on input buffer@>;
  564. update_terminal; mark_error;
  565. @!debug debug_skipped:=debug_cycle;debug_help;@+gubed
  566. @ The error locations can be indicated by using the global variables
  567. |loc|, |line|, and |changing|, which tell respectively the first
  568. unlooked-at position in |buffer|, the current line number, and whether or not
  569. the current line is from |change_file| or |web_file|.
  570. This routine should be modified on systems whose standard text editor
  571. has special line-numbering conventions.
  572. @^system dependencies@>
  573. @<Print error location based on input buffer@>=
  574. begin if changing then print('. (change file ')@+else print('. (');
  575. print_ln('l.', line:1, ')');
  576. if loc>=limit then l:=limit else l:=loc;
  577. for k:=1 to l do
  578.   if buffer[k-1]=tab_mark then print(' ')
  579.   else print(xchr[buffer[k-1]]); {print the characters already read}
  580. new_line;
  581. for k:=1 to l do print(' '); {space out the next line}
  582. for k:=l+1 to limit do print(xchr[buffer[k-1]]); {print the part not yet read}
  583. if buffer[limit]="|" then print(xchr["|"]);
  584.   {end of \PASCAL\ text in module names}
  585. print(' '); {this space separates the message from future asterisks}
  586. @ The |jump_out| procedure just cuts across all active procedure levels
  587. and jumps out of the program. This is the only non-local \&{goto} statement
  588. in \.{WEAVE}. It is used when no recovery from a particular error has
  589. been provided.
  590. Some \PASCAL\ compilers do not implement non-local |goto| statements.
  591. @^system dependencies@>
  592. In such cases the code that appears at label |end_of_WEAVE| should be
  593. copied into the |jump_out| procedure, followed by a call to a system procedure
  594. that terminates the program.
  595. @d fatal_error(#)==begin new_line; print(#); error; mark_fatal; jump_out;
  596.   end
  597. @<Error handling...@>=
  598. procedure jump_out;
  599. begin goto end_of_WEAVE;
  600. @ Sometimes the program's behavior is far different from what it should be,
  601. and \.{WEAVE} prints an error message that is really for the \.{WEAVE}
  602. maintenance person, not the user. In such cases the program says
  603. |confusion('indication of where we are')|.
  604. @d confusion(#)==fatal_error('! This can''t happen (',#,')')
  605. @.This can't happen@>
  606. @ An overflow stop occurs if \.{WEAVE}'s tables aren't large enough.
  607. @d overflow(#)==fatal_error('! Sorry, ',#,' capacity exceeded')
  608. @.Sorry, x capacity exceeded@>
  609. @* Data structures.
  610. During the first phase of its processing, \.{WEAVE} puts identifier names,
  611. index entries, and module names into the large |byte_mem| array, which is
  612. packed with eight-bit integers. Allocation is sequential, since names are
  613. never deleted.
  614. An auxiliary array |byte_start| is used as a directory for |byte_mem|,
  615. and the |link|, |ilk|, and |xref| arrays give further information about names.
  616. These auxiliary arrays consist of sixteen-bit items.
  617. @<Types...@>=
  618. @!eight_bits=0..255; {unsigned one-byte quantity}
  619. @!sixteen_bits=0..65535; {unsigned two-byte quantity}
  620. @ \.{WEAVE} has been designed to avoid the need for indices that are more
  621. than sixteen bits wide, so that it can be used on most computers. But
  622. there are programs that need more than 65536 bytes; \TeX\ is one of these.
  623. To get around this problem, a slight complication has been added to the
  624. data structures:  |byte_mem| is a two-dimensional array, whose first index
  625. is either 0 or 1. (For generality, the first index is actually allowed to
  626. run between 0 and |ww-1|, where |ww| is defined to be 2; the program will
  627. work for any positive value of |ww|, and it can be simplified in obvious
  628. ways if |ww=1|.)
  629. @d ww=2 {we multiply the byte capacity by approximately this amount}
  630. @<Globals...@>=
  631. @!byte_mem: packed array [0..ww-1,0..max_bytes] of ASCII_code;
  632.   {characters of names}
  633. @!byte_start: array [0..max_names] of sixteen_bits; {directory into |byte_mem|}
  634. @!link: array [0..max_names] of sixteen_bits; {hash table or tree links}
  635. @!ilk: array [0..max_names] of sixteen_bits; {type codes or tree links}
  636. @!xref: array [0..max_names] of sixteen_bits; {heads of cross-reference lists}
  637. @ The names of identifiers are found by computing a hash address |h| and
  638. then looking at strings of bytes signified by |hash[h]|, |link[hash[h]]|,
  639. |link[link[hash[h]]]|, \dots, until either finding the desired name
  640. or encountering a zero.
  641. A `|name_pointer|' variable, which signifies a name, is an index into
  642. |byte_start|. The actual sequence of characters in the name pointed to by
  643. |p| appears in positions |byte_start[p]| to |byte_start[p+ww]-1|, inclusive,
  644. in the segment of |byte_mem| whose first index is |p mod ww|. Thus, when
  645. |ww=2| the even-numbered name bytes appear in |byte_mem[0,@t$*$@>]|
  646. and the odd-numbered ones appear in |byte_mem[1,@t$*$@>]|.
  647. The pointer 0 is used for undefined module names; we don't
  648. want to use it for the names of identifiers, since 0 stands for a null
  649. pointer in a linked list.
  650. We usually have |byte_start[name_ptr+w]=byte_ptr[(name_ptr+w) mod ww]|
  651. for |0<=w<ww|, since these are the starting positions for the next |ww|
  652. names to be stored in |byte_mem|.
  653. @d length(#)==byte_start[#+ww]-byte_start[#] {the length of a name}
  654. @<Types...@>=
  655. @!name_pointer=0..max_names; {identifies a name}
  656. @ @<Global...@>=
  657. @!name_ptr:name_pointer; {first unused position in |byte_start|}
  658. @!byte_ptr:array [0..ww-1] of 0..max_bytes;
  659.   {first unused position in |byte_mem|}
  660. @ @<Local variables for init...@>=
  661. @!wi: 0..ww-1; {to initialize the |byte_mem| indices}
  662. @ @<Set init...@>=
  663. for wi:=0 to ww-1 do
  664.   begin byte_start[wi]:=0; byte_ptr[wi]:=0;
  665.   end;
  666. byte_start[ww]:=0; {this makes name 0 of length zero}
  667. name_ptr:=1;
  668. @ Several types of identifiers are distinguished by their |ilk|:
  669. \yskip\hang |normal| identifiers are part of the \PASCAL\ program and
  670. will appear in italic type.
  671. \yskip\hang |roman| identifiers are index entries that appear after
  672. \.{@@\^} in the \.{WEB} file.
  673. \yskip\hang |wildcard| identifiers are index entries that appear after
  674. \.{@@:} in the \.{WEB} file.
  675. \yskip\hang |typewriter| identifiers are index entries that appear after
  676. \.{@@.} in the \.{WEB} file.
  677. \yskip\hang |array_like|, |begin_like|, \dots, |var_like|
  678. identifiers are \PASCAL\ reserved words whose |ilk| explains how they are
  679. to be treated when \PASCAL\ code is being formatted.
  680. \yskip\hang Finally, if |c| is an ASCII code, an |ilk| equal to
  681. |char_like+c| denotes a reserved word that will be converted to character
  682. @d normal=0 {ordinary identifiers have |normal| ilk}
  683. @d roman=1 {normal index entries have |roman| ilk}
  684. @d wildcard=2 {user-formatted index entries have |wildcard| ilk}
  685. @d typewriter=3 {`typewriter type' entries have |typewriter| ilk}
  686. @d reserved(#)==(ilk[#]>typewriter) {tells if a name is a reserved word}
  687. @d array_like=4 {\&{array}, \&{file}, \&{set}}
  688. @d begin_like=5 {\&{begin}}
  689. @d case_like=6 {\&{case}}
  690. @d const_like=7 {\&{const}, \&{label}, \&{type}}
  691. @d div_like=8 {\&{div}, \&{mod}}
  692. @d do_like=9 {\&{do}, \&{of}, \&{then}}
  693. @d else_like=10 {\&{else}}
  694. @d end_like=11 {\&{end}}
  695. @d for_like=12 {\&{for}, \&{while}, \&{with}}
  696. @d goto_like=13 {\&{goto}, \&{packed}}
  697. @d if_like=14 {\&{if}}
  698. @d in_like=15 {\&{in}}
  699. @d nil_like=16 {\&{nil}}
  700. @d proc_like=17 {\&{function}, \&{procedure}, \&{program}}
  701. @d record_like=18 {\&{record}}
  702. @d repeat_like=19 {\&{repeat}}
  703. @d to_like=20 {\&{downto}, \&{to}}
  704. @d until_like=21 {\&{until}}
  705. @d var_like=22 {\&{var}}
  706. @d loop_like=23 {\&{loop}, \&{xclause}}
  707. @d char_like=24 {\&{and}, \&{or}, \&{not}, \&{in}}
  708. @ The names of modules are stored in |byte_mem| together
  709. with the identifier names, but a hash table is not used for them because
  710. \.{WEAVE} needs to be able to recognize a module name when given a prefix of
  711. that name. A conventional binary seach tree is used to retrieve module names,
  712. with fields called |llink| and |rlink| in place of |link| and |ilk|. The
  713. root of this tree is |rlink[0]|.
  714. @d llink==link {left link in binary search tree for module names}
  715. @d rlink==ilk {right link in binary search tree for module names}
  716. @d root==rlink[0] {the root of the binary search tree for module names}
  717. @<Set init...@>=
  718. root:=0; {the binary search tree starts out with nothing in it}
  719. @ Here is a little procedure that prints the text of a given name on the
  720. user's terminal.
  721. @p procedure print_id(@!p:name_pointer); {print identifier or module name}
  722. var k:0..max_bytes; {index into |byte_mem|}
  723. @!w:0..ww-1; {row of |byte_mem|}
  724. begin if p>=name_ptr then print('IMPOSSIBLE')
  725. else  begin w:=p mod ww;
  726.   for k:=byte_start[p] to byte_start[p+ww]-1 do
  727.     print(xchr[byte_mem[w,k]]);
  728.   end;
  729. @ We keep track of the current module number in
  730. |module_count|, which is the total number of modules that have started.
  731. Modules which have been altered by a change file entry
  732. have their |changed_module| flag turned on during the first phase.
  733. @<Globals...@>=
  734. @!module_count:0..max_modules; {the current module number}
  735. @!changed_module: packed array [0..max_modules] of boolean; {is it changed?}
  736. @!change_exists: boolean; {has any module changed?}
  737. @ The other large memory area in \.{WEAVE} keeps the cross-reference data.
  738. All uses of the name |p| are recorded in a linked list beginning at
  739. |xref[p]|, which points into the |xmem| array. Entries in |xmem| consist
  740. of two sixteen-bit items per word, called the |num| and |xlink| fields.
  741. If |x| is an index into |xmem|, reached from name |p|, the value of |num(x)|
  742. is either a module number where |p| is used, or it is |def_flag| plus a
  743. module number where |p| is defined; and |xlink(x)| points to the next such
  744. cross reference for |p|, if any. This list of cross references is in
  745. decreasing order by module number. The current number of cross references
  746. is |xref_ptr|.
  747. The global variable |xref_switch| is set either to |def_flag| or to zero,
  748. depending on whether the next cross reference to an identifier is to be
  749. underlined or not in the index. This switch is set to |def_flag| when
  750. \.{@@!} or \.{@@d} or \.{@@f} is scanned, and it is cleared to zero when
  751. the next identifier or index entry cross reference has been made. Similarly,
  752. the global variable |mod_xref_switch| is either |def_flag| or zero, depending
  753. on whether a module name is being defined or used.
  754. @d num(#)==xmem[#].num_field
  755. @d xlink(#)==xmem[#].xlink_field
  756. @d def_flag=10240 {must be strictly larger than |max_modules|}
  757. @ @<Types...@>=
  758. @!xref_number=0..max_refs;
  759. @ @<Globals...@>=
  760. @!xmem:array[xref_number] of packed record@t@>@/
  761.   @!num_field: sixteen_bits; {module number plus zero or |def_flag|}
  762.   @!xlink_field: sixteen_bits; {pointer to the previous cross reference}
  763.   end;
  764. @!xref_ptr:xref_number; {the largest occupied position in |xmem|}
  765. @!xref_switch,@!mod_xref_switch:0..def_flag; {either zero or |def_flag|}
  766. @ @<Set init...@>=xref_ptr:=0; xref_switch:=0; mod_xref_switch:=0; num(0):=0;
  767. xref[0]:=0; {cross references to undefined modules}
  768. @ A new cross reference for an identifier is formed by calling |new_xref|,
  769. which discards duplicate entries and ignores non-underlined references
  770. to one-letter identifiers or \PASCAL's reserved words.
  771. @d append_xref(#)==if xref_ptr=max_refs then overflow('cross reference')
  772.   else  begin incr(xref_ptr); num(xref_ptr):=#;
  773.     end
  774. @p procedure new_xref(@!p:name_pointer);
  775. label exit;
  776. var q:xref_number; {pointer to previous cross reference}
  777. @!m,@!n: sixteen_bits; {new and previous cross-reference value}
  778. begin if (reserved(p)or(byte_start[p]+1=byte_start[p+ww]))and
  779.   (xref_switch=0) then return;
  780. m:=module_count+xref_switch; xref_switch:=0; q:=xref[p];
  781. if q>0 then
  782.   begin n:=num(q);
  783.   if (n=m)or(n=m+def_flag) then return
  784.   else if m=n+def_flag then
  785.     begin num(q):=m; return;
  786.     end;
  787.   end;
  788. append_xref(m); xlink(xref_ptr):=q; xref[p]:=xref_ptr;
  789. exit: end;
  790. @ The cross reference lists for module names are slightly different. Suppose
  791. that a module name is defined in modules $m_1$, \dots, $m_k$ and used in
  792. modules $n_1$, \dots, $n_l$. Then its list will contain $m_1+|def_flag|$,
  793. $m_k+|def_flag|$, \dots, $m_2+|def_flag|$, $n_l$, \dots, $n_1$, in
  794. this order.  After Phase II, however, the order will be
  795. $m_1+|def_flag|$, \dots, $m_k+|def_flag|$, $n_1$, \dots, $n_l$.
  796. @p procedure new_mod_xref(@!p:name_pointer);
  797. var q,@!r:xref_number; {pointers to previous cross references}
  798. begin q:=xref[p]; r:=0;
  799. if q>0 then
  800.   begin if mod_xref_switch=0 then while num(q)>=def_flag do
  801.     begin r:=q; q:=xlink(q);
  802.     end
  803.   else if num(q)>=def_flag then
  804.     begin r:=q; q:=xlink(q);
  805.     end;
  806.   end;
  807. append_xref(module_count+mod_xref_switch); xlink(xref_ptr):=q;
  808. mod_xref_switch:=0;
  809. if r=0 then xref[p]:=xref_ptr
  810. else xlink(r):=xref_ptr;
  811. @ A third large area of memory is used for sixteen-bit `tokens', which appear
  812. in short lists similar to the strings of characters in |byte_mem|. Token lists
  813. are used to contain the result of \PASCAL\ code translated into \TeX\ form;
  814. further details about them will be explained later. A |text_pointer| variable
  815. is an index into |tok_start|.
  816. @<Types...@>=
  817. @!text_pointer=0..max_texts; {identifies a token list}
  818. @ The first position of |tok_mem|
  819. that is unoccupied by replacement text is called |tok_ptr|, and the first
  820. unused location of |tok_start| is called |text_ptr|.
  821. Thus, we usually have |tok_start[text_ptr]=tok_ptr|.
  822. @<Glob...@>=
  823. @t\hskip1em@>@!tok_mem: packed array [0..max_toks] of sixteen_bits; {tokens}
  824. @t\hskip1em@>@!tok_start: array [text_pointer] of sixteen_bits;
  825.   {directory into |tok_mem|}
  826. @t\hskip1em@>@!text_ptr:text_pointer; {first unused position in |tok_start|}
  827. @t\hskip1em@>@!tok_ptr:0..max_toks; {first unused position in |tok_mem|}
  828. stat@!max_tok_ptr,@!max_txt_ptr:0..max_toks; {largest values occurring}
  829. @ @<Set init...@>=
  830. tok_ptr:=1; text_ptr:=1; tok_start[0]:=1; tok_start[1]:=1;
  831. stat max_tok_ptr:=1; max_txt_ptr:=1;@+tats
  832. @* Searching for identifiers.
  833. The hash table described above is updated by the |id_lookup| procedure,
  834. which finds a given identifier and returns a pointer to its index in
  835. |byte_start|. The identifier is supposed to match character by character
  836. and it is also supposed to have a given |ilk| code; the same name may be
  837. present more than once if it is supposed to appear in the index with
  838. different typesetting conventions.
  839. If the identifier was not already present, it is inserted into the table.
  840. Because of the way \.{WEAVE}'s scanning mechanism works, it is most convenient
  841. to let |id_lookup| search for an identifier that is present in the |buffer|
  842. array. Two other global variables specify its position in the buffer: the
  843. first character is |buffer[id_first]|, and the last is |buffer[id_loc-1]|.
  844. @<Glob...@>=
  845. @!id_first:0..long_buf_size; {where the current identifier begins in the buffer}
  846. @!id_loc:0..long_buf_size; {just after the current identifier in the buffer}
  847. @!hash:array [0..hash_size] of sixteen_bits; {heads of hash lists}
  848. @ Initially all the hash lists are empty.
  849. @<Local variables for init...@>=
  850. @!h:0..hash_size; {index into hash-head array}
  851. @ @<Set init...@>=
  852. for h:=0 to hash_size-1 do hash[h]:=0;
  853. @ Here now is the main procedure for finding identifiers (and index
  854. entries).  The parameter |t| is set to the desired |ilk| code. The
  855. identifier must either have |ilk=t|, or we must have
  856. |t=normal| and the identifier must be a reserved word.
  857. @p function id_lookup(@!t:eight_bits):name_pointer; {finds current identifier}
  858. label found;
  859. var i:0..long_buf_size; {index into |buffer|}
  860. @!h:0..hash_size; {hash code}
  861. @!k:0..max_bytes; {index into |byte_mem|}
  862. @!w:0..ww-1; {row of |byte_mem|}
  863. @!l:0..long_buf_size; {length of the given identifier}
  864. @!p:name_pointer; {where the identifier is being sought}
  865. begin l:=id_loc-id_first; {compute the length}
  866. @<Compute the hash code |h|@>;
  867. @<Compute the name location |p|@>;
  868. if p=name_ptr then @<Enter a new name into the table at position |p|@>;
  869. id_lookup:=p;
  870. @ A simple hash code is used: If the sequence of
  871. ASCII codes is $c_1c_2\ldots c_m$, its hash value will be
  872. $$(2^{n-1}c_1+2^{n-2}c_2+\cdots+c_n)\,\bmod\,|hash_size|.$$
  873. @<Compute the hash...@>=
  874. h:=buffer[id_first]; i:=id_first+1;
  875. while i<id_loc do
  876.   begin h:=(h+h+buffer[i]) mod hash_size; incr(i);
  877.   end
  878. @ If the identifier is new, it will be placed in position |p=name_ptr|,
  879. otherwise |p| will point to its existing location.
  880. @<Compute the name location...@>=
  881. p:=hash[h];
  882. while p<>0 do
  883.   begin if (length(p)=l)and((ilk[p]=t)or((t=normal)and reserved(p))) then
  884.     @<Compare name |p| with current identifier,
  885.       |goto found| if equal@>;
  886.   p:=link[p];
  887.   end;
  888. p:=name_ptr; {the current identifier is new}
  889. link[p]:=hash[h]; hash[h]:=p; {insert |p| at beginning of hash list}
  890. found:
  891. @ @<Compare name |p|...@>=
  892. begin i:=id_first; k:=byte_start[p]; w:=p mod ww;
  893. while (i<id_loc)and(buffer[i]=byte_mem[w,k]) do
  894.   begin incr(i); incr(k);
  895.   end;
  896. if i=id_loc then goto found; {all characters agree}
  897. @ When we begin the following segment of the program, |p=name_ptr|.
  898. @<Enter a new name...@>=
  899. begin w:=name_ptr mod ww;
  900. if byte_ptr[w]+l>max_bytes then overflow('byte memory');
  901. if name_ptr+ww>max_names then overflow('name');
  902. i:=id_first; k:=byte_ptr[w]; {get ready to move the identifier into |byte_mem|}
  903. while i<id_loc do
  904.   begin byte_mem[w,k]:=buffer[i]; incr(k); incr(i);
  905.   end;
  906. byte_ptr[w]:=k; byte_start[name_ptr+ww]:=k; incr(name_ptr);
  907. ilk[p]:=t; xref[p]:=0;
  908. @* Initializing the table of reserved words.
  909. We have to get \PASCAL's reserved words into the hash table, and the
  910. simplest way to do this is to insert them every time \.{WEAVE} is run.
  911. A few macros permit us to do the initialization with a compact program.
  912. @d sid9(#)==buffer[9]:=#;cur_name:=id_lookup
  913. @d sid8(#)==buffer[8]:=#;sid9
  914. @d sid7(#)==buffer[7]:=#;sid8
  915. @d sid6(#)==buffer[6]:=#;sid7
  916. @d sid5(#)==buffer[5]:=#;sid6
  917. @d sid4(#)==buffer[4]:=#;sid5
  918. @d sid3(#)==buffer[3]:=#;sid4
  919. @d sid2(#)==buffer[2]:=#;sid3
  920. @d sid1(#)==buffer[1]:=#;sid2
  921. @d id2==id_first:=8; sid8
  922. @d id3==id_first:=7; sid7
  923. @d id4==id_first:=6; sid6
  924. @d id5==id_first:=5; sid5
  925. @d id6==id_first:=4; sid4
  926. @d id7==id_first:=3; sid3
  927. @d id8==id_first:=2; sid2
  928. @d id9==id_first:=1; sid1
  929. @<Globals...@>=
  930. @!cur_name:name_pointer; {points to the identifier just inserted}
  931. @ The intended use of the macros above might not be immediately obvious,
  932. but the riddle is answered by the following:
  933. @<Store all the reserved words@>=
  934. id_loc:=10;@/
  935. id3("a")("n")("d")(char_like+and_sign);@/
  936. id5("a")("r")("r")("a")("y")(array_like);@/
  937. id5("b")("e")("g")("i")("n")(begin_like);@/
  938. id4("c")("a")("s")("e")(case_like);@/
  939. id5("c")("o")("n")("s")("t")(const_like);@/
  940. id3("d")("i")("v")(div_like);@/
  941. id2("d")("o")(do_like);@/
  942. id6("d")("o")("w")("n")("t")("o")(to_like);@/
  943. id4("e")("l")("s")("e")(else_like);@/
  944. id3("e")("n")("d")(end_like);@/
  945. id4("f")("i")("l")("e")(array_like);@/
  946. id3("f")("o")("r")(for_like);@/
  947. id8("f")("u")("n")("c")("t")("i")("o")("n")(proc_like);@/
  948. id4("g")("o")("t")("o")(goto_like);@/
  949. id2("i")("f")(if_like);@/
  950. id2("i")("n")(char_like+set_element_sign);@/
  951. id5("l")("a")("b")("e")("l")(const_like);@/
  952. id3("m")("o")("d")(div_like);@/
  953. id3("n")("i")("l")(nil_like);@/
  954. id3("n")("o")("t")(char_like+not_sign);@/
  955. id2("o")("f")(do_like);@/
  956. id2("o")("r")(char_like+or_sign);@/
  957. id6("p")("a")("c")("k")("e")("d")(goto_like);@/
  958. id9("p")("r")("o")("c")("e")("d")("u")("r")("e")(proc_like);@/
  959. id7("p")("r")("o")("g")("r")("a")("m")(proc_like);@/
  960. id6("r")("e")("c")("o")("r")("d")(record_like);@/
  961. id6("r")("e")("p")("e")("a")("t")(repeat_like);@/
  962. id3("s")("e")("t")(array_like);@/
  963. id4("t")("h")("e")("n")(do_like);@/
  964. id2("t")("o")(to_like);@/
  965. id4("t")("y")("p")("e")(const_like);@/
  966. id5("u")("n")("t")("i")("l")(until_like);@/
  967. id3("v")("a")("r")(var_like);@/
  968. id5("w")("h")("i")("l")("e")(for_like);@/
  969. id4("w")("i")("t")("h")(for_like);@/
  970. id7("x")("c")("l")("a")("u")("s")("e")(loop_like);@/
  971. @* Searching for module names.
  972. The |mod_lookup| procedure finds the module name |mod_text[1..l]| in the
  973. search tree, after inserting it if necessary, and returns a pointer to
  974. where it was found.
  975. @<Glob...@>=
  976. @!mod_text:array [0..longest_name] of ASCII_code; {name being sought for}
  977. @ According to the rules of \.{WEB}, no module name
  978. should be a proper prefix of another, so a ``clean'' comparison should
  979. occur between any two names. The result of |mod_lookup| is 0 if this
  980. prefix condition is violated. An error message is printed when such violations
  981. are detected during phase two of \.{WEAVE}.
  982. @d less=0 {the first name is lexicographically less than the second}
  983. @d equal=1 {the first name is equal to the second}
  984. @d greater=2 {the first name is lexicographically greater than the second}
  985. @d prefix=3 {the first name is a proper prefix of the second}
  986. @d extension=4 {the first name is a proper extension of the second}
  987. @p function mod_lookup(@!l:sixteen_bits):name_pointer; {finds module name}
  988. label found;
  989. var c:less..extension; {comparison between two names}
  990. @!j:0..longest_name; {index into |mod_text|}
  991. @!k:0..max_bytes; {index into |byte_mem|}
  992. @!w:0..ww-1; {row of |byte_mem|}
  993. @!p:name_pointer; {current node of the search tree}
  994. @!q:name_pointer; {father of node |p|}
  995. begin c:=greater; q:=0; p:=root;
  996. while p<>0 do
  997.   begin @<Set variable |c| to the result of comparing the given name
  998.     to name |p|@>;
  999.   q:=p;
  1000.   if c=less then p:=llink[q]
  1001.   else if c=greater then p:=rlink[q]
  1002.   else goto found;
  1003.   end;
  1004. @<Enter a new module name into the tree@>;
  1005. found: if c<>equal then
  1006.   begin err_print('! Incompatible section names'); p:=0;
  1007. @.Incompatible section names@>
  1008.   end;
  1009. mod_lookup:=p;
  1010. @ @<Enter a new module name...@>=
  1011. w:=name_ptr mod ww; k:=byte_ptr[w];
  1012. if k+l>max_bytes then overflow('byte memory');
  1013. if name_ptr>max_names-ww then overflow('name');
  1014. p:=name_ptr;
  1015. if c=less then llink[q]:=p else rlink[q]:=p;
  1016. llink[p]:=0; rlink[p]:=0; xref[p]:=0; c:=equal;
  1017. for j:=1 to l do byte_mem[w,k+j-1]:=mod_text[j];
  1018. byte_ptr[w]:=k+l; byte_start[name_ptr+ww]:=k+l; incr(name_ptr);
  1019. @ @<Set variable |c|...@>=
  1020. begin k:=byte_start[p]; w:=p mod ww; c:=equal; j:=1;
  1021. while (k<byte_start[p+ww]) and (j<=l) and (mod_text[j]=byte_mem[w,k]) do
  1022.   begin incr(k); incr(j);
  1023.   end;
  1024. if k=byte_start[p+ww] then
  1025.   if j>l then c:=equal
  1026.   else c:=extension
  1027. else if j>l then c:=prefix
  1028. else if mod_text[j]<byte_mem[w,k] then c:=less
  1029. else c:=greater;
  1030. @ The |prefix_lookup| procedure is supposed to find exactly one module
  1031. name that has |mod_text[1..l]| as a prefix. Actually the algorithm
  1032. silently accepts also the situation that some module name is a prefix of
  1033. |mod_text[1..l]|, because the user who painstakingly typed in more than
  1034. necessary probably doesn't want to be told about the wasted effort.
  1035. Recall that error messages are not printed during phase one. It is
  1036. possible that the |prefix_lookup| procedure will fail on the first pass,
  1037. because there is no match, yet the second pass might detect no error if a
  1038. matching module name has occurred after the offending prefix. In such a
  1039. case the cross-reference information will be incorrect and \.{WEAVE} will
  1040. report no error. However, such a mistake will be detected by the
  1041. \.{TANGLE} processor.
  1042. @p function prefix_lookup(@!l:sixteen_bits):name_pointer; {finds name extension}
  1043. var c:less..extension; {comparison between two names}
  1044. @!count:0..max_names; {the number of hits}
  1045. @!j:0..longest_name; {index into |mod_text|}
  1046. @!k:0..max_bytes; {index into |byte_mem|}
  1047. @!w:0..ww-1; {row of |byte_mem|}
  1048. @!p:name_pointer; {current node of the search tree}
  1049. @!q:name_pointer; {another place to resume the search after one branch is done}
  1050. @!r:name_pointer; {extension found}
  1051. begin q:=0; p:=root; count:=0; r:=0; {begin search at root of tree}
  1052. while p<>0 do
  1053.   begin @<Set variable |c| to the result of comparing...@>;
  1054.   if c=less then p:=llink[p]
  1055.   else if c=greater then p:=rlink[p]
  1056.   else  begin r:=p; incr(count); q:=rlink[p]; p:=llink[p];
  1057.     end;
  1058.   if p=0 then
  1059.     begin p:=q; q:=0;
  1060.     end;
  1061.   end;
  1062. if count<>1 then
  1063.   if count=0 then err_print('! Name does not match')
  1064. @.Name does not match@>
  1065.   else err_print('! Ambiguous prefix');
  1066. @.Ambiguous prefix@>
  1067. prefix_lookup:=r; {the result will be 0 if there was no match}
  1068. @* Lexical scanning.
  1069. Let us now consider the subroutines that read the \.{WEB} source file
  1070. and break it into meaningful units. There are four such procedures:
  1071. One simply skips to the next `\.{@@\ }' or `\.{@@*}' that begins a
  1072. module; another passes over the \TeX\ text at the beginning of a
  1073. module; the third passes over the \TeX\ text in a \PASCAL\ comment;
  1074. and the last, which is the most interesting, gets the next token of
  1075. a \PASCAL\ text.
  1076. @ But first we need to consider the low-level routine |get_line|
  1077. that takes care of merging |change_file| into |web_file|. The |get_line|
  1078. procedure also updates the line numbers for error messages.
  1079. @<Globals...@>=
  1080. @!ii:integer; {general purpose |for| loop variable in the outer block}
  1081. @!line:integer; {the number of the current line in the current file}
  1082. @!other_line:integer; {the number of the current line in the input file that
  1083.   is not currently being read}
  1084. @!temp_line:integer; {used when interchanging |line| with |other_line|}
  1085. @!limit:0..long_buf_size; {the last character position occupied in the buffer}
  1086. @!loc:0..long_buf_size; {the next character position to be read from the buffer}
  1087. @!input_has_ended: boolean; {if |true|, there is no more input}
  1088. @!changing: boolean; {if |true|, the current line is from |change_file|}
  1089. @!change_pending: boolean; {if |true|, the current change is not yet
  1090.   recorded in |changed_module[module_count]|}
  1091. @ As we change |changing| from |true| to |false| and back again, we must
  1092. remember to swap the values of |line| and |other_line| so that the |err_print|
  1093. routine will be sure to report the correct line number.
  1094. @d change_changing==
  1095.   changing := not changing;
  1096.   temp_line:=other_line; other_line:=line; line:=temp_line
  1097.     {|line @t$\null\BA\null$@> other_line|}
  1098. @ When |changing| is |false|, the next line of |change_file| is kept in
  1099. |change_buffer[0..change_limit]|, for purposes of comparison with the next
  1100. line of |web_file|. After the change file has been completely input, we
  1101. set |change_limit:=0|, so that no further matches will be made.
  1102. @<Globals...@>=
  1103. @!change_buffer:array[0..buf_size] of ASCII_code;
  1104. @!change_limit:0..buf_size; {the last position occupied in |change_buffer|}
  1105. @ Here's a simple function that checks if the two buffers are different.
  1106. @p function lines_dont_match:boolean;
  1107. label exit;
  1108. var k:0..buf_size; {index into the buffers}
  1109. begin lines_dont_match:=true;
  1110. if change_limit<>limit then return;
  1111. if limit>0 then
  1112.   for k:=0 to limit-1 do if change_buffer[k]<>buffer[k] then return;
  1113. lines_dont_match:=false;
  1114. exit: end;
  1115. @ Procedure |prime_the_change_buffer| sets |change_buffer| in preparation
  1116. for the next matching operation. Since blank lines in the change file are
  1117. not used for matching, we have |(change_limit=0)and not changing| if and
  1118. only if the change file is exhausted. This procedure is called only
  1119. when |changing| is true; hence error messages will be reported correctly.
  1120. @p procedure prime_the_change_buffer;
  1121. label continue, done, exit;
  1122. var k:0..buf_size; {index into the buffers}
  1123. begin change_limit:=0; {this value will be used if the change file ends}
  1124. @<Skip over comment lines in the change file; |return| if end of file@>;
  1125. @<Skip to the next nonblank line; |return| if end of file@>;
  1126. @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>;
  1127. exit: end;
  1128. @ While looking for a line that begins with \.{@@x} in the change file,
  1129. we allow lines that begin with \.{@@}, as long as they don't begin with
  1130. \.{@@y} or \.{@@z} (which would probably indicate that the change file is
  1131. fouled up).
  1132. @<Skip over comment lines in the change file...@>=
  1133. loop@+  begin incr(line);
  1134.   if not input_ln(change_file) then return;
  1135.   if limit<2 then goto continue;
  1136.   if buffer[0]<>"@@" then goto continue;
  1137.   if (buffer[1]>="X")and(buffer[1]<="Z") then
  1138.     buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  1139.   if buffer[1]="x" then goto done;
  1140.   if (buffer[1]="y")or(buffer[1]="z") then
  1141.     begin loc:=2; err_print('! Where is the matching @@x?');
  1142. @.Where is the match...@>
  1143.     end;
  1144. continue: end;
  1145. done:
  1146. @ Here we are looking at lines following the \.{@@x}.
  1147. @<Skip to the next nonblank line...@>=
  1148. repeat incr(line);
  1149.   if not input_ln(change_file) then
  1150.     begin err_print('! Change file ended after @@x');
  1151. @.Change file ended...@>
  1152.     return;
  1153.     end;
  1154. until limit>0;
  1155. @ @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>=
  1156. begin change_limit:=limit;
  1157. if limit>0 then for k:=0 to limit-1 do change_buffer[k]:=buffer[k];
  1158. @ The following procedure is used to see if the next change entry should
  1159. go into effect; it is called only when |changing| is false.
  1160. The idea is to test whether or not the current
  1161. contents of |buffer| matches the current contents of |change_buffer|.
  1162. If not, there's nothing more to do; but if so, a change is called for:
  1163. All of the text down to the \.{@@y} is supposed to match. An error
  1164. message is issued if any discrepancy is found. Then the procedure
  1165. prepares to read the next line from |change_file|.
  1166. When a match is found, the current module is marked as changed unless
  1167. the first line after the \.{@@x} and after the \.{@@y} both start with
  1168. either |'@@*'| or |'@@ '| (possibly preceded by whitespace).
  1169. @d if_module_start_then_make_change_pending(#)==
  1170.   loc:=0; buffer[limit]:="!";
  1171.   while (buffer[loc]=" ")or(buffer[loc]=tab_mark) do incr(loc);
  1172.   buffer[limit]:=" ";
  1173.   if buffer[loc]="@@" then
  1174.     if (buffer[loc+1]="*") or
  1175.        (buffer[loc+1]=" ") or (buffer[loc+1]=tab_mark) then
  1176.       change_pending:=#
  1177. @p procedure check_change; {switches to |change_file| if the buffers match}
  1178. label exit;
  1179. var n:integer; {the number of discrepancies found}
  1180. @!k:0..buf_size; {index into the buffers}
  1181. begin if lines_dont_match then return;
  1182. change_pending:=false;
  1183. if not changed_module[module_count] then
  1184.   begin if_module_start_then_make_change_pending(true);
  1185.   if not change_pending then changed_module[module_count]:=true;
  1186.   end;
  1187. n:=0;
  1188. loop@+  begin change_changing; {now it's |true|}
  1189.   incr(line);
  1190.   if not input_ln(change_file) then
  1191.     begin err_print('! Change file ended before @@y');
  1192. @.Change file ended...@>
  1193.     change_limit:=0;  change_changing; {|false| again}
  1194.     return;
  1195.     end;
  1196.   @<If the current line starts with \.{@@y},
  1197.     report any discrepancies and |return|@>;
  1198.   @<Move |buffer| and |limit|...@>;
  1199.   change_changing; {now it's |false|}
  1200.   incr(line);
  1201.   if not input_ln(web_file) then
  1202.     begin err_print('! WEB file ended during a change');
  1203. @.WEB file ended...@>
  1204.     input_has_ended:=true; return;
  1205.     end;
  1206.   if lines_dont_match then incr(n);
  1207.   end;
  1208. exit: end;
  1209. @ @<If the current line starts with \.{@@y}...@>=
  1210. if limit>1 then if buffer[0]="@@" then
  1211.   begin if (buffer[1]>="X")and(buffer[1]<="Z") then
  1212.     buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  1213.   if (buffer[1]="x")or(buffer[1]="z") then
  1214.     begin loc:=2; err_print('! Where is the matching @@y?');
  1215. @.Where is the match...@>
  1216.     end
  1217.   else if buffer[1]="y" then
  1218.     begin if n>0 then
  1219.       begin loc:=2; err_print('! Hmm... ',n:1,
  1220.         ' of the preceding lines failed to match');
  1221. @.Hmm... n of the preceding...@>
  1222.       end;
  1223.     return;
  1224.     end;
  1225.   end
  1226. @ The |reset_input| procedure, which gets \.{WEAVE} ready to read the
  1227. user's \.{WEB} input, is used at the beginning of phases one and two.
  1228. @p procedure reset_input;
  1229. begin open_input; line:=0; other_line:=0;@/
  1230. changing:=true; prime_the_change_buffer; change_changing;@/
  1231. limit:=0; loc:=1; buffer[0]:=" "; input_has_ended:=false;
  1232. @ The |get_line| procedure is called when |loc>limit|; it puts the next
  1233. line of merged input into the buffer and updates the other variables
  1234. appropriately. A space is placed at the right end of the line.
  1235. @p procedure get_line; {inputs the next line}
  1236. label restart;
  1237. begin restart:if changing then
  1238.   @<Read from |change_file| and maybe turn off |changing|@>;
  1239. if not changing then
  1240.   begin @<Read from |web_file| and maybe turn on |changing|@>;
  1241.   if changing then goto restart;
  1242.   end;
  1243. loc:=0; buffer[limit]:=" ";
  1244. @ @<Read from |web_file|...@>=
  1245. begin incr(line);
  1246. if not input_ln(web_file) then input_has_ended:=true
  1247. else if limit=change_limit then
  1248.   if buffer[0]=change_buffer[0] then
  1249.     if change_limit>0 then check_change;
  1250. @ @<Read from |change_file|...@>=
  1251. begin incr(line);
  1252. if not input_ln(change_file) then
  1253.   begin err_print('! Change file ended without @@z');
  1254. @.Change file ended...@>
  1255.   buffer[0]:="@@"; buffer[1]:="z"; limit:=2;
  1256.   end;
  1257. if limit>0 then {check if the change has ended}
  1258.   begin if change_pending then
  1259.     begin if_module_start_then_make_change_pending(false);
  1260.     if change_pending then
  1261.       begin changed_module[module_count]:=true; change_pending:=false;
  1262.       end;
  1263.     end;
  1264.   buffer[limit]:=" ";
  1265.   if buffer[0]="@@" then
  1266.     begin if (buffer[1]>="X")and(buffer[1]<="Z") then
  1267.       buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  1268.     if (buffer[1]="x")or(buffer[1]="y") then
  1269.       begin loc:=2; err_print('! Where is the matching @@z?');
  1270. @.Where is the match...@>
  1271.       end
  1272.     else if buffer[1]="z" then
  1273.       begin prime_the_change_buffer; change_changing;
  1274.       end;
  1275.     end;
  1276.   end;
  1277. @ At the end of the program, we will tell the user if the change file
  1278. had a line that didn't match any relevant line in |web_file|.
  1279. @<Check that all changes have been read@>=
  1280. if change_limit<>0 then {|changing| is false}
  1281.   begin for ii:=0 to change_limit do buffer[ii]:=change_buffer[ii];
  1282.   limit:=change_limit; changing:=true; line:=other_line; loc:=change_limit;
  1283.   err_print('! Change file entry did not match');
  1284. @.Change file entry did not match@>
  1285.   end
  1286. @ Control codes in \.{WEB}, which begin with `\.{@@}', are converted
  1287. into a numeric code designed to simplify \.{WEAVE}'s logic; for example,
  1288. larger numbers are given to the control codes that denote more significant
  1289. milestones, and the code of |new_module| should be the largest of
  1290. all. Some of these numeric control codes take the place of ASCII
  1291. control codes that will not otherwise appear in the output of the
  1292. scanning routines.
  1293. @^ASCII code@>
  1294. @d ignore=0 {control code of no interest to \.{WEAVE}}
  1295. @d verbatim=@'2 {extended ASCII alpha will not appear}
  1296. @d force_line=@'3 {extended ASCII beta will not appear}
  1297. @d begin_comment=@'11 {ASCII tab mark will not appear}
  1298. @d end_comment=@'12 {ASCII line feed will not appear}
  1299. @d octal=@'14 {ASCII form feed will not appear}
  1300. @d hex=@'15 {ASCII carriage return will not appear}
  1301. @d double_dot=@'40 {ASCII space will not appear except in strings}
  1302. @d no_underline=@'175 {this code will be intercepted without confusion}
  1303. @d underline=@'176 {this code will be intercepted without confusion}
  1304. @d param=@'177 {ASCII delete will not appear}
  1305. @d xref_roman=@'203 {control code for `\.{@@\^}'}
  1306. @d xref_wildcard=@'204 {control code for `\.{@@:}'}
  1307. @d xref_typewriter=@'205 {control code for `\.{@@.}'}
  1308. @d TeX_string=@'206 {control code for `\.{@@t}'}
  1309. @d check_sum=@'207 {control code for `\.{@@\$}'}
  1310. @d join=@'210 {control code for `\.{@@\&}'}
  1311. @d thin_space=@'211 {control code for `\.{@@,}'}
  1312. @d math_break=@'212 {control code for `\.{@@\char'174}'}
  1313. @d line_break=@'213 {control code for `\.{@@/}'}
  1314. @d big_line_break=@'214 {control code for `\.{@@\#}'}
  1315. @d no_line_break=@'215 {control code for `\.{@@+}'}
  1316. @d pseudo_semi=@'216 {control code for `\.{@@;}'}
  1317. @d format=@'217 {control code for `\.{@@f}'}
  1318. @d definition=@'220 {control code for `\.{@@d}'}
  1319. @d begin_Pascal=@'221 {control code for `\.{@@p}'}
  1320. @d module_name=@'222 {control code for `\.{@@<}'}
  1321. @d new_module=@'223 {control code for `\.{@@\ }' and `\.{@@*}'}
  1322. @ Control codes are converted from ASCII to \.{WEAVE}'s internal
  1323. representation by the |control_code| routine.
  1324. @p function control_code(@!c:ASCII_code):eight_bits; {convert |c|
  1325.   after \.{@@}}
  1326. begin case c of
  1327. "@@": control_code:="@@"; {`quoted' at sign}
  1328. "'": control_code:=octal; {precedes octal constant}
  1329. """": control_code:=hex; {precedes hexadecimal constant}
  1330. "$": control_code:=check_sum; {precedes check sum constant}
  1331. " ",tab_mark,"*": control_code:=new_module; {beginning of a new module}
  1332. "=": control_code:=verbatim;
  1333. "\": control_code:=force_line;
  1334. "D","d": control_code:=definition; {macro definition}
  1335. "F","f": control_code:=format; {format definition}
  1336. "{": control_code:=begin_comment; {begin-comment delimiter}
  1337. "}": control_code:=end_comment; {end-comment delimiter}
  1338. "P","p": control_code:=begin_Pascal; {\PASCAL\ text in unnamed module}
  1339. "&": control_code:=join; {concatenate two tokens}
  1340. "<": control_code:=module_name; {beginning of a module name}
  1341. ">": begin err_print('! Extra @@>'); control_code:=ignore;
  1342. @.Extra \AT!>@>
  1343.   end; {end of module name should not be discovered in this way}
  1344. "T","t": control_code:=TeX_string; {\TeX\ box within \PASCAL}
  1345. "!": control_code:=underline; {set definition flag}
  1346. "?": control_code:=no_underline; {reset definition flag}
  1347. "^": control_code:=xref_roman; {index entry to be typeset normally}
  1348. ":": control_code:=xref_wildcard; {index entry to be in user format}
  1349. ".": control_code:=xref_typewriter; {index entry to be in typewriter type}
  1350. ",": control_code:=thin_space; {puts extra space in \PASCAL\ format}
  1351. "|": control_code:=math_break; {allows a break in a formula}
  1352. "/": control_code:=line_break; {forces end-of-line in \PASCAL\ format}
  1353. "#": control_code:=big_line_break; {forces end-of-line and some space besides}
  1354. "+": control_code:=no_line_break; {cancels end-of-line down to single space}
  1355. ";": control_code:=pseudo_semi; {acts like a semicolon, but is invisible}
  1356. @t\4@>@<Special control codes allowed only when debugging@>@;
  1357. othercases begin err_print('! Unknown control code'); control_code:=ignore;
  1358. @.Unknown control code@>
  1359.   end
  1360. endcases;
  1361. @ If \.{WEAVE} is compiled with debugging commands, one can write
  1362. \.{@@2}, \.{@@1}, and \.{@@0} to turn tracing fully on, partly on,
  1363. and off, respectively.
  1364. @.\AT!2@>
  1365. @.\AT!1@>
  1366. @<Special control codes...@>=
  1367. @!debug@t@>@/
  1368. "0","1","2": begin tracing:=c-"0"; control_code:=ignore;
  1369.   end;
  1370. gubed
  1371. @ The |skip_limbo| routine is used on the first pass to skip through
  1372. portions of the input that are not in any modules, i.e., that precede
  1373. the first module. After this procedure has been called, the value of
  1374. |input_has_ended| will tell whether or not a new module has
  1375. actually been found.
  1376. @p procedure skip_limbo; {skip to next module}
  1377. label exit;
  1378. var c:ASCII_code; {character following \.{@@}}
  1379. begin loop if loc>limit then
  1380.     begin get_line;
  1381.     if input_has_ended then return;
  1382.     end
  1383.   else  begin buffer[limit+1]:="@@";
  1384.     while buffer[loc]<>"@@" do incr(loc);
  1385.     if loc<=limit then
  1386.       begin loc:=loc+2; c:=buffer[loc-1];
  1387.       if (c=" ")or(c=tab_mark)or(c="*") then return;
  1388.       end;
  1389.     end;
  1390. exit: end;
  1391. @ The |skip_TeX| routine is used on the first pass to skip through
  1392. the \TeX\ code at the beginning of a module. It returns the next
  1393. control code or `\v' found in the input. A |new_module| is
  1394. assumed to exist at the very end of the file.
  1395. @p function skip_TeX: eight_bits; {skip past pure \TeX\ code}
  1396. label done;
  1397. var c:eight_bits; {control code found}
  1398. begin loop begin if loc>limit then
  1399.     begin get_line;
  1400.     if input_has_ended then
  1401.       begin c:=new_module; goto done;
  1402.       end;
  1403.     end;
  1404.   buffer[limit+1]:="@@";
  1405.   repeat c:=buffer[loc]; incr(loc);
  1406.   if c="|" then goto done;
  1407.   until c="@@";
  1408.   if loc<=limit then
  1409.     begin c:=control_code(buffer[loc]); incr(loc); goto done;
  1410.     end;
  1411.   end;
  1412. done:skip_TeX:=c;
  1413. @ The |skip_comment| routine is used on the first pass to skip
  1414. through \TeX\ code in \PASCAL\ comments. The |bal| parameter
  1415. tells how many left braces are assumed to have been scanned when
  1416. this routine is called, and the procedure returns a corresponding
  1417. value of |bal| at the point that scanning has stopped. Scanning
  1418. stops either at a `\v' that introduces \PASCAL\ text,
  1419. in which case the returned value is positive, or it stops at the
  1420. end of the comment, in which case the returned value is zero.
  1421. The scanning also stops in anomalous situations when the comment
  1422. doesn't end or when it contains an illegal use of \.{@@}.
  1423. One should call |skip_comment(1)| when beginning to scan a comment.
  1424. @p function skip_comment(@!bal:eight_bits):eight_bits; {skips \TeX\
  1425.   code in comments}
  1426. label done;
  1427. var c:ASCII_code; {the current character}
  1428. begin loop begin if loc>limit then
  1429.     begin get_line;
  1430.     if input_has_ended then
  1431.       begin bal:=0; goto done;
  1432.       end; {an error message will occur in phase two}
  1433.     end;
  1434.   c:=buffer[loc]; incr(loc);
  1435.   if c="|" then goto done;
  1436.   @<Do special things when |c="@@", "\", "{", "}"|; |goto done| at end@>;
  1437.   end;
  1438. done: skip_comment:=bal;
  1439. @ @<Do special things when |c="@@"...@>=
  1440. if c="@@" then
  1441.   begin c:=buffer[loc];
  1442.   if (c<>" ")and(c<>tab_mark)and(c<>"*") then incr(loc)
  1443.   else  begin decr(loc); bal:=0; goto done;
  1444.     end {an error message will occur in phase two}
  1445.   end
  1446. else if (c="\")and(buffer[loc]<>"@@") then incr(loc)
  1447. else if c="{" then incr(bal)
  1448. else if c="}" then
  1449.   begin decr(bal);
  1450.   if bal=0 then goto done;
  1451.   end
  1452. @* Inputting the next token.
  1453. As stated above, \.{WEAVE}'s most interesting lexical scanning routine is the
  1454. |get_next| function that inputs the next token of \PASCAL\ input. However,
  1455. |get_next| is not especially complicated.
  1456. The result of |get_next| is either an ASCII code for some special character,
  1457. or it is a special code representing a pair of characters (e.g., `\.{:=}'
  1458. or `\.{..}'), or it is the numeric value computed by the |control_code|
  1459. procedure, or it is one of the following special codes:
  1460. \yskip\hang |exponent|: The `\.E' in a real constant.
  1461. \yskip\hang |identifier|: In this case the global variables |id_first|
  1462. and |id_loc| will have been set to the appropriate values needed by the
  1463. |id_lookup| routine.
  1464. \yskip\hang |string|: In this case the global variables |id_first| and
  1465. |id_loc| will have been set to the beginning and ending-plus-one locations
  1466. in the buffer.  The string ends with the first reappearance of its initial
  1467. delimiter; thus, for example, $$\.{\'This isn\'\'t a single string\'}$$
  1468. will be treated as two consecutive strings, the first being \.{\'This
  1469. isn\'}.
  1470. \yskip\noindent Furthermore, some of the control codes cause
  1471. |get_next| to take additional actions:
  1472. \yskip\hang |xref_roman|, |xref_wildcard|,
  1473. |xref_typewriter|, |TeX_string|: The values of
  1474. |id_first| and |id_loc| will be set so that the string in question appears
  1475. in |buffer[id_first..(id_loc-1)]|.
  1476. \yskip\hang |module_name|: In this case the global variable |cur_module| will
  1477. point to the |byte_start| entry for the module name that has just been scanned.
  1478. \yskip\noindent If |get_next| sees `\.{@@!}' or `\.{@@?}',
  1479. it sets |xref_switch| to |def_flag| or zero and goes on to the next token.
  1480. A global variable called |scanning_hex| is set |true| during the time that
  1481. the letters \.A through \.F should be treated as if they were digits.
  1482. @d exponent=@'200 {\.E or \.e following a digit}
  1483. @d string=@'201 {\PASCAL\ string or \.{WEB} precomputed string}
  1484. @d identifier=@'202 {\PASCAL\ identifier or reserved word}
  1485. @<Globals...@>=
  1486. @!cur_module: name_pointer; {name of module just scanned}
  1487. @!scanning_hex: boolean; {are we scanning a hexadecimal constant?}
  1488. @ @<Set init...@>=
  1489. scanning_hex:=false;
  1490. @ As one might expect, |get_next| consists mostly of a big switch
  1491. that branches to the various special cases that can arise.
  1492. @d up_to(#)==#-24,#-23,#-22,#-21,#-20,#-19,#-18,#-17,#-16,#-15,#-14,
  1493.   #-13,#-12,#-11,#-10,#-9,#-8,#-7,#-6,#-5,#-4,#-3,#-2,#-1,#
  1494. @p function get_next:eight_bits; {produces the next input token}
  1495. label restart,done,found;
  1496. var c:eight_bits; {the current character}
  1497. @!d:eight_bits; {the next character}
  1498. @!j,@!k:0..longest_name; {indices into |mod_text|}
  1499. begin restart: if loc>limit then
  1500.   begin get_line;
  1501.   if input_has_ended then
  1502.     begin c:=new_module; goto found;
  1503.     end;
  1504.   end;
  1505. c:=buffer[loc]; incr(loc);
  1506. if scanning_hex then @<Go to |found| if |c| is a hexadecimal digit,
  1507.   otherwise set |scanning_hex:=false|@>;
  1508. case c of
  1509. "A",up_to("Z"),"a",up_to("z"): @<Get an identifier@>;
  1510. "'","""": @<Get a string@>;
  1511. "@@": @<Get control code and possible module name@>;
  1512. @t\4@>@<Compress two-symbol combinations like `\.{:=}'@>@;
  1513. " ",tab_mark: goto restart; {ignore spaces and tabs}
  1514. "}": begin err_print('! Extra }'); goto restart;
  1515. @.Extra \}@>
  1516.   end;
  1517. othercases if c>=128 then goto restart {ignore nonstandard characters}
  1518.   else do_nothing
  1519. endcases;
  1520. found:@!debug if trouble_shooting then debug_help;@;@+gubed@/
  1521. get_next:=c;
  1522. @ @<Go to |found| if |c| is a hexadecimal digit...@>=
  1523. if ((c>="0")and(c<="9"))or((c>="A")and(c<="F")) then goto found
  1524. else scanning_hex:=false
  1525. @ Note that the following code substitutes \.{@@\{} and \.{@@\}} for the
  1526. respective combinations `\.{(*}' and `\.{*)}'. Explicit braces should be used
  1527. for \TeX\ comments in \PASCAL\ text.
  1528. @d compress(#)==begin if loc<=limit then begin c:=#; incr(loc); end; end
  1529. @<Compress two-symbol...@>=
  1530. ".": if buffer[loc]="." then compress(double_dot)
  1531.   else if buffer[loc]=")" then compress("]");
  1532. ":": if buffer[loc]="=" then compress(left_arrow);
  1533. "=": if buffer[loc]="=" then compress(equivalence_sign);
  1534. ">": if buffer[loc]="=" then compress(greater_or_equal);
  1535. "<": if buffer[loc]="=" then compress(less_or_equal)
  1536.   else if buffer[loc]=">" then compress(not_equal);
  1537. "(": if buffer[loc]="*" then compress(begin_comment)
  1538.   else if buffer[loc]="." then compress("[");
  1539. "*": if buffer[loc]=")" then compress(end_comment);
  1540. @ @<Get an identifier@>=
  1541. begin if ((c="E")or(c="e"))and(loc>1) then
  1542.   if (buffer[loc-2]<="9")and(buffer[loc-2]>="0") then c:=exponent;
  1543. if c<>exponent then
  1544.   begin decr(loc); id_first:=loc;
  1545.   repeat incr(loc); d:=buffer[loc];
  1546.   until ((d<"0")or((d>"9")and(d<"A"))or((d>"Z")and(d<"a"))or(d>"z"))and(d<>"_");
  1547.   c:=identifier; id_loc:=loc;
  1548.   end;
  1549. @ A string that starts and ends with single or double quote marks is
  1550. scanned by the following piece of the program.
  1551. @<Get a string@>=
  1552. begin id_first:=loc-1;
  1553. repeat d:=buffer[loc]; incr(loc);
  1554. if loc>limit then
  1555.   begin err_print('! String constant didn''t end');
  1556. @.String constant didn't end@>
  1557.   loc:=limit; d:=c;
  1558.   end;
  1559. until d=c;
  1560. id_loc:=loc; c:=string;
  1561. @ After an \.{@@} sign has been scanned, the next character tells us
  1562. whether there is more work to do.
  1563. @<Get control code and possible module name@>=
  1564. begin c:=control_code(buffer[loc]); incr(loc);
  1565. if c=underline then
  1566.   begin xref_switch:=def_flag; goto restart;
  1567.   end
  1568. else if c=no_underline then
  1569.   begin xref_switch:=0; goto restart;
  1570.   end
  1571. else if (c<=TeX_string)and(c>=xref_roman) then
  1572.   @<Scan to the next \.{@@>}@>
  1573. else if c=hex then scanning_hex:=true
  1574. else if c=module_name then
  1575.   @<Scan the module name and make |cur_module| point to it@>
  1576. else if c=verbatim then @<Scan a verbatim string@>;
  1577. @ The occurrence of a module name sets |xref_switch| to zero,
  1578. because the module name might (for example) follow \&{var}.
  1579. @<Scan the module name...@>=
  1580. begin @<Put module name into |mod_text[1..k]|@>;
  1581. if k>3 then
  1582.   begin if (mod_text[k]=".")and(mod_text[k-1]=".")and(mod_text[k-2]=".") then
  1583.     cur_module:=prefix_lookup(k-3)
  1584.   else cur_module:=mod_lookup(k);
  1585.   end
  1586. else cur_module:=mod_lookup(k);
  1587. xref_switch:=0;
  1588. @ Module names are placed into the |mod_text| array with consecutive spaces,
  1589. tabs, and carriage-returns replaced by single spaces. There will be no
  1590. spaces at the beginning or the end. (We set |mod_text[0]:=" "| to facilitate
  1591. this, since the |mod_lookup| routine uses |mod_text[1]| as the first
  1592. character of the name.)
  1593. @<Set init...@>=mod_text[0]:=" ";
  1594. @ @<Put module name...@>=
  1595. k:=0;
  1596. loop@+  begin if loc>limit then
  1597.     begin get_line;
  1598.     if input_has_ended then
  1599.       begin err_print('! Input ended in section name');
  1600. @.Input ended in section name@>
  1601.       loc:=1; goto done;
  1602.       end;
  1603.     end;
  1604.   d:=buffer[loc];
  1605.   @<If end of name, |goto done|@>;
  1606.   incr(loc); if k<longest_name-1 then incr(k);
  1607.   if (d=" ")or(d=tab_mark) then
  1608.     begin d:=" "; if mod_text[k-1]=" " then decr(k);
  1609.     end;
  1610.   mod_text[k]:=d;
  1611.   end;
  1612. done: @<Check for overlong name@>;
  1613. if (mod_text[k]=" ")and(k>0) then decr(k)
  1614. @ @<If end of name,...@>=
  1615. if d="@@" then
  1616.   begin d:=buffer[loc+1];
  1617.   if d=">" then
  1618.     begin loc:=loc+2; goto done;
  1619.     end;
  1620.   if (d=" ")or(d=tab_mark)or(d="*") then
  1621.     begin err_print('! Section name didn''t end'); goto done;
  1622. @.Section name didn't end@>
  1623.     end;
  1624.   incr(k); mod_text[k]:="@@"; incr(loc); {now |d=buffer[loc]| again}
  1625.   end
  1626. @ @<Check for overlong name@>=
  1627. if k>=longest_name-2 then
  1628.   begin print_nl('! Section name too long: ');
  1629. @.Section name too long@>
  1630.   for j:=1 to 25 do print(xchr[mod_text[j]]);
  1631.   print('...'); mark_harmless;
  1632.   end
  1633. @ @<Scan to the next...@>=
  1634. begin id_first:=loc; buffer[limit+1]:="@@";
  1635. while buffer[loc]<>"@@" do incr(loc);
  1636. id_loc:=loc;
  1637. if loc>limit then
  1638.   begin err_print('! Control text didn''t end'); loc:=limit;
  1639. @.Control text didn't end@>
  1640.   end
  1641. else  begin loc:=loc+2;
  1642.   if buffer[loc-1]<>">" then
  1643.     err_print('! Control codes are forbidden in control text');
  1644. @.Control codes are forbidden...@>
  1645.   end;
  1646. @ A verbatim \PASCAL\ string will be treated like ordinary strings, but
  1647. with no surrounding delimiters.  At the present point in the program we
  1648. have |buffer[loc-1]=verbatim|; we must set |id_first| to the beginning
  1649. of the string itself, and |id_loc| to its ending-plus-one location in the
  1650. buffer.  We also set |loc| to the position just after the ending delimiter.
  1651. @<Scan a verbatim string@>=
  1652. begin id_first:=loc; incr(loc);
  1653. buffer[limit+1]:="@@"; buffer[limit+2]:=">";
  1654. while (buffer[loc]<>"@@")or(buffer[loc+1]<>">") do incr(loc);
  1655. if loc>=limit then err_print('! Verbatim string didn''t end');
  1656. @.Verbatim string didn't end@>
  1657. id_loc:=loc; loc:=loc+2;
  1658. @* Phase one processing.
  1659. We now have accumulated enough subroutines to make it possible to carry out
  1660. \.{WEAVE}'s first pass over the source file. If everything works right,
  1661. both phase one and phase two of \.{WEAVE} will assign the same numbers to
  1662. modules, and these numbers will agree with what \.{TANGLE} does.
  1663. The global variable |next_control| often contains the most recent output of
  1664. |get_next|; in interesting cases, this will be the control code that
  1665. ended a module or part of a module.
  1666. @<Glob...@>=@!next_control:eight_bits; {control code waiting to be acting upon}
  1667. @ The overall processing strategy in phase one has the following
  1668. straightforward outline.
  1669. @<Phase I: Read all the user's text and store the cross references@>=
  1670. phase_one:=true; phase_three:=false;
  1671. reset_input;
  1672. module_count:=0; skip_limbo; change_exists:=false;
  1673. while not input_has_ended do
  1674.   @<Store cross reference data for the current module@>;
  1675. changed_module[module_count]:=change_exists;
  1676.   {the index changes if anything does}
  1677. phase_one:=false; {prepare for second phase}
  1678. @<Print error messages about unused or undefined module names@>;
  1679. @ @<Store cross reference data...@>=
  1680. begin incr(module_count);
  1681. if module_count=max_modules then overflow('section number');
  1682. changed_module[module_count]:=changing;
  1683.  {it will become |true| if any line changes}
  1684. if buffer[loc-1]="*" then
  1685.   begin print('*',module_count:1);
  1686.   update_terminal; {print a progress report}
  1687.   end;
  1688. @<Store cross references in the \TeX\ part of a module@>;
  1689. @<Store cross references in the \(definition part of a module@>;
  1690. @<Store cross references in the \PASCAL\ part of a module@>;
  1691. if changed_module[module_count] then change_exists:=true;
  1692. @ The |Pascal_xref| subroutine stores references to identifiers in
  1693. \PASCAL\ text material beginning with the current value of |next_control|
  1694. and continuing until |next_control| is `\.\{' or `\v', or until the next
  1695. ``milestone'' is passed (i.e., |next_control>=format|). If
  1696. |next_control>=format| when |Pascal_xref| is called, nothing will happen;
  1697. but if |next_control="|"| upon entry, the procedure assumes that this is
  1698. the `\v' preceding \PASCAL\ text that is to be processed.
  1699. The program uses the fact that our internal code numbers satisfy
  1700. the relations |xref_roman=identifier+roman| and |xref_wildcard=identifier
  1701. +wildcard| and |xref_typewriter=identifier+
  1702. typewriter| and |normal=0|. An implied `\.{@@!}' is inserted after
  1703. \&{function}, \&{procedure}, \&{program}, and \&{var}.
  1704. @p procedure Pascal_xref; {makes cross references for \PASCAL\ identifiers}
  1705. label exit;
  1706. var p:name_pointer; {a referenced name}
  1707. begin while next_control<format do
  1708.   begin if (next_control>=identifier)and
  1709.       (next_control<=xref_typewriter) then
  1710.     begin p:=id_lookup(next_control-identifier); new_xref(p);
  1711.     if (ilk[p]=proc_like)or(ilk[p]=var_like) then
  1712.       xref_switch:=def_flag; {implied `\.{@@!}'}
  1713.     end;
  1714.   next_control:=get_next;
  1715.   if (next_control="|")or(next_control="{") then return;
  1716.   end;
  1717. exit:end;
  1718. @ The |outer_xref| subroutine is like |Pascal_xref| but it begins
  1719. with |next_control<>"|"| and ends with |next_control>=format|. Thus, it
  1720. handles \PASCAL\ text with embedded comments.
  1721. @p procedure outer_xref; {extension of |Pascal_xref|}
  1722. var bal:eight_bits; {brace level in comment}
  1723. begin while next_control<format do
  1724.   if next_control<>"{" then Pascal_xref
  1725.   else  begin bal:=skip_comment(1); next_control:="|";
  1726.     while bal>0 do
  1727.       begin Pascal_xref;
  1728.       if next_control="|" then bal:=skip_comment(bal)
  1729.       else bal:=0; {an error will be reported in phase two}
  1730.       end;
  1731.     end;
  1732. @ In the \TeX\ part of a module, cross reference entries are made only for
  1733. the identifiers in \PASCAL\ texts enclosed in \pb, or for control texts
  1734. enclosed in \.{@@\^}$\,\ldots\,$\.{@@>} or \.{@@.}$\,\ldots\,$\.{@@>}
  1735. or \.{@@:}$\,\ldots\,$\.{@@>}.
  1736. @<Store cross references in the \T...@>=
  1737. repeat next_control:=skip_TeX;
  1738. case next_control of
  1739. underline: xref_switch:=def_flag;
  1740. no_underline: xref_switch:=0;
  1741. "|": Pascal_xref;
  1742. xref_roman, xref_wildcard, xref_typewriter, module_name:
  1743.   begin loc:=loc-2; next_control:=get_next; {scan to \.{@@>}}
  1744.   if next_control<>module_name then
  1745.     new_xref(id_lookup(next_control-identifier));
  1746.   end;
  1747. othercases do_nothing
  1748. endcases;
  1749. until next_control>=format
  1750. @ During the definition and \PASCAL\ parts of a module, cross references
  1751. are made for all identifiers except reserved words; however, the
  1752. identifiers in a format definition are referenced even if they are
  1753. reserved. The \TeX\ code in comments is, of course, ignored, except for
  1754. \PASCAL\ portions enclosed in \pb; the text of a module name is skipped
  1755. entirely, even if it contains \pb\ constructions.
  1756. The variables |lhs| and |rhs| point to the respective identifiers involved
  1757. in a format definition.
  1758. @<Global...@>=
  1759. @!lhs,@!rhs:name_pointer; {indices into |byte_start| for format identifiers}
  1760. @ When we get to the following code we have |next_control>=format|.
  1761. @<Store cross references in the \(d...@>=
  1762. while next_control<=definition do {|format| or |definition|}
  1763.   begin xref_switch:=def_flag; {implied \.{@@!}}
  1764.   if next_control=definition then next_control:=get_next
  1765.   else @<Process a format definition@>;
  1766.   outer_xref;
  1767.   end
  1768. @ Error messages for improper format definitions will be issued in phase
  1769. two. Our job in phase one is to define the |ilk| of a properly formatted
  1770. identifier, and to fool the |new_xref| routine into thinking that the
  1771. identifier on the right-hand side of the format definition is not a
  1772. reserved word.
  1773. @<Process a form...@>=
  1774. begin next_control:=get_next;
  1775. if next_control=identifier then
  1776.   begin lhs:=id_lookup(normal); ilk[lhs]:=normal; new_xref(lhs);
  1777.   next_control:=get_next;
  1778.   if next_control=equivalence_sign then
  1779.     begin next_control:=get_next;
  1780.     if next_control=identifier then
  1781.       begin rhs:=id_lookup(normal);
  1782.       ilk[lhs]:=ilk[rhs]; ilk[rhs]:=normal; new_xref(rhs);
  1783.       ilk[rhs]:=ilk[lhs]; next_control:=get_next;
  1784.       end;
  1785.     end;
  1786.   end;
  1787. @ Finally, when the \TeX\ and definition parts have been treated, we have
  1788. |next_control>=begin_Pascal|.
  1789. @<Store cross references in the \P...@>=
  1790. if next_control<=module_name then {|begin_Pascal| or |module_name|}
  1791.   begin if next_control=begin_Pascal then mod_xref_switch:=0
  1792.   else mod_xref_switch:=def_flag;
  1793.   repeat if next_control=module_name then new_mod_xref(cur_module);
  1794.     next_control:=get_next; outer_xref;
  1795.   until next_control>module_name;
  1796.   end
  1797. @ After phase one has looked at everything, we want to check that each
  1798. module name was both defined and used.
  1799. The variable |cur_xref| will point to cross references for the
  1800. current module name of interest.
  1801. @<Glob...@>=@!cur_xref:xref_number; {temporary cross reference pointer}
  1802. @ The following recursive procedure
  1803. walks through the tree of module names and prints out anomalies.
  1804. @^recursion@>
  1805. @p procedure mod_check(@!p:name_pointer); {print anomalies in subtree |p|}
  1806. begin if p>0 then
  1807.   begin mod_check(llink[p]);@/
  1808.   cur_xref:=xref[p];
  1809.   if num(cur_xref)<def_flag then
  1810.     begin print_nl('! Never defined: <'); print_id(p);
  1811. @.Never defined: <section name>@>
  1812.     print('>'); mark_harmless;
  1813.     end;
  1814.   while num(cur_xref)>=def_flag do cur_xref:=xlink(cur_xref);
  1815.   if cur_xref=0 then
  1816.     begin print_nl('! Never used: <'); print_id(p); print('>');
  1817. @.Never used: <section name>@>
  1818.     mark_harmless;
  1819.     end;
  1820.   mod_check(rlink[p]);
  1821.   end;
  1822. @ @<Print error messages about un...@>=@+mod_check(root)
  1823. @* Low-level output routines.
  1824. The \TeX\ output is supposed to appear in lines at most |line_length|
  1825. characters long, so we place it into an output buffer. During the output
  1826. process, |out_line| will hold the current line number of the line about to
  1827. be output.
  1828. @<Glo...@>=
  1829. @!out_buf:array[0..line_length] of ASCII_code; {assembled characters}
  1830. @!out_ptr:0..line_length; {number of characters in |out_buf|}
  1831. @!out_line: integer; {coordinates of next line to be output}
  1832. @ The |flush_buffer| routine empties the buffer up to a given breakpoint,
  1833. and moves any remaining characters to the beginning of the next line.
  1834. If the |per_cent| parameter is |true|, a |"%"| is appended to the line
  1835. that is being output; in this case the breakpoint |b| should be strictly
  1836. less than |line_length|. If the |per_cent| parameter is |false|,
  1837. trailing blanks are suppressed.
  1838. The characters emptied from the buffer form a new line of output;
  1839. if the |carryover| parameter is true, a |"%"| in that line will be
  1840. carried over to the next line (so that \TeX\ will ignore the completion
  1841. of commented-out text).
  1842. @p procedure flush_buffer(@!b:eight_bits;@!per_cent,@!carryover:boolean);
  1843.   {outputs |out_buf[1..b]|, where |b<=out_ptr|}
  1844. label done,found;
  1845. var j,@!k:0..line_length;
  1846. begin j:=b;
  1847. if not per_cent then {remove trailing blanks}
  1848.   loop@+  begin if j=0 then goto done;
  1849.     if out_buf[j]<>" " then goto done;
  1850.     decr(j);
  1851.     end;
  1852. done: for k:=1 to j do write(tex_file,xchr[out_buf[k]]);
  1853. if per_cent then write(tex_file,xchr["%"]);
  1854. write_ln(tex_file); incr(out_line);
  1855. if carryover then
  1856.   for k:=1 to j do
  1857.     if out_buf[k]="%" then
  1858.       if (k=1)or(out_buf[k-1]<>"\") then {comment mode should be preserved}
  1859.         begin out_buf[b]:="%"; decr(b); goto found;
  1860.         end;
  1861. found: if (b<out_ptr) then
  1862.   for k:=b+1 to out_ptr do out_buf[k-b]:=out_buf[k];
  1863. out_ptr:=out_ptr-b;
  1864. @ When we are copying \TeX\ source material, we retain line breaks
  1865. that occur in the input, except that an empty line is not
  1866. output when the \TeX\ source line was nonempty. For example, a line
  1867. of the \TeX\ file that contains only an index cross-reference entry
  1868. will not be copied. The |finish_line| routine is called just before
  1869. |get_line| inputs a new line, and just after a line break token has
  1870. been emitted during the output of translated \PASCAL\ text.
  1871. @p procedure finish_line; {do this at the end of a line}
  1872. label exit;
  1873. var k:0..buf_size; {index into |buffer|}
  1874. begin if out_ptr>0 then flush_buffer(out_ptr,false,false)
  1875. else  begin for k:=0 to limit do
  1876.     if (buffer[k]<>" ")and(buffer[k]<>tab_mark) then return;
  1877.   flush_buffer(0,false,false);
  1878.   end;
  1879. exit:end;
  1880. @ In particular, the |finish_line| procedure is called near the very
  1881. beginning of phase two. We initialize the output variables in a slightly
  1882. tricky way so that the first line of the output file will be
  1883. `\.{\\input webmac}'.
  1884. @.\\input webmac@>
  1885. @.webmac@>
  1886. @<Set init...@>=
  1887. out_ptr:=1; out_line:=1; out_buf[1]:="c"; write(tex_file,'\input webma');
  1888. @ When we wish to append the character |c| to the output buffer, we write
  1889. `$|out|(c)$'; this will cause the buffer to be emptied if it was already
  1890. full. Similarly, `$|out2|(c_1)(c_2)$' appends a pair of characters.
  1891. A line break will occur at a space or after a single-nonletter
  1892. \TeX\ control sequence.
  1893. @d oot(#)==@;@/
  1894.   if out_ptr=line_length then break_out;
  1895.   incr(out_ptr); out_buf[out_ptr]:=#;
  1896. @d oot1(#)==oot(#)@+end
  1897. @d oot2(#)==oot(#)@,oot1
  1898. @d oot3(#)==oot(#)@,oot2
  1899. @d oot4(#)==oot(#)@,oot3
  1900. @d oot5(#)==oot(#)@,oot4
  1901. @d out==@+begin oot1
  1902. @d out2==@+begin oot2
  1903. @d out3==@+begin oot3
  1904. @d out4==@+begin oot4
  1905. @d out5==@+begin oot5
  1906. @ The |break_out| routine is called just before the output buffer is about
  1907. to overflow. To make this routine a little faster, we initialize position
  1908. 0 of the output buffer to `\.\\'; this character isn't really output.
  1909. @<Set init...@>=
  1910. out_buf[0]:="\";
  1911. @ A long line is broken at a blank space or just before a backslash that isn't
  1912. preceded by another backslash. In the latter case, a |"%"| is output at
  1913. the break.
  1914. @p procedure break_out; {finds a way to break the output line}
  1915. label exit;
  1916. var k:0..line_length; {index into |out_buf|}
  1917. @!d:ASCII_code; {character from the buffer}
  1918. begin k:=out_ptr;
  1919. loop@+  begin if k=0 then
  1920.     @<Print warning message, break the line, |return|@>;
  1921.   d:=out_buf[k];
  1922.   if d=" " then
  1923.     begin flush_buffer(k,false,true); return;
  1924.     end;
  1925.   if (d="\")and(out_buf[k-1]<>"\") then {in this case |k>1|}
  1926.     begin flush_buffer(k-1,true,true); return;
  1927.     end;
  1928.   decr(k);
  1929.   end;
  1930. exit:end;
  1931. @ We get to this module only in unusual cases that the entire output line
  1932. consists of a string of backslashes followed by a string of nonblank
  1933. non-backslashes. In such cases it is almost always safe to break the
  1934. line by putting a |"%"| just before the last character.
  1935. @<Print warning message...@>=
  1936. begin print_nl('! Line had to be broken (output l.',out_line:1);
  1937. @.Line had to be broken@>
  1938. print_ln('):');
  1939. for k:=1 to out_ptr-1 do print(xchr[out_buf[k]]);
  1940. new_line; mark_harmless;
  1941. flush_buffer(out_ptr-1,true,true); return;
  1942. @ Here is a procedure that outputs a module number in decimal notation.
  1943. @<Glob...@>=@!dig:array[0..4] of 0..9; {digits to output}
  1944. @ The number to be converted by |out_mod| is known to be less than
  1945. |def_flag|, so it cannot have more than five decimal digits.  If
  1946. the module is changed, we output `\.{\\*}' just after the number.
  1947. @p procedure out_mod(@!m:integer); {output a module number}
  1948. var k:0..5; {index into |dig|}
  1949. @!a:integer; {accumulator}
  1950. begin k:=0; a:=m;
  1951. repeat dig[k]:=a mod 10; a:=a div 10; incr(k);
  1952. until a=0;
  1953. repeat decr(k); out(dig[k]+"0");
  1954. until k=0;
  1955. if changed_module[m] then out2("\")("*");
  1956. @.\\*@>
  1957. @ The |out_name| subroutine is used to output an identifier or index
  1958. entry, enclosing it in braces.
  1959. @p procedure out_name(@!p:name_pointer); {outputs a name}
  1960. var k:0..max_bytes; {index into |byte_mem|}
  1961. @!w:0..ww-1; {row of |byte_mem|}
  1962. begin out("{"); w:=p mod ww;
  1963. for k:=byte_start[p] to byte_start[p+ww]-1 do
  1964.   begin if byte_mem[w,k]="_" then out("\");
  1965. @.\\_@>
  1966.   out(byte_mem[w,k]);
  1967.   end;
  1968. out("}");
  1969. @* Routines that copy \TeX\ material.
  1970. During phase two, we use the subroutines |copy_limbo|, |copy_TeX|, and
  1971. |copy_comment| in place of the analogous |skip_limbo|, |skip_TeX|, and
  1972. |skip_comment| that were used in phase one.
  1973. The |copy_limbo| routine, for example, takes \TeX\ material that is not
  1974. part of any module and transcribes it almost verbatim to the output file.
  1975. No `\.{@@}' signs should occur in such material except in `\.{@@@@}'
  1976. pairs; such pairs are replaced by singletons.
  1977. @p procedure copy_limbo; {copy \TeX\ code until the next module begins}
  1978. label exit;
  1979. var c:ASCII_code; {character following \.{@@} sign}
  1980. begin loop if loc>limit then
  1981.     begin finish_line; get_line;
  1982.     if input_has_ended then return;
  1983.     end
  1984.   else  begin buffer[limit+1]:="@@";
  1985.     @<Copy up to control code, |return| if finished@>;
  1986.     end;
  1987. exit:end;
  1988. @ @<Copy up to control...@>=
  1989. while buffer[loc]<>"@@" do
  1990.   begin out(buffer[loc]); incr(loc);
  1991.   end;
  1992. if loc<=limit then
  1993.   begin loc:=loc+2; c:=buffer[loc-1];
  1994.   if (c=" ")or(c=tab_mark)or(c="*") then return;
  1995.   if (c<>"z")and(c<>"Z") then
  1996.     begin out("@@");
  1997.     if c<>"@@" then err_print('! Double @@ required outside of sections');
  1998. @.Double \AT! required...@>
  1999.     end;
  2000.   end
  2001. @ The |copy_TeX| routine processes the \TeX\ code at the beginning of a
  2002. module; for example, the words you are now reading were copied in this
  2003. way. It returns the next control code or `\v' found in the input.
  2004. @p function copy_TeX:eight_bits; {copy pure \TeX\ material}
  2005. label done;
  2006. var c:eight_bits; {control code found}
  2007. begin loop begin if loc>limit then
  2008.     begin finish_line; get_line;
  2009.     if input_has_ended then
  2010.       begin c:=new_module; goto done;
  2011.       end;
  2012.     end;
  2013.   buffer[limit+1]:="@@";
  2014.   @<Copy up to `\v' or control code, |goto done| if finished@>;
  2015.   end;
  2016. done:copy_TeX:=c;
  2017. @ We don't copy spaces or tab marks into the beginning of a line. This
  2018. makes the test for empty lines in |finish_line| work.
  2019. @<Copy up to `\v'...@>=
  2020. repeat c:=buffer[loc]; incr(loc);
  2021. if c="|" then goto done;
  2022. if c<>"@@" then
  2023.   begin out(c);
  2024.   if (out_ptr=1)and((c=" ")or(c=tab_mark)) then decr(out_ptr);
  2025.   end;
  2026. until c="@@";
  2027. if loc<=limit then
  2028.   begin c:=control_code(buffer[loc]); incr(loc);
  2029.   goto done;
  2030.   end
  2031. @ The |copy_comment| uses and returns a brace-balance value, following the
  2032. conventions of |skip_comment| above. Instead of copying the \TeX\ material
  2033. into the output buffer, this procedure copies it into the token memory.
  2034. The abbreviation |app_tok(t)| is used to append token |t| to the current
  2035. token list, and it also makes sure that it is possible to append at least
  2036. one further token without overflow.
  2037. @d app_tok(#)==begin if tok_ptr+2>max_toks then overflow('token');
  2038.   tok_mem[tok_ptr]:=#; incr(tok_ptr);
  2039.   end
  2040. @p function copy_comment(@!bal:eight_bits):eight_bits; {copies \TeX\ code in
  2041.   comments}
  2042. label done;
  2043. var c:ASCII_code; {current character being copied}
  2044. begin loop begin if loc>limit then
  2045.     begin get_line;
  2046.     if input_has_ended then
  2047.       begin err_print('! Input ended in mid-comment');
  2048. @.Input ended in mid-comment@>
  2049.       loc:=1; @<Clear |bal| and |goto done|@>;
  2050.       end;
  2051.     end;
  2052.   c:=buffer[loc]; incr(loc);
  2053.   if c="|" then goto done;
  2054.   app_tok(c);
  2055.   @<Copy special things when |c="@@", "\", "{", "}"|;
  2056.     |goto done| at end@>;
  2057.   end;
  2058. done: copy_comment:=bal;
  2059. @ @<Copy special things when |c="@@"...@>=
  2060. if c="@@" then
  2061.   begin incr(loc);
  2062.   if buffer[loc-1]<>"@@" then
  2063.     begin err_print('! Illegal use of @@ in comment');
  2064. @.Illegal use of \AT!...@>
  2065.     loc:=loc-2; decr(tok_ptr); @<Clear |bal|...@>;
  2066.     end;
  2067.   end
  2068. else if (c="\")and(buffer[loc]<>"@@") then
  2069.   begin app_tok(buffer[loc]); incr(loc);
  2070.   end
  2071. else if c="{" then incr(bal)
  2072. else if c="}" then
  2073.   begin decr(bal);
  2074.   if bal=0 then goto done;
  2075.   end
  2076. @ When the comment has terminated abruptly due to an error, we output
  2077. enough right braces to keep \TeX\ happy.
  2078. @<Clear |bal|...@>=
  2079. app_tok(" "); {this is done in case the previous character was `\.\\'}
  2080. repeat app_tok("}"); decr(bal);
  2081. until bal=0;
  2082. goto done;
  2083. @* Parsing.
  2084. The most intricate part of \.{WEAVE} is its mechanism for converting
  2085. \PASCAL-like code into \TeX\ code, and we might as well plunge into this
  2086. aspect of the program now. A ``bottom up'' approach is used to parse the
  2087. \PASCAL-like material, since \.{WEAVE} must deal with fragmentary
  2088. constructions whose overall ``part of speech'' is not known.
  2089. At the lowest level, the input is represented as a sequence of entities
  2090. that we shall call {\it scraps}, where each scrap of information consists
  2091. of two parts, its {\it category} and its {\it translation}. The category
  2092. is essentially a syntactic class, and the translation is a token list that
  2093. represents \TeX\ code. Rules of syntax and semantics tell us how to
  2094. combine adjacent scraps into larger ones, and if we are lucky an entire
  2095. \PASCAL\ text that starts out as hundreds of small scraps will join
  2096. together into one gigantic scrap whose translation is the desired \TeX\
  2097. code. If we are unlucky, we will be left with several scraps that don't
  2098. combine; their translations will simply be output, one by one.
  2099. The combination rules are given as context-sensitive productions that are
  2100. applied from left to right. Suppose that we are currently working on the
  2101. sequence of scraps $s_1\,s_2\ldots s_n$. We try first to find the longest
  2102. production that applies to an initial substring $s_1\,s_2\ldots\,$; but if
  2103. no such productions exist, we find to find the longest production
  2104. applicable to the next substring $s_2\,s_3\ldots\,$; and if that fails, we
  2105. try to match $s_3\,s_4\ldots\,$, etc.
  2106. A production applies if the category codes have a given pattern. For
  2107. example, one of the productions is
  2108. $$|open|\;|math|\;|semi|\;\RA\;|open|\;|math|$$
  2109. and it means that three consecutive scraps whose respective categories are
  2110. |open|, |math|, and |semi| are con\-verted to two scraps whose categories
  2111. are |open| and |math|. This production also has an associated rule that
  2112. tells how to combine the translation parts:
  2113. $$\eqalign{O_2&=O_1\cr
  2114. M_2&=M_1\,S\,\.{\\,}\,\hbox{|opt|\thinspace\tt5}\cr}$$
  2115. This means that the |open| scrap has not changed, while the new |math| scrap
  2116. has a translation $M_2$ composed of the translation $M_1$ of the original
  2117. |math| scrap followed by the translation |S| of the |semi| scrap followed
  2118. by `\.{\\,}' followed by `|opt|' followed by `\.5'. (In the \TeX\ file,
  2119. this will specify an additional thin space after the semicolon, followed
  2120. by an optional line break with penalty 50.) Translation rules use subscripts
  2121. to distinguish between translations of scraps whose categories have the
  2122. same initial letter; these subscripts are assigned from left to right.
  2123. $\.{WEAVE}$ also has the production rule
  2124. $$|semi|\;\RA\;|terminator|$$
  2125. (meaning that a semicolon can terminate a \PASCAL\ statement). Since
  2126. productions are applied from left to right, this rule will be activated
  2127. only if the |semi| is not preceded by scraps that match other productions;
  2128. in particular, a |semi| that is preceded by `|open| |math|' will have
  2129. disappeared because of the production above, and such semicolons do not
  2130. act as statement terminators.  This incidentally is how \.{WEAVE} is able
  2131. to treat semicolons in two distinctly different ways, the first of which
  2132. is intended for semicolons in the parameter list of a procedure
  2133. declaration.
  2134. The translation rule corresponding to $|semi|\;\RA\;|terminator|$ is
  2135. $$T=S$$
  2136. but we shall not mention translation rules in the common case that the
  2137. translation of the new scrap on the right-hand side is simply the
  2138. concatenation of the disappearing scraps on the left-hand side.
  2139. @ Here is a list of the category codes that scraps can have.
  2140. @d simp=1 {the translation can be used both in horizontal mode
  2141.   and in math mode of \TeX}
  2142. @d math=2 {the translation should be used only in \TeX\ math mode}
  2143. @d intro=3 {a statement is expected to follow this, after a space and
  2144.   an optional break}
  2145. @d open=4 {denotes an incomplete parenthesized quantity to be used in
  2146.   math mode}
  2147. @d beginning=5 {denotes an incomplete compound statement to be used in
  2148.   horizontal mode}
  2149. @d close=6 {ends a parenthesis or compound statement}
  2150. @d alpha=7 {denotes the beginning of a clause}
  2151. @d omega=8 {denotes the ending of a clause and possible comment following}
  2152. @d semi=9 {denotes a semicolon and possible comment following it}
  2153. @d terminator=10 {something that ends a statement or declaration}
  2154. @d stmt=11 {denotes a statement or declaration including its terminator}
  2155. @d cond=12 {precedes an \&{if} clause that might have a matching \&{else}}
  2156. @d clause=13 {precedes a statement after which indentation ends}
  2157. @d colon=14 {denotes a colon}
  2158. @d exp=15 {stands for the E in a floating point constant}
  2159. @d proc=16 {denotes a procedure or program or function heading}
  2160. @d case_head=17 {denotes a case statement or record heading}
  2161. @d record_head=18 {denotes a record heading without indentation}
  2162. @d var_head=19 {denotes a variable declaration heading}
  2163. @d elsie=20 {\&{else}}
  2164. @d casey=21 {\&{case}}
  2165. @d mod_scrap=22 {denotes a module name}
  2166. @p @!debug procedure print_cat(@!c:eight_bits);
  2167.   {symbolic printout of a category}
  2168. begin case c of
  2169. simp: print('simp');
  2170. math: print('math');
  2171. intro: print('intro');
  2172. open: print('open');
  2173. beginning: print('beginning');
  2174. close: print('close');
  2175. alpha: print('alpha');
  2176. omega: print('omega');
  2177. semi: print('semi');
  2178. terminator: print('terminator');
  2179. stmt: print('stmt');
  2180. cond: print('cond');
  2181. clause: print('clause');
  2182. colon: print('colon');
  2183. exp: print('exp');
  2184. proc: print('proc');
  2185. case_head: print('casehead');
  2186. record_head: print('recordhead');
  2187. var_head: print('varhead');
  2188. elsie: print('elsie');
  2189. casey: print('casey');
  2190. mod_scrap: print('module');
  2191. othercases print('UNKNOWN')
  2192. endcases;
  2193. gubed
  2194. @ The token lists for translated \TeX\ output contain some special control
  2195. symbols as well as ordinary characters. These control symbols are
  2196. interpreted by \.{WEAVE} before they are written to the output file.
  2197. \yskip\hang |break_space| denotes an optional line break or an en space;
  2198. \yskip\hang |force| denotes a line break;
  2199. \yskip\hang |big_force| denotes a line break with additional vertical space;
  2200. \yskip\hang |opt| denotes an optional line break (with the continuation
  2201. line indented two ems with respect to the normal starting position)---this
  2202. code is followed by an integer |n|, and the break will occur with penalty
  2203. $10n$;
  2204. \yskip\hang |backup| denotes a backspace of one em;
  2205. \yskip\hang |cancel| obliterates any |break_space| or |force| or |big_force|
  2206. tokens that immediately precede or follow it and also cancels any
  2207. |backup| tokens that follow it;
  2208. \yskip\hang |indent| causes future lines to be indented one more em;
  2209. \yskip\hang |outdent| causes future lines to be indented one less em.
  2210. \yskip\noindent All of these tokens are removed from the \TeX\ output that
  2211. comes from \PASCAL\ text between \pb\ signs; |break_space| and |force| and
  2212. |big_force| become single spaces in this mode. The translation of other
  2213. \PASCAL\ texts results in \TeX\ control sequences \.{\\1}, \.{\\2},
  2214. \.{\\3}, \.{\\4}, \.{\\5}, \.{\\6}, \.{\\7} corresponding respectively to
  2215. |indent|, |outdent|, |opt|, |backup|, |break_space|, |force|, and
  2216. |big_force|. However, a sequence of consecutive `\.\ ', |break_space|,
  2217. |force|, and/or |big_force| tokens is first replaced by a single token
  2218. (the maximum of the given ones).
  2219. The tokens |math_rel|, |math_bin|, |math_op| will be translated into
  2220. \.{\\mathrel\{}, \.{\\mathbin\{}, and \.{\\mathop\{}, respectively.
  2221. Other control sequences in the \TeX\ output will be `\.{\\\\\{}$\,\ldots\,$\.\}'
  2222. surrounding identifiers, `\.{\\\&\{}$\,\ldots\,$\.\}' surrounding
  2223. reserved words, `\.{\\.\{}$\,\ldots\,$\.\}' surrounding strings,
  2224. `\.{\\C\{}$\,\ldots\,$\.\}$\,$|force|' surrounding comments, and
  2225. `\.{\\X$n$:}$\,\ldots\,$\.{\\X}' surrounding module names, where
  2226. |n| is the module number.
  2227. @d math_bin=@'203
  2228. @d math_rel=@'204
  2229. @d math_op=@'205
  2230. @d big_cancel=@'206 {like |cancel|, also overrides spaces}
  2231. @d cancel=@'207 {overrides |backup|, |break_space|, |force|, |big_force|}
  2232. @d indent=cancel+1 {one more tab (\.{\\1})}
  2233. @d outdent=cancel+2 {one less tab (\.{\\2})}
  2234. @d opt=cancel+3 {optional break in mid-statement (\.{\\3})}
  2235. @d backup=cancel+4 {stick out one unit to the left (\.{\\4})}
  2236. @d break_space=cancel+5 {optional break between statements (\.{\\5})}
  2237. @d force=cancel+6 {forced break between statements (\.{\\6})}
  2238. @d big_force=cancel+7 {forced break with additional space (\.{\\7})}
  2239. @d end_translation=big_force+1 {special sentinel token at end of list}
  2240. @ The raw input is converted into scraps according to the following table,
  2241. which gives category codes followed by the translations. Sometimes a single
  2242. item of input produces more than one scrap.
  2243. \def\stars {\.{**}}%
  2244. (The symbol `\stars' stands for `\.{\\\&\{{\rm identifier}\}}',
  2245. i.e., the identifier itself treated as a reserved word. In a few cases the
  2246. category is given as `|@!comment|'; this is not an actual category code, it
  2247. means that the translation will be treated as a comment, as explained
  2248. below.)
  2249. \yskip\halign{\quad#\hfil&\quad#\hfil\cr
  2250. \.{<>}&|math:|\.{\\I}\cr
  2251. \.{<=}&|math:|\.{\\L}\cr
  2252. \.{>=}&|math:|\.{\\G}\cr
  2253. \.{:=}&|math:|\.{\\K}\cr
  2254. \.{==}&|math:|\.{\\S}\cr
  2255. \.{(*}&|math:|\.{\\B}\cr
  2256. \.{*)}&|math:|\.{\\T}\cr
  2257. \.{(.}&|open:|\.[\cr
  2258. \.{.)}&|close:|\.]\cr
  2259. \."$\,$string$\,$\."&|simp:|\.{\\.\{"{\rm$\,$modified string$\,$}"\}}\cr
  2260. \.\'$\,$string$\,$\.\'&|simp:|\.{\\.\{\\\'{\rm$\,$modified
  2261.   string$\,$}\\\'\}}\cr
  2262. \.{@@=}$\,$string$\,$\.{@@>}&|simp:|\.{\\=\{{\rm$\,$modified string$\,$}\}}\cr
  2263. \#&|math:|\.{\\\#}\cr
  2264. \.\$&|math:|\.{\\\$}\cr
  2265. \.\_&|math:|\.{\\\_}\cr
  2266. \.\%&|math:|\.{\\\%}\cr
  2267. \.\^&|math:|\.{\\\^}\cr
  2268. \.(&|open:|\.(\cr
  2269. \.)&|close:|\.)\cr
  2270. \.[&|open:|\.[\cr
  2271. \.]&|close:|\.]\cr
  2272. \.*&|math:|\.{\\ast}\cr
  2273. \.,&|math:|\.,|@,opt@,|\.9\cr
  2274. \.{..}&|math:|\.{\\to}\cr
  2275. \..&|simp:|\..\cr
  2276. \.:&|colon:|\.:\cr
  2277. \.;&|semi:|\.;\cr
  2278. identifier&|simp:|\.{\\\\\{{\rm$\,$identifier$\,$}\}}\cr
  2279. \.E in constant&|exp:|\.{\\E\{}\cr
  2280. digit $d$&|simp:|$d$\cr
  2281. other character $c$&|math:|$c$\cr
  2282. \.{and}&|math:|\.{\\W}\cr
  2283. \.{array}&|alpha:|\stars\cr
  2284. \.{begin}&|beginning:|$|force|\,\stars\,|cancel|$\qquad|intro:|\cr
  2285. \.{case}&|casey:|\qquad|alpha:|$|force|\,\stars$\cr
  2286. \.{const}&|intro:|$|force|\,|backup|\,\stars$\cr
  2287. \.{div}&|math:|$|math_bin|\,\stars\,\.\}$\cr
  2288. \.{do}&|omega:|\stars\cr
  2289. \.{downto}&|math:|$|math_rel|\,\stars\,\.\}$\cr
  2290. \.{else}&|terminator:|\qquad|elsie:|$|force|\,|backup|\,\stars$\cr
  2291. \.{end}&|terminator:|\qquad|close:|$|force|\,\stars$\cr
  2292. \.{file}&|alpha:|\stars\cr
  2293. \.{for}&|alpha:|$|force|\,\stars$\cr
  2294. \.{function}&|proc:|$|force|\,|backup|\,\stars\,|cancel|$\qquad
  2295.   |intro:|$|indent|\,\.{\\\ }$\cr
  2296. \.{goto}&|intro:|\stars\cr
  2297. \.{if}&|cond:|\qquad|alpha:|$|force|\,\stars$\cr
  2298. \.{in}&|math:|\.{\\in}\cr
  2299. \.{label}&|intro:|$|force|\,|backup|\,\stars$\cr
  2300. \.{mod}&|math:|$|math_bin|\,\stars\,\.\}$\cr
  2301. \.{nil}&|simp:|\stars\cr
  2302. \.{not}&|math:|\.{\\R}\cr
  2303. \.{of}&|omega:|\stars\cr
  2304. \.{or}&|math:|\.{\\V}\cr
  2305. \.{packed}&|intro:|\stars\cr
  2306. \.{procedure}&|proc:|$|force|\,|backup|\,\stars\,|cancel|$\qquad
  2307.   |intro:|$|indent|\,\.{\\\ }$\cr
  2308. \.{program}&|proc:|$|force|\,|backup|\,\stars\,|cancel|$\qquad
  2309.   |intro:|$|indent|\,\.{\\\ }$\cr
  2310. \.{record}&|record_head:|\stars\qquad|intro:|\cr
  2311. \.{repeat}&|beginning:|$|force|\,|indent|\,\stars\,|cancel|$\qquad|intro:|\cr
  2312. \.{set}&|alpha:|\stars\cr
  2313. \.{then}&|omega:|\stars\cr
  2314. \.{to}&|math:|$|math_rel|\,\stars\,\.\}$\cr
  2315. \.{type}&|intro:|$|force|\,|backup|\,\stars$\cr
  2316. \.{until}&|terminator:|\qquad|close:|$|force|\,|backup|\,\stars$\qquad
  2317.   |clause:|\cr
  2318. \.{var}&|var_head:|$|force|\,|backup|\,\stars\,|cancel|$\qquad|intro:|\cr
  2319. \.{while}&|alpha:|$|force|\,\stars$\cr
  2320. \.{with}&|alpha:|$|force|\,\stars$\cr
  2321. \.{xclause}&|alpha:|$|force|\,\.{\\\~}$\qquad|omega:|\stars\cr
  2322. \.{@@\'}$\,$const&|simp:|\.{\\O\{}\hbox{const}\.\}\cr
  2323. \.{@@"}$\,$const&|simp:|\.{\\H\{}\hbox{const}\.\}\cr
  2324. \.{@@\$}&|simp:|\.{\\)}\cr
  2325. \.{@@\\}&|simp:|\.{\\]}\cr
  2326. \.{@@,}&|math:|\.{\\,}\cr
  2327. \.{@@t}$\,$stuff$\,$\.{@@>}&|simp:|\.{\\hbox\{{\rm$\,$stuff$\,$}\}}\cr
  2328. \.{@@<}$\,$module$\,$\.{@@>}&|mod_scrap:|\.{\\X$n$:{\rm$\,$module$\,$}\\X}\cr
  2329. \.{@@\#}&|comment:||big_force|\cr
  2330. \.{@@/}&|comment:||force|\cr
  2331. \.{@@\char'174}&|simp:|$|opt|\,\.0$\cr
  2332. \.{@@+}&|comment:|$|big_cancel|\,\.{\\\ }\,|big_cancel|$\cr
  2333. \.{@@;}&|semi:|\cr
  2334. \.{@@\&}&|math:|\.{\\J}\cr
  2335. \.{@@\{}&|math:|\.{\\B}\cr
  2336. \.{@@\}}&|math:|\.{\\T}\cr}
  2337. \yskip\noindent When a string is output, certain characters are preceded by
  2338. `\.\\' signs so that they will print properly.
  2339. A comment in the input will be combined with the preceding
  2340. |omega| or |semi| scrap, or with the following |terminator| scrap, if
  2341. possible; otherwise it will be inserted as a separate |terminator| scrap.
  2342. An additional ``comment'' is effectively appended at the end of the
  2343. \PASCAL\ text, just before translation begins; this consists of a |cancel|
  2344. token in the case of \PASCAL\ text in \pb, otherwise it consists of a
  2345. |force| token.
  2346. From this table it is evident that \.{WEAVE} will parse a lot of non-\PASCAL\
  2347. programs. For example, the reserved words `\.{for}' and `\.{array}' are
  2348. treated in an identical way by \.{WEAVE} from a syntactic standpoint,
  2349. and semantically they are equivalent except that a forced line break occurs
  2350. just before `\&{for}'; \PASCAL\ programmers may well be surprised at this
  2351. similarity. The idea is to keep \.{WEAVE}'s rules as simple as possible,
  2352. consistent with doing a reasonable job on syntactically correct \PASCAL\
  2353. programs. The production rules below have been formulated in the same
  2354. spirit of ``almost anything goes.''
  2355. @ Here is a table of all the productions. The reader can best get a feel for
  2356. @^productions, table of@>
  2357. how they work by trying them out by hand on small examples; no amount of
  2358. explanation will be as effective as watching the rules in action.
  2359. Parsing can also be watched by debugging with `\.{@@2}'.
  2360. \def\[#1]{\quad$\dleft#1\dright$}
  2361. \def\sp{\.{\ }}
  2362. \yskip
  2363. \halign to\the\hsize{\hfil\it# &
  2364.   #\hfil\hskip-200pt\tabskip 0pt plus 100pt&
  2365.   #\hfil\tabskip0pt\cr
  2366. &Production categories\[\hbox{translations}]&Remarks\cr
  2367. \noalign{\yskip}
  2368. 1&|alpha@,math@,colon| $\RA$ |alpha@,math|&e.g., |case v:boolean of|\cr
  2369. 2&|alpha@,math@,omega| $\RA$ |clause|\[C=A\,\sp\,\.\$\,M\,\.\$\,\sp\,|indent|\,
  2370. O]&e.g., |while x>0 do|\cr
  2371. 3&|alpha@,omega| $\RA$ |clause|\[C=A\,\sp\,|indent|\,O]&e.g., |file of|\cr
  2372. 4&|alpha@,simp| $\RA$ |alpha@,math|&convert to math mode\cr
  2373. 5&|beginning@,close@,(terminator@t or @>stmt)| $\RA$ |stmt|&compound statement
  2374. ends\cr
  2375. 6&|beginning@,stmt| $\RA$ |beginning|\[B_2=B_1\,|break_space|\,S]&compound
  2376. statement grows\cr
  2377. 7&|case_head@,casey@,clause| $\RA$ |case_head|\[C_4=C_1\,|outdent|\,C_2\,C_3]&
  2378. variant records\cr
  2379. 8&|case_head@,close@,terminator| $\RA$ |stmt|\[S=C_1\,|cancel|\,|outdent|\,
  2380. C_2\,T]&end of case statement\cr
  2381. 9&|case_head@,stmt| $\RA$ |case_head|\[C_2=C_1\,|force|\,S]&case statement
  2382. grows\cr
  2383. 10&|casey@,clause| $\RA$ |case_head|&beginning of case statement\cr
  2384. 11&|clause@,stmt| $\RA$ |stmt|\[S_2=C\,|break_space|\,S_1\,|cancel|\,|outdent|\,
  2385. |force|]&end of controlled statement\cr
  2386. 12&|cond@,clause@,stmt@,elsie| $\RA$ |clause|\[C_3=C_1\,C_2\,|break_space|\,S\,
  2387. E\,\sp\,|cancel|]&complete conditional\cr
  2388. 13&|cond@,clause@,stmt| $\RA$ |stmt|\cr
  2389. &\qquad\[S_2=C_1\,C_2\,|break_space|\,S_1\,
  2390. |cancel|\,|outdent|\,|force|]&incomplete conditional\cr
  2391. 14&|elsie| $\RA$ |intro|&unmatched else\cr
  2392. 15&|exp@,math@,simp|* $\RA$ |math|\[M_2=E\,M_1\,S\,\.\}]&signed exponent\cr
  2393. 16&|exp@,simp|* $\RA$ |math|\[M=E\,S\,\.\}]&unsigned exponent\cr
  2394. 17&|intro@,stmt| $\RA$ |stmt|\[S_2=I\,\sp\,|opt|\,\.7\,|cancel|\,S_1]&labeled
  2395. statement, etc.\cr
  2396. 18&|math@,close| $\RA$ |stmt@,close|\[S=\.\$\,M\,\.\$]&end of field list\cr
  2397. 19&|math@,colon| $\RA$ |intro|\[I=|force|\,|backup|\,\.\$\,M\,\.\$\,C]&compound
  2398. label\cr
  2399. 20&|math@,math| $\RA$ |math|&simple concatenation\cr
  2400. 21&|math@,simp| $\RA$ |math|&simple concatenation\cr
  2401. 22&|math@,stmt| $\RA$ |stmt|\cr
  2402. &\qquad\[S_2=\.\$\,M\,\.\$\,|indent|\,|break_space|\,
  2403. S_1\,|cancel|\,|outdent|\,|force|]¯o or type definition\cr
  2404. 23&|math@,terminator| $\RA$ |stmt|\[S=\.\$\,M\,\.\$\,T]&statement involving
  2405. math\cr
  2406. 24&|mod_scrap@,(terminator@t or @>semi)| $\RA$ |stmt|\[S=M\,T\,|force|]&module
  2407. like a statement\cr
  2408. 25&|mod_scrap| $\RA$ |simp|&module unlike a statement\cr
  2409. 26&|open@,case_head@,close| $\RA$ |math|\[M=O\,\.\$\,|cancel|\,C_1\,
  2410. |cancel|\,|outdent|\,\.\$\,C_2]&case in field list\cr
  2411. 27&|open@,close| $\RA$ |math|\[M=O\,\.\\\,\.,\,C]&empty set |[]|\cr
  2412. 28&|open@,math@,case_head@,close| $\RA$ |math|\cr
  2413. &\qquad\[M_2=O\,M_1\,\.\$\,|cancel|\,
  2414. C_1\,|cancel|\,|outdent|\,\.\$\,C_2]&case in field list\cr
  2415. 29&|open@,math@,close| $\RA$ |math|&parenthesized group\cr
  2416. 30&|open@,math@,colon| $\RA$ |open@,math|&colon in parentheses\cr
  2417. 31&|open@,math@,proc@,intro| $\RA$ |open@,math|\[M_2=M_1\,|math_op|\,|cancel|\,
  2418. P\,\.\}]&|procedure| in parentheses\cr
  2419. 32&|open@,math@,semi| $\RA$ |open@,math|\[M_2=M_1\,S\,\.\\\,\.,\,|opt|\,
  2420. \.5]&semicolon in parentheses\cr
  2421. 33&|open@,math@,var_head@,intro| $\RA$ |open@,math|\[M_2=M_1\,|math_op|\,
  2422. |cancel|\,V\,\.\}]&|var| in parentheses\cr
  2423. 34&|open@,proc@,intro| $\RA$ |open@,math|\[M=|math_op|\,|cancel|\,
  2424. P\,\.\}]&|procedure| in parentheses\cr
  2425. 35&|open@,simp| $\RA$ |open@,math|&convert to math mode\cr
  2426. 36&|open@,stmt@,close| $\RA$ |math|\[M=O\,\.\$\,|cancel|\,S\,|cancel|\,
  2427. \.\$\,C]&field list\cr
  2428. 37&|open@,var_head@,intro| $\RA$ |open@,math|\[M=|math_op|\,|cancel|\,V\,
  2429. \.\}]&|var| in parentheses\cr
  2430. 38&|proc@,beginning@,close@,terminator| $\RA$ |stmt|\[S=P\,|cancel|\,
  2431. |outdent|\,B\,C\,T]&end of procedure declaration\cr
  2432. 39&|proc@,stmt| $\RA$ |proc|\[P_2=P_1\,|break_space|\,S]&procedure declaration
  2433. grows\cr
  2434. 40&|record_head@,intro@,casey| $\RA$ |casey|\[C_2=R\,I\,\sp\,|cancel|\,C_1]&
  2435. \&{record case} $\ldots$\cr
  2436. 41&|record_head| $\RA$ |case_head|\[C=|indent|\,R\,|cancel|]&other \&{record}
  2437. structures\cr
  2438. 42&|semi| $\RA$ |terminator|&semicolon after statement\cr
  2439. 43&|simp@,close| $\RA$ |stmt@,close|&end of field list\cr
  2440. 44&|simp@,colon| $\RA$ |intro|\[I=|force|\,|backup|\,S\,C]&simple label\cr
  2441. 45&|simp@,math| $\RA$ |math|&simple concatenation\cr
  2442. 46&|simp@,mod_scrap| $\RA$ |mod_scrap|&in emergencies\cr
  2443. 47&|simp@,simp| $\RA$ |simp|&simple concatenation\cr
  2444. 48&|simp@,terminator| $\RA$ |stmt|&simple statement\cr
  2445. 49&|stmt@,stmt| $\RA$ |stmt|\[S_3=S_1\,|break_space|\,S_2]&adjacent
  2446. statements\cr
  2447. 50&|terminator| $\RA$ |stmt|&empty statement\cr
  2448. 51&|var_head@,beginning| $\RA$ |stmt@,beginning|&end of variable
  2449. declarations\cr
  2450. 52&|var_head@,math@,colon| $\RA$ |var_head@,intro|\[I=\.\$\,M\,\.\$\,C]&
  2451. variable declaration\cr
  2452. 53&|var_head@,simp@,colon| $\RA$ |var_head@,intro|&variable declaration\cr
  2453. 54&|var_head@,stmt| $\RA$ |var_head|\[V_2=V_1\,|break_space|\,S]&variable
  2454. declarations grow\cr}
  2455. \yskip\noindent
  2456. Translations are not specified here when they are simple concatenations
  2457. of the scraps that change. For example, the full translation of
  2458. `|open@,math@,colon| $\RA$ |open@,math|' is $O_2=O_1$, $M_2=M_1C$.
  2459. The notation `|simp|*', in the |exp|-related productions above,
  2460. stands for a |simp| scrap that isn't followed by another |simp|.
  2461. @* Implementing the productions.
  2462. When \PASCAL\ text is to be processed with the grammar above, we put its
  2463. initial scraps $s_1\ldots s_n$ into two arrays |cat[1..n]| and |trans[1..n]|.
  2464. The value of |cat[k]| is simply a category code from the list above; the
  2465. value of |trans[k]| is a text pointer, i.e., an index into |tok_start|.
  2466. Our production rules have the nice property that the right-hand side is never
  2467. longer than the left-hand side. Therefore it is convenient to use sequential
  2468. allocation for the current sequence of scraps. Five pointers are used to
  2469. manage the parsing:
  2470. \yskip\hang |pp| (the parsing pointer) is such that we are trying to match
  2471. the category codes |cat[pp]@,cat[pp+1]|$\,\ldots\,$ to the left-hand sides
  2472. of productions.
  2473. \yskip\hang |scrap_base|, |lo_ptr|, |hi_ptr|, and |scrap_ptr| are such that
  2474. the current sequence of scraps appears in positions |scrap_base| through
  2475. |lo_ptr| and |hi_ptr| through |scrap_ptr|, inclusive, in the |cat| and
  2476. |trans| arrays. Scraps located between |scrap_base| and |lo_ptr| have
  2477. been examined, while those in positions |>=hi_ptr| have not yet been
  2478. looked at by the parsing process.
  2479. \yskip\noindent Initially |scrap_ptr| is set to the position of the final
  2480. scrap to be parsed, and it doesn't change its value. The parsing process
  2481. makes sure that |lo_ptr>=pp+3|, since productions have as many as four terms,
  2482. by moving scraps from |hi_ptr| to |lo_ptr|. If there are
  2483. fewer than |pp+3| scraps left, the positions up to |pp+3| are filled with
  2484. blanks that will not match in any productions. Parsing stops when
  2485. |pp=lo_ptr+1| and |hi_ptr=scrap_ptr+1|.
  2486. The |trans| array elements are declared to be of type |0..10239| instead
  2487. of type |text_pointer|, because the final sorting phase of \.{WEAVE}
  2488. uses this array to contain elements of type |name_pointer|. Both
  2489. of these types are subranges of |0..10239|.
  2490. @<Glo...@>=
  2491. @!cat:array[0..max_scraps] of eight_bits; {category codes of scraps}
  2492. @!trans:array[0..max_scraps] of 0..10239; {translation texts of scraps}
  2493. @!pp:0..max_scraps; {current position for reducing productions}
  2494. @!scrap_base:0..max_scraps; {beginning of the current scrap sequence}
  2495. @!scrap_ptr:0..max_scraps; {ending of the current scrap sequence}
  2496. @!lo_ptr:0..max_scraps; {last scrap that has been examined}
  2497. @!hi_ptr:0..max_scraps; {first scrap that has not been examined}
  2498. stat@!max_scr_ptr:0..max_scraps; {largest value assumed by |scrap_ptr|}
  2499. @ @<Set init...@>=
  2500. scrap_base:=1; scrap_ptr:=0;
  2501. stat max_scr_ptr:=0; @+tats
  2502. @ Token lists in |@!tok_mem| are composed of the following kinds of
  2503. items for \TeX\ output.
  2504. \yskip\item{$\bullet$}ASCII codes and special codes like |force| and
  2505. |math_rel| represent themselves;
  2506. \item{$\bullet$}|id_flag+p| represents \.{\\\\\{{\rm identifier $p$}\}};
  2507. \item{$\bullet$}|res_flag+p| represents \.{\\\&\{{\rm identifier $p$}\}};
  2508. \item{$\bullet$}|mod_flag+p| represents module name |p|;
  2509. \item{$\bullet$}|tok_flag+p| represents token list number |p|;
  2510. \item{$\bullet$}|inner_tok_flag+p| represents token list number |p|, to be
  2511. translated without line-break controls.
  2512. @d id_flag=10240 {signifies an identifier}
  2513. @d res_flag=id_flag+id_flag {signifies a reserved word}
  2514. @d mod_flag=res_flag+id_flag {signifies a module name}
  2515. @d tok_flag==mod_flag+id_flag {signifies a token list}
  2516. @d inner_tok_flag==tok_flag+id_flag {signifies a token list in `\pb'}
  2517. @d lbrace==xchr["{"] {this avoids possible \PASCAL\ compiler confusion}
  2518. @d rbrace==xchr["}"] {because these braces might occur within comments}
  2519. @p @!debug procedure print_text(@!p:text_pointer); {prints a token list}
  2520. var j:0..max_toks; {index into |tok_mem|}
  2521. @!r:0..id_flag-1; {remainder of token after the flag has been stripped off}
  2522. begin if p>=text_ptr then print('BAD')
  2523. else for j:=tok_start[p] to tok_start[p+1]-1 do
  2524.   begin r:=tok_mem[j] mod id_flag;
  2525.   case tok_mem[j] div id_flag of
  2526.   1: begin print('\\',lbrace); print_id(r); print(rbrace);
  2527.     end; {|id_flag|}
  2528.   2: begin print('\&',lbrace); print_id(r); print(rbrace);
  2529.     end; {|res_flag|}
  2530.   3: begin print('<'); print_id(r); print('>');
  2531.     end; {|mod_flag|}
  2532.   4: print('[[',r:1,']]'); {|tok_flag|}
  2533.   5: print('|[[',r:1,']]|'); {|inner_tok_flag|}
  2534.   othercases @<Print token |r| in symbolic form@>
  2535.   endcases;
  2536.   end;
  2537. gubed
  2538. @ @<Print token |r|...@>=
  2539. case r of
  2540. math_bin: print('\mathbin',lbrace);
  2541. math_rel: print('\mathrel',lbrace);
  2542. math_op: print('\mathop',lbrace);
  2543. big_cancel: print('[ccancel]');
  2544. cancel: print('[cancel]');
  2545. indent: print('[indent]');
  2546. outdent: print('[outdent]');
  2547. backup: print('[backup]');
  2548. opt: print('[opt]');
  2549. break_space: print('[break]');
  2550. force: print('[force]');
  2551. big_force: print('[fforce]');
  2552. end_translation: print('[quit]');
  2553. othercases print(xchr[r])
  2554. endcases
  2555. @ The production rules listed above are embedded directly into the \.{WEAVE}
  2556. program, since it is easier to do this than to write an interpretive system
  2557. that would handle production systems in general. Several macros are defined
  2558. here so that the program for each production is fairly short.
  2559. All of our productions conform to the general notion that some |k|
  2560. consecutive scraps starting at some position |j| are to be replaced by a
  2561. single scrap of some category |c| whose translation is composed from the
  2562. translations of the disappearing scraps. After this production has been
  2563. applied, the production pointer |pp| should change by an amount |d|. Such
  2564. a production can be represented by the quadruple $(j,k,c,d)$. For example,
  2565. the production `|simp@,math| $\RA$ |math|' would be represented by
  2566. `$(|pp|,2,|math|,-1)$'; in this case the pointer $pp$ should decrease by 1
  2567. after the production has been applied, because some productions with
  2568. |math| in their second positions might now match, but no productions have
  2569. |math| in the third or fourth position of their left-hand sides. Note that
  2570. the value of |d| is determined by the whole collection of productions, not
  2571. by an individual one. Consider the further example
  2572. `|var_head@,math@,colon| $\RA$ |var_head@,intro|', which is represented by
  2573. `$(|pp|+1,2,|intro|,+1)$'; the $+1$ here is deduced by looking at the
  2574. grammar and seeing that no matches could possibly occur at positions |<=pp|
  2575. after this production has been applied. The determination of |d| has been
  2576. done by hand in each case, based on the full set of productions but not on
  2577. the grammar of \PASCAL\ or on the rules for constructing the initial
  2578. scraps.
  2579. We also attach a serial number to each production, so that additional
  2580. information is available when debugging. For example, the program below
  2581. contains the statement `|reduce(pp+1,2,intro,+1)(52)|' when it implements
  2582. the production just mentioned.
  2583. Before calling |reduce|, the program should have appended the tokens of
  2584. the new translation to the |tok_mem| array. We commonly want to append
  2585. copies of several existing translations, and macros are defined to
  2586. simplify these common cases. For example, |app2(pp)| will append the
  2587. translations of two consecutive scraps, |trans[pp]| and |trans[pp+1]|, to
  2588. the current token list. If the entire new translation is formed in this
  2589. way, we write `$|squash|(j,k,c,d)$' instead of `$|reduce|(j,k,c,d)$'. For
  2590. example, `|squash(pp,2,math,-1)|' is an abbreviation for `|app2(pp);
  2591. reduce(pp,2,math,-1)|'.
  2592. The code below is an exact translation of the production rules into
  2593. \PASCAL, using such macros, and the reader should have no difficulty
  2594. understanding the format by comparing the code with the symbolic
  2595. productions as they were listed earlier.
  2596. {\sl Caution:\/} The macros |app|, |app1|, |app2|, and |app3| are
  2597. sequences of statements that are not enclosed with |begin| and $|end|$,
  2598. because such delimiters would make the \PASCAL\ program much longer. This
  2599. means that it is necessary to write |begin| and |end| explicitly when such
  2600. a macro is used as a single statement. Several mysterious bugs in the
  2601. original programming of \.{WEAVE} were caused by a failure to remember
  2602. this fact.  Next time the author will know better.
  2603. @d production(#)==@!debug prod(#) gubed; goto found
  2604. @d reduce(#)==red(#); production
  2605. @d production_end(#)==@!debug prod(#) gubed; goto found;
  2606.   end
  2607. @d squash(#)==begin sq(#); production_end
  2608. @d app(#)==tok_mem[tok_ptr]:=#; incr(tok_ptr) {this is like |app_tok|,
  2609.   but it doesn't test for overflow}
  2610. @d app1(#)==tok_mem[tok_ptr]:=tok_flag+trans[#]; incr(tok_ptr)
  2611. @d app2(#)==app1(#);app1(#+1)
  2612. @d app3(#)==app2(#);app1(#+2)
  2613. @ Let us consider the big case statement for productions now, before looking
  2614. at its context. We want to design the program so that this case statement
  2615. works, so we might as well not keep ourselves in suspense about exactly what
  2616. code needs to be provided with a proper environment.
  2617. The code here is more complicated than it need be, since some popular
  2618. \PASCAL\ compilers are unable to deal with procedures that contain a lot
  2619. of program text. The |translate| procedure, which incorporates the |case|
  2620. statement here, would become too long for those compilers if we did
  2621. not do something to split the cases into parts. Therefore
  2622. a separate procedure called |five_cases| has been introduced.
  2623. @^split procedures@>
  2624. This auxiliary procedure contains approximately half of the program text
  2625. that |translate| would otherwise have had. There's also a procedure
  2626. called |alpha_cases|, which turned out to be necessary because the best
  2627. two-way split wasn't good enough. The procedure could be split further
  2628. in an analogous manner, but the present scheme works on all compilers
  2629. known to the author.
  2630. @<Match a production at |pp|, or increase |pp| if there is no match@>=
  2631. if cat[pp]<=alpha then
  2632.   if cat[pp]<alpha then five_cases@+else alpha_cases
  2633. else  begin case cat[pp] of
  2634.   case_head: @<Cases for |case_head|@>;
  2635.   casey: @<Cases for |casey|@>;
  2636.   clause: @<Cases for |clause|@>;
  2637.   cond: @<Cases for |cond|@>;
  2638.   elsie: @<Cases for |elsie|@>;
  2639.   exp: @<Cases for |exp|@>;
  2640.   mod_scrap: @<Cases for |mod_scrap|@>;
  2641.   proc: @<Cases for |proc|@>;
  2642.   record_head: @<Cases for |record_head|@>;
  2643.   semi: @<Cases for |semi|@>;
  2644.   stmt: @<Cases for |stmt|@>;
  2645.   terminator: @<Cases for |terminator|@>;
  2646.   var_head: @<Cases for |var_head|@>;
  2647.   othercases do_nothing
  2648.   endcases;@/
  2649.   incr(pp); {if no match was found, we move to the right}
  2650.   found: end
  2651. @ Here are the procedures that need to be present for the reason just
  2652. explained.
  2653. @<Declaration of subprocedures for |translate|@>=
  2654. procedure five_cases; {handles almost half of the syntax}
  2655. label found;
  2656. begin case cat[pp] of
  2657. beginning: @<Cases for |beginning|@>;
  2658. intro: @<Cases for |intro|@>;
  2659. math: @<Cases for |math|@>;
  2660. open: @<Cases for |open|@>;
  2661. simp: @<Cases for |simp|@>;
  2662. othercases do_nothing
  2663. endcases;@/
  2664. incr(pp); {if no match was found, we move to the right}
  2665. found: end;
  2666. procedure alpha_cases;
  2667. label found;
  2668. begin @<Cases for |alpha|@>;
  2669. incr(pp); {if no match was found, we move to the right}
  2670. found: end;
  2671. @ Now comes the code that tries to match each production starting
  2672. with a particular type of scrap. Whenever a match is discovered,
  2673. the |squash| or |reduce| macro will cause the appropriate action
  2674. to be performed, followed by |goto found|.
  2675. @<Cases for |alpha|@>=
  2676. if cat[pp+1]=math then
  2677.   begin if cat[pp+2]=colon then squash(pp+1,2,math,0)(1)
  2678.   else if cat[pp+2]=omega then
  2679.     begin app1(pp); app(" "); app("$"); app1(pp+1);
  2680.     app("$"); app(" "); app(indent); app1(pp+2);
  2681.     reduce(pp,3,clause,-2)(2);
  2682.     end;
  2683.   end
  2684. else if cat[pp+1]=omega then
  2685.   begin app1(pp); app(" "); app(indent); app1(pp+1);
  2686.   reduce(pp,2,clause,-2)(3);
  2687.   end
  2688. else if cat[pp+1]=simp then squash(pp+1,1,math,0)(4)
  2689. @ @<Cases for |beginning|@>=
  2690. if cat[pp+1]=close then
  2691.   begin if (cat[pp+2]=terminator)or(cat[pp+2]=stmt) then
  2692.     squash(pp,3,stmt,-2)(5);
  2693.   end
  2694. else if cat[pp+1]=stmt then
  2695.   begin app1(pp); app(break_space); app1(pp+1);
  2696.   reduce(pp,2,beginning,-1)(6);
  2697.   end
  2698. @ @<Cases for |case_head|@>=
  2699. if cat[pp+1]=casey then
  2700.   begin if cat[pp+2]=clause then
  2701.     begin app1(pp); app(outdent); app2(pp+1);
  2702.     reduce(pp,3,case_head,0)(7);
  2703.     end;
  2704.   end
  2705. else if cat[pp+1]=close then
  2706.   begin if cat[pp+2]=terminator then
  2707.     begin app1(pp); app(cancel); app(outdent); app2(pp+1);
  2708.     reduce(pp,3,stmt,-2)(8);
  2709.     end;
  2710.   end
  2711. else if cat[pp+1]=stmt then
  2712.   begin app1(pp); app(force); app1(pp+1);
  2713.   reduce(pp,2,case_head,0)(9);
  2714.   end
  2715. @ @<Cases for |casey|@>=
  2716. if cat[pp+1]=clause then squash(pp,2,case_head,0)(10)
  2717. @ @<Cases for |clause|@>=
  2718. if cat[pp+1]=stmt then
  2719.   begin app1(pp); app(break_space); app1(pp+1);
  2720.   app(cancel); app(outdent);
  2721.   app(force); reduce(pp,2,stmt,-2)(11);
  2722.   end
  2723. @ @<Cases for |cond|@>=
  2724. if (cat[pp+1]=clause)and(cat[pp+2]=stmt) then
  2725.   if cat[pp+3]=elsie then
  2726.     begin app2(pp); app(break_space); app2(pp+2); app(" ");
  2727.     app(cancel); reduce(pp,4,clause,-2)(12);
  2728.     end
  2729.   else  begin app2(pp); app(break_space); app1(pp+2); app(cancel);
  2730.     app(outdent); app(force); reduce(pp,3,stmt,-2)(13);
  2731.     end
  2732. @ @<Cases for |elsie|@>=
  2733. squash(pp,1,intro,-3)(14)
  2734. @ @<Cases for |exp|@>=
  2735. if cat[pp+1]=math then
  2736.   begin if cat[pp+2]=simp then if cat[pp+3]<>simp then
  2737.     begin app3(pp); app("}"); reduce(pp,3,math,-1)(15);
  2738.     end;
  2739.   end
  2740. else if cat[pp+1]=simp then if cat[pp+2]<>simp then
  2741.   begin app2(pp); app("}"); reduce(pp,2,math,-1)(16);
  2742.   end
  2743. @ @<Cases for |intro|@>=
  2744. if cat[pp+1]=stmt then
  2745.   begin app1(pp); app(" "); app(opt); app("7");
  2746.   app(cancel); app1(pp+1); reduce(pp,2,stmt,-2)(17);
  2747.   end
  2748. @ @<Cases for |math|@>=
  2749. if cat[pp+1]=close then
  2750.   begin app("$"); app1(pp); app("$"); reduce(pp,1,stmt,-2)(18);
  2751.   end
  2752. else if cat[pp+1]=colon then
  2753.   begin app(force); app(backup); app("$"); app1(pp);
  2754.   app("$"); app1(pp+1); reduce(pp,2,intro,-3)(19);
  2755.   end
  2756. else if cat[pp+1]=math then squash(pp,2,math,-1)(20)
  2757. else if cat[pp+1]=simp then squash(pp,2,math,-1)(21)
  2758. else if cat[pp+1]=stmt then
  2759.   begin app("$"); app1(pp); app("$"); app(indent);
  2760.   app(break_space); app1(pp+1); app(cancel); app(outdent);
  2761.   app(force); reduce(pp,2,stmt,-2)(22);
  2762.   end
  2763. else if cat[pp+1]=terminator then
  2764.   begin app("$"); app1(pp); app("$"); app1(pp+1);
  2765.   reduce(pp,2,stmt,-2)(23);
  2766.   end
  2767. @ @<Cases for |mod_scrap|@>=
  2768. if (cat[pp+1]=terminator)or(cat[pp+1]=semi) then
  2769.   begin app2(pp); app(force); reduce(pp,2,stmt,-2)(24);
  2770.   end
  2771. else squash(pp,1,simp,-2)(25)
  2772. @ @<Cases for |open|@>=
  2773. if (cat[pp+1]=case_head)and(cat[pp+2]=close) then
  2774.   begin app1(pp); app("$"); app(cancel); app1(pp+1); app(cancel);
  2775.   app(outdent); app("$"); app1(pp+2); reduce(pp,3,math,-1)(26);
  2776.   end
  2777. else if cat[pp+1]=close then
  2778.   begin app1(pp); app("\"); app(","); app1(pp+1);
  2779. @.\\,@>
  2780.   reduce(pp,2,math,-1)(27);
  2781.   end
  2782. else if cat[pp+1]=math then @<Cases for |open@,math|@>
  2783. else if cat[pp+1]=proc then
  2784.   begin if cat[pp+2]=intro then
  2785.     begin app(math_op); app(cancel); app1(pp+1); app("}");
  2786.     reduce(pp+1,2,math,0)(34);
  2787.     end;
  2788.   end
  2789. else if cat[pp+1]=simp then squash(pp+1,1,math,0)(35)
  2790. else if (cat[pp+1]=stmt)and(cat[pp+2]=close) then
  2791.   begin app1(pp); app("$"); app(cancel); app1(pp+1); app(cancel);
  2792.   app("$"); app1(pp+2); reduce(pp,3,math,-1)(36);
  2793.   end
  2794. else if cat[pp+1]=var_head then
  2795.   begin if cat[pp+2]=intro then
  2796.     begin app(math_op); app(cancel); app1(pp+1); app("}");
  2797.     reduce(pp+1,2,math,0)(37);
  2798.     end;
  2799.   end
  2800. @ @<Cases for |open@,math|@>=
  2801. begin if (cat[pp+2]=case_head)and(cat[pp+3]=close) then
  2802.   begin app2(pp); app("$"); app(cancel); app1(pp+2); app(cancel);
  2803.   app(outdent); app("$"); app1(pp+3); reduce(pp,4,math,-1)(28);
  2804.   end
  2805. else if cat[pp+2]=close then squash(pp,3,math,-1)(29)
  2806. else if cat[pp+2]=colon then squash(pp+1,2,math,0)(30)
  2807. else if cat[pp+2]=proc then
  2808.   begin if cat[pp+3]=intro then
  2809.     begin app1(pp+1); app(math_op); app(cancel);
  2810.     app1(pp+2); app("}"); reduce(pp+1,3,math,0)(31);
  2811.     end;
  2812.   end
  2813. else if cat[pp+2]=semi then
  2814.   begin app2(pp+1); app("\"); app(","); app(opt); app("5");
  2815. @.\\,@>
  2816.   reduce(pp+1,2,math,0)(32);
  2817.   end
  2818. else if cat[pp+2]=var_head then
  2819.   begin if cat[pp+3]=intro then
  2820.     begin app1(pp+1); app(math_op); app(cancel);
  2821.     app1(pp+2); app("}"); reduce(pp+1,3,math,0)(31);
  2822.     end;
  2823.   end;
  2824. @ @<Cases for |proc|@>=
  2825. if cat[pp+1]=beginning then
  2826.   begin if (cat[pp+2]=close)and(cat[pp+3]=terminator) then
  2827.     begin app1(pp); app(cancel); app(outdent); app3(pp+1);
  2828.     reduce(pp,4,stmt,-2)(38);
  2829.     end;
  2830.   end
  2831. else if cat[pp+1]=stmt then
  2832.   begin app1(pp); app(break_space); app1(pp+1);
  2833.   reduce(pp,2,proc,-2)(39);
  2834.   end
  2835. @ @<Cases for |record_head|@>=
  2836. if (cat[pp+1]=intro)and(cat[pp+2]=casey) then
  2837.   begin app2(pp); app(" "); app(cancel); app1(pp+2);
  2838.   reduce(pp,3,casey,-2)(40);
  2839.   end
  2840. else  begin app(indent); app1(pp); app(cancel);
  2841.   reduce(pp,1,case_head,0)(41);
  2842.   end
  2843. @ @<Cases for |semi|@>=
  2844. squash(pp,1,terminator,-3)(42)
  2845. @ @<Cases for |simp|@>=
  2846. if cat[pp+1]=close then squash(pp,1,stmt,-2)(43)
  2847. else if cat[pp+1]=colon then
  2848.   begin app(force); app(backup); app2(pp); reduce(pp,2,intro,-3)(44);
  2849.   end
  2850. else if cat[pp+1]=math then squash(pp,2,math,-1)(45)
  2851. else if cat[pp+1]=mod_scrap then squash(pp,2,mod_scrap,0)(46)
  2852. else if cat[pp+1]=simp then squash(pp,2,simp,-2)(47)
  2853. else if cat[pp+1]=terminator then squash(pp,2,stmt,-2)(48)
  2854. @ @<Cases for |stmt|@>=
  2855. if cat[pp+1]=stmt then
  2856.   begin app1(pp); app(break_space); app1(pp+1);
  2857.   reduce(pp,2,stmt,-2)(49);
  2858.   end
  2859. @ @<Cases for |terminator|@>=
  2860. squash(pp,1,stmt,-2)(50)
  2861. @ @<Cases for |var_head|@>=
  2862. if cat[pp+1]=beginning then squash(pp,1,stmt,-2)(51)
  2863. else if cat[pp+1]=math then
  2864.   begin if cat[pp+2]=colon then
  2865.     begin app("$"); app1(pp+1); app("$"); app1(pp+2);
  2866.     reduce(pp+1,2,intro,+1)(52);
  2867.     end;
  2868.   end
  2869. else if cat[pp+1]=simp then
  2870.   begin if cat[pp+2]=colon then squash(pp+1,2,intro,+1)(53);
  2871.   end
  2872. else if cat[pp+1]=stmt then
  2873.   begin app1(pp); app(break_space); app1(pp+1);
  2874.   reduce(pp,2,var_head,-2)(54);
  2875.   end
  2876. @ The `|freeze_text|' macro is used to give official status to a token list.
  2877. Before saying |freeze_text|, items are appended to the current token list,
  2878. and we know that the eventual number of this token list will be the current
  2879. value of |text_ptr|. But no list of that number really exists as yet,
  2880. because no ending point for the current list has been
  2881. stored in the |tok_start| array. After saying |freeze_text|, the
  2882. old current token list becomes legitimate, and its number is the current
  2883. value of |text_ptr-1| since |text_ptr| has been increased. The new
  2884. current token list is empty and ready to be appended to.
  2885. Note that |freeze_text| does not check to see that |text_ptr| hasn't gotten
  2886. too large, since it is assumed that this test was done beforehand.
  2887. @d freeze_text==incr(text_ptr); tok_start[text_ptr]:=tok_ptr
  2888. @ The `|reduce|' macro used in our code for productions actually calls on
  2889. a procedure named `|red|', which makes the appropriate changes to the
  2890. scrap list.
  2891. @p procedure red(@!j:sixteen_bits; @!k:eight_bits; @!c:eight_bits;
  2892.   @!d:integer);
  2893. var i:0..max_scraps; {index into scrap memory}
  2894. begin cat[j]:=c; trans[j]:=text_ptr; freeze_text;
  2895. if k>1 then
  2896.   begin for i:=j+k to lo_ptr do
  2897.     begin cat[i-k+1]:=cat[i]; trans[i-k+1]:=trans[i];
  2898.     end;
  2899.   lo_ptr:=lo_ptr-k+1;
  2900.   end;
  2901. @<Change |pp| to $\max(|scrap_base|,|pp+d|)$@>;
  2902. @ @<Change |pp| to $\max(|scrap_base|,|pp+d|)$@>=
  2903. if pp+d>=scrap_base then pp:=pp+d
  2904. else pp:=scrap_base
  2905. @ Similarly, the `|squash|' macro invokes a procedure called `|sq|'. This
  2906. procedure takes advantage of the simplification that occurs when |k=1|.
  2907. @p procedure sq(@!j:sixteen_bits; @!k:eight_bits; @!c:eight_bits;
  2908.   @!d:integer);
  2909. var i:0..max_scraps; {index into scrap memory}
  2910. begin if k=1 then
  2911.   begin cat[j]:=c; @<Change |pp|...@>;
  2912.   end
  2913. else  begin for i:=j to j+k-1 do
  2914.     begin app1(i);
  2915.     end;
  2916.   red(j,k,c,d);
  2917.   end;
  2918. @ Here now is the code that applies productions as long as possible. It
  2919. requires two local labels (|found| and |done|), as well as a local
  2920. variable (|i|).
  2921. @<Reduce the scraps using the productions until no more rules apply@>=
  2922. loop@+begin @<Make sure the entries |cat[pp..(pp+3)]| are defined@>;
  2923.   if (tok_ptr+8>max_toks)or(text_ptr+4>max_texts) then
  2924.     begin stat if tok_ptr>max_tok_ptr then max_tok_ptr:=tok_ptr;
  2925.     if text_ptr>max_txt_ptr then max_txt_ptr:=text_ptr;
  2926.     tats@;@/
  2927.     overflow('token/text');
  2928.     end;
  2929.   if pp>lo_ptr then goto done;
  2930.   @<Match a production...@>;
  2931.   end;
  2932. done:
  2933. @ If we get to the end of the scrap list, category codes equal to zero are
  2934. stored, since zero does not match anything in a production.
  2935. @<Make sure the entries...@>=
  2936. if lo_ptr<pp+3 then
  2937.   begin repeat if hi_ptr<=scrap_ptr then
  2938.     begin incr(lo_ptr);@/
  2939.     cat[lo_ptr]:=cat[hi_ptr]; trans[lo_ptr]:=trans[hi_ptr];@/
  2940.     incr(hi_ptr);
  2941.     end;
  2942.   until (hi_ptr>scrap_ptr)or(lo_ptr=pp+3);
  2943.   for i:=lo_ptr+1 to pp+3 do cat[i]:=0;
  2944.   end
  2945. @ If \.{WEAVE} is being run in debugging mode, the production numbers and
  2946. current stack categories will be printed out when |tracing| is set to 2;
  2947. a sequence of two or more irreducible scraps will be printed out when
  2948. |tracing| is set to 1.
  2949. @.\AT!2@>
  2950. @.\AT!1@>
  2951. @<Glo...@>=
  2952. @!debug@!tracing:0..2; {can be used to show parsing details}
  2953. gubed
  2954. @ The |prod| procedure is called in debugging mode just after |reduce| or
  2955. |squash|; its parameter is the number of the production that has just
  2956. been applied.
  2957. @p @!debug procedure prod(@!n:eight_bits); {shows current categories}
  2958. var k:1..max_scraps; {index into |cat|}
  2959. begin if tracing=2 then
  2960.   begin print_nl(n:1,':');
  2961.   for k:=scrap_base to lo_ptr do
  2962.     begin if k=pp then print('*') @+ else print(' ');
  2963.     print_cat(cat[k]);
  2964.     end;
  2965.   if hi_ptr<=scrap_ptr then print('...'); {indicate that more is coming}
  2966.   end;
  2967. gubed
  2968. @ The |translate| function assumes that scraps have been stored in
  2969. positions |scrap_base| through |scrap_ptr| of |cat| and |trans|. It
  2970. appends a |terminator| scrap and begins to apply productions as much as
  2971. possible. The result is a token list containing the translation of
  2972. the given sequence of scraps.
  2973. After calling |translate|, we will have |text_ptr+3<=max_texts| and
  2974. |tok_ptr+6<=max_toks|, so it will be possible to create up to three token
  2975. lists with up to six tokens without checking for overflow. Before calling
  2976. |translate|, we should have |text_ptr<max_texts| and |scrap_ptr<max_scraps|,
  2977. since |translate| might add a new text and a new scrap before it checks
  2978. for overflow.
  2979. @p @<Declaration of subprocedures for |translate|@>@;
  2980. function translate:text_pointer; {converts a sequence of scraps}
  2981. label done,found;
  2982. var i: 1..max_scraps; {index into |cat|}
  2983. @!j:0..max_scraps; {runs through final scraps}
  2984. @!k:0..long_buf_size; {index into |buffer|}
  2985. begin pp:=scrap_base; lo_ptr:=pp-1; hi_ptr:=pp;
  2986. @<If tracing, print an indication of where we are@>;
  2987. @<Reduce the scraps...@>;
  2988. if (lo_ptr=scrap_base)and(cat[lo_ptr]<>math) then translate:=trans[lo_ptr]
  2989. else @<Combine the irreducible scraps that remain@>;
  2990. @ If the initial sequence of scraps does not reduce to a single scrap,
  2991. we concatenate the translations of all remaining scraps, separated by
  2992. blank spaces, with dollar signs surrounding the translations of |math|
  2993. scraps.
  2994. @<Combine the irreducible...@>=
  2995. begin @<If semi-tracing, show the irreducible scraps@>;
  2996. for j:=scrap_base to lo_ptr do
  2997.   begin if j<>scrap_base then
  2998.     begin app(" ");
  2999.     end;
  3000.   if cat[j]=math then
  3001.     begin app("$");
  3002.     end;
  3003.   app1(j);
  3004.   if cat[j]=math then
  3005.     begin app("$");
  3006.     end;
  3007.   if tok_ptr+6>max_toks then overflow('token');
  3008.   end;
  3009. freeze_text; translate:=text_ptr-1;
  3010. @ @<If semi-tracing, show the irreducible scraps@>=
  3011. @!debug if (lo_ptr>scrap_base)and(tracing=1) then
  3012.   begin print_nl('Irreducible scrap sequence in section ',module_count:1);
  3013.   print_ln(':'); mark_harmless;
  3014.   for j:=scrap_base to lo_ptr do
  3015.     begin print(' '); print_cat(cat[j]);
  3016.     end;
  3017.   end;
  3018. gubed
  3019. @ @<If tracing,...@>=
  3020. @!debug if tracing=2 then
  3021.   begin print_nl('Tracing after l.',line:1,':'); mark_harmless;
  3022.   if loc>50 then
  3023.     begin print('...');
  3024.     for k:=loc-50 to loc do print(xchr[buffer[k-1]]);
  3025.     end
  3026.   else for k:=1 to loc do print(xchr[buffer[k-1]]);
  3027.   end
  3028. gubed
  3029. @* Initializing the scraps.
  3030. If we are going to use the powerful production mechanism just developed, we
  3031. must get the scraps set up in the first place, given a \PASCAL\ text. A table
  3032. of the initial scraps corresponding to \PASCAL\ tokens appeared above in the
  3033. section on parsing; our goal now is to implement that table. We shall do this
  3034. by implementing a subroutine called |Pascal_parse| that is analogous to the
  3035. |Pascal_xref| routine used during phase one.
  3036. Like |Pascal_xref|, the |Pascal_parse| procedure starts with the current
  3037. value of |next_control| and it uses the operation |next_control:=get_next|
  3038. repeatedly to read \PASCAL\ text until encountering the next `\v' or
  3039. `\.\{', or until |next_control>=format|. The scraps corresponding to what
  3040. it reads are appended into the |cat| and |trans| arrays, and |scrap_ptr|
  3041. is advanced.
  3042. Like |prod|, this procedure has to split into pieces so that each
  3043. part is short enough to be handled by \PASCAL\ compilers that discriminate
  3044. against long subroutines. This time there are two split-off routines,
  3045. called |easy_cases| and |sub_cases|.
  3046. @^split procedures@>
  3047. After studying |Pascal_parse|, we will look at the sub-procedures
  3048. |app_comment|, |app_octal|, and |app_hex| that are used in some of its
  3049. branches.
  3050. @p @<Declaration of the |app_comment| procedure@>@;
  3051. @<Declaration of the |app_octal| and |app_hex| procedures@>@;
  3052. @<Declaration of the |easy_cases| procedure@>@;
  3053. @<Declaration of the |sub_cases| procedure@>@;
  3054. procedure Pascal_parse; {creates scraps from \PASCAL\ tokens}
  3055. label reswitch, exit;
  3056. var j:0..long_buf_size; {index into |buffer|}
  3057. @!p:name_pointer; {identifier designator}
  3058. begin while next_control<format do
  3059.   begin @<Append the scrap appropriate to |next_control|@>;
  3060.   next_control:=get_next;
  3061.   if (next_control="|")or(next_control="{") then return;
  3062.   end;
  3063. exit:end;
  3064. @ The macros defined here are helpful abbreviations for the operations
  3065. needed when generating the scraps. A scrap of category |c| whose
  3066. translation has three tokens $t_1$, $t_2$, $t_3$ is generated by
  3067. |sc3|$(t_1)(t_2)(t_3)(c)$, etc.
  3068. @d s0(#)==incr(scrap_ptr); cat[scrap_ptr]:=#; trans[scrap_ptr]:=text_ptr;
  3069.   freeze_text;
  3070.   end
  3071. @d s1(#)==app(#);s0
  3072. @d s2(#)==app(#);s1
  3073. @d s3(#)==app(#);s2
  3074. @d s4(#)==app(#);s3
  3075. @d sc4==@+begin s4
  3076. @d sc3==@+begin s3
  3077. @d sc2==@+begin s2
  3078. @d sc1==@+begin s1
  3079. @d sc0(#)==begin incr(scrap_ptr); cat[scrap_ptr]:=#; trans[scrap_ptr]:=0;
  3080.   end
  3081. @d comment_scrap(#)==begin app(#); app_comment;
  3082.   end
  3083. @ @<Append the scr...@>=
  3084. @<Make sure that there is room for at least four more scraps, six more
  3085. tokens, and four more texts@>;
  3086. reswitch: case next_control of
  3087. string,verbatim: @<Append a \(string scrap@>;
  3088. identifier: @<Append an identifier scrap@>;
  3089. TeX_string: @<Append a \TeX\ string scrap@>;
  3090. othercases easy_cases
  3091. endcases
  3092. @ The |easy_cases| each result in straightforward scraps.
  3093. @<Declaration of the |easy_cases| procedure@>=
  3094. procedure easy_cases; {a subprocedure of |Pascal_parse|}
  3095. begin case next_control of
  3096. set_element_sign: sc3("\")("i")("n")(math);
  3097. @.\\in@>
  3098. double_dot: sc3("\")("t")("o")(math);
  3099. @.\\to@>
  3100. "#","$","%","^","_": sc2("\")(next_control)(math);
  3101. @.\\\#@>
  3102. @.\\\$@>
  3103. @.\\\%@>
  3104. @.\\\^@>
  3105. ignore,"|",xref_roman,xref_wildcard,xref_typewriter: do_nothing;
  3106. "(","[": sc1(next_control)(open);
  3107. ")","]": sc1(next_control)(close);
  3108. "*": sc4("\")("a")("s")("t")(math);
  3109. @.\\ast@>
  3110. ",": sc3(",")(opt)("9")(math);
  3111. ".","0","1","2","3","4","5","6","7","8","9": sc1(next_control)(simp);
  3112. ";": sc1(";")(semi);
  3113. ":": sc1(":")(colon);
  3114. @t\4@>  @<Cases involving nonstandard ASCII characters@>@;
  3115. exponent: sc3("\")("E")("{")(exp);
  3116. @.\\E@>
  3117. begin_comment: sc2("\")("B")(math);
  3118. @.\\B@>
  3119. end_comment: sc2("\")("T")(math);
  3120. @.\\T@>
  3121. octal: app_octal;
  3122. hex: app_hex;
  3123. check_sum: sc2("\")(")")(simp);
  3124. @.\\)@>
  3125. force_line: sc2("\")("]")(simp);
  3126. @.\\]@>
  3127. thin_space: sc2("\")(",")(math);
  3128. @.\\,@>
  3129. math_break: sc2(opt)("0")(simp);
  3130. line_break: comment_scrap(force);
  3131. big_line_break: comment_scrap(big_force);
  3132. no_line_break: begin app(big_cancel); app("\"); app(" ");
  3133. @.\\\ @>
  3134.   comment_scrap(big_cancel);
  3135.   end;
  3136. pseudo_semi: sc0(semi);
  3137. join: sc2("\")("J")(math);
  3138. @.\\J@>
  3139. othercases sc1(next_control)(math)
  3140. endcases;
  3141. @ @<Make sure that there is room for at least four...@>=
  3142. if (scrap_ptr+4>max_scraps)or(tok_ptr+6>max_toks)or(text_ptr+4>max_texts) then
  3143.   begin stat if scrap_ptr>max_scr_ptr then max_scr_ptr:=scrap_ptr;
  3144.   if tok_ptr>max_tok_ptr then max_tok_ptr:=tok_ptr;
  3145.   if text_ptr>max_txt_ptr then max_txt_ptr:=text_ptr;
  3146.   tats@;@/
  3147.   overflow('scrap/token/text');
  3148.   end
  3149. @ Some nonstandard ASCII characters may have entered \.{WEAVE} by means of
  3150. standard ones. They are converted to \TeX\ control sequences so that it is
  3151. possible to keep \.{WEAVE} from stepping beyond standard ASCII.
  3152. @<Cases involving nonstandard...@>=
  3153. not_equal: sc2("\")("I")(math);
  3154. @.\\I@>
  3155. less_or_equal: sc2("\")("L")(math);
  3156. @.\\L@>
  3157. greater_or_equal: sc2("\")("G")(math);
  3158. @.\\G@>
  3159. equivalence_sign: sc2("\")("S")(math);
  3160. @.\\S@>
  3161. and_sign: sc2("\")("W")(math);
  3162. @.\\W@>
  3163. or_sign: sc2("\")("V")(math);
  3164. @.\\V@>
  3165. not_sign: sc2("\")("R")(math);
  3166. @.\\R@>
  3167. left_arrow: sc2("\")("K")(math);
  3168. @.\\K@>
  3169. @ The following code must use |app_tok| instead of |app| in order to
  3170. protect against overflow. Note that |tok_ptr+1<=max_toks| after |app_tok|
  3171. has been used, so another |app| is legitimate before testing again.
  3172. Many of the special characters in a string must be prefixed by `\.\\' so that
  3173. \TeX\ will print them properly.
  3174. @^special string characters@>
  3175. @<Append a \(string scrap@>=
  3176. begin app("\");
  3177. if next_control=verbatim then
  3178.   begin app("=");
  3179. @.\\=@>
  3180.   end
  3181. else  begin app(".");
  3182. @.\\.@>
  3183.   end;
  3184. app("{"); j:=id_first;
  3185. while j<id_loc do
  3186.   begin case buffer[j] of
  3187.   " ","\","#","%","$","^","'","`","{","}","~","&","_":
  3188.       begin app("\");
  3189.       end;
  3190. @.\\\ @>
  3191. @.\\\\@>
  3192. @.\\\#@>
  3193. @.\\\%@>
  3194. @.\\\$@>
  3195. @.\\\^@>
  3196. @.\\\'@>
  3197. @.\\\`@>
  3198. @.\\\{@>
  3199. @.\\\}@>
  3200. @.\\\~@>
  3201. @.\\\&@>
  3202. @.\\_@>
  3203.   "@@": if buffer[j+1]="@@" then incr(j)
  3204.     else err_print('! Double @@ should be used in strings');
  3205. @.Double \AT! should be used...@>
  3206.   othercases do_nothing
  3207.   endcases;@/
  3208.   app_tok(buffer[j]); incr(j);
  3209.   end;
  3210. sc1("}")(simp);
  3211. @ @<Append a \TeX\ string scrap@>=
  3212. begin app("\"); app("h"); app("b"); app("o"); app("x");
  3213. app("{");
  3214. for j:=id_first to id_loc-1 do app_tok(buffer[j]);
  3215. sc1("}")(simp);
  3216. @ @<Append an identifier scrap@>=
  3217. begin p:=id_lookup(normal);
  3218. case ilk[p] of
  3219. normal,array_like,const_like,div_like,
  3220.   do_like,for_like,goto_like,nil_like,to_like: sub_cases(p);
  3221. @t\4@>@<Cases that generate more than one scrap@>@;
  3222. othercases begin next_control:=ilk[p]-char_like; goto reswitch;
  3223.   end {\&{and}, \&{in}, \&{not}, \&{or}}
  3224. endcases;
  3225. @ The |sub_cases| also result in straightforward scraps.
  3226. @<Declaration of the |sub_cases| procedure@>=
  3227. procedure sub_cases(@!p:name_pointer); {a subprocedure of |Pascal_parse|}
  3228. begin case ilk[p] of
  3229. normal: sc1(id_flag+p)(simp); {not a reserved word}
  3230. array_like: sc1(res_flag+p)(alpha); {\&{array}, \&{file}, \&{set}}
  3231. const_like: sc3(force)(backup)(res_flag+p)(intro);
  3232.   {\&{const}, \&{label}, \&{type}}
  3233. div_like: sc3(math_bin)(res_flag+p)("}")(math); {\&{div}, \&{mod}}
  3234. do_like: sc1(res_flag+p)(omega); {\&{do}, \&{of}, \&{then}}
  3235. for_like: sc2(force)(res_flag+p)(alpha); {\&{for}, \&{while}, \&{with}}
  3236. goto_like: sc1(res_flag+p)(intro); {\&{goto}, \&{packed}}
  3237. nil_like: sc1(res_flag+p)(simp); {\&{nil}}
  3238. to_like: sc3(math_rel)(res_flag+p)("}")(math); {\&{downto}, \&{to}}
  3239. @ @<Cases that generate more than one scrap@>=
  3240. begin_like: begin sc3(force)(res_flag+p)(cancel)(beginning); sc0(intro);
  3241.   end; {\&{begin}}
  3242. case_like: begin sc0(casey); sc2(force)(res_flag+p)(alpha);
  3243.   end; {\&{case}}
  3244. else_like: begin @<Append |terminator| if not already present@>;
  3245.   sc3(force)(backup)(res_flag+p)(elsie);
  3246.   end; {\&{else}}
  3247. end_like: begin @<Append |term...@>;
  3248.   sc2(force)(res_flag+p)(close);
  3249.   end; {\&{end}}
  3250. if_like: begin sc0(cond); sc2(force)(res_flag+p)(alpha);
  3251.   end; {\&{if}}
  3252. loop_like: begin sc3(force)("\")("~")(alpha);
  3253. @.\\\~@>
  3254.   sc1(res_flag+p)(omega);
  3255.   end; {\&{xclause}}
  3256. proc_like: begin sc4(force)(backup)(res_flag+p)(cancel)(proc);
  3257.   sc3(indent)("\")(" ")(intro);
  3258. @.\\\ @>
  3259.   end; {\&{function}, \&{procedure}, \&{program}}
  3260. record_like: begin sc1(res_flag+p)(record_head); sc0(intro);
  3261.   end; {\&{record}}
  3262. repeat_like: begin sc4(force)(indent)(res_flag+p)(cancel)(beginning);
  3263.   sc0(intro);
  3264.   end; {\&{repeat}}
  3265. until_like: begin @<Append |term...@>;
  3266.   sc3(force)(backup)(res_flag+p)(close); sc0(clause);
  3267.   end; {\&{until}}
  3268. var_like: begin sc4(force)(backup)(res_flag+p)(cancel)(var_head); sc0(intro);
  3269.   end; {\&{var}}
  3270. @ If a comment or semicolon appears before the reserved words \&{end},
  3271. \&{else}, or \&{until}, the |semi| or |terminator| scrap that is already
  3272. present overrides the |terminator| scrap belonging to this reserved word.
  3273. @<Append |termin...@>=
  3274. if (scrap_ptr<scrap_base)or((cat[scrap_ptr]<>terminator)and
  3275.     (cat[scrap_ptr]<>semi)) then sc0(terminator)
  3276. @ A comment is incorporated into the previous scrap if that scrap is of type
  3277. |omega| or |semi| or |terminator|. (These three categories have consecutive
  3278. category codes.) Otherwise the comment is entered as a separate scrap
  3279. of type |terminator|, and it will combine with a |terminator| scrap that
  3280. immediately follows~it.
  3281. The |app_comment| procedure takes care of placing a comment at the end of the
  3282. current scrap list. When |app_comment| is called, we assume that the current
  3283. token list is the translation of the comment involved.
  3284. @<Declaration of the |app_comment|...@>=
  3285. procedure app_comment; {append a comment to the scrap list}
  3286. begin freeze_text;
  3287. if (scrap_ptr<scrap_base)or(cat[scrap_ptr]<omega)or
  3288.     (cat[scrap_ptr]>terminator) then sc0(terminator)
  3289. else  begin app1(scrap_ptr); {|cat[scrap_ptr]| is
  3290.     |omega| or |semi| or |terminator|}
  3291.   end;
  3292. app(text_ptr-1+tok_flag); trans[scrap_ptr]:=text_ptr; freeze_text;
  3293. @ We are now finished with |Pascal_parse|, except for two relatively
  3294. trivial subprocedures that convert constants into tokens.
  3295. @<Declaration of the |app_octal| and...@>=
  3296. procedure app_octal;
  3297. begin app("\"); app("O"); app("{");
  3298. @.\\O@>
  3299. while (buffer[loc]>="0")and(buffer[loc]<="7") do
  3300.   begin app_tok(buffer[loc]); incr(loc);
  3301.   end;
  3302. sc1("}")(simp);
  3303. procedure app_hex;
  3304. begin app("\"); app("H"); app("{");
  3305. @.\\H@>
  3306. while ((buffer[loc]>="0")and(buffer[loc]<="9"))or@|
  3307.     ((buffer[loc]>="A")and(buffer[loc]<="F")) do
  3308.   begin app_tok(buffer[loc]); incr(loc);
  3309.   end;
  3310. sc1("}")(simp);
  3311. @ When the `\v' that introduces \PASCAL\ text is sensed, a call on
  3312. |Pascal_translate| will return a pointer to the \TeX\ translation of
  3313. that text. If scraps exist in the |cat| and |trans| arrays, they are
  3314. unaffected by this translation process.
  3315. @p function Pascal_translate: text_pointer;
  3316. var p:text_pointer; {points to the translation}
  3317. @!save_base:0..max_scraps; {holds original value of |scrap_base|}
  3318. begin save_base:=scrap_base; scrap_base:=scrap_ptr+1;
  3319. Pascal_parse; {get the scraps together}
  3320. if next_control<>"|" then err_print('! Missing "|" after Pascal text');
  3321. @.Missing "|"...@>
  3322. app_tok(cancel); app_comment; {place a |cancel| token as a final ``comment''}
  3323. p:=translate; {make the translation}
  3324. stat if scrap_ptr>max_scr_ptr then max_scr_ptr:=scrap_ptr;@;@+tats@;@/
  3325. scrap_ptr:=scrap_base-1; scrap_base:=save_base; {scrap the scraps}
  3326. Pascal_translate:=p;
  3327. @ The |outer_parse| routine is to |Pascal_parse| as |outer_xref|
  3328. is to |Pascal_xref|: It constructs a sequence of scraps for \PASCAL\ text
  3329. until |next_control>=format|. Thus, it takes care of embedded comments.
  3330. @p procedure outer_parse; {makes scraps from \PASCAL\ tokens and comments}
  3331. var bal:eight_bits; {brace level in comment}
  3332. @!p,@!q:text_pointer; {partial comments}
  3333. begin while next_control<format do
  3334.   if next_control<>"{" then Pascal_parse
  3335.   else  begin @<Make sure that there is room for at least seven more
  3336.       tokens, three more texts, and one more scrap@>;
  3337.     app("\"); app("C"); app("{");
  3338. @.\\C@>
  3339.     bal:=copy_comment(1); next_control:="|";
  3340.     while bal>0 do
  3341.       begin p:=text_ptr; freeze_text; q:=Pascal_translate;
  3342.       {at this point we have |tok_ptr+6<=max_toks|}
  3343.       app(tok_flag+p); app(inner_tok_flag+q);
  3344.       if next_control="|" then bal:=copy_comment(bal)
  3345.       else bal:=0; {an error has been reported}
  3346.       end;
  3347.     app(force); app_comment; {the full comment becomes a scrap}
  3348.     end;
  3349. @ @<Make sure that there is room for at least seven more...@>=
  3350. if (tok_ptr+7>max_toks)or(text_ptr+3>max_texts)or(scrap_ptr>=max_scraps) then
  3351.   begin stat if scrap_ptr>max_scr_ptr then max_scr_ptr:=scrap_ptr;
  3352.   if tok_ptr>max_tok_ptr then max_tok_ptr:=tok_ptr;
  3353.   if text_ptr>max_txt_ptr then max_txt_ptr:=text_ptr;
  3354.   tats@;@/
  3355.   overflow('token/text/scrap');
  3356.   end
  3357. @* Output of tokens.
  3358. So far our programs have only built up multi-layered token lists in
  3359. \.{WEAVE}'s internal memory; we have to figure out how to get them into
  3360. the desired final form. The job of converting token lists to characters in
  3361. the \TeX\ output file is not difficult, although it is an implicitly
  3362. recursive process. Four main considerations had to be kept in mind when
  3363. this part of \.{WEAVE} was designed.  (a) There are two modes of output:
  3364. |outer| mode, which translates tokens like |force| into line-breaking
  3365. control sequences, and |inner| mode, which ignores them except that blank
  3366. spaces take the place of line breaks. (b) The |cancel| instruction applies
  3367. to adjacent token or tokens that are output, and this cuts across levels
  3368. of recursion since `|cancel|' occurs at the beginning or end of a token
  3369. list on one level. (c) The \TeX\ output file will be semi-readable if line
  3370. breaks are inserted after the result of tokens like |break_space| and
  3371. |force|.  (d) The final line break should be suppressed, and there should
  3372. be no |force| token output immediately after `\.{\\Y\\P}'.
  3373. @ The output process uses a stack to keep track of what is going on at
  3374. different ``levels'' as the token lists are being written out. Entries on
  3375. this stack have three parts:
  3376. \yskip\hang |end_field| is the |tok_mem| location where the token list of a
  3377. particular level will end;
  3378. \yskip\hang |tok_field| is the |tok_mem| location from which the next token
  3379. on a particular level will be read;
  3380. \yskip\hang |mode_field| is the current mode, either |inner| or |outer|.
  3381. \yskip\noindent The current values of these quantities are referred to
  3382. quite frequently, so they are stored in a separate place instead of in the
  3383. |stack| array. We call the current values |cur_end|, |cur_tok|, and
  3384. |cur_mode|.
  3385. The global variable |stack_ptr| tells how many levels of output are
  3386. currently in progress. The end of output occurs when an |end_translation|
  3387. token is found, so the stack is never empty except when we first begin the
  3388. output process.
  3389. @d inner=0 {value of |mode| for \PASCAL\ texts within \TeX\ texts}
  3390. @d outer=1 {value of |mode| for \PASCAL\ texts in modules}
  3391. @<Types...@>=
  3392. @!mode=inner..outer;@/
  3393. @!output_state=record@!end_field:sixteen_bits; {ending location of token list}
  3394.   @!tok_field:sixteen_bits; {present location within token list}
  3395.   @!mode_field:mode; {interpretation of control tokens}
  3396.   end;
  3397. @ @d cur_end==cur_state.end_field {current ending location in |tok_mem|}
  3398. @d cur_tok==cur_state.tok_field {location of next output token in |tok_mem|}
  3399. @d cur_mode==cur_state.mode_field {current mode of interpretation}
  3400. @d init_stack==stack_ptr:=0;cur_mode:=outer {do this to initialize the stack}
  3401. @<Glob...@>=
  3402. @!cur_state:output_state; {|cur_end|, |cur_tok|, |cur_mode|}
  3403. @!stack:array[1..stack_size] of output_state; {info for non-current levels}
  3404. @!stack_ptr:0..stack_size; {first unused location in the output state stack}
  3405. stat@!max_stack_ptr:0..stack_size; {largest value assumed by |stack_ptr|}
  3406. @ @<Set init...@>=stat max_stack_ptr:=0;@+tats
  3407. @ To insert token-list |p| into the output, the |push_level| subroutine
  3408. is called; it saves the old level of output and gets a new one going.
  3409. The value of |cur_mode| is not changed.
  3410. @p procedure push_level(@!p:text_pointer); {suspends the current level}
  3411. begin if stack_ptr=stack_size then overflow('stack')
  3412. else  begin if stack_ptr>0 then
  3413.     stack[stack_ptr]:=cur_state; {save |cur_end|$\,\ldots\,$|cur_mode|}
  3414.   incr(stack_ptr);
  3415.   stat if stack_ptr>max_stack_ptr then
  3416.     max_stack_ptr:=stack_ptr;@;@+tats@;@/
  3417.   cur_tok:=tok_start[p]; cur_end:=tok_start[p+1];
  3418.   end;
  3419. @ Conversely, the |pop_level| routine restores the conditions that were in
  3420. force when the current level was begun. This subroutine will never be
  3421. called when |stack_ptr=1|. It is so simple, we declare it as a macro:
  3422. @d pop_level==begin decr(stack_ptr); cur_state:=stack[stack_ptr];
  3423.   end {do this when |cur_tok| reaches |cur_end|}
  3424. @ The |get_output| function returns the next byte of output that is not a
  3425. reference to a token list. It returns the values |identifier| or |res_word|
  3426. or |mod_name| if the next token is to be an identifier (typeset in
  3427. italics), a reserved word (typeset in boldface) or a module name (typeset
  3428. by a complex routine that might generate additional levels of output).
  3429. In these cases |cur_name| points to the identifier or module name in
  3430. question.
  3431. @d res_word=@'201 {returned by |get_output| for reserved words}
  3432. @d mod_name=@'200 {returned by |get_output| for module names}
  3433. @p function get_output:eight_bits; {returns the next token of output}
  3434. label restart;
  3435. var a:sixteen_bits; {current item read from |tok_mem|}
  3436. begin restart: while cur_tok=cur_end do pop_level;
  3437. a:=tok_mem[cur_tok]; incr(cur_tok);
  3438. if a>=@'400 then
  3439.   begin cur_name:=a mod id_flag;
  3440.   case a div id_flag of
  3441.   2: a:=res_word; {|a=res_flag+cur_name|}
  3442.   3: a:=mod_name; {|a=mod_flag+cur_name|}
  3443.   4: begin push_level(cur_name); goto restart;
  3444.     end; {|a=tok_flag+cur_name|}
  3445.   5: begin push_level(cur_name); cur_mode:=inner; goto restart;
  3446.     end; {|a=inner_tok_flag+cur_name|}
  3447.   othercases a:=identifier {|a=id_flag+cur_name|}
  3448.   endcases;
  3449.   end;
  3450. @!debug if trouble_shooting then debug_help; @+ gubed@/
  3451. get_output:=a;
  3452. @ The real work associated with token output is done by |make_output|.
  3453. This procedure appends an |end_translation| token to the current token list,
  3454. and then it repeatedly calls |get_output| and feeds characters to the output
  3455. buffer until reaching the |end_translation| sentinel. It is possible for
  3456. |make_output| to
  3457. be called recursively, since a module name may include embedded \PASCAL\
  3458. text; however, the depth of recursion never exceeds one level, since
  3459. module names cannot be inside of module names.
  3460. A procedure called |output_Pascal| does the scanning, translation, and
  3461. output of \PASCAL\ text within `\pb' brackets, and this procedure uses
  3462. |make_output| to output the current token list. Thus, the recursive call
  3463. of |make_output| actually occurs when |make_output| calls |output_Pascal|
  3464. while outputting the name of a module.
  3465. @^recursion@>
  3466. @p procedure make_output; forward; @t\2@>@#
  3467. procedure output_Pascal; {outputs the current token list}
  3468. var save_tok_ptr,@!save_text_ptr,@!save_next_control:sixteen_bits;
  3469.   {values to be restored}
  3470. p:text_pointer; {translation of the \PASCAL\ text}
  3471. begin save_tok_ptr:=tok_ptr; save_text_ptr:=text_ptr;
  3472. save_next_control:=next_control; next_control:="|"; p:=Pascal_translate;
  3473. app(p+inner_tok_flag);
  3474. make_output; {output the list}
  3475. stat if text_ptr>max_txt_ptr then max_txt_ptr:=text_ptr;
  3476. if tok_ptr>max_tok_ptr then max_tok_ptr:=tok_ptr;@;@+tats@;@/
  3477. text_ptr:=save_text_ptr; tok_ptr:=save_tok_ptr; {forget the tokens}
  3478. next_control:=save_next_control; {restore |next_control| to original state}
  3479. @ Here is \.{WEAVE}'s major output handler.
  3480. @p procedure make_output; {outputs the equivalents of tokens}
  3481. label reswitch,exit,found;
  3482. var a:eight_bits; {current output byte}
  3483. @!b:eight_bits; {next output byte}
  3484. @!k,@!k_limit:0..max_bytes; {indices into |byte_mem|}
  3485. @!w:0..ww-1; {row of |byte_mem|}
  3486. @!j:0..long_buf_size; {index into |buffer|}
  3487. @!string_delimiter:ASCII_code; {first and last character of
  3488.   string being copied}
  3489. @!save_loc,@!save_limit:0..long_buf_size; {|loc| and |limit| to be restored}
  3490. @!cur_mod_name:name_pointer; {name of module being output}
  3491. @!save_mode:mode; {value of |cur_mode| before a sequence of breaks}
  3492. begin app(end_translation); {append a sentinel}
  3493. freeze_text; push_level(text_ptr-1);
  3494. loop@+  begin a:=get_output;
  3495. reswitch: case a of
  3496.   end_translation: return;
  3497.   identifier,res_word:@<Output an identifier@>;
  3498.   mod_name:@<Output a module name@>;
  3499.   math_bin,math_op,math_rel:@<Output a \.{\\math} operator@>;
  3500.   cancel: begin repeat a:=get_output;
  3501.     until (a<backup)or(a>big_force);
  3502.     goto reswitch;
  3503.     end;
  3504.   big_cancel: begin repeat a:=get_output;
  3505.     until ((a<backup)and(a<>" "))or(a>big_force);
  3506.     goto reswitch;
  3507.     end;
  3508.   indent,outdent,opt,backup,break_space,force,big_force:@<Output a
  3509.     \(control, look ahead in case of line breaks,
  3510.     possibly |goto reswitch|@>;
  3511.   othercases out(a) {otherwise |a| is an ASCII character}
  3512.   endcases;
  3513.   end;
  3514. exit:end;
  3515. @ An identifier of length one does not have to be enclosed in braces, and it
  3516. looks slightly better if set in a math-italic font instead of a (slightly
  3517. narrower) text-italic font. Thus we output `\.{\\\char'174a}' but
  3518. `\.{\\\\\{aa\}}'.
  3519. @<Output an identifier@>=
  3520. begin out("\");
  3521. if a=identifier then
  3522.   if length(cur_name)=1 then out("|")
  3523. @.\\|@>
  3524.   else out("\")
  3525. @.\\\\@>
  3526. else out("&"); {|a=res_word|}
  3527. @.\\\&@>
  3528. if length(cur_name)=1 then out(byte_mem[cur_name mod ww,byte_start[cur_name]])
  3529. else out_name(cur_name);
  3530. @ @<Output a \....@>=
  3531. begin out5("\")("m")("a")("t")("h");
  3532. if a=math_bin then out3("b")("i")("n")
  3533. else if a=math_rel then out3("r")("e")("l")
  3534. else out2("o")("p");
  3535. out("{");
  3536. @ The current mode does not affect the behavior of \.{WEAVE}'s output routine
  3537. except when we are outputting control tokens.
  3538. @<Output a \(control...@>=
  3539. if a<break_space then
  3540.   begin if cur_mode=outer then
  3541.     begin out2("\")(a-cancel+"0");
  3542. @.\\1@>
  3543. @.\\2@>
  3544. @.\\3@>
  3545. @.\\4@>
  3546. @.\\5@>
  3547. @.\\6@>
  3548. @.\\7@>
  3549.     if a=opt then out(get_output) {|opt| is followed by a digit}
  3550.     end
  3551.   else if a=opt then b:=get_output {ignore digit following |opt|}
  3552.   end
  3553. else @<Look ahead for strongest line break, |goto reswitch|@>
  3554. @ If several of the tokens |break_space|, |force|, |big_force| occur in a
  3555. row, possibly mixed with blank spaces (which are ignored),
  3556. the largest one is used. A line break also occurs in the output file,
  3557. except at the very end of the translation. The very first line break
  3558. is suppressed (i.e., a line break that follows `\.{\\Y\\P}').
  3559. @<Look ahead for st...@>=
  3560. begin b:=a; save_mode:=cur_mode;
  3561. loop@+  begin a:=get_output;
  3562.   if (a=cancel)or(a=big_cancel) then goto reswitch;
  3563.     {|cancel| overrides everything}
  3564.   if ((a<>" ")and(a<break_space))or(a>big_force) then
  3565.     begin if save_mode=outer then
  3566.       begin if out_ptr>3 then
  3567.         if (out_buf[out_ptr]="P")and
  3568.           (out_buf[out_ptr-1]="\")and
  3569. @.\\P@>
  3570. @.\\Y@>
  3571.           (out_buf[out_ptr-2]="Y")and
  3572.           (out_buf[out_ptr-3]="\") then
  3573.           goto reswitch;
  3574. @.\\1@>
  3575. @.\\2@>
  3576. @.\\3@>
  3577. @.\\4@>
  3578. @.\\5@>
  3579. @.\\6@>
  3580. @.\\7@>
  3581.       out2("\")(b-cancel+"0");
  3582.       if a<>end_translation then finish_line;
  3583.       end
  3584.     else if (a<>end_translation)and(cur_mode=inner) then out(" ");
  3585.     goto reswitch;
  3586.     end;
  3587.   if a>b then b:=a; {if |a=" "| we have |a<b|}
  3588.   end;
  3589. @ The remaining part of |make_output| is somewhat more complicated. When we
  3590. output a module name, we may need to enter the parsing and translation
  3591. routines, since the name may contain \PASCAL\ code embedded in
  3592. \pb\ constructions. This \PASCAL\ code is placed at the end of the active
  3593. input buffer and the translation process uses the end of the active
  3594. |tok_mem| area.
  3595. @<Output a module name@>=
  3596. begin out2("\")("X");
  3597. @.\\X@>
  3598. cur_xref:=xref[cur_name];
  3599. if num(cur_xref)>=def_flag then
  3600.   begin out_mod(num(cur_xref)-def_flag);
  3601.   if phase_three then
  3602.     begin cur_xref:=xlink(cur_xref);
  3603.     while num(cur_xref)>=def_flag do
  3604.       begin out2(",")(" ");
  3605.       out_mod(num(cur_xref)-def_flag);
  3606.       cur_xref:=xlink(cur_xref);
  3607.       end;
  3608.     end;
  3609.   end
  3610. else out("0"); {output the module number, or zero if it was undefined}
  3611. out(":"); @<Output the text of the module name@>;
  3612. out2("\")("X");
  3613. @ @<Output the text...@>=
  3614. k:=byte_start[cur_name]; w:=cur_name mod ww; k_limit:=byte_start[cur_name+ww];
  3615. cur_mod_name:=cur_name;
  3616. while k<k_limit do
  3617.   begin b:=byte_mem[w,k]; incr(k);
  3618.   if b="@@" then @<Skip next character, give error if not `\.{@@}'@>;
  3619.   if b<>"|" then out(b)
  3620.   else  begin @<Copy the \PASCAL\ text into |buffer[(limit+1)..j]|@>;
  3621.     save_loc:=loc; save_limit:=limit; loc:=limit+2; limit:=j+1;
  3622.     buffer[limit]:="|"; output_Pascal;
  3623.     loc:=save_loc; limit:=save_limit;
  3624.     end;
  3625.   end
  3626. @ @<Skip next char...@>=
  3627. begin if byte_mem[w,k]<>"@@" then
  3628.   begin print_nl('! Illegal control code in section name:');
  3629. @.Illegal control code...@>
  3630.   print_nl('<'); print_id(cur_mod_name); print('> '); mark_error;
  3631.   end;
  3632. incr(k);
  3633. @ The \PASCAL\ text enclosed in \pb\ should not contain `\v' characters,
  3634. except within strings. We put a `\v' at the front of the buffer, so that an
  3635. error message that displays the whole buffer will look a little bit sensible.
  3636. The variable |string_delimiter| is zero outside of strings, otherwise it
  3637. equals the delimiter that began the string being copied.
  3638. @<Copy the \PASCAL\ text into...@>=
  3639. j:=limit+1; buffer[j]:="|"; string_delimiter:=0;
  3640. loop@+  begin if k>=k_limit then
  3641.     begin print_nl('! Pascal text in section name didn''t end:');
  3642. @.Pascal text...didn't end@>
  3643.     print_nl('<'); print_id(cur_mod_name); print('> '); mark_error;
  3644.     goto found;
  3645.     end;
  3646.   b:=byte_mem[w,k]; incr(k);
  3647.   if b="@@" then @<Copy a control code into the buffer@>
  3648.   else  begin if (b="""")or(b="'") then
  3649.       if string_delimiter=0 then string_delimiter:=b
  3650.       else if string_delimiter=b then string_delimiter:=0;
  3651.     if (b<>"|")or(string_delimiter<>0) then
  3652.       begin if j>long_buf_size-3 then overflow('buffer');
  3653.       incr(j); buffer[j]:=b;
  3654.       end
  3655.     else goto found;
  3656.     end;
  3657.   end;
  3658. found:
  3659. @ @<Copy a control code into the buffer@>=
  3660. begin if j>long_buf_size-4 then overflow('buffer');
  3661. buffer[j+1]:="@@"; buffer[j+2]:=byte_mem[w,k]; j:=j+2; incr(k);
  3662. @* Phase two processing.
  3663. We have assembled enough pieces of the puzzle in order to be ready to specify
  3664. the processing in \.{WEAVE}'s main pass over the source file. Phase two
  3665. is analogous to phase one, except that more work is involved because we must
  3666. actually output the \TeX\ material instead of merely looking at the
  3667. \.{WEB} specifications.
  3668. @<Phase II: Read all the text again and translate it to \TeX\ form@>=
  3669. reset_input; print_nl('Writing the output file...');
  3670. module_count:=0;
  3671. copy_limbo;
  3672. finish_line; flush_buffer(0,false,false); {insert a blank line, it looks nice}
  3673. while not input_has_ended do @<Translate the \(current module@>
  3674. @ The output file will contain the control sequence \.{\\Y} between non-null
  3675. sections of a module, e.g., between the \TeX\ and definition parts if both
  3676. are nonempty. This puts a little white space between the parts when they are
  3677. printed. However, we don't want \.{\\Y} to occur between two definitions
  3678. within a single module. The variables |out_line| or |out_ptr| will
  3679. change if a section is non-null, so the following macros `|save_position|'
  3680. and `|emit_space_if_needed|' are able to handle the situation:
  3681. @d save_position==save_line:=out_line; save_place:=out_ptr
  3682. @d emit_space_if_needed==if (save_line<>out_line)or(save_place<>out_ptr) then
  3683.   out2("\")("Y")
  3684. @.\\Y@>
  3685. @<Glo...@>=
  3686. @!save_line:integer; {former value of |out_line|}
  3687. @!save_place:sixteen_bits; {former value of |out_ptr|}
  3688. @ @<Translate the \(current module@>=
  3689. begin incr(module_count);@/
  3690. @<Output the code for the beginning of a new module@>;
  3691. save_position;@/
  3692. @<Translate the \TeX\ part of the current module@>;
  3693. @<Translate the \(definition part of the current module@>;
  3694. @<Translate the \PASCAL\ part of the current module@>;
  3695. @<Show cross references to this module@>;
  3696. @<Output the code for the end of a module@>;
  3697. @ Modules beginning with the \.{WEB} control sequence `\.{@@\ }' start in the
  3698. output with the \TeX\ control sequence `\.{\\M}', followed by the module
  3699. number. Similarly, `\.{@@*}' modules lead to the control sequence `\.{\\N}'.
  3700. If this is a changed module, we put \.{*} just before the module number.
  3701. @<Output the code for the beginning...@>=
  3702. out("\");
  3703. if buffer[loc-1]<>"*" then out("M")
  3704. @.\\M@>
  3705. else  begin out("N"); print('*',module_count:1);
  3706. @.\\N@>
  3707.   update_terminal; {print a progress report}
  3708.   end;
  3709. out_mod(module_count); out2(".")(" ")
  3710. @ In the \TeX\ part of a module, we simply copy the source text, except that
  3711. index entries are not copied and \PASCAL\ text within \pb\ is translated.
  3712. @<Translate the \T...@>=
  3713. repeat next_control:=copy_TeX;
  3714. case next_control of
  3715. "|": begin init_stack; output_Pascal;
  3716.   end;
  3717. "@@": out("@@");
  3718. octal: @<Translate an octal constant appearing in \TeX\ text@>;
  3719. hex: @<Translate a hexadecimal constant appearing in \TeX\ text@>;
  3720. TeX_string,xref_roman,xref_wildcard,xref_typewriter,module_name:
  3721.   begin loc:=loc-2; next_control:=get_next; {skip to \.{@@>}}
  3722.   if next_control=TeX_string then
  3723.     err_print('! TeX string should be in Pascal text only');
  3724. @.TeX string should be...@>
  3725.   end;
  3726. begin_comment,end_comment,check_sum,thin_space,math_break,line_break,
  3727.   big_line_break,no_line_break,join,pseudo_semi:
  3728.     err_print('! You can''t do that in TeX text');
  3729. @.You can't do that...@>
  3730. othercases do_nothing
  3731. endcases;
  3732. until next_control>=format
  3733. @ @<Translate an octal constant appearing in \TeX\ text@>=
  3734. begin out3("\")("O")("{");
  3735. @.\\O@>
  3736. while (buffer[loc]>="0")and(buffer[loc]<="7") do
  3737.   begin out(buffer[loc]); incr(loc);
  3738.   end; {since |buffer[limit]=" "|, this loop will end}
  3739. out("}");
  3740. @ @<Translate a hexadecimal constant appearing in \TeX\ text@>=
  3741. begin out3("\")("H")("{");
  3742. @.\\H@>
  3743. while ((buffer[loc]>="0")and(buffer[loc]<="9"))or@|
  3744.     ((buffer[loc]>="A")and(buffer[loc]<="F")) do
  3745.   begin out(buffer[loc]); incr(loc);
  3746.   end;
  3747. out("}");
  3748. @ When we get to the following code we have |next_control>=format|, and
  3749. the token memory is in its initial empty state.
  3750. @<Translate the \(d...@>=
  3751. if next_control<=definition then {definition part non-empty}
  3752.   begin emit_space_if_needed; save_position;
  3753.   end;
  3754. while next_control<=definition do {|format| or |definition|}
  3755.   begin init_stack;
  3756.   if next_control=definition then @<Start a macro definition@>
  3757.   else @<Start a format definition@>;
  3758.   outer_parse; finish_Pascal;
  3759.   end
  3760. @ The |finish_Pascal| procedure outputs the translation of the current
  3761. scraps, preceded by the control sequence `\.{\\P}' and followed by the
  3762. control sequence `\.{\\par}'. It also restores the token and scrap
  3763. memories to their initial empty state.
  3764. A |force| token is appended to the current scraps before translation
  3765. takes place, so that the translation will normally end with \.{\\6} or
  3766. \.{\\7} (the \TeX\ macros for |force| and |big_force|). This \.{\\6} or
  3767. \.{\\7} is replaced by the concluding \.{\\par} or by \.{\\Y\\par}.
  3768. @p procedure finish_Pascal; {finishes a definition or a \PASCAL\ part}
  3769. var p:text_pointer; {translation of the scraps}
  3770. begin out2("\")("P"); app_tok(force); app_comment; p:=translate;
  3771. @.\\P@>
  3772. app(p+tok_flag); make_output; {output the list}
  3773. if out_ptr>1 then
  3774.   if out_buf[out_ptr-1]="\" then
  3775. @.\\6@>
  3776. @.\\7@>
  3777. @.\\Y@>
  3778.     if out_buf[out_ptr]="6" then out_ptr:=out_ptr-2
  3779.     else if out_buf[out_ptr]="7" then out_buf[out_ptr]:="Y";
  3780. out4("\")("p")("a")("r"); finish_line;
  3781. stat if text_ptr>max_txt_ptr then max_txt_ptr:=text_ptr;
  3782. if tok_ptr>max_tok_ptr then max_tok_ptr:=tok_ptr;
  3783. if scrap_ptr>max_scr_ptr then max_scr_ptr:=scrap_ptr;
  3784. tats@;@/
  3785. tok_ptr:=1; text_ptr:=1; scrap_ptr:=0; {forget the tokens and the scraps}
  3786. @ @<Start a macro...@>=
  3787. begin sc2("\")("D")(intro); {this will produce `\&{define }'}
  3788. @.\\D@>
  3789. next_control:=get_next;
  3790. if next_control<>identifier then err_print('! Improper macro definition')
  3791. @.Improper macro definition@>
  3792. else sc1(id_flag+id_lookup(normal))(math);
  3793. next_control:=get_next;
  3794. @ @<Start a format...@>=
  3795. begin sc2("\")("F")(intro); {this will produce `\&{format }'}
  3796. @.\\F@>
  3797. next_control:=get_next;
  3798. if next_control=identifier then
  3799.   begin sc1(id_flag+id_lookup(normal))(math);
  3800.   next_control:=get_next;
  3801.   if next_control=equivalence_sign then
  3802.     begin sc2("\")("S")(math); {output an equivalence sign}
  3803. @.\\S@>
  3804.     next_control:=get_next;
  3805.     if next_control=identifier then
  3806.       begin sc1(id_flag+id_lookup(normal))(math);
  3807.       sc0(semi); {insert an invisible semicolon}
  3808.       next_control:=get_next;
  3809.       end;
  3810.     end;
  3811.   end;
  3812. if scrap_ptr<>5 then err_print('! Improper format definition');
  3813. @.Improper format definition@>
  3814. @ Finally, when the \TeX\ and definition parts have been treated, we have
  3815. |next_control>=begin_Pascal|. We will make the global variable |this_module|
  3816. point to the current module name, if it has a name.
  3817. @<Glob...@>=@!this_module:name_pointer; {the current module name, or zero}
  3818. @ @<Translate the \P...@>=
  3819. this_module:=0;
  3820. if next_control<=module_name then
  3821.   begin emit_space_if_needed; init_stack;
  3822.   if next_control=begin_Pascal then next_control:=get_next
  3823.   else  begin this_module:=cur_module;
  3824.     @<Check that |=| or |==| follows this module name, and
  3825.       emit the scraps to start the module definition@>;
  3826.     end;
  3827.   while next_control<=module_name do
  3828.     begin outer_parse;
  3829.     @<Emit the scrap for a module name if present@>;
  3830.     end;
  3831.   finish_Pascal;
  3832.   end
  3833. @ @<Check that |=|...@>=
  3834. repeat next_control:=get_next;
  3835. until next_control<>"+"; {allow optional `\.{+=}'}
  3836. if (next_control<>"=")and(next_control<>equivalence_sign) then
  3837.   err_print('! You need an = sign after the section name')
  3838. @.You need an = sign...@>
  3839. else next_control:=get_next;
  3840. if out_ptr>1 then
  3841.   if (out_buf[out_ptr]="Y")and(out_buf[out_ptr-1]="\") then
  3842. @.\\Y@>
  3843.     begin app(backup); {the module name will be flush left}
  3844.     end;
  3845. sc1(mod_flag+this_module)(mod_scrap);
  3846. cur_xref:=xref[this_module];
  3847. if num(cur_xref)<>module_count+def_flag then
  3848.   begin sc3(math_rel)("+")("}")(math);
  3849.     {module name is multiply defined}
  3850.   this_module:=0; {so we won't give cross-reference info here}
  3851.   end;
  3852. sc2("\")("S")(math); {output an equivalence sign}
  3853. @.\\S@>
  3854. sc1(force)(semi); {this forces a line break unless `\.{@@+}' follows}
  3855. @ @<Emit the scrap...@>=
  3856. if next_control<module_name then
  3857.   begin err_print('! You can''t do that in Pascal text');
  3858. @.You can't do that...@>
  3859.   next_control:=get_next;
  3860.   end
  3861. else if next_control=module_name then
  3862.   begin sc1(mod_flag+cur_module)(mod_scrap); next_control:=get_next;
  3863.   end
  3864. @ Cross references relating to a named module are given after the module ends.
  3865. @<Show cross...@>=
  3866. if this_module>0 then
  3867.   begin @<Rearrange the list pointed to by |cur_xref|@>;
  3868.   footnote(def_flag); footnote(0);
  3869.   end
  3870. @ To rearrange the order of the linked list of cross references, we need
  3871. four more variables that point to cross reference entries.  We'll end up
  3872. with a list pointed to by |cur_xref|.
  3873. @<Glob...@>=
  3874. @!next_xref,@!this_xref,@!first_xref,@!mid_xref:xref_number;
  3875.   {pointer variables for rearranging a list}
  3876. @ We want to rearrange the cross reference list so that all the entries with
  3877. |def_flag| come first, in ascending order; then come all the other
  3878. entries, in ascending order.  There may be no entries in either one or both
  3879. of these categories.
  3880. @<Rearrange the list...@>=
  3881. first_xref:=xref[this_module];
  3882. this_xref:=xlink(first_xref); {bypass current module number}
  3883. if num(this_xref)>def_flag then
  3884.   begin mid_xref:=this_xref; cur_xref:=0; {this value doesn't matter}
  3885.   repeat  next_xref:=xlink(this_xref); xlink(this_xref):=cur_xref;
  3886.     cur_xref:=this_xref; this_xref:=next_xref;
  3887.   until num(this_xref)<=def_flag;
  3888.   xlink(first_xref):=cur_xref;
  3889.   end
  3890. else mid_xref:=0; {first list null}
  3891. cur_xref:=0;
  3892. while this_xref<>0 do
  3893.   begin next_xref:=xlink(this_xref); xlink(this_xref):=cur_xref;
  3894.   cur_xref:=this_xref; this_xref:=next_xref;
  3895.   end;
  3896. if mid_xref>0 then xlink(mid_xref):=cur_xref
  3897. else xlink(first_xref):=cur_xref;
  3898. cur_xref:=xlink(first_xref)
  3899. @ The |footnote| procedure gives cross reference information about
  3900. multiply defined module names (if the |flag| parameter is |def_flag|), or about
  3901. the uses of a module name (if the |flag| parameter is zero). It assumes that
  3902. |cur_xref| points to the first cross-reference entry of interest, and it
  3903. leaves |cur_xref| pointing to the first element not printed.  Typical outputs:
  3904. `\.{\\A101.}'; `\.{\\Us370\\ET1009.}'; `\.{\\As8, 27\\*, 51\\ETs64.}'.
  3905. @p procedure footnote(@!flag:sixteen_bits); {outputs module cross-references}
  3906. label done,exit;
  3907. var q:xref_number; {cross-reference pointer variable}
  3908. begin if num(cur_xref)<=flag then return;
  3909. finish_line; out("\");
  3910. @.\\A@>
  3911. @.\\U@>
  3912. if flag=0 then out("U")@+else out("A");
  3913. @<Output all the module numbers on the reference list |cur_xref|@>;
  3914. out(".");
  3915. exit:end;
  3916. @ The following code distinguishes three cases, according as the number
  3917. of cross references is one, two, or more than two. Variable |q| points
  3918. to the first cross reference, and the last link is a zero.
  3919. @<Output all the module numbers...@>=
  3920. q:=cur_xref; if num(xlink(q))>flag then out("s"); {plural}
  3921. @.\\As@>
  3922. @.\\Us@>
  3923. loop@+  begin out_mod(num(cur_xref)-flag);
  3924.   cur_xref:=xlink(cur_xref); {point to the next cross reference to output}
  3925.   if num(cur_xref)<=flag then goto done;
  3926.   if num(xlink(cur_xref))>flag then out2(",")(" ") {not the last}
  3927.   else begin out3("\")("E")("T"); {the last}
  3928. @.\\ET@>
  3929.     if cur_xref<>xlink(q) then out("s"); {the last of more than two}
  3930. @.\\ETs@>
  3931.     end;
  3932.   end;
  3933. done:
  3934. @ @<Output the code for the end of a module@>=
  3935. out3("\")("f")("i"); finish_line;
  3936. flush_buffer(0,false,false); {insert a blank line, it looks nice}
  3937. @.\\fi@>
  3938. @* Phase three processing.
  3939. We are nearly finished! \.{WEAVE}'s only remaining task is to write out the
  3940. index, after sorting the identifiers and index entries.
  3941. @<Phase III: Output the cross-reference index@>=
  3942. phase_three:=true; print_nl('Writing the index...');
  3943. if change_exists then
  3944.   begin finish_line; @<Tell about changed modules@>;
  3945.   end;
  3946. finish_line; out4("\")("i")("n")("x"); finish_line;
  3947. @.\\inx@>
  3948. @<Do the first pass of sorting@>;
  3949. @<Sort and output the index@>;
  3950. out4("\")("f")("i")("n"); finish_line;
  3951. @.\\fin@>
  3952. @<Output all the module names@>;
  3953. out4("\")("c")("o")("n"); finish_line;
  3954. @.\\con@>
  3955. print('Done.');
  3956. @ Just before the index comes a list of all the changed modules, including
  3957. the index module itself.
  3958. @<Glob...@>=
  3959. @!k_module:0..max_modules; {runs through the modules}
  3960. @ @<Tell about changed modules@>=
  3961. begin {remember that the index is already marked as changed}
  3962. k_module:=1;
  3963. out4("\")("c")("h")(" ");
  3964. while k_module<module_count do
  3965.   begin if changed_module[k_module] then
  3966.     begin out_mod(k_module); out2(",")(" ");
  3967.     end;
  3968.   incr(k_module);
  3969.   end;
  3970. out_mod(k_module);
  3971. out(".");
  3972. @ A left-to-right radix sorting method is used, since this makes it easy to
  3973. adjust the collating sequence and since the running time will be at worst
  3974. proportional to the total length of all entries in the index. We put the
  3975. identifiers into 230 different lists based on their first characters.
  3976. (Uppercase letters are put into the same list as the corresponding lowercase
  3977. letters, since we want to have `$t<\\{TeX}<\&{to}$'.) The
  3978. list for character |c| begins at location |bucket[c]| and continues through
  3979. the |blink| array.
  3980. @<Glob...@>=
  3981. @!bucket:array[ASCII_code] of name_pointer;
  3982. @!next_name: name_pointer; {successor of |cur_name| when sorting}
  3983. @!c:ASCII_code; {index into |bucket|}
  3984. @!h:0..hash_size; {index into |hash|}
  3985. @!blink:array[0..max_names] of sixteen_bits; {links in the buckets}
  3986. @ To begin the sorting, we go through all the hash lists and put each entry
  3987. having a nonempty cross-reference list into the proper bucket.
  3988. @<Do the first pass...@>=
  3989. for c:=0 to 255 do bucket[c]:=0;
  3990. for h:=0 to hash_size-1 do
  3991.   begin next_name:=hash[h];
  3992.   while next_name<>0 do
  3993.     begin cur_name:=next_name; next_name:=link[cur_name];
  3994.     if xref[cur_name]<>0 then
  3995.       begin c:=byte_mem[cur_name mod ww,byte_start[cur_name]];
  3996.       if (c<="Z")and(c>="A") then c:=c+@'40;
  3997.       blink[cur_name]:=bucket[c]; bucket[c]:=cur_name;
  3998.       end;
  3999.     end;
  4000.   end
  4001. @ During the sorting phase we shall use the |cat| and |trans| arrays from
  4002. \.{WEAVE}'s parsing algorithm and rename them |depth| and |head|. They now
  4003. represent a stack of identifier lists for all the index entries that have
  4004. not yet been output. The variable |sort_ptr| tells how many such lists are
  4005. present; the lists are output in reverse order (first |sort_ptr|, then
  4006. |sort_ptr-1|, etc.). The |j|th list starts at |head[j]|, and if the first
  4007. |k| characters of all entries on this list are known to be equal we have
  4008. |depth[j]=k|.
  4009. @d depth==cat {reclaims memory that is no longer needed for parsing}
  4010. @d head==trans {ditto}
  4011. @d sort_ptr==scrap_ptr {ditto}
  4012. @d max_sorts==max_scraps {ditto}
  4013. @<Globals...@>=
  4014. @!cur_depth:eight_bits; {depth of current buckets}
  4015. @!cur_byte:0..max_bytes; {index into |byte_mem|}
  4016. @!cur_bank:0..ww-1; {row of |byte_mem|}
  4017. @!cur_val:sixteen_bits; {current cross reference number}
  4018. stat@!max_sort_ptr:0..max_sorts;@+tats {largest value of |sort_ptr|}
  4019. @ @<Set init...@>=stat max_sort_ptr:=0;@+tats
  4020. @ The desired alphabetic order is specified by the |collate| array; namely,
  4021. |collate[0]<collate[1]<@t$\cdots$@><collate[229]|.
  4022. @<Glob...@>=@!collate:array[0..229] of ASCII_code; {collation order}
  4023. @ @<Local variables for init...@>=
  4024. @!c:ASCII_code; {used to initialize |collate|}
  4025. @ We use the order $\hbox{null}<\.\ <\hbox{other characters}<\.\_<
  4026. \.A=\.a<\cdots<\.Z=\.z<\.0<\cdots<\.9.$
  4027. @<Set init...@>=
  4028. collate[0]:=0; collate[1]:=" ";
  4029. for c:=1 to " "-1 do collate[c+1]:=c;
  4030. for c:=" "+1 to "0"-1 do collate[c]:=c;
  4031. for c:="9"+1 to "A"-1 do collate[c-10]:=c;
  4032. for c:="Z"+1 to "_"-1 do collate[c-36]:=c;
  4033. collate["_"-36]:="_"+1;
  4034. for c:="z"+1 to 255 do collate[c-63]:=c;
  4035. collate[193]:="_";
  4036. for c:="a" to "z" do collate[c-"a"+194]:=c;
  4037. for c:="0" to "9" do collate[c-"0"+220]:=c;
  4038. @ Procedure |unbucket| goes through the buckets and adds nonempty lists
  4039. to the stack, using the collating sequence specified in the |collate| array.
  4040. The parameter to |unbucket| tells the current depth in the buckets.
  4041. Any two sequences that agree in their first 255 character positions are
  4042. regarded as identical.
  4043. @d infinity=255 {$\infty$ (approximately)}
  4044. @p procedure unbucket(@!d:eight_bits); {empties buckets having depth |d|}
  4045. var c:ASCII_code; {index into |bucket|}
  4046. begin for c:=229 downto 0 do if bucket[collate[c]]>0 then
  4047.   begin if sort_ptr>max_sorts then overflow('sorting');
  4048.   incr(sort_ptr);
  4049.   stat if sort_ptr>max_sort_ptr then max_sort_ptr:=sort_ptr;@;@+tats@;@/
  4050.   if c=0 then depth[sort_ptr]:=infinity else depth[sort_ptr]:=d;
  4051.   head[sort_ptr]:=bucket[collate[c]]; bucket[collate[c]]:=0;
  4052.   end;
  4053. @ @<Sort and output...@>=
  4054. sort_ptr:=0; unbucket(1);
  4055. while sort_ptr>0 do
  4056.   begin cur_depth:=cat[sort_ptr];
  4057.   if (blink[head[sort_ptr]]=0)or(cur_depth=infinity) then
  4058.     @<Output index entries for the list at |sort_ptr|@>
  4059.   else @<Split the list at |sort_ptr| into further lists@>;
  4060.   end
  4061. @ @<Split the list...@>=
  4062. begin next_name:=head[sort_ptr];
  4063. repeat cur_name:=next_name; next_name:=blink[cur_name];
  4064.   cur_byte:=byte_start[cur_name]+cur_depth; cur_bank:=cur_name mod ww;
  4065.   if cur_byte=byte_start[cur_name+ww] then c:=0 {we hit the end of the name}
  4066.   else  begin c:=byte_mem[cur_bank,cur_byte];
  4067.     if (c<="Z")and(c>="A") then c:=c+@'40;
  4068.     end;
  4069.   blink[cur_name]:=bucket[c]; bucket[c]:=cur_name;
  4070. until next_name=0;
  4071. decr(sort_ptr); unbucket(cur_depth+1);
  4072. @ @<Output index...@>=
  4073. begin cur_name:=head[sort_ptr];
  4074. @!debug if trouble_shooting then debug_help;@;@+gubed@/
  4075. repeat out2("\")(":");
  4076. @.\\:@>
  4077.   @<Output the name at |cur_name|@>;
  4078.   @<Output the cross-references at |cur_name|@>;
  4079.   cur_name:=blink[cur_name];
  4080. until cur_name=0;
  4081. decr(sort_ptr);
  4082. @ @<Output the name...@>=
  4083. case ilk[cur_name] of
  4084. normal: if length(cur_name)=1 then out2("\")("|")@+else out2("\")("\");
  4085. @.\\|@>
  4086. @.\\\\@>
  4087. roman: do_nothing;
  4088. wildcard: out2("\")("9");
  4089. @.\\9@>
  4090. typewriter: out2("\")(".");
  4091. @.\\.@>
  4092. othercases out2("\")("&")
  4093. @.\\\&@>
  4094. endcases;@/
  4095. out_name(cur_name)
  4096. @ Section numbers that are to be underlined are enclosed in
  4097. `\.{\\[}$\,\ldots\,$\.]'.
  4098. @<Output the cross-references...@>=
  4099. @<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>;
  4100. repeat out2(",")(" "); cur_val:=num(cur_xref);
  4101. if cur_val<def_flag then out_mod(cur_val)
  4102. else  begin out2("\")("["); out_mod(cur_val-def_flag); out("]");
  4103. @.\\[@>
  4104.   end;
  4105. cur_xref:=xlink(cur_xref);
  4106. until cur_xref=0;
  4107. out("."); finish_line
  4108. @ List inversion is best thought of as popping elements off one stack and
  4109. pushing them onto another. In this case |cur_xref| will be the head of
  4110. the stack that we push things onto.
  4111. @<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>=
  4112. this_xref:=xref[cur_name]; cur_xref:=0;
  4113. repeat next_xref:=xlink(this_xref); xlink(this_xref):=cur_xref;
  4114. cur_xref:=this_xref; this_xref:=next_xref;
  4115. until this_xref=0
  4116. @ The following recursive procedure walks through the tree of module names and
  4117. prints them.
  4118. @^recursion@>
  4119. @p procedure mod_print(p:name_pointer); {print all module names in subtree |p|}
  4120. begin if p>0 then
  4121.   begin mod_print(llink[p]);@/
  4122.   out2("\")(":");@/
  4123. @.\\:@>
  4124.   tok_ptr:=1; text_ptr:=1; scrap_ptr:=0; init_stack;
  4125.   app(p+mod_flag); make_output;
  4126.   footnote(0); {|cur_xref| was set by |make_output|}
  4127.   finish_line;@/
  4128.   mod_print(rlink[p]);
  4129.   end;
  4130. @ @<Output all the module names@>=@+mod_print(root)
  4131. @* Debugging.
  4132. The \PASCAL\ debugger with which \.{WEAVE} was developed allows breakpoints
  4133. to be set, and variables can be read and changed, but procedures cannot be
  4134. executed. Therefore a `|debug_help|' procedure has been inserted in the main
  4135. loops of each phase of the program; when |ddt| and |dd| are set to appropriate
  4136. values, symbolic printouts of various tables will appear.
  4137. The idea is to set a breakpoint inside the |debug_help| routine, at the
  4138. place of `\ignorespaces|breakpoint:|\unskip' below.  Then when
  4139. |debug_help| is to be activated, set |trouble_shooting| equal to |true|.
  4140. The |debug_help| routine will prompt you for values of |ddt| and |dd|,
  4141. discontinuing this when |ddt<=0|; thus you type $2n+1$ integers, ending
  4142. with zero or a negative number. Then control either passes to the
  4143. breakpoint, allowing you to look at and/or change variables (if you typed
  4144. zero), or to exit the routine (if you typed a negative value).
  4145. Another global variable, |debug_cycle|, can be used to skip silently
  4146. past calls on |debug_help|. If you set |debug_cycle>1|, the program stops
  4147. only every |debug_cycle| times |debug_help| is called; however,
  4148. any error stop will set |debug_cycle| to zero.
  4149. @<Globals...@>=
  4150. @!debug@!trouble_shooting:boolean; {is |debug_help| wanted?}
  4151. @!ddt:integer; {operation code for the |debug_help| routine}
  4152. @!dd:integer; {operand in procedures performed by |debug_help|}
  4153. @!debug_cycle:integer; {threshold for |debug_help| stopping}
  4154. @!debug_skipped:integer; {we have skipped this many |debug_help| calls}
  4155. @!term_in:text_file; {the user's terminal as an input file}
  4156. gubed
  4157. @ The debugging routine needs to read from the user's terminal.
  4158. @^system dependencies@>
  4159. @<Set init...@>=
  4160. @!debug trouble_shooting:=true; debug_cycle:=1; debug_skipped:=0; tracing:=0;@/
  4161. trouble_shooting:=false; debug_cycle:=99999; {use these when it almost works}
  4162. reset(term_in,'TTY:','/I'); {open |term_in| as the terminal, don't do a |get|}
  4163. gubed
  4164. @ @d breakpoint=888 {place where a breakpoint is desirable}
  4165. @^system dependencies@>
  4166. @p @!debug procedure debug_help; {routine to display various things}
  4167. label breakpoint,exit;
  4168. var k:integer; {index into various arrays}
  4169. begin incr(debug_skipped);
  4170. if debug_skipped<debug_cycle then return;
  4171. debug_skipped:=0;
  4172. loop@+  begin write(term_out,'#'); update_terminal; {prompt}
  4173.   read(term_in,ddt); {read a list of integers}
  4174.   if ddt<0 then return
  4175.   else if ddt=0 then
  4176.     begin goto breakpoint;@\ {go to every label at least once}
  4177.     breakpoint: ddt:=0;@\
  4178.     end
  4179.   else  begin read(term_in,dd);
  4180.     case ddt of
  4181.     1: print_id(dd);
  4182.     2: print_text(dd);
  4183.     3: for k:=1 to dd do print(xchr[buffer[k]]);
  4184.     4: for k:=1 to dd do print(xchr[mod_text[k]]);
  4185.     5: for k:=1 to out_ptr do print(xchr[out_buf[k]]);
  4186.     6: for k:=1 to dd do
  4187.       begin print_cat(cat[k]); print(' ');
  4188.       end;
  4189.     othercases print('?')
  4190.     endcases;
  4191.     end;
  4192.   end;
  4193. exit:end;
  4194. gubed
  4195. @* The main program.
  4196. Let's put it all together now: \.{WEAVE} starts and ends here.
  4197. @^system dependencies@>
  4198. The main procedure has been split into three sub-procedures in order to
  4199. keep certain \PASCAL\ compilers from overflowing their capacity.
  4200. @^split procedures@>
  4201. @p procedure Phase_I;
  4202. begin @<Phase I:...@>;
  4203. procedure Phase_II;
  4204. begin @<Phase II:...@>;
  4205. begin initialize; {beginning of the main program}
  4206. print_ln(banner); {print a ``banner line''}
  4207. @<Store all the reserved words@>;
  4208. Phase_I; Phase_II;@/
  4209. @<Phase III:...@>;
  4210. @<Check that all changes have been read@>;
  4211. end_of_WEAVE:
  4212. stat @<Print statistics about memory usage@>;@+tats@;@/
  4213. @t\4\4@>{here files should be closed if the operating system requires it}
  4214. @<Print the job |history|@>;
  4215. @ @<Print statistics about memory usage@>=
  4216. print_nl('Memory usage statistics: ',
  4217.   name_ptr:1,' names, ', xref_ptr:1,' cross references, ',
  4218.   byte_ptr[0]:1);
  4219. for cur_bank:=1 to ww-1 do print('+',byte_ptr[cur_bank]:1);
  4220.   print(' bytes;');
  4221. print_nl('parsing required ',max_scr_ptr:1,' scraps, ',max_txt_ptr:1,
  4222.   ' texts, ',max_tok_ptr:1,' tokens, ', max_stack_ptr:1,' levels;');
  4223. print_nl('sorting required ',max_sort_ptr:1, ' levels.')
  4224. @ Some implementations may wish to pass the |history| value to the
  4225. operating system so that it can be used to govern whether or not other
  4226. programs are started. Here we simply report the history to the user.
  4227. @^system dependencies@>
  4228. @<Print the job |history|@>=
  4229. case history of
  4230. spotless: print_nl('(No errors were found.)');
  4231. harmless_message: print_nl('(Did you see the warning message above?)');
  4232. error_message: print_nl('(Pardon me, but I think I spotted something wrong.)');
  4233. fatal_message: print_nl('(That was a fatal error, my friend.)');
  4234. end {there are no other cases}
  4235. @* System-dependent changes.
  4236. This module should be replaced, if necessary, by changes to the program
  4237. that are necessary to make \.{WEAVE} work at a particular installation.
  4238. It is usually best to design your change file so that all changes to
  4239. previous modules preserve the module numbering; then everybody's version
  4240. will be consistent with the printed program. More extensive changes,
  4241. which introduce new modules, can be inserted here; then only the index
  4242. itself will get a new module number.
  4243. @^system dependencies@>
  4244. @* Index.
  4245. If you have read and understood the code for Phase III above, you know what
  4246. is in this index and how it got here. All modules in which an identifier is
  4247. used are listed with that identifier, except that reserved words are
  4248. indexed only when they appear in format definitions, and the appearances
  4249. of identifiers in module names are not indexed. Underlined entries
  4250. correspond to where the identifier was declared. Error messages, control
  4251. sequences put into the output, and a few
  4252. other things like ``recursion'' are indexed here too.
  4253.