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 / tangle.web (.txt) < prev    next >
Texinfo Document  |  1996-09-28  |  130KB  |  2,839 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.2 added @@= and @@\ and introduced {:nnn} comments (December, 1982).
  6. % Version 1.4 added "history" (February, 1983).
  7. % Version 1.5 conformed to TeX version 0.96 and fixed @@\ (March, 1983).
  8. % Version 1.7 introduced the new change file format (June, 1983).
  9. % Version 2.0 was released in July, 1983, with version 0.999 of TeX.
  10. % Version 2.5 was released in November, 1983, with version 1.0 of TeX.
  11. % Version 2.6 fixed a bug: force-line-break after a constant (August, 1984).
  12. % Version 2.7 fixed the definition of check_sum_prime (May, 1985).
  13. % Version 2.8 fixed a bug in change_buffer movement (August, 1985).
  14. % Version 2.9 allows nonnumeric macros before their def (December, 1988).
  15. % Version 3, for Sewell's book, fixed long-line bug in input_ln (March, 1989).
  16. % Version 4 was major change to allow 8-bit input (September, 1989).
  17. % Version 4.1 conforms to ANSI standard for-loop rules (September, 1990).
  18. % Version 4.2 fixes stat report if phase one dies (March, 1991).
  19. % Version 4.3 fixes @@ bug in verbatim, catches extra } (September, 1991).
  20. % Here is TeX material that gets inserted after \input webmac
  21. \def\hang{\hangindent 3em\indent\ignorespaces}
  22. \font\ninerm=cmr9
  23. \let\mc=\ninerm % medium caps for names like SAIL
  24. \def\PASCAL{Pascal}
  25. \def\pb{$\.|\ldots\.|$} % Pascal brackets (|...|)
  26. \def\v{\.{\char'174}} % vertical (|) in typewriter font
  27. \mathchardef\BA="3224 % double arrow
  28. \def\({} % kludge for alphabetizing certain module names
  29. \def\title{TANGLE}
  30. \def\contentspagenumber{123} % should be odd
  31. \def\topofcontents{\null\vfill
  32.   \titlefalse % include headline on the contents page
  33.   \def\rheader{\mainfont Appendix E\hfil \contentspagenumber}
  34.   \centerline{\titlefont The {\ttitlefont TANGLE} processor}
  35.   \vskip 15pt
  36.   \centerline{(Version 4.3)}
  37.   \vfill}
  38. \pageno=\contentspagenumber \advance\pageno by 1
  39. @* Introduction.
  40. This program converts a \.{WEB} file to a \PASCAL\ file. It was written
  41. by D. E. Knuth in September, 1981; a somewhat similar {\mc SAIL} program had
  42. been developed in March, 1979. Since this program describes itself, a
  43. bootstrapping process involving hand-translation had to be used to get started.
  44. For large \.{WEB} files one should have a large memory, since \.{TANGLE} keeps
  45. all the \PASCAL\ text in memory (in an abbreviated form). The program uses
  46. a few features of the local \PASCAL\ compiler that may need to be changed in
  47. other installations:
  48. \yskip\item{1)} Case statements have a default.
  49. \item{2)} Input-output routines may need to be adapted for use with a particular
  50. character set and/or for printing messages on the user's terminal.
  51. \yskip\noindent
  52. These features are also present in the \PASCAL\ version of \TeX, where they
  53. are used in a similar (but more complex) way. System-dependent portions
  54. of \.{TANGLE} can be identified by looking at the entries for `system
  55. dependencies' in the index below.
  56. @!@^system dependencies@>
  57. The ``banner line'' defined here should be changed whenever \.{TANGLE}
  58. is modified.
  59. @d banner=='This is TANGLE, Version 4.3'
  60. @ The program begins with a fairly normal header, made up of pieces that
  61. @^system dependencies@>
  62. will mostly be filled in later. The \.{WEB} input comes from files |web_file|
  63. and |change_file|, the \PASCAL\ output goes to file |Pascal_file|,
  64. and the string pool output goes to file |pool|.
  65. If it is necessary to abort the job because of a fatal error, the program
  66. calls the `|jump_out|' procedure, which goes to the label |end_of_TANGLE|.
  67. @d end_of_TANGLE = 9999 {go here to wrap it up}
  68. @p @t\4@>@<Compiler directives@>@/
  69. program TANGLE(@!web_file,@!change_file,@!Pascal_file,@!pool);
  70. label end_of_TANGLE; {go here to finish}
  71. const @<Constants in the outer block@>@/
  72. type @<Types in the outer block@>@/
  73. var @<Globals in the outer block@>@/
  74. @<Error handling procedures@>@/
  75. procedure initialize;
  76.   var @<Local variables for initialization@>@/
  77.   begin @<Set initial values@>@/
  78.   end;
  79. @ Some of this code is optional for use when debugging only;
  80. such material is enclosed between the delimiters |debug| and $|gubed|$.
  81. Other parts, delimited by |stat| and $|tats|$, are optionally included if
  82. statistics about \.{TANGLE}'s memory usage are desired.
  83. @d debug==@{ {change this to `$\\{debug}\equiv\null$' when debugging}
  84. @d gubed==@t@>@} {change this to `$\\{gubed}\equiv\null$' when debugging}
  85. @f debug==begin
  86. @f gubed==end
  87. @d stat==@{ {change this to `$\\{stat}\equiv\null$'
  88.   when gathering usage statistics}
  89. @d tats==@t@>@} {change this to `$\\{tats}\equiv\null$'
  90.   when gathering usage statistics}
  91. @f stat==begin
  92. @f tats==end
  93. @ The \PASCAL\ compiler used to develop this system has ``compiler
  94. directives'' that can appear in comments whose first character is a dollar sign.
  95. In production versions of \.{TANGLE} these directives tell the compiler that
  96. @^system dependencies@>
  97. it is safe to avoid range checks and to leave out the extra code it inserts
  98. for the \PASCAL\ debugger's benefit, although interrupts will occur if
  99. there is arithmetic overflow.
  100. @<Compiler directives@>=
  101. @{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
  102. @!debug @{@&$C+,D+@}@+ gubed {but turn everything on when debugging}
  103. @ Labels are given symbolic names by the following definitions. We insert
  104. the label `|exit|:' just before the `\ignorespaces|end|\unskip' of a
  105. procedure in which we have used the `|return|' statement defined below;
  106. the label `|restart|' is occasionally used at the very beginning of a
  107. procedure; and the label `|reswitch|' is occasionally used just prior to
  108. a \&{case} statement in which some cases change the conditions and we wish to
  109. branch to the newly applicable case.
  110. Loops that are set up with the \&{loop} construction defined below are
  111. commonly exited by going to `|done|' or to `|found|' or to `|not_found|',
  112. and they are sometimes repeated by going to `|continue|'.
  113. @d exit=10 {go here to leave a procedure}
  114. @d restart=20 {go here to start a procedure again}
  115. @d reswitch=21 {go here to start a case statement again}
  116. @d continue=22 {go here to resume a loop}
  117. @d done=30 {go here to exit a loop}
  118. @d found=31 {go here when you've found it}
  119. @d not_found=32 {go here when you've found something else}
  120. @ Here are some macros for common programming idioms.
  121. @d incr(#) == #:=#+1 {increase a variable by unity}
  122. @d decr(#) == #:=#-1 {decrease a variable by unity}
  123. @d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
  124. @d do_nothing == {empty statement}
  125. @d return == goto exit {terminate a procedure call}
  126. @f return == nil
  127. @f loop == xclause
  128. @ We assume that |case| statements may include a default case that applies
  129. if no matching label is found. Thus, we shall use constructions like
  130. @^system dependencies@>
  131. $$\vbox{\halign{#\hfil\cr
  132. |case x of|\cr
  133. 1: $\langle\,$code for $x=1\,\rangle$;\cr
  134. 3: $\langle\,$code for $x=3\,\rangle$;\cr
  135. |othercases| $\langle\,$code for |x<>1| and |x<>3|$\,\rangle$\cr
  136. |endcases|\cr}}$$
  137. since most \PASCAL\ compilers have plugged this hole in the language by
  138. incorporating some sort of default mechanism. For example, the compiler
  139. used to develop \.{WEB} and \TeX\ allows `|others|:' as a default label,
  140. and other \PASCAL s allow syntaxes like `\ignorespaces|else|\unskip' or
  141. `\&{otherwise}' or `\\{otherwise}:', etc. The definitions of |othercases|
  142. and |endcases| should be changed to agree with local conventions. (Of
  143. course, if no default mechanism is available, the |case| statements of
  144. this program must be extended by listing all remaining cases. The author
  145. would have taken the trouble to modify \.{TANGLE} so that such extensions
  146. were done automatically, if he had not wanted to encourage \PASCAL\
  147. compiler writers to make this important change in \PASCAL, where it belongs.)
  148. @d othercases == others: {default for cases not listed explicitly}
  149. @d endcases == @+end {follows the default case in an extended |case| statement}
  150. @f othercases == else
  151. @f endcases == end
  152. @ The following parameters are set big enough to handle \TeX, so they
  153. should be sufficient for most applications of \.{TANGLE}.
  154. @<Constants...@>=
  155. @!buf_size=100; {maximum length of input line}
  156. @!max_bytes=45000; {|1/ww| times the number of bytes in identifiers,
  157.   strings, and module names; must be less than 65536}
  158. @!max_toks=50000; {|1/zz| times the number of bytes in compressed \PASCAL\ code;
  159.   must be less than 65536}
  160. @!max_names=4000; {number of identifiers, strings, module names;
  161.   must be less than 10240}
  162. @!max_texts=2000; {number of replacement texts, must be less than 10240}
  163. @!hash_size=353; {should be prime}
  164. @!longest_name=400; {module names shouldn't be longer than this}
  165. @!line_length=72; {lines of \PASCAL\ output have at most this many characters}
  166. @!out_buf_size=144; {length of output buffer, should be twice |line_length|}
  167. @!stack_size=50; {number of simultaneous levels of macro expansion}
  168. @!max_id_length=12; {long identifiers are chopped to this length, which must
  169.   not exceed |line_length|}
  170. @!unambig_length=7; {identifiers must be unique if chopped to this length}
  171.   {note that 7 is more strict than \PASCAL's 8, but this can be varied}
  172. @ A global variable called |history| will contain one of four values
  173. at the end of every run: |spotless| means that no unusual messages were
  174. printed; |harmless_message| means that a message of possible interest
  175. was printed but no serious errors were detected; |error_message| means that
  176. at least one error was found; |fatal_message| means that the program
  177. terminated abnormally. The value of |history| does not influence the
  178. behavior of the program; it is simply computed for the convenience
  179. of systems that might want to use such information.
  180. @d spotless=0 {|history| value for normal jobs}
  181. @d harmless_message=1 {|history| value when non-serious info was printed}
  182. @d error_message=2 {|history| value when an error was noted}
  183. @d fatal_message=3 {|history| value when we had to stop prematurely}
  184. @d mark_harmless==@t@>@+if history=spotless then history:=harmless_message
  185. @d mark_error==history:=error_message
  186. @d mark_fatal==history:=fatal_message
  187. @<Glob...@>=@!history:spotless..fatal_message; {how bad was this run?}
  188. @ @<Set init...@>=history:=spotless;
  189. @* The character set.
  190. One of the main goals in the design of \.{WEB} has been to make it readily
  191. portable between a wide variety of computers. Yet \.{WEB} by its very
  192. nature must use a greater variety of characters than most computer
  193. programs deal with, and character encoding is one of the areas in which
  194. existing machines differ most widely from each other.
  195. To resolve this problem, all input to \.{WEAVE} and \.{TANGLE} is converted
  196. to an internal eight-bit code that is essentially standard ASCII, the ``American
  197. Standard Code for Information Interchange.''  The conversion is done
  198. immediately when each character is read in. Conversely, characters are
  199. converted from ASCII to the user's external representation just before
  200. they are output. (The original ASCII code was seven bits only; \.{WEB} now
  201. allows eight bits in an attempt to keep up with modern times.)
  202. Such an internal code is relevant to users of \.{WEB} only because it is
  203. the code used for preprocessed constants like \.{"A"}. If you are writing
  204. a program in \.{WEB} that makes use of such one-character constants, you
  205. should convert your input to ASCII form, like \.{WEAVE} and \.{TANGLE} do.
  206. Otherwise \.{WEB}'s internal coding scheme does not affect you.
  207. @^ASCII code@>
  208. Here is a table of the standard visible ASCII codes:
  209. $$\def\:{\char\count255\global\advance\count255 by 1}
  210. \count255='40
  211. \vbox{
  212. \hbox{\hbox to 40pt{\it\hfill0\/\hfill}%
  213. \hbox to 40pt{\it\hfill1\/\hfill}%
  214. \hbox to 40pt{\it\hfill2\/\hfill}%
  215. \hbox to 40pt{\it\hfill3\/\hfill}%
  216. \hbox to 40pt{\it\hfill4\/\hfill}%
  217. \hbox to 40pt{\it\hfill5\/\hfill}%
  218. \hbox to 40pt{\it\hfill6\/\hfill}%
  219. \hbox to 40pt{\it\hfill7\/\hfill}}
  220. \vskip 4pt
  221. \hrule
  222. \def\^{\vrule height 10.5pt depth 4.5pt}
  223. \halign{\hbox to 0pt{\hskip -24pt\O{#0}\hfill}&\^
  224. \hbox to 40pt{\tt\hfill#\hfill\^}&
  225. &\hbox to 40pt{\tt\hfill#\hfill\^}\cr
  226. 04&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  227. 05&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  228. 06&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  229. 07&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  230. 10&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  231. 11&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  232. 12&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  233. 13&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  234. 14&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  235. 15&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  236. 16&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  237. 17&\:&\:&\:&\:&\:&\:&\:\cr}
  238. \hrule width 280pt}$$
  239. (Actually, of course, code @'040 is an invisible blank space.)  Code @'136
  240. was once an upward arrow (\.{\char'13}), and code @'137 was
  241. once a left arrow (\.^^X), in olden times when the first draft
  242. of ASCII code was prepared; but \.{WEB} works with today's standard
  243. ASCII in which those codes represent circumflex and underline as shown.
  244. @<Types...@>=
  245. @!ASCII_code=0..255; {eight-bit numbers, a subrange of the integers}
  246. @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
  247. character sets were common, so it did not make provision for lowercase
  248. letters. Nowadays, of course, we need to deal with both capital and small
  249. letters in a convenient way, so \.{WEB} assumes that it is being used
  250. with a \PASCAL\ whose character set contains at least the characters of
  251. standard ASCII as listed above. Some \PASCAL\ compilers use the original
  252. name |char| for the data type associated with the characters in text files,
  253. while other \PASCAL s consider |char| to be a 64-element subrange of a larger
  254. data type that has some other name.
  255. In order to accommodate this difference, we shall use the name |text_char|
  256. to stand for the data type of the characters in the input and output
  257. files.  We shall also assume that |text_char| consists of the elements
  258. |chr(first_text_char)| through |chr(last_text_char)|, inclusive. The
  259. following definitions should be adjusted if necessary.
  260. @^system dependencies@>
  261. @d text_char == char {the data type of characters in text files}
  262. @d first_text_char=0 {ordinal number of the smallest element of |text_char|}
  263. @d last_text_char=255 {ordinal number of the largest element of |text_char|}
  264. @<Types...@>=
  265. @!text_file=packed file of text_char;
  266. @ The \.{WEAVE} and \.{TANGLE} processors convert between ASCII code and
  267. the user's external character set by means of arrays |xord| and |xchr|
  268. that are analogous to \PASCAL's |ord| and |chr| functions.
  269. @<Globals...@>=
  270. @!xord: array [text_char] of ASCII_code;
  271.   {specifies conversion of input characters}
  272. @!xchr: array [ASCII_code] of text_char;
  273.   {specifies conversion of output characters}
  274. @ If we assume that every system using \.{WEB} is able to read and write the
  275. visible characters of standard ASCII (although not necessarily using the
  276. ASCII codes to represent them), the following assignment statements initialize
  277. most of the |xchr| array properly, without needing any system-dependent
  278. changes. For example, the statement \.{xchr[@@\'101]:=\'A\'} that appears
  279. in the present \.{WEB} file might be encoded in, say, {\mc EBCDIC} code
  280. on the external medium on which it resides, but \.{TANGLE} will convert from
  281. this external code to ASCII and back again. Therefore the assignment
  282. statement \.{XCHR[65]:=\'A\'} will appear in the corresponding \PASCAL\ file,
  283. and \PASCAL\ will compile this statement so that |xchr[65]| receives the
  284. character \.A in the external (|char|) code. Note that it would be quite
  285. incorrect to say \.{xchr[@@\'101]:="A"}, because |"A"| is a constant of
  286. type |integer|, not |char|, and because we have $|"A"|=65$ regardless of
  287. the external character set.
  288. @<Set init...@>=
  289. xchr[@'40]:=' ';
  290. xchr[@'41]:='!';
  291. xchr[@'42]:='"';
  292. xchr[@'43]:='#';
  293. xchr[@'44]:='$';
  294. xchr[@'45]:='%';
  295. xchr[@'46]:='&';
  296. xchr[@'47]:='''';@/
  297. xchr[@'50]:='(';
  298. xchr[@'51]:=')';
  299. xchr[@'52]:='*';
  300. xchr[@'53]:='+';
  301. xchr[@'54]:=',';
  302. xchr[@'55]:='-';
  303. xchr[@'56]:='.';
  304. xchr[@'57]:='/';@/
  305. xchr[@'60]:='0';
  306. xchr[@'61]:='1';
  307. xchr[@'62]:='2';
  308. xchr[@'63]:='3';
  309. xchr[@'64]:='4';
  310. xchr[@'65]:='5';
  311. xchr[@'66]:='6';
  312. xchr[@'67]:='7';@/
  313. xchr[@'70]:='8';
  314. xchr[@'71]:='9';
  315. xchr[@'72]:=':';
  316. xchr[@'73]:=';';
  317. xchr[@'74]:='<';
  318. xchr[@'75]:='=';
  319. xchr[@'76]:='>';
  320. xchr[@'77]:='?';@/
  321. xchr[@'100]:='@@';
  322. xchr[@'101]:='A';
  323. xchr[@'102]:='B';
  324. xchr[@'103]:='C';
  325. xchr[@'104]:='D';
  326. xchr[@'105]:='E';
  327. xchr[@'106]:='F';
  328. xchr[@'107]:='G';@/
  329. xchr[@'110]:='H';
  330. xchr[@'111]:='I';
  331. xchr[@'112]:='J';
  332. xchr[@'113]:='K';
  333. xchr[@'114]:='L';
  334. xchr[@'115]:='M';
  335. xchr[@'116]:='N';
  336. xchr[@'117]:='O';@/
  337. xchr[@'120]:='P';
  338. xchr[@'121]:='Q';
  339. xchr[@'122]:='R';
  340. xchr[@'123]:='S';
  341. xchr[@'124]:='T';
  342. xchr[@'125]:='U';
  343. xchr[@'126]:='V';
  344. xchr[@'127]:='W';@/
  345. xchr[@'130]:='X';
  346. xchr[@'131]:='Y';
  347. xchr[@'132]:='Z';
  348. xchr[@'133]:='[';
  349. xchr[@'134]:='\';
  350. xchr[@'135]:=']';
  351. xchr[@'136]:='^';
  352. xchr[@'137]:='_';@/
  353. xchr[@'140]:='`';
  354. xchr[@'141]:='a';
  355. xchr[@'142]:='b';
  356. xchr[@'143]:='c';
  357. xchr[@'144]:='d';
  358. xchr[@'145]:='e';
  359. xchr[@'146]:='f';
  360. xchr[@'147]:='g';@/
  361. xchr[@'150]:='h';
  362. xchr[@'151]:='i';
  363. xchr[@'152]:='j';
  364. xchr[@'153]:='k';
  365. xchr[@'154]:='l';
  366. xchr[@'155]:='m';
  367. xchr[@'156]:='n';
  368. xchr[@'157]:='o';@/
  369. xchr[@'160]:='p';
  370. xchr[@'161]:='q';
  371. xchr[@'162]:='r';
  372. xchr[@'163]:='s';
  373. xchr[@'164]:='t';
  374. xchr[@'165]:='u';
  375. xchr[@'166]:='v';
  376. xchr[@'167]:='w';@/
  377. xchr[@'170]:='x';
  378. xchr[@'171]:='y';
  379. xchr[@'172]:='z';
  380. xchr[@'173]:='{';
  381. xchr[@'174]:='|';
  382. xchr[@'175]:='}';
  383. xchr[@'176]:='~';@/
  384. xchr[0]:=' '; xchr[@'177]:=' '; {these ASCII codes are not used}
  385. @ Some of the ASCII codes below @'40 have been given symbolic names in
  386. \.{WEAVE} and \.{TANGLE} because they are used with a special meaning.
  387. @d and_sign=@'4 {equivalent to `\.{and}'}
  388. @d not_sign=@'5 {equivalent to `\.{not}'}
  389. @d set_element_sign=@'6 {equivalent to `\.{in}'}
  390. @d tab_mark=@'11 {ASCII code used as tab-skip}
  391. @d line_feed=@'12 {ASCII code thrown away at end of line}
  392. @d form_feed=@'14 {ASCII code used at end of page}
  393. @d carriage_return=@'15 {ASCII code used at end of line}
  394. @d left_arrow=@'30 {equivalent to `\.{:=}'}
  395. @d not_equal=@'32 {equivalent to `\.{<>}'}
  396. @d less_or_equal=@'34 {equivalent to `\.{<=}'}
  397. @d greater_or_equal=@'35 {equivalent to `\.{>=}'}
  398. @d equivalence_sign=@'36 {equivalent to `\.{==}'}
  399. @d or_sign=@'37 {equivalent to `\.{or}'}
  400. @ When we initialize the |xord| array and the remaining parts of |xchr|,
  401. it will be convenient to make use of an index variable, |i|.
  402. @<Local variables for init...@>=
  403. @!i:0..255;
  404. @ Here now is the system-dependent part of the character set.
  405. If \.{WEB} is being implemented on a garden-variety \PASCAL\ for which
  406. only standard ASCII codes will appear in the input and output files, you
  407. don't need to make any changes here. But if you have, for example, an extended
  408. character set like the one in Appendix~C of {\sl The \TeX book}, the first
  409. line of code in this module should be changed to
  410. $$\hbox{|for i:=1 to @'37 do xchr[i]:=chr(i);|}$$
  411. \.{WEB}'s character set is essentially identical to \TeX's, even with respect to
  412. characters less than @'40.
  413. @^system dependencies@>
  414. Changes to the present module will make \.{WEB} more friendly on computers
  415. that have an extended character set, so that one can type things like
  416. \.^^Z\ instead of \.{<>}. If you have an extended set of characters that
  417. are easily incorporated into text files, you can assign codes arbitrarily
  418. here, giving an |xchr| equivalent to whatever characters the users of
  419. \.{WEB} are allowed to have in their input files, provided that unsuitable
  420. characters do not correspond to special codes like |carriage_return|
  421. that are listed above.
  422. (The present file \.{TANGLE.WEB} does not contain any of the non-ASCII
  423. characters, because it is intended to be used with all implementations of
  424. \.{WEB}.  It was originally created on a Stanford system that has a
  425. convenient extended character set, then ``sanitized'' by applying another
  426. program that transliterated all of the non-standard characters into
  427. standard equivalents.)
  428. @<Set init...@>=
  429. for i:=1 to @'37 do xchr[i]:=' ';
  430. for i:=@'200 to @'377 do xchr[i]:=' ';
  431. @ The following system-independent code makes the |xord| array contain a
  432. suitable inverse to the information in |xchr|.
  433. @<Set init...@>=
  434. for i:=first_text_char to last_text_char do xord[chr(i)]:=" ";
  435. for i:=1 to @'377 do xord[xchr[i]]:=i;
  436. xord[' ']:=" ";
  437. @* Input and output.
  438. The input conventions of this program are intended to be very much like those
  439. of \TeX\ (except, of course, that they are much simpler, because much less
  440. needs to be done). Furthermore they are identical to those of \.{WEAVE}.
  441. Therefore people who need to make modifications to all three systems
  442. should be able to do so without too many headaches.
  443. We use the standard \PASCAL\ input/output procedures in several places that
  444. \TeX\ cannot, since \.{TANGLE} does not have to deal with files that are named
  445. dynamically by the user, and since there is no input from the terminal.
  446. @ Terminal output is done by writing on file |term_out|, which is assumed to
  447. consist of characters of type |text_char|:
  448. @^system dependencies@>
  449. @d print(#)==write(term_out,#) {`|print|' means write on the terminal}
  450. @d print_ln(#)==write_ln(term_out,#) {`|print|' and then start new line}
  451. @d new_line==write_ln(term_out) {start new line}
  452. @d print_nl(#)==  {print information starting on a new line}
  453.   begin new_line; print(#);
  454.   end
  455. @<Globals...@>=
  456. @!term_out:text_file; {the terminal as an output file}
  457. @ Different systems have different ways of specifying that the output on a
  458. certain file will appear on the user's terminal. Here is one way to do this
  459. on the \PASCAL\ system that was used in \.{TANGLE}'s initial development:
  460. @^system dependencies@>
  461. @<Set init...@>=
  462. rewrite(term_out,'TTY:'); {send |term_out| output to the terminal}
  463. @ The |update_terminal| procedure is called when we want
  464. to make sure that everything we have output to the terminal so far has
  465. actually left the computer's internal buffers and been sent.
  466. @^system dependencies@>
  467. @d update_terminal == break(term_out) {empty the terminal output buffer}
  468. @ The main input comes from |web_file|; this input may be overridden
  469. by changes in |change_file|. (If |change_file| is empty, there are no changes.)
  470. @<Globals...@>=
  471. @!web_file:text_file; {primary input}
  472. @!change_file:text_file; {updates}
  473. @ The following code opens the input files.  Since these files were listed
  474. in the program header, we assume that the \PASCAL\ runtime system has
  475. already checked that suitable file names have been given; therefore no
  476. additional error checking needs to be done.
  477. @^system dependencies@>
  478. @p procedure open_input; {prepare to read |web_file| and |change_file|}
  479. begin reset(web_file); reset(change_file);
  480. @ The main output goes to |Pascal_file|, and string pool constants are
  481. written to the |pool| file.
  482. @<Globals...@>=
  483. @!Pascal_file: text_file;
  484. @!pool: text_file;
  485. @ The following code opens |Pascal_file| and |pool|.
  486. Since these files were listed in the program header, we assume that the
  487. \PASCAL\ runtime system has checked that suitable external file names have
  488. been given.
  489. @^system dependencies@>
  490. @<Set init...@>=
  491. rewrite(Pascal_file); rewrite(pool);
  492. @ Input goes into an array called |buffer|.
  493. @<Globals...@>=@!buffer: array[0..buf_size] of ASCII_code;
  494. @ The |input_ln| procedure brings the next line of input from the specified
  495. file into the |buffer| array and returns the value |true|, unless the file has
  496. already been entirely read, in which case it returns |false|. The conventions
  497. of \TeX\ are followed; i.e., |ASCII_code| numbers representing the next line
  498. of the file are input into |buffer[0]|, |buffer[1]|, \dots,
  499. |buffer[limit-1]|; trailing blanks are ignored;
  500. and the global variable |limit| is set to the length of the
  501. @^system dependencies@>
  502. line. The value of |limit| must be strictly less than |buf_size|.
  503. We assume that none of the |ASCII_code| values
  504. of |buffer[j]| for |0<=j<limit| is equal to 0, @'177, |line_feed|, |form_feed|,
  505. or |carriage_return|.
  506. @p function input_ln(var f:text_file):boolean;
  507.   {inputs a line or returns |false|}
  508. var final_limit:0..buf_size; {|limit| without trailing blanks}
  509. begin limit:=0; final_limit:=0;
  510. if eof(f) then input_ln:=false
  511. else  begin while not eoln(f) do
  512.     begin buffer[limit]:=xord[f^]; get(f);
  513.     incr(limit);
  514.     if buffer[limit-1]<>" " then final_limit:=limit;
  515.     if limit=buf_size then
  516.       begin while not eoln(f) do get(f);
  517.       decr(limit); {keep |buffer[buf_size]| empty}
  518.       if final_limit>limit then final_limit:=limit;
  519.       print_nl('! Input line too long'); loc:=0; error;
  520. @.Input line too long@>
  521.       end;
  522.     end;
  523.   read_ln(f); limit:=final_limit; input_ln:=true;
  524.   end;
  525. @* Reporting errors to the user.
  526. The \.{TANGLE} processor operates in two phases: first it inputs the source
  527. file and stores a compressed representation of the program, then it produces
  528. the \PASCAL\ output from the compressed representation.
  529. The global variable |phase_one| tells whether we are in Phase I or not.
  530. @<Globals...@>=
  531. @!phase_one: boolean; {|true| in Phase I, |false| in Phase II}
  532. @ If an error is detected while we are debugging,
  533. we usually want to look at the contents of memory.
  534. A special procedure will be declared later for this purpose.
  535. @<Error handling...@>=
  536. @!debug @+ procedure debug_help; forward;@+ gubed
  537. @ During the first phase, syntax errors are reported to the user by saying
  538. $$\hbox{`|err_print('! Error message')|'},$$
  539. followed by `|jump_out|' if no recovery from the error is provided.
  540. This will print the error message followed by an indication of where the error
  541. was spotted in the source file. Note that no period follows the error message,
  542. since the error routine will automatically supply a period.
  543. Errors that are noticed during the second phase are reported to the user
  544. in the same fashion, but the error message will be
  545. followed by an indication of where the error was spotted in the output file.
  546. The actual error indications are provided by a procedure called |error|.
  547. @d err_print(#)==begin new_line; print(#); error;
  548.   end
  549. @<Error handling...@>=
  550. procedure error; {prints '\..' and location of error message}
  551. var j: 0..out_buf_size; {index into |out_buf|}
  552. @!k,@!l: 0..buf_size; {indices into |buffer|}
  553. begin if phase_one then @<Print error location based on input buffer@>
  554. else @<Print error location based on output buffer@>;
  555. update_terminal; mark_error;
  556. @!debug debug_help;@+gubed
  557. @ The error locations during Phase I can be indicated by using the global
  558. variables |loc|, |line|, and |changing|, which tell respectively the first
  559. unlooked-at position in |buffer|, the current line number, and whether or not
  560. the current line is from |change_file| or |web_file|.
  561. This routine should be modified on systems whose standard text editor
  562. has special line-numbering conventions.
  563. @^system dependencies@>
  564. @<Print error location based on input buffer@>=
  565. begin if changing then print('. (change file ')@+else print('. (');
  566. print_ln('l.', line:1, ')');
  567. if loc>=limit then l:=limit else l:=loc;
  568. for k:=1 to l do
  569.   if buffer[k-1]=tab_mark then print(' ')
  570.   else print(xchr[buffer[k-1]]); {print the characters already read}
  571. new_line;
  572. for k:=1 to l do print(' '); {space out the next line}
  573. for k:=l+1 to limit do print(xchr[buffer[k-1]]); {print the part not yet read}
  574. print(' '); {this space separates the message from future asterisks}
  575. @ The position of errors detected during the second phase can be indicated
  576. by outputting the partially-filled output buffer, which contains |out_ptr|
  577. entries.
  578. @<Print error location based on output...@>=
  579. begin print_ln('. (l.',line:1,')');
  580. for j:=1 to out_ptr do print(xchr[out_buf[j-1]]); {print current partial line}
  581. print('... '); {indicate that this information is partial}
  582. @ The |jump_out| procedure just cuts across all active procedure levels
  583. and jumps out of the program. This is the only non-local |goto| statement
  584. in \.{TANGLE}. It is used when no recovery from a particular error has
  585. been provided.
  586. Some \PASCAL\ compilers do not implement non-local |goto| statements.
  587. @^system dependencies@>
  588. In such cases the code that appears at label |end_of_TANGLE| should be
  589. copied into the |jump_out| procedure, followed by a call to a system procedure
  590. that terminates the program.
  591. @d fatal_error(#)==begin new_line; print(#); error; mark_fatal; jump_out;
  592.   end
  593. @<Error handling...@>=
  594. procedure jump_out;
  595. begin goto end_of_TANGLE;
  596. @ Sometimes the program's behavior is far different from what it should be,
  597. and \.{TANGLE} prints an error message that is really for the \.{TANGLE}
  598. maintenance person, not the user. In such cases the program says
  599. |confusion('indication of where we are')|.
  600. @d confusion(#)==fatal_error('! This can''t happen (',#,')')
  601. @.This can't happen@>
  602. @ An overflow stop occurs if \.{TANGLE}'s tables aren't large enough.
  603. @d overflow(#)==fatal_error('! Sorry, ',#,' capacity exceeded')
  604. @.Sorry, x capacity exceeded@>
  605. @* Data structures.
  606. Most of the user's \PASCAL\ code is packed into eight-bit integers
  607. in two large arrays called |byte_mem| and |tok_mem|.
  608. The |byte_mem| array holds the names of identifiers, strings, and modules;
  609. the |tok_mem| array holds the replacement texts
  610. for macros and modules. Allocation is sequential, since things are deleted only
  611. during Phase II, and only in a last-in-first-out manner.
  612. Auxiliary arrays |byte_start| and |tok_start| are used as directories to
  613. |byte_mem| and |tok_mem|, and the |link|, |ilk|, |equiv|, and |text_link|
  614. arrays give further information about names. These auxiliary arrays
  615. consist of sixteen-bit items.
  616. @<Types...@>=
  617. @!eight_bits=0..255; {unsigned one-byte quantity}
  618. @!sixteen_bits=0..65535; {unsigned two-byte quantity}
  619. @ \.{TANGLE} has been designed to avoid the need for indices that are more
  620. than sixteen bits wide, so that it can be used on most computers. But
  621. there are programs that need more than 65536 tokens, and some programs
  622. even need more than 65536 bytes; \TeX\ is one of these.  To get around
  623. this problem, a slight complication has been added to the data structures:
  624. |byte_mem| and |tok_mem| are two-dimensional arrays, whose first index is
  625. either 0 or 1. (For generality, the first index is actually allowed to run
  626. between 0 and |ww-1| in |byte_mem|, or between 0 and |zz-1| in |tok_mem|,
  627. where |ww| and |zz| are set to 2 and~3; the program will work for any
  628. positive values of |ww| and |zz|, and it can be simplified in obvious ways
  629. if |ww=1| or |zz=1|.)
  630. @d ww=2 {we multiply the byte capacity by approximately this amount}
  631. @d zz=3 {we multiply the token capacity by approximately this amount}
  632. @<Globals...@>=
  633. @!byte_mem: packed array [0..ww-1,0..max_bytes] of ASCII_code;
  634.   {characters of names}
  635. @!tok_mem: packed array [0..zz-1,0..max_toks] of eight_bits; {tokens}
  636. @!byte_start: array [0..max_names] of sixteen_bits; {directory into |byte_mem|}
  637. @!tok_start: array [0..max_texts] of sixteen_bits; {directory into |tok_mem|}
  638. @!link: array [0..max_names] of sixteen_bits; {hash table or tree links}
  639. @!ilk: array [0..max_names] of sixteen_bits; {type codes or tree links}
  640. @!equiv: array [0..max_names] of sixteen_bits; {info corresponding to names}
  641. @!text_link: array [0..max_texts] of sixteen_bits; {relates replacement texts}
  642. @ The names of identifiers are found by computing a hash address |h| and
  643. then looking at strings of bytes signified by |hash[h]|, |link[hash[h]]|,
  644. |link[link[hash[h]]]|, \dots, until either finding the desired name
  645. or encountering a zero.
  646. A `|name_pointer|' variable, which signifies a name, is an index into
  647. |byte_start|. The actual sequence of characters in the name pointed to by
  648. |p| appears in positions |byte_start[p]| to |byte_start[p+ww]-1|, inclusive,
  649. in the segment of |byte_mem| whose first index is |p mod ww|. Thus, when
  650. |ww=2| the even-numbered name bytes appear in |byte_mem[0,@t$*$@>]|
  651. and the odd-numbered ones appear in |byte_mem[1,@t$*$@>]|.
  652. The pointer 0 is used for undefined module names; we don't
  653. want to use it for the names of identifiers, since 0 stands for a null
  654. pointer in a linked list.
  655. Strings are treated like identifiers; the first character (a double-quote)
  656. distinguishes a string from an alphabetic name, but for \.{TANGLE}'s purposes
  657. strings behave like numeric macros. (A `string' here refers to the
  658. strings delimited by double-quotes that \.{TANGLE} processes. \PASCAL\
  659. string constants delimited by single-quote marks are not given such special
  660. treatment; they simply appear as sequences of characters in the \PASCAL\
  661. texts.)  The total number of strings in the string
  662. pool is called |string_ptr|, and the total number of names in |byte_mem|
  663. is called |name_ptr|. The total number of bytes occupied in
  664. |byte_mem[w,@t$*$@>]| is called |byte_ptr[w]|.
  665. We usually have |byte_start[name_ptr+w]=byte_ptr[(name_ptr+w) mod ww]|
  666. for |0<=w<ww|, since these are the starting positions for the next |ww|
  667. names to be stored in |byte_mem|.
  668. @d length(#)==byte_start[#+ww]-byte_start[#] {the length of a name}
  669. @<Types...@>=
  670. @!name_pointer=0..max_names; {identifies a name}
  671. @ @<Global...@>=
  672. @!name_ptr:name_pointer; {first unused position in |byte_start|}
  673. @!string_ptr:name_pointer; {next number to be given to a string of length |<>1|}
  674. @!byte_ptr:array [0..ww-1] of 0..max_bytes;
  675.   {first unused position in |byte_mem|}
  676. @!pool_check_sum:integer; {sort of a hash for the whole string pool}
  677. @ @<Local variables for init...@>=
  678. @!wi: 0..ww-1; {to initialize the |byte_mem| indices}
  679. @ @<Set init...@>=
  680. for wi:=0 to ww-1 do
  681.   begin byte_start[wi]:=0; byte_ptr[wi]:=0;
  682.   end;
  683. byte_start[ww]:=0; {this makes name 0 of length zero}
  684. name_ptr:=1; string_ptr:=256; pool_check_sum:=271828;
  685. @ Replacement texts are stored in |tok_mem|, using similar conventions.
  686. A `|text_pointer|' variable is an index into |tok_start|, and the
  687. replacement text that corresponds to |p| runs from positions
  688. |tok_start[p]| to |tok_start[p+zz]-1|, inclusive, in the segment of
  689. |tok_mem| whose first index is |p mod zz|. Thus, when |zz=2| the
  690. even-numbered replacement texts appear in |tok_mem[0,@t$*$@>]| and the
  691. odd-numbered ones appear in |tok_mem[1,@t$*$@>]|.  Furthermore,
  692. |text_link[p]| is used to connect pieces of text that have the same name,
  693. as we shall see later. The pointer 0 is used for undefined replacement
  694. texts.
  695. The first position of |tok_mem[z,@t$*$@>]| that is unoccupied by
  696. replacement text is called |tok_ptr[z]|, and the first unused location of
  697. |tok_start| is called |text_ptr|.  We usually have the identity
  698. |tok_start[text_ptr+z]=tok_ptr[(text_ptr+z) mod zz]|, for |0<=z<zz|, since
  699. these are the starting positions for the next |zz| replacement texts to
  700. be stored in |tok_mem|.
  701. @<Types...@>=
  702. @!text_pointer=0..max_texts; {identifies a replacement text}
  703. @ It is convenient to maintain a variable |z| that is equal to |text_ptr
  704. mod zz|, so that we always insert tokens into segment |z| of |tok_mem|.
  705. @<Glob...@>=
  706. @t\hskip1em@>@!text_ptr:text_pointer; {first unused position in |tok_start|}
  707. @t\hskip1em@>@!tok_ptr:array[0..zz-1] of 0..max_toks;
  708.   {first unused position in a given segment of |tok_mem|}
  709. @t\hskip1em@>@!z:0..zz-1; {current segment of |tok_mem|}
  710. stat @!max_tok_ptr:array[0..zz-1] of 0..max_toks;
  711.   {largest values assumed by |tok_ptr|}
  712. @ @<Local variables for init...@>=
  713. @!zi:0..zz-1; {to initialize the |tok_mem| indices}
  714. @ @<Set init...@>=
  715. for zi:=0 to zz-1 do
  716.   begin tok_start[zi]:=0; tok_ptr[zi]:=0;
  717.   end;
  718. tok_start[zz]:=0; {this makes replacement text 0 of length zero}
  719. text_ptr:=1; z:=1 mod zz;
  720. @ Four types of identifiers are distinguished by their |ilk|:
  721. \yskip\hang |normal| identifiers will appear in the \PASCAL\ program as
  722. ordinary identifiers since they have not been defined to be macros; the
  723. corresponding value in the |equiv| array
  724. for such identifiers is a link in a secondary hash table that
  725. is used to check whether any two of them agree in their first |unambig_length|
  726. characters after underline symbols are removed and lowercase letters are
  727. changed to uppercase.
  728. \yskip\hang |numeric| identifiers have been defined to be numeric macros;
  729. their |equiv| value contains the corresponding numeric value plus $2^{15}$.
  730. Strings are treated as numeric macros.
  731. \yskip\hang |simple| identifiers have been defined to be simple macros;
  732. their |equiv| value points to the corresponding replacement text.
  733. \yskip\hang |parametric| identifiers have been defined to be parametric macros;
  734. like simple identifiers, their |equiv| value points to the replacement text.
  735. @d normal=0 {ordinary identifiers have |normal| ilk}
  736. @d numeric=1 {numeric macros and strings have |numeric| ilk}
  737. @d simple=2 {simple macros have |simple| ilk}
  738. @d parametric=3 {parametric macros have |parametric| ilk}
  739. @ The names of modules are stored in |byte_mem| together
  740. with the identifier names, but a hash table is not used for them because
  741. \.{TANGLE} needs to be able to recognize a module name when given a prefix of
  742. that name. A conventional binary seach tree is used to retrieve module names,
  743. with fields called |llink| and |rlink| in place of |link| and |ilk|. The
  744. root of this tree is |rlink[0]|. If |p| is a pointer to a module name,
  745. |equiv[p]| points to its replacement text, just as in simple and parametric
  746. macros, unless this replacement text has not yet been defined (in which case
  747. |equiv[p]=0|).
  748. @d llink==link {left link in binary search tree for module names}
  749. @d rlink==ilk {right link in binary search tree for module names}
  750. @<Set init...@>=
  751. rlink[0]:=0; {the binary search tree starts out with nothing in it}
  752. equiv[0]:=0; {the undefined module has no replacement text}
  753. @ Here is a little procedure that prints the text of a given name.
  754. @p procedure print_id(@!p:name_pointer); {print identifier or module name}
  755. var k:0..max_bytes; {index into |byte_mem|}
  756. @!w:0..ww-1; {segment of |byte_mem|}
  757. begin if p>=name_ptr then print('IMPOSSIBLE')
  758. else  begin w:=p mod ww;
  759.   for k:=byte_start[p] to byte_start[p+ww]-1 do print(xchr[byte_mem[w,k]]);
  760.   end;
  761. @* Searching for identifiers.
  762. The hash table described above is updated by the |id_lookup| procedure,
  763. which finds a given identifier and returns a pointer to its index in
  764. |byte_start|. If the identifier was not already present, it is inserted with
  765. a given |ilk| code; and an error message is printed if the identifier is being
  766. doubly defined.
  767. Because of the way \.{TANGLE}'s scanning mechanism works, it is most convenient
  768. to let |id_lookup| search for an identifier that is present in the |buffer|
  769. array. Two other global variables specify its position in the buffer: the
  770. first character is |buffer[id_first]|, and the last is |buffer[id_loc-1]|.
  771. Furthermore, if the identifier is really a string, the global variable
  772. |double_chars| tells how many of the characters in the buffer appear
  773. twice (namely \.{@@@@} and \.{""}), since this additional information makes
  774. it easy to calculate the true length of the string. The final double-quote
  775. of the string is not included in its ``identifier,'' but the first one is,
  776. so the string length is |id_loc-id_first-double_chars-1|.
  777. We have mentioned that |normal| identifiers belong to two hash tables,
  778. one for their true names as they appear in the \.{WEB} file and the other
  779. when they have been reduced to their first |unambig_length| characters.
  780. The hash tables are kept by the method of simple chaining, where the
  781. heads of the individual lists appear in the |hash| and |chop_hash| arrays.
  782. If |h| is a hash code, the primary hash table list starts at |hash[h]| and
  783. proceeds through |link| pointers; the secondary hash table list starts at
  784. |chop_hash[h]| and proceeds through |equiv| pointers. Of course, the same
  785. identifier will probably have two different values of |h|.
  786. The |id_lookup| procedure uses an auxiliary array called |chopped_id| to
  787. contain up to |unambig_length| characters of the current identifier, if
  788. it is necessary to compute the secondary hash code. (This array could be
  789. declared local to |id_lookup|, but in general we are making all array
  790. declarations global in this program, because some compilers and some machine
  791. architectures make dynamic array allocation inefficient.)
  792. @<Glob...@>=
  793. @!id_first:0..buf_size; {where the current identifier begins in the buffer}
  794. @!id_loc:0..buf_size; {just after the current identifier in the buffer}
  795. @!double_chars:0..buf_size; {correction to length in case of strings}
  796. @!hash,@!chop_hash:array [0..hash_size] of sixteen_bits; {heads of hash lists}
  797. @!chopped_id:array [0..unambig_length] of ASCII_code; {chopped identifier}
  798. @ Initially all the hash lists are empty.
  799. @<Local variables for init...@>=
  800. @!h:0..hash_size; {index into hash-head arrays}
  801. @ @<Set init...@>=
  802. for h:=0 to hash_size-1 do
  803.   begin hash[h]:=0; chop_hash[h]:=0;
  804.   end;
  805. @ Here now is the main procedure for finding identifiers (and strings).
  806. The parameter |t| is set to |normal| except when the identifier is
  807. a macro name that is just being defined; in the latter case, |t| will be
  808. |numeric|, |simple|, or |parametric|.
  809. @p function id_lookup(@!t:eight_bits):name_pointer; {finds current identifier}
  810. label found, not_found;
  811. var c:eight_bits; {byte being chopped}
  812. @!i:0..buf_size; {index into |buffer|}
  813. @!h:0..hash_size; {hash code}
  814. @!k:0..max_bytes; {index into |byte_mem|}
  815. @!w:0..ww-1; {segment of |byte_mem|}
  816. @!l:0..buf_size; {length of the given identifier}
  817. @!p,@!q:name_pointer; {where the identifier is being sought}
  818. @!s:0..unambig_length; {index into |chopped_id|}
  819. begin l:=id_loc-id_first; {compute the length}
  820. @<Compute the hash code |h|@>;
  821. @<Compute the name location |p|@>;
  822. if (p=name_ptr)or(t<>normal) then
  823.   @<Update the tables and check for possible errors@>;
  824. id_lookup:=p;
  825. @ A simple hash code is used: If the sequence of
  826. ASCII codes is $c_1c_2\ldots c_m$, its hash value will be
  827. $$(2^{n-1}c_1+2^{n-2}c_2+\cdots+c_n)\,\bmod\,|hash_size|.$$
  828. @<Compute the hash...@>=
  829. h:=buffer[id_first]; i:=id_first+1;
  830. while i<id_loc do
  831.   begin h:=(h+h+buffer[i]) mod hash_size; incr(i);
  832.   end
  833. @ If the identifier is new, it will be placed in position |p=name_ptr|,
  834. otherwise |p| will point to its existing location.
  835. @<Compute the name location...@>=
  836. p:=hash[h];
  837. while p<>0 do
  838.   begin if length(p)=l then
  839.       @<Compare name |p| with current identifier, |goto found| if equal@>;
  840.   p:=link[p];
  841.   end;
  842. p:=name_ptr; {the current identifier is new}
  843. link[p]:=hash[h]; hash[h]:=p; {insert |p| at beginning of hash list}
  844. found:
  845. @ @<Compare name |p|...@>=
  846. begin i:=id_first; k:=byte_start[p]; w:=p mod ww;
  847. while (i<id_loc)and(buffer[i]=byte_mem[w,k]) do
  848.   begin incr(i); incr(k);
  849.   end;
  850. if i=id_loc then goto found; {all characters agree}
  851. @ @<Update the tables...@>=
  852. begin if ((p<>name_ptr)and(t<>normal)and(ilk[p]=normal)) or
  853.     ((p=name_ptr)and(t=normal)and(buffer[id_first]<>"""")) then
  854.   @<Compute the secondary hash code |h| and put the first characters
  855.   into the auxiliary array |chopped_id|@>;
  856. if p<>name_ptr then
  857.   @<Give double-definition error, if necessary, and change |p| to type |t|@>
  858. else @<Enter a new identifier into the table at position |p|@>;
  859. @ The following routine, which is called into play when it is necessary to
  860. look at the secondary hash table, computes the same hash function as before
  861. (but on the chopped data), and places a zero after the chopped identifier
  862. in |chopped_id| to serve as a convenient sentinel.
  863. @<Compute the secondary...@>=
  864. begin i:=id_first; s:=0; h:=0;
  865. while (i<id_loc)and(s<unambig_length) do
  866.   begin if buffer[i]<>"_" then
  867.     begin if buffer[i]>="a" then chopped_id[s]:=buffer[i]-@'40
  868.     else chopped_id[s]:=buffer[i];
  869.     h:=(h+h+chopped_id[s]) mod hash_size; incr(s);
  870.     end;
  871.   incr(i);
  872.   end;
  873. chopped_id[s]:=0;
  874. @ If a nonnumeric macro has appeared before it was defined, \.{TANGLE}
  875. will still work all right; after all, such behavior is typical of the
  876. replacement texts for modules, which act very much like macros.
  877. However, an undefined numeric macro may not be used on the right-hand
  878. side of another numeric macro definition, so \.{TANGLE} finds it
  879. simplest to make a blanket rule that numeric macros should be defined
  880. before they are used. The following routine gives an error message and
  881. also fixes up any damage that may have been caused.
  882. @<Give double...@>= {now |p<>name_ptr| and |t<>normal|}
  883. begin if ilk[p]=normal then
  884.   begin if t=numeric then err_print('! This identifier has already appeared');
  885. @.This identifier has already...@>
  886.   @<Remove |p| from secondary hash table@>;
  887.   end
  888. else err_print('! This identifier was defined before');
  889. @.This identifier was defined...@>
  890. ilk[p]:=t;
  891. @ When we have to remove a secondary hash entry, because a |normal| identifier
  892. is changing to another |ilk|, the hash code |h| and chopped identifier have
  893. already been computed.
  894. @<Remove |p| from secondary...@>=
  895. q:=chop_hash[h];
  896. if q=p then chop_hash[h]:=equiv[p]
  897. else  begin while equiv[q]<>p do q:=equiv[q];
  898.   equiv[q]:=equiv[p];
  899.   end
  900. @ The following routine could make good use of a generalized |pack| procedure
  901. that puts items into just part of a packed array instead of the whole thing.
  902. @<Enter a new identifier...@>=
  903. begin if (t=normal)and(buffer[id_first]<>"""") then
  904.   @<Check for ambiguity and update secondary hash@>;
  905. w:=name_ptr mod ww; k:=byte_ptr[w];
  906. if k+l>max_bytes then overflow('byte memory');
  907. if name_ptr>max_names-ww then overflow('name');
  908. i:=id_first; {get ready to move the identifier into |byte_mem|}
  909. while i<id_loc do
  910.   begin byte_mem[w,k]:=buffer[i]; incr(k); incr(i);
  911.   end;
  912. byte_ptr[w]:=k; byte_start[name_ptr+ww]:=k; incr(name_ptr);
  913. if buffer[id_first]<>"""" then ilk[p]:=t
  914. else @<Define and output a new string of the pool@>;
  915. @ @<Check for ambig...@>=
  916. begin q:=chop_hash[h];
  917. while q<>0 do
  918.   begin @<Check if |q| conflicts with |p|@>;
  919.   q:=equiv[q];
  920.   end;
  921. equiv[p]:=chop_hash[h]; chop_hash[h]:=p; {put |p| at front of secondary list}
  922. @ @<Check if |q| conflicts...@>=
  923. begin k:=byte_start[q]; s:=0; w:=q mod ww;
  924. while (k<byte_start[q+ww]) and (s<unambig_length) do
  925.   begin c:=byte_mem[w,k];
  926.   if c<>"_" then
  927.     begin if c>="a" then c:=c-@'40; {merge lowercase with uppercase}
  928.     if chopped_id[s]<>c then goto not_found;
  929.     incr(s);
  930.     end;
  931.   incr(k);
  932.   end;
  933. if (k=byte_start[q+ww])and(chopped_id[s]<>0) then goto not_found;
  934. print_nl('! Identifier conflict with ');
  935. @.Identifier conflict...@>
  936. for k:=byte_start[q] to byte_start[q+ww]-1 do print(xchr[byte_mem[w,k]]);
  937. error; q:=0; {only one conflict will be printed, since |equiv[0]=0|}
  938. not_found:
  939. @ We compute the string pool check sum by working modulo a prime number
  940. that is large but not so large that overflow might occur.
  941. @d check_sum_prime==@'3777777667 {$2^{29}-73$}
  942. @^preprocessed strings@>
  943. @<Define and output a new string...@>=
  944. begin ilk[p]:=numeric; {strings are like numeric macros}
  945. if l-double_chars=2 then {this string is for a single character}
  946.   equiv[p]:=buffer[id_first+1]+@'100000
  947. else  begin equiv[p]:=string_ptr+@'100000;
  948.   l:=l-double_chars-1;
  949.   if l>99 then err_print('! Preprocessed string is too long');
  950. @.Preprocessed string is too long@>
  951.   incr(string_ptr);
  952.   write(pool,xchr["0"+l div 10],xchr["0"+l mod 10]); {output the length}
  953.   pool_check_sum:=pool_check_sum+pool_check_sum+l;
  954.   while pool_check_sum>check_sum_prime do
  955.     pool_check_sum:=pool_check_sum-check_sum_prime;
  956.   i:=id_first+1;
  957.   while i<id_loc do
  958.     begin write(pool,xchr[buffer[i]]); {output characters of string}
  959.     pool_check_sum:=pool_check_sum+pool_check_sum+buffer[i];
  960.     while pool_check_sum>check_sum_prime do
  961.       pool_check_sum:=pool_check_sum-check_sum_prime;
  962.     if (buffer[i]="""") or (buffer[i]="@@") then
  963.       i:=i+2 {omit second appearance of doubled character}
  964.     else incr(i);
  965.     end;
  966.   write_ln(pool);
  967.   end;
  968. @* Searching for module names.
  969. The |mod_lookup| procedure finds the module name |mod_text[1..l]| in the
  970. search tree, after inserting it if necessary, and returns a pointer to
  971. where it was found.
  972. @<Glob...@>=
  973. @!mod_text:array [0..longest_name] of ASCII_code; {name being sought for}
  974. @ According to the rules of \.{WEB}, no module name
  975. should be a proper prefix of another, so a ``clean'' comparison should
  976. occur between any two names. The result of |mod_lookup| is 0 if this
  977. prefix condition is violated. An error message is printed when such violations
  978. are detected during phase two of \.{WEAVE}.
  979. @d less=0 {the first name is lexicographically less than the second}
  980. @d equal=1 {the first name is equal to the second}
  981. @d greater=2 {the first name is lexicographically greater than the second}
  982. @d prefix=3 {the first name is a proper prefix of the second}
  983. @d extension=4 {the first name is a proper extension of the second}
  984. @p function mod_lookup(@!l:sixteen_bits):name_pointer; {finds module name}
  985. label found;
  986. var c:less..extension; {comparison between two names}
  987. @!j:0..longest_name; {index into |mod_text|}
  988. @!k:0..max_bytes; {index into |byte_mem|}
  989. @!w:0..ww-1; {segment of |byte_mem|}
  990. @!p:name_pointer; {current node of the search tree}
  991. @!q:name_pointer; {father of node |p|}
  992. begin c:=greater; q:=0; p:=rlink[0]; {|rlink[0]| is the root of the tree}
  993. while p<>0 do
  994.   begin @<Set \(|c| to the result of comparing the given name to
  995.     name |p|@>;
  996.   q:=p;
  997.   if c=less then p:=llink[q]
  998.   else if c=greater then p:=rlink[q]
  999.   else goto found;
  1000.   end;
  1001. @<Enter a new module name into the tree@>;
  1002. found: if c<>equal then
  1003.   begin err_print('! Incompatible section names'); p:=0;
  1004. @.Incompatible module names@>
  1005.   end;
  1006. mod_lookup:=p;
  1007. @ @<Enter a new module name...@>=
  1008. w:=name_ptr mod ww; k:=byte_ptr[w];
  1009. if k+l>max_bytes then overflow('byte memory');
  1010. if name_ptr>max_names-ww then overflow('name');
  1011. p:=name_ptr;
  1012. if c=less then llink[q]:=p else rlink[q]:=p;
  1013. llink[p]:=0; rlink[p]:=0; c:=equal; equiv[p]:=0;
  1014. for j:=1 to l do byte_mem[w,k+j-1]:=mod_text[j];
  1015. byte_ptr[w]:=k+l; byte_start[name_ptr+ww]:=k+l; incr(name_ptr);
  1016. @ @<Set \(|c|...@>=
  1017. begin k:=byte_start[p]; w:=p mod ww; c:=equal; j:=1;
  1018. while (k<byte_start[p+ww]) and (j<=l) and (mod_text[j]=byte_mem[w,k]) do
  1019.   begin incr(k); incr(j);
  1020.   end;
  1021. if k=byte_start[p+ww] then
  1022.   if j>l then c:=equal
  1023.   else c:=extension
  1024. else if j>l then c:=prefix
  1025. else if mod_text[j]<byte_mem[w,k] then c:=less
  1026. else c:=greater;
  1027. @ The |prefix_lookup| procedure is supposed to find exactly one module
  1028. name that has |mod_text[1..l]| as a prefix. Actually the algorithm silently
  1029. accepts also the situation that some module name is a prefix of
  1030. |mod_text[1..l]|, because the user who painstakingly typed in more than
  1031. necessary probably doesn't want to be told about the wasted effort.
  1032. @p function prefix_lookup(@!l:sixteen_bits):name_pointer; {finds name extension}
  1033. var c:less..extension; {comparison between two names}
  1034. @!count:0..max_names; {the number of hits}
  1035. @!j:0..longest_name; {index into |mod_text|}
  1036. @!k:0..max_bytes; {index into |byte_mem|}
  1037. @!w:0..ww-1; {segment of |byte_mem|}
  1038. @!p:name_pointer; {current node of the search tree}
  1039. @!q:name_pointer; {another place to resume the search after one branch is done}
  1040. @!r:name_pointer; {extension found}
  1041. begin q:=0; p:=rlink[0]; count:=0; r:=0; {begin search at root of tree}
  1042. while p<>0 do
  1043.   begin @<Set \(|c|...@>;
  1044.   if c=less then p:=llink[p]
  1045.   else if c=greater then p:=rlink[p]
  1046.   else  begin r:=p; incr(count); q:=rlink[p]; p:=llink[p];
  1047.     end;
  1048.   if p=0 then
  1049.     begin p:=q; q:=0;
  1050.     end;
  1051.   end;
  1052. if count<>1 then
  1053.   if count=0 then err_print('! Name does not match')
  1054. @.Name does not match@>
  1055.   else err_print('! Ambiguous prefix');
  1056. @.Ambiguous prefix@>
  1057. prefix_lookup:=r; {the result will be 0 if there was no match}
  1058. @* Tokens.
  1059. Replacement texts, which represent \PASCAL\ code in a compressed format,
  1060. appear in |tok_mem| as mentioned above. The codes in
  1061. these texts are called `tokens'; some tokens occupy two consecutive
  1062. eight-bit byte positions, and the others take just one byte.
  1063. If $p>0$ points to a replacement text, |tok_start[p]| is the |tok_mem| position
  1064. of the first eight-bit code of that text. If |text_link[p]=0|,
  1065. this is the replacement text for a macro, otherwise it is the replacement
  1066. text for a module. In the latter case |text_link[p]| is either equal to
  1067. |module_flag|, which means that there is no further text for this module, or
  1068. |text_link[p]| points to a
  1069. continuation of this replacement text; such links are created when
  1070. several modules have \PASCAL\ texts with the same name, and they also
  1071. tie together all the \PASCAL\ texts of unnamed modules.
  1072. The replacement text pointer for the first unnamed module
  1073. appears in |text_link[0]|, and the most recent such pointer is |last_unnamed|.
  1074. @d module_flag==max_texts {final |text_link| in module replacement texts}
  1075. @<Glob...@>=
  1076. @!last_unnamed:text_pointer; {most recent replacement text of unnamed module}
  1077. @ @<Set init...@>= last_unnamed:=0; text_link[0]:=0;
  1078. @ If the first byte of a token is less than @'200, the token occupies a
  1079. single byte. Otherwise we make a sixteen-bit token by combining two consecutive
  1080. bytes |a| and |b|. If |@'200<=a<@'250|, then $(a-@'200)\times2^8+b$ points
  1081. to an identifier; if |@'250<=a<@'320|, then
  1082. $(a-@'250)\times2^8+b$ points to a module name; otherwise, i.e., if
  1083. |@'320<=a<@'400|, then $(a-@'320)\times2^8+b$ is the number of the module
  1084. in which the current replacement text appears.
  1085. Codes less than @'200 are 7-bit ASCII codes that represent themselves.
  1086. In particular, a single-character identifier like `|x|' will be a one-byte
  1087. token, while all longer identifiers will occupy two bytes.
  1088. Some of the 7-bit ASCII codes will not be present, however, so we can
  1089. use them for special purposes. The following symbolic names are used:
  1090. \yskip\hang |param| denotes insertion of a parameter. This occurs only in
  1091. the replacement texts of parametric macros, outside of single-quoted strings
  1092. in those texts.
  1093. \hang |begin_comment| denotes \.{@@\{}, which will become either
  1094. \.{\{} or \.{[}.
  1095. \hang |end_comment| denotes \.{@@\}}, which will become either
  1096. \.{\}} or \.{]}.
  1097. \hang |octal| denotes the \.{@@\'} that precedes an octal constant.
  1098. \hang |hex| denotes the \.{@@"} that precedes a hexadecimal constant.
  1099. \hang |check_sum| denotes the \.{@@\char'44} that denotes the string pool
  1100. check sum.
  1101. \hang |join| denotes the concatenation of adjacent items with no
  1102. space or line breaks allowed between them (the \.{@@\&} operation of \.{WEB}).
  1103. \hang |double_dot| denotes `\.{..}' in \PASCAL.
  1104. \hang |verbatim| denotes the \.{@@=} that begins a verbatim \PASCAL\ string.
  1105. It is also used for the end of the string.
  1106. \hang |force_line| denotes the \.{@@\\} that forces a new line in the
  1107. \PASCAL\ output.
  1108. @^ASCII code@>
  1109. @d param=0 {ASCII null code will not appear}
  1110. @d verbatim=@'2 {extended ASCII alpha should not appear}
  1111. @d force_line=@'3 {extended ASCII beta should not appear}
  1112. @d begin_comment=@'11 {ASCII tab mark will not appear}
  1113. @d end_comment=@'12 {ASCII line feed will not appear}
  1114. @d octal=@'14 {ASCII form feed will not appear}
  1115. @d hex=@'15 {ASCII carriage return will not appear}
  1116. @d double_dot=@'40 {ASCII space will not appear except in strings}
  1117. @d check_sum=@'175 {will not be confused with right brace}
  1118. @d join=@'177 {ASCII delete will not appear}
  1119. @ The following procedure is used to enter a two-byte value into
  1120. |tok_mem| when a replacement text is being generated.
  1121. @p procedure store_two_bytes(@!x:sixteen_bits);
  1122.   {stores high byte, then low byte}
  1123. begin if tok_ptr[z]+2>max_toks then overflow('token');
  1124. tok_mem[z,tok_ptr[z]]:=x div@'400; {this could be done by a shift command}
  1125. tok_mem[z,tok_ptr[z]+1]:=x mod@'400; {this could be done by a logical and}
  1126. tok_ptr[z]:=tok_ptr[z]+2;
  1127. @ When \.{TANGLE} is being operated in debug mode, it has a procedure to display
  1128. a replacement text in symbolic form. This procedure has not been spruced up to
  1129. generate a real great format, but at least the results are not as bad as
  1130. a memory dump.
  1131. @p @!debug procedure print_repl(@!p:text_pointer);
  1132. var k:0..max_toks; {index into |tok_mem|}
  1133. @!a: sixteen_bits; {current byte(s)}
  1134. @!zp: 0..zz-1; {segment of |tok_mem| being accessed}
  1135. begin if p>=text_ptr then print('BAD')
  1136. else  begin k:=tok_start[p]; zp:=p mod zz;
  1137.   while k<tok_start[p+zz] do
  1138.     begin a:=tok_mem[zp,k];
  1139.     if a>=@'200 then @<Display two-byte token starting with |a|@>
  1140.     else @<Display one-byte token |a|@>;
  1141.     incr(k);
  1142.     end;
  1143.   end;
  1144. gubed
  1145. @ @<Display two-byte...@>=
  1146. begin incr(k);
  1147. if a<@'250 then {identifier or string}
  1148.   begin a:=(a-@'200)*@'400+tok_mem[zp,k]; print_id(a);
  1149.   if byte_mem[a mod ww,byte_start[a]]="""" then print('"')
  1150.   else print(' ');
  1151.   end
  1152. else if a<@'320 then {module name}
  1153.   begin print('@@<'); print_id((a-@'250)*@'400+tok_mem[zp,k]);
  1154.   print('@@>');
  1155.   end
  1156. else  begin a:=(a-@'320)*@'400+tok_mem[zp,k]; {module number}
  1157.   print('@@',xchr["{"],a:1,'@@',xchr["}"]); {can't use right brace
  1158.     between \&{debug} and \&{gubed}}
  1159.   end;
  1160. @ @<Display one-byte...@>=
  1161. case a of
  1162. begin_comment: print('@@',xchr["{"]);
  1163. end_comment: print('@@',xchr["}"]); {can't use right brace
  1164.     between \&{debug} and \&{gubed}}
  1165. octal: print('@@''');
  1166. hex: print('@@"');
  1167. check_sum: print('@@$');
  1168. param: print('#');
  1169. "@@": print('@@@@');
  1170. verbatim: print('@@=');
  1171. force_line: print('@@\');
  1172. othercases print(xchr[a])
  1173. endcases
  1174. @* Stacks for output.
  1175. Let's make sure that our data structures contain enough information to
  1176. produce the entire \PASCAL\ program as desired, by working next on the
  1177. algorithms that actually do produce that program.
  1178. @ The output process uses a stack to keep track of what is going on at
  1179. different ``levels'' as the macros are being expanded.
  1180. Entries on this stack have five parts:
  1181. \yskip\hang |end_field| is the |tok_mem| location where the replacement
  1182. text of a particular level will end;
  1183. \hang |byte_field| is the |tok_mem| location from which the next token
  1184. on a particular level will be read;
  1185. \hang |name_field| points to the name corresponding to a particular level;
  1186. \hang |repl_field| points to the replacement text currently being read
  1187. at a particular level;
  1188. \hang |mod_field| is the module number, or zero if this is a macro.
  1189. \yskip\noindent The current values of these five quantities are referred to
  1190. quite frequently, so they are stored in a separate place instead of in
  1191. the |stack| array. We call the current values |cur_end|, |cur_byte|,
  1192. |cur_name|, |cur_repl|, and |cur_mod|.
  1193. The global variable |stack_ptr| tells how many levels of output are
  1194. currently in progress. The end of all output occurs when the stack is
  1195. empty, i.e., when |stack_ptr=0|.
  1196. @<Types...@>=
  1197. @t\4@>@!output_state=record
  1198.   @!end_field: sixteen_bits; {ending location of replacement text}
  1199.   @!byte_field: sixteen_bits; {present location within replacement text}
  1200.   @!name_field: name_pointer; {|byte_start| index for text being output}
  1201.   @!repl_field: text_pointer; {|tok_start| index for text being output}
  1202.   @!mod_field: 0..@'27777; {module number or zero if not a module}
  1203.   end;
  1204. @ @d cur_end==cur_state.end_field {current ending location in |tok_mem|}
  1205. @d cur_byte==cur_state.byte_field {location of next output byte in |tok_mem|}
  1206. @d cur_name==cur_state.name_field {pointer to current name being expanded}
  1207. @d cur_repl==cur_state.repl_field {pointer to current replacement text}
  1208. @d cur_mod==cur_state.mod_field {current module number being expanded}
  1209. @<Globals...@>=
  1210. @!cur_state : output_state; {|cur_end|, |cur_byte|, |cur_name|,
  1211.   |cur_repl|, |cur_mod|}
  1212. @!stack : array [1..stack_size] of output_state; {info for non-current levels}
  1213. @!stack_ptr: 0..stack_size; {first unused location in the output state stack}
  1214. @ It is convenient to keep a global variable |zo| equal to |cur_repl mod zz|.
  1215. @<Glob...@>=
  1216. @!zo:0..zz-1; {the segment of |tok_mem| from which output is coming}
  1217. @ Parameters must also be stacked. They are placed in
  1218. |tok_mem| just above the other replacement texts, and dummy parameter
  1219. `names' are placed in |byte_start| just after the other names.
  1220. The variables |text_ptr| and |tok_ptr[z]| essentially serve as parameter
  1221. stack pointers during the output phase, so there is no need for a separate
  1222. data structure to handle this problem.
  1223. @ There is an implicit stack corresponding to meta-comments that are output
  1224. via \.{@@\{} and \.{@@\}}. But this stack need not be represented in detail,
  1225. because we only need to know whether it is empty or not. A global variable
  1226. |brace_level| tells how many items would be on this stack if it were present.
  1227. @<Globals...@>=
  1228. @!brace_level: eight_bits; {current depth of $\.{@@\{}\ldots\.{@@\}}$ nesting}
  1229. @ To get the output process started, we will perform the following
  1230. initialization steps. We may assume that |text_link[0]| is nonzero, since it
  1231. points to the \PASCAL\ text in the first unnamed module that generates
  1232. code; if there are no such modules, there is nothing to output, and an
  1233. error message will have been generated before we do any of the initialization.
  1234. @<Initialize the output stacks@>=
  1235. stack_ptr:=1; brace_level:=0; cur_name:=0; cur_repl:=text_link[0];
  1236. zo:=cur_repl mod zz; cur_byte:=tok_start[cur_repl];
  1237. cur_end:=tok_start[cur_repl+zz]; cur_mod:=0;
  1238. @ When the replacement text for name |p| is to be inserted into the output,
  1239. the following subroutine is called to save the old level of output and get
  1240. the new one going.
  1241. @p procedure push_level(@!p:name_pointer); {suspends the current level}
  1242. begin if stack_ptr=stack_size then overflow('stack')
  1243. else  begin stack[stack_ptr]:=cur_state; {save |cur_end|, |cur_byte|, etc.}
  1244.   incr(stack_ptr);
  1245.   cur_name:=p; cur_repl:=equiv[p]; zo:=cur_repl mod zz;
  1246.   cur_byte:=tok_start[cur_repl]; cur_end:=tok_start[cur_repl+zz];
  1247.   cur_mod:=0;
  1248.   end;
  1249. @ When we come to the end of a replacement text, the |pop_level| subroutine
  1250. does the right thing: It either moves to the continuation of this replacement
  1251. text or returns the state to the most recently stacked level. Part of this
  1252. subroutine, which updates the parameter stack, will be given later when we
  1253. study the parameter stack in more detail.
  1254. @p procedure pop_level; {do this when |cur_byte| reaches |cur_end|}
  1255. label exit;
  1256. begin if text_link[cur_repl]=0 then {end of macro expansion}
  1257.   begin if ilk[cur_name]=parametric then
  1258.     @<Remove a parameter from the parameter stack@>;
  1259.   end
  1260. else if text_link[cur_repl]<module_flag then {link to a continuation}
  1261.   begin cur_repl:=text_link[cur_repl]; {we will stay on the same level}
  1262.   zo:=cur_repl mod zz;
  1263.   cur_byte:=tok_start[cur_repl]; cur_end:=tok_start[cur_repl+zz];
  1264.   return;
  1265.   end;
  1266. decr(stack_ptr); {we will go down to the previous level}
  1267. if stack_ptr>0 then
  1268.   begin cur_state:=stack[stack_ptr]; zo:=cur_repl mod zz;
  1269.   end;
  1270. exit: end;
  1271. @ The heart of the output procedure is the |get_output| routine, which produces
  1272. the next token of output that is not a reference to a macro. This procedure
  1273. handles all the stacking and unstacking that is necessary. It returns the
  1274. value |number| if the next output has a numeric value (the value of a
  1275. numeric macro or string), in which case |cur_val| has been set to the
  1276. number in question. The procedure also returns the value |module_number|
  1277. if the next output begins or ends the replacement text of some module,
  1278. in which case |cur_val| is that module's number (if beginning) or the
  1279. negative of that value (if ending). And it returns the value |identifier|
  1280. if the next output is an identifier of length two or more, in which case
  1281. |cur_val| points to that identifier name.
  1282. @d number=@'200 {code returned by |get_output| when next output is numeric}
  1283. @d module_number=@'201 {code returned by |get_output| for module numbers}
  1284. @d identifier=@'202 {code returned by |get_output| for identifiers}
  1285. @<Globals...@>=
  1286. @!cur_val:integer; {additional information corresponding to output token}
  1287. @ If |get_output| finds that no more output remains, it returns the value zero.
  1288. @p function get_output:sixteen_bits; {returns next token after macro expansion}
  1289. label restart, done, found;
  1290. var a:sixteen_bits; {value of current byte}
  1291. @!b:eight_bits; {byte being copied}
  1292. @!bal:sixteen_bits; {excess of \.( versus \.) while copying a parameter}
  1293. @!k:0..max_bytes; {index into |byte_mem|}
  1294. @!w:0..ww-1; {segment of |byte_mem|}
  1295. begin restart: if stack_ptr=0 then
  1296.   begin a:=0; goto found;
  1297.   end;
  1298. if cur_byte=cur_end then
  1299.   begin cur_val:=-cur_mod; pop_level;
  1300.   if cur_val=0 then goto restart;
  1301.   a:=module_number; goto found;
  1302.   end;
  1303. a:=tok_mem[zo,cur_byte]; incr(cur_byte);
  1304. if a<@'200 then {one-byte token}
  1305.   if a=param then
  1306.       @<Start scanning current macro parameter, |goto restart|@>
  1307.   else goto found;
  1308. a:=(a-@'200)*@'400+tok_mem[zo,cur_byte]; incr(cur_byte);
  1309. if a<@'24000 then {|@'24000=(@'250-@'200)*@'400|}
  1310.   @<Expand macro |a| and |goto found|, or |goto restart| if no output found@>;
  1311. if a<@'50000 then {|@'50000=(@'320-@'200)*@'400|}
  1312.   @<Expand module |a-@'24000|, |goto restart|@>;
  1313. cur_val:=a-@'50000; a:=module_number; cur_mod:=cur_val;
  1314. found:
  1315. @!debug if trouble_shooting then debug_help;@;@+gubed@/
  1316. get_output:=a;
  1317. @ The user may have forgotten to give any \PASCAL\ text for a module name,
  1318. or the \PASCAL\ text may have been associated with a different name by mistake.
  1319. @<Expand module |a-...@>=
  1320. begin a:=a-@'24000;
  1321. if equiv[a]<>0 then push_level(a)
  1322. else if a<>0 then
  1323.   begin print_nl('! Not present: <'); print_id(a); print('>'); error;
  1324. @.Not present: <section name>@>
  1325.   end;
  1326. goto restart;
  1327. @ @<Expand macro ...@>=
  1328. begin case ilk[a] of
  1329. normal: begin cur_val:=a; a:=identifier;
  1330.   end;
  1331. numeric: begin cur_val:=equiv[a]-@'100000; a:=number;
  1332.   end;
  1333. simple: begin push_level(a); goto restart;
  1334.   end;
  1335. parametric: begin @<Put a parameter on the parameter stack,
  1336.   or |goto restart| if error occurs@>;
  1337.   push_level(a); goto restart;
  1338.   end;
  1339. othercases confusion('output')
  1340. endcases;@/
  1341. goto found;
  1342. @ We come now to the interesting part, the job of putting a parameter on
  1343. the parameter stack. First we pop the stack if necessary until getting to
  1344. a level that hasn't ended. Then the next character must be a `\.(';
  1345. and since parentheses are balanced on each level, the entire parameter must
  1346. be present, so we can copy it without difficulty.
  1347. @<Put a parameter...@>=
  1348. while (cur_byte=cur_end)and(stack_ptr>0) do pop_level;
  1349. if (stack_ptr=0)or(tok_mem[zo,cur_byte]<>"(") then
  1350.   begin print_nl('! No parameter given for '); print_id(a); error;
  1351. @.No parameter given for macro@>
  1352.   goto restart;
  1353.   end;
  1354. @<Copy the parameter into |tok_mem|@>;
  1355. equiv[name_ptr]:=text_ptr; ilk[name_ptr]:=simple; w:=name_ptr mod ww;
  1356. k:=byte_ptr[w];
  1357. @!debug if k=max_bytes then overflow('byte memory');
  1358. byte_mem[w,k]:="#"; incr(k); byte_ptr[w]:=k;
  1359. gubed {this code has set the parameter identifier for debugging printouts}
  1360. if name_ptr>max_names-ww then overflow('name');
  1361. byte_start[name_ptr+ww]:=k; incr(name_ptr);
  1362. if text_ptr>max_texts-zz then overflow('text');
  1363. text_link[text_ptr]:=0; tok_start[text_ptr+zz]:=tok_ptr[z];
  1364. incr(text_ptr);
  1365. z:=text_ptr mod zz
  1366. @ The |pop_level| routine undoes the effect of parameter-pushing when
  1367. a parameter macro is finished:
  1368. @<Remove a parameter...@>=
  1369. begin decr(name_ptr); decr(text_ptr);
  1370. z:=text_ptr mod zz;
  1371. stat if tok_ptr[z]>max_tok_ptr[z] then max_tok_ptr[z]:=tok_ptr[z];
  1372. tats {the maximum value of |tok_ptr| occurs just before parameter popping}
  1373. tok_ptr[z]:=tok_start[text_ptr];
  1374. @!debug decr(byte_ptr[name_ptr mod ww]);@+gubed
  1375. @ When a parameter occurs in a replacement text, we treat it as a simple
  1376. macro in position (|name_ptr-1|):
  1377. @<Start scanning...@>=
  1378. begin push_level(name_ptr-1); goto restart;
  1379. @ Similarly, a |param| token encountered as we copy a parameter is converted
  1380. into a simple macro call for |name_ptr-1|.
  1381. Some care is needed to handle cases like \\{macro}|(#; print('#)'))|; the
  1382. \.{\#} token will have been changed to |param| outside of strings, but we
  1383. still must distinguish `real' parentheses from those in strings.
  1384. @d app_repl(#)==begin if tok_ptr[z]=max_toks then overflow('token');
  1385.   tok_mem[z,tok_ptr[z]]:=#; incr(tok_ptr[z]); end
  1386. @<Copy the parameter...@>=
  1387. bal:=1; incr(cur_byte); {skip the opening `\.('}
  1388. loop@+  begin b:=tok_mem[zo,cur_byte]; incr(cur_byte);
  1389.   if b=param then store_two_bytes(name_ptr+@'77777)
  1390.   else  begin if b>=@'200 then
  1391.       begin app_repl(b);
  1392.       b:=tok_mem[zo,cur_byte]; incr(cur_byte);
  1393.       end
  1394.     else   case b of
  1395.       "(": incr(bal);
  1396.       ")":  begin decr(bal);
  1397.         if bal=0 then goto done;
  1398.         end;
  1399.       "'": repeat app_repl(b);
  1400.         b:=tok_mem[zo,cur_byte]; incr(cur_byte);
  1401.         until b="'"; {copy string, don't change |bal|}
  1402.       othercases do_nothing
  1403.       endcases;
  1404.     app_repl(b);
  1405.     end;
  1406.   end;
  1407. done:
  1408. @* Producing the output.
  1409. The |get_output| routine above handles most of the complexity of output
  1410. generation, but there are two further considerations that have a nontrivial
  1411. effect on \.{TANGLE}'s algorithms.
  1412. First, we want to make sure that the output is broken into lines not
  1413. exceeding |line_length| characters per line, where these breaks occur at
  1414. valid places (e.g., not in the middle of a string or a constant or an
  1415. identifier, not between `\.<' and `\.>', not at a `\.{@@\&}' position
  1416. where quantities are being joined together). Therefore we assemble the
  1417. output into a buffer before deciding where the line breaks will appear.
  1418. However, we make very little attempt to make ``logical'' line breaks that
  1419. would enhance the readability of the output; people are supposed to read
  1420. the input of \.{TANGLE} or the \TeX ed output of \.{WEAVE}, but not the
  1421. tangled-up output. The only concession to readability is that a break after
  1422. a semicolon will be made if possible, since commonly used ``pretty
  1423. printing'' routines give better results in such cases.
  1424. Second, we want to decimalize non-decimal constants, and to combine integer
  1425. quantities that are added or subtracted, because \PASCAL\ doesn't allow
  1426. constant expressions in subrange types or in case labels. This means we
  1427. want to have a procedure that treats a construction like \.{(E-15+17)}
  1428. as equivalent to `\.{(E+2)}', while also leaving `\.{(1E-15+17)}' and
  1429. `\.{(E-15+17*y)}' untouched. Consider also `\.{-15+17.5}' versus
  1430. `\.{-15+17..5}'. We shall not combine integers preceding or following
  1431. \.*, \./, \.{div}, \.{mod}, or \.{@@\&}. Note that if |y| has been defined
  1432. to equal $-2$, we must expand `\.{x*y}' into `\.{x*(-2)}'; but `\.{x-y}'
  1433. can expand into `\.{x+2}' and we can even change `\.{x - y mod z}' to
  1434. @^mod@>
  1435. `\.{x + 2 mod z}' because \PASCAL\ has a nonstandard \&{mod} operation!
  1436. The following solution to these problems has been adopted: An array
  1437. |out_buf| contains characters that have been generated but not yet output,
  1438. and there are three pointers into this array. One of these, |out_ptr|, is
  1439. the number of characters currently in the buffer, and we will have
  1440. |1<=out_ptr<=line_length| most of the time. The second is |break_ptr|,
  1441. which is the largest value |<=out_ptr| such that we are definitely entitled
  1442. to end a line by outputting the characters |out_buf[1..(break_ptr-1)]|;
  1443. we will always have |break_ptr<=line_length|. Finally, |semi_ptr| is either
  1444. zero or the largest known value of a legal break after a semicolon or comment
  1445. on the current line; we will always have |semi_ptr<=break_ptr|.
  1446. @<Globals...@>=
  1447. @!out_buf: array [0..out_buf_size] of ASCII_code; {assembled characters}
  1448. @!out_ptr: 0..out_buf_size; {first available place in |out_buf|}
  1449. @!break_ptr: 0..out_buf_size; {last breaking place in |out_buf|}
  1450. @!semi_ptr: 0..out_buf_size; {last semicolon breaking place in |out_buf|}
  1451. @ Besides having those three pointers,
  1452. the output process is in one of several states:
  1453. \yskip\hang |num_or_id| means that the last item in the buffer is a number or
  1454. identifier, hence a blank space or line break must be inserted if the next
  1455. item is also a number or identifier.
  1456. \yskip\hang |unbreakable| means that the last item in the buffer was followed
  1457. by the \.{@@\&} operation that inhibits spaces between it and the next item.
  1458. \yskip\hang |sign| means that the last item in the buffer is to be followed
  1459. by \.+ or \.-, depending on whether |out_app| is positive or negative.
  1460. \yskip\hang |sign_val| means that the decimal equivalent of
  1461. $\vert|out_val|\vert$ should be appended to the buffer. If |out_val<0|,
  1462. or if |out_val=0| and |last_sign<0|, the number should be preceded by a minus
  1463. sign. Otherwise it should be preceded by the character |out_sign| unless
  1464. |out_sign=0|; the |out_sign| variable is either 0 or \.{"\ "} or \.{"+"}.
  1465. \yskip\hang |sign_val_sign| is like |sign_val|, but also append \.+ or \.-
  1466. afterwards, depending on whether |out_app| is positive or negative.
  1467. \yskip\hang |sign_val_val| is like |sign_val|, but also append the decimal
  1468. equivalent of |out_app| including its sign, using |last_sign| in case
  1469. |out_app=0|.
  1470. \yskip\hang |misc| means none of the above.
  1471. \yskip\noindent
  1472. For example, the output buffer and output state run through the following
  1473. sequence as we generate characters from `\.{(x-15+19-2)}':
  1474. $$\vbox{\halign{$\hfil#\hfil$\quad&#\hfil&\quad\hfil#\hfil&\quad
  1475. \hfil#\hfil&\quad\hfil#\hfil&\quad\hfil#\hfil\quad&\hfil#\hfil\cr
  1476. output&|out_buf|&|out_state|&|out_sign|&|out_val|&|out_app|&|last_sign|\cr
  1477. \noalign{\vskip 3pt}
  1478. (&\.(&|misc|\cr
  1479. x&\.{(x}&|num_or_id|\cr
  1480. -&\.{(x}&|sign|&&&$-1$&$-1$\cr
  1481. 15&\.{(x}&|sign_val|&\.{"+"}&$-15$&&$-15$\cr
  1482. +&\.{(x}&|sign_val_sign|&\.{"+"}&$-15$&$+1$&$+1$\cr
  1483. 19&\.{(x}&|sign_val_val|&\.{"+"}&$-15$&$+19$&$+1$\cr
  1484. -&\.{(x}&|sign_val_sign|&\.{"+"}&$+4$&$-1$&$-1$\cr
  1485. 2&\.{(x}&|sign_val_val|&\.{"+"}&$+4$&$-2$&$-2$\cr
  1486. )&\.{(x+2)}&|misc|\cr}}$$
  1487. At each stage we have put as much into the buffer as possible without
  1488. knowing what is coming next. Examples like `\.{x-0.1}' indicate why
  1489. |last_sign| is needed to associate the proper sign with an output of zero.
  1490. In states |num_or_id|, |unbreakable|, and |misc| the last item in the buffer
  1491. lies between |break_ptr| and |out_ptr-1|, inclusive; in the other states we
  1492. have |break_ptr=out_ptr|.
  1493. The numeric values assigned to |num_or_id|, etc., have been chosen to
  1494. shorten some of the program logic; for example, the program makes use of
  1495. the fact that |sign+2=sign_val_sign|.
  1496. @d misc=0 {state associated with special characters}
  1497. @d num_or_id=1 {state associated with numbers and identifiers}
  1498. @d sign=2 {state associated with pending \.+ or \.-}
  1499. @d sign_val=num_or_id+2 {state associated with pending sign and value}
  1500. @d sign_val_sign=sign+2 {|sign_val| followed by another pending sign}
  1501. @d sign_val_val=sign_val+2 {|sign_val| followed by another pending value}
  1502. @d unbreakable=sign_val_val+1 {state associated with \.{@@\&}}
  1503. @<Globals...@>=
  1504. @!out_state:eight_bits; {current status of partial output}
  1505. @!out_val,@!out_app:integer; {pending values}
  1506. @!out_sign:ASCII_code; {sign to use if appending |out_val>=0|}
  1507. @!last_sign:-1..+1; {sign to use if appending a zero}
  1508. @ During the output process, |line| will equal the number of the next line
  1509. to be output.
  1510. @<Initialize the output buffer@>=
  1511. out_state:=misc; out_ptr:=0; break_ptr:=0; semi_ptr:=0; out_buf[0]:=0; line:=1;
  1512. @ Here is a routine that is invoked when |out_ptr>line_length|
  1513. or when it is time to flush out the final line. The |flush_buffer| procedure
  1514. often writes out the line up to the current |break_ptr| position, then moves the
  1515. remaining information to the front of |out_buf|. However, it prefers to
  1516. write only up to |semi_ptr|, if the residual line won't be too long.
  1517. @d check_break==if out_ptr>line_length then flush_buffer
  1518. @p procedure flush_buffer; {writes one line to output file}
  1519. var k:0..out_buf_size; {index into |out_buf|}
  1520. @!b:0..out_buf_size; {value of |break_ptr| upon entry}
  1521. begin b:=break_ptr;
  1522. if (semi_ptr<>0)and(out_ptr-semi_ptr<=line_length) then break_ptr:=semi_ptr;
  1523. for k:=1 to break_ptr do write(Pascal_file,xchr[out_buf[k-1]]);
  1524. write_ln(Pascal_file); incr(line);
  1525. if line mod 100 = 0 then
  1526.   begin print('.');
  1527.   if line mod 500 = 0 then print(line:1);
  1528.   update_terminal; {progress report}
  1529.   end;
  1530. if break_ptr<out_ptr then
  1531.   begin if out_buf[break_ptr]=" " then
  1532.     begin incr(break_ptr); {drop space at break}
  1533.     if break_ptr>b then b:=break_ptr;
  1534.     end;
  1535.   for k:=break_ptr to out_ptr-1 do out_buf[k-break_ptr]:=out_buf[k];
  1536.   end;
  1537. out_ptr:=out_ptr-break_ptr; break_ptr:=b-break_ptr; semi_ptr:=0;
  1538. if out_ptr>line_length then
  1539.   begin err_print('! Long line must be truncated'); out_ptr:=line_length;
  1540. @.Long line must be truncated@>
  1541.   end;
  1542. @ @<Empty the last line from the buffer@>=
  1543. break_ptr:=out_ptr; semi_ptr:=0; flush_buffer;
  1544. if brace_level<>0 then
  1545.   err_print('! Program ended at brace level ',brace_level:1);
  1546. @.Program ended at brace level n@>
  1547. @ Another simple and useful routine appends the decimal equivalent of
  1548. a nonnegative integer to the output buffer.
  1549. @d app(#)==begin out_buf[out_ptr]:=#; incr(out_ptr); {append a single character}
  1550.   end
  1551. @p procedure app_val(@!v:integer); {puts |v| into buffer, assumes |v>=0|}
  1552. var k:0..out_buf_size; {index into |out_buf|}
  1553. begin k:=out_buf_size; {first we put the digits at the very end of |out_buf|}
  1554. repeat out_buf[k]:=v mod 10; v:=v div 10; decr(k);
  1555. until v=0;
  1556. repeat incr(k); app(out_buf[k]+"0");
  1557. until k=out_buf_size; {then we append them, most significant first}
  1558. @ The output states are kept up to date by the output routines, which are
  1559. called |send_out|, |send_val|, and |send_sign|. The |send_out| procedure
  1560. has two parameters: |t| tells the type of information being sent and
  1561. |v| contains the information proper. Some information may also be passed
  1562. in the array |out_contrib|.
  1563. \yskip\hang If |t=misc| then |v| is a character to be output.
  1564. \hang If |t=str| then |v| is the length of a string or something like `\.{<>}'
  1565. in |out_contrib|.
  1566. \hang If |t=ident| then |v| is the length of an identifier in |out_contrib|.
  1567. \hang If |t=frac| then |v| is the length of a fraction and/or exponent in
  1568. |out_contrib|.
  1569. @d str=1 {|send_out| code for a string}
  1570. @d ident=2 {|send_out| code for an identifier}
  1571. @d frac=3 {|send_out| code for a fraction}
  1572. @<Glob...@>=
  1573. @!out_contrib:array[1..line_length] of ASCII_code; {a contribution to |out_buf|}
  1574. @ A slightly subtle point in the following code is that the user may ask
  1575. for a |join| operation (i.e., \.{@@\&}) following whatever is being sent
  1576. out.  We will see later that |join| is implemented in part by calling
  1577. |send_out(frac,0)|.
  1578. @p procedure send_out(@!t:eight_bits; @!v:sixteen_bits);
  1579.   {outputs |v| of type |t|}
  1580. label restart;
  1581. var k: 0..line_length; {index into |out_contrib|}
  1582. begin @<Get the buffer ready for appending the new information@>;
  1583. if t<>misc then for k:=1 to v do app(out_contrib[k])
  1584. else app(v);
  1585. check_break;
  1586. if (t=misc)and((v=";")or(v="}")) then
  1587.   begin semi_ptr:=out_ptr; break_ptr:=out_ptr;
  1588.   end;
  1589. if t>=ident then out_state:=num_or_id {|t=ident| or |frac|}
  1590. else out_state:=misc {|t=str| or |misc|}
  1591. @ Here is where the buffer states for signs and values collapse into simpler
  1592. states, because we are about to append something that doesn't combine with
  1593. the previous integer constants.
  1594. We use an ASCII-code trick: Since |","-1="+"| and |","+1="-"|, we have
  1595. |","-c=@t sign of $c$@>|, when $\vert c\vert=1$.
  1596. @<Get the buffer ready...@>=
  1597. restart: case out_state of
  1598. num_or_id: if t<>frac then
  1599.   begin break_ptr:=out_ptr;
  1600.   if t=ident then app(" ");
  1601.   end;
  1602. sign: begin app(","-out_app); check_break; break_ptr:=out_ptr;
  1603.   end;
  1604. sign_val,sign_val_sign: begin @<Append \(|out_val| to buffer@>;
  1605.   out_state:=out_state-2; goto restart;
  1606.   end;
  1607. sign_val_val: @<Reduce |sign_val_val| to |sign_val| and |goto restart|@>;
  1608. misc: if t<>frac then break_ptr:=out_ptr;@/
  1609. othercases do_nothing {this is for |unbreakable| state}
  1610. endcases
  1611. @ @<Append \(|out_val|...@>=
  1612. if (out_val<0)or((out_val=0)and(last_sign<0)) then app("-")
  1613. else if out_sign>0 then app(out_sign);
  1614. app_val(abs(out_val)); check_break;
  1615. @ @<Reduce |sign_val_val|...@>=
  1616. begin if (t=frac)or(@<Contribution is \.* or \./ or \.{DIV} or \.{MOD}@>) then
  1617.   begin @<Append \(|out_val| to buffer@>;
  1618.   out_sign:="+"; out_val:=out_app;
  1619.   end
  1620. else out_val:=out_val+out_app;
  1621. out_state:=sign_val; goto restart;
  1622. @ @<Contribution is \.*...@>=
  1623. ((t=ident)and(v=3)and@|
  1624.  (((out_contrib[1]="D")and(out_contrib[2]="I")and(out_contrib[3]="V")) or@|
  1625.  ((out_contrib[1]="M")and(out_contrib[2]="O")and(out_contrib[3]="D")) ))or@|
  1626. @^uppercase@>
  1627.  ((t=misc)and((v="*")or(v="/")))
  1628. @ The following routine is called with $v=\pm1$ when a plus or minus sign is
  1629. appended to the output. It extends \PASCAL\ to allow repeated signs
  1630. (e.g., `\.{--}' is equivalent to `\.+'), rather than to give an error message.
  1631. The signs following `\.E' in real constants are treated as part of a fraction,
  1632. so they are not seen by this routine.
  1633. @p procedure send_sign(@!v:integer);
  1634. begin case out_state of
  1635. sign, sign_val_sign: out_app:=out_app*v;
  1636. sign_val:begin out_app:=v; out_state:=sign_val_sign;
  1637.   end;
  1638. sign_val_val: begin out_val:=out_val+out_app; out_app:=v;
  1639.   out_state:=sign_val_sign;
  1640.   end;
  1641. othercases begin break_ptr:=out_ptr; out_app:=v; out_state:=sign;
  1642.   end
  1643. endcases;@/
  1644. last_sign:=out_app;
  1645. @ When a (signed) integer value is to be output, we call |send_val|.
  1646. @d bad_case=666 {this is a label used below}
  1647. @p procedure send_val(@!v:integer); {output the (signed) value |v|}
  1648. label bad_case, {go here if we can't keep |v| in the output state}
  1649.   exit;
  1650. begin case out_state of
  1651. num_or_id: begin @<If previous output was \.{DIV} or \.{MOD}, |goto bad_case|@>;
  1652.   out_sign:=" "; out_state:=sign_val; out_val:=v; break_ptr:=out_ptr;
  1653.   last_sign:=+1;
  1654.   end;
  1655. misc: begin @<If previous output was \.* or \./, |goto bad_case|@>;
  1656.   out_sign:=0; out_state:=sign_val; out_val:=v; break_ptr:=out_ptr;
  1657.   last_sign:=+1;
  1658.   end;
  1659. @t\4@>@<Handle cases of |send_val| when |out_state| contains a sign@>@;
  1660. othercases goto bad_case
  1661. endcases;@/
  1662. return;
  1663. bad_case: @<Append the decimal value of |v|, with parentheses if negative@>;
  1664. exit: end;
  1665. @ @<Handle cases of |send_val|...@>=
  1666. sign: begin out_sign:="+"; out_state:=sign_val; out_val:=out_app*v;
  1667.   end;
  1668. sign_val: begin out_state:=sign_val_val; out_app:=v;
  1669.   err_print('! Two numbers occurred without a sign between them');
  1670.   end;
  1671. sign_val_sign: begin out_state:=sign_val_val; out_app:=out_app*v;
  1672.   end;
  1673. sign_val_val: begin out_val:=out_val+out_app; out_app:=v;
  1674.   err_print('! Two numbers occurred without a sign between them');
  1675. @.Two numbers occurred...@>
  1676.   end;
  1677. @ @<If previous output was \.*...@>=
  1678. if (out_ptr=break_ptr+1)and((out_buf[break_ptr]="*")or(out_buf[break_ptr]="/"))
  1679.   then goto bad_case
  1680. @ @<If previous output was \.{DIV}...@>=
  1681. if (out_ptr=break_ptr+3)or
  1682.  ((out_ptr=break_ptr+4)and(out_buf[break_ptr]=" ")) then
  1683. @^uppercase@>
  1684.   if ((out_buf[out_ptr-3]="D")and(out_buf[out_ptr-2]="I")and
  1685.     (out_buf[out_ptr-1]="V"))or @/
  1686.      ((out_buf[out_ptr-3]="M")and(out_buf[out_ptr-2]="O")and
  1687.     (out_buf[out_ptr-1]="D")) then@/ goto bad_case
  1688. @ @<Append the decimal value...@>=
  1689. if v>=0 then
  1690.   begin if out_state=num_or_id then
  1691.     begin break_ptr:=out_ptr; app(" ");
  1692.     end;
  1693.   app_val(v); check_break; out_state:=num_or_id;
  1694.   end
  1695. else  begin app("("); app("-"); app_val(-v); app(")"); check_break;
  1696.   out_state:=misc;
  1697.   end
  1698. @* The big output switch.
  1699. To complete the output process, we need a routine that takes the results
  1700. of |get_output| and feeds them to |send_out|, |send_val|, or |send_sign|.
  1701. This procedure `|send_the_output|' will be invoked just once, as follows:
  1702. @<Phase II: Output the contents of the compressed tables@>=
  1703. if text_link[0]=0 then
  1704.   begin print_nl('! No output was specified.'); mark_harmless;
  1705. @.No output was specified@>
  1706.   end
  1707. else  begin print_nl('Writing the output file'); update_terminal;@/
  1708.   @<Initialize the output stacks@>;
  1709.   @<Initialize the output buffer@>;
  1710.   send_the_output;@/
  1711.   @<Empty the last line...@>;
  1712.   print_nl('Done.');
  1713.   end
  1714. @ A many-way switch is used to send the output:
  1715. @d get_fraction=2 {this label is used below}
  1716. @p procedure send_the_output;
  1717. label get_fraction, {go here to finish scanning a real constant}
  1718.   reswitch, continue;
  1719. var cur_char:eight_bits; {the latest character received}
  1720.   @!k:0..line_length; {index into |out_contrib|}
  1721.   @!j:0..max_bytes; {index into |byte_mem|}
  1722.   @!w:0..ww-1; {segment of |byte_mem|}
  1723.   @!n:integer; {number being scanned}
  1724. begin while stack_ptr>0 do
  1725.   begin cur_char:=get_output;
  1726.   reswitch: case cur_char of
  1727.   0: do_nothing; {this case might arise if output ends unexpectedly}
  1728.   @t\4@>@<Cases related to identifiers@>@;
  1729.   @t\4@>@<Cases related to constants, possibly leading to
  1730.     |get_fraction| or |reswitch|@>@;
  1731.   "+","-": send_sign(","-cur_char);
  1732.   @t\4@>@<Cases like \.{<>} and \.{:=}@>@;
  1733.   "'": @<Send a string, |goto reswitch|@>;
  1734.   @<Other printable characters@>: send_out(misc,cur_char);
  1735.   @t\4@>@<Cases involving \.{@@\{} and \.{@@\}}@>@;
  1736.   join: begin send_out(frac,0); out_state:=unbreakable;
  1737.     end;
  1738.   verbatim: @<Send verbatim string@>;
  1739.   force_line: @<Force a line break@>;
  1740.   othercases err_print('! Can''t output ASCII code ',cur_char:1)
  1741. @.Can't output ASCII code n@>
  1742.   endcases;@/
  1743.   goto continue;
  1744.   get_fraction: @<Special code to finish real constants@>;
  1745.   continue: end;
  1746. @ @<Cases like \.{<>}...@>=
  1747. and_sign: begin out_contrib[1]:="A"; out_contrib[2]:="N"; out_contrib[3]:="D";
  1748. @^uppercase@>
  1749.   send_out(ident,3);
  1750.   end;
  1751. not_sign: begin out_contrib[1]:="N"; out_contrib[2]:="O"; out_contrib[3]:="T";
  1752.   send_out(ident,3);
  1753.   end;
  1754. set_element_sign: begin out_contrib[1]:="I"; out_contrib[2]:="N";
  1755.   send_out(ident,2);
  1756.   end;
  1757. or_sign: begin out_contrib[1]:="O"; out_contrib[2]:="R"; send_out(ident,2);
  1758.   end;
  1759. left_arrow: begin out_contrib[1]:=":"; out_contrib[2]:="="; send_out(str,2);
  1760.   end;
  1761. not_equal: begin out_contrib[1]:="<"; out_contrib[2]:=">"; send_out(str,2);
  1762.   end;
  1763. less_or_equal: begin out_contrib[1]:="<"; out_contrib[2]:="="; send_out(str,2);
  1764.   end;
  1765. greater_or_equal: begin out_contrib[1]:=">"; out_contrib[2]:="=";
  1766.   send_out(str,2);
  1767.   end;
  1768. equivalence_sign: begin out_contrib[1]:="="; out_contrib[2]:="=";
  1769.   send_out(str,2);
  1770.   end;
  1771. double_dot: begin out_contrib[1]:="."; out_contrib[2]:="."; send_out(str,2);
  1772.   end;
  1773. @ Please don't ask how all of the following characters can actually get
  1774. through \.{TANGLE} outside of strings. It seems that |""""| and |"{"|
  1775. cannot actually occur at this point of the program, but they have
  1776. been included just in case \.{TANGLE} changes.
  1777. If \.{TANGLE} is producing code for a \PASCAL\ compiler that uses `\.{(.}'
  1778. and `\.{.)}' instead of square brackets (e.g., on machines with {\mc EBCDIC}
  1779. code), one should remove |"["| and |"]"| from this list and put them into
  1780. the preceding module in the appropriate way. Similarly, some compilers
  1781. want `\.\^' to be converted to `\.{@@}'.
  1782. @^system dependencies@>@^EBCDIC@>
  1783. @<Other printable characters@>=
  1784. "!","""","#","$","%","&","(",")","*",",","/",":",";","<","=",">","?",
  1785. "@@","[","\","]","^","_","`","{","|"
  1786. @ Single-character identifiers represent themselves, while longer ones
  1787. appear in |byte_mem|. All must be converted to uppercase,
  1788. with underlines removed. Extremely long identifiers must be chopped.
  1789. (Some \PASCAL\ compilers work with lowercase letters instead of
  1790. uppercase. If this module of \.{TANGLE} is changed, it's also necessary
  1791. to change from uppercase to lowercase in the modules that are
  1792. listed in the index under ``uppercase''.)
  1793. @^system dependencies@>
  1794. @^uppercase@>
  1795. @d up_to(#)==#-24,#-23,#-22,#-21,#-20,#-19,#-18,#-17,#-16,#-15,#-14,
  1796.   #-13,#-12,#-11,#-10,#-9,#-8,#-7,#-6,#-5,#-4,#-3,#-2,#-1,#
  1797. @<Cases related to identifiers@>=
  1798. "A",up_to("Z"): begin out_contrib[1]:=cur_char; send_out(ident,1);
  1799.   end;
  1800. "a",up_to("z"): begin out_contrib[1]:=cur_char-@'40; send_out(ident,1);
  1801.   end;
  1802. identifier: begin k:=0; j:=byte_start[cur_val]; w:=cur_val mod ww;
  1803.   while (k<max_id_length)and(j<byte_start[cur_val+ww]) do
  1804.     begin incr(k); out_contrib[k]:=byte_mem[w,j]; incr(j);
  1805.     if out_contrib[k]>="a" then out_contrib[k]:=out_contrib[k]-@'40
  1806.     else if out_contrib[k]="_" then decr(k);
  1807.     end;
  1808.   send_out(ident,k);
  1809.   end;
  1810. @ After sending a string, we need to look ahead at the next character, in order
  1811. to see if there were two consecutive single-quote marks. Afterwards we go to
  1812. |reswitch| to process the next character.
  1813. @<Send a string...@>=
  1814. begin k:=1; out_contrib[1]:="'";
  1815. repeat if k<line_length then incr(k);
  1816. out_contrib[k]:=get_output;
  1817. until (out_contrib[k]="'")or(stack_ptr=0);
  1818. if k=line_length then err_print('! String too long');
  1819. @.String too long@>
  1820. send_out(str,k); cur_char:=get_output;
  1821. if cur_char="'" then out_state:=unbreakable;
  1822. goto reswitch;
  1823. @ Sending a verbatim string is similar, but we don't have to look ahead.
  1824. @<Send verbatim string@>=
  1825. begin k:=0;
  1826. repeat if k<line_length then incr(k);
  1827. out_contrib[k]:=get_output;
  1828. until (out_contrib[k]=verbatim)or(stack_ptr=0);
  1829. if k=line_length then err_print('! Verbatim string too long');
  1830. @.Verbatim string too long@>
  1831. send_out(str,k-1);
  1832. @ In order to encourage portable software, \.{TANGLE} complains
  1833. if the constants get dangerously close to the largest value representable
  1834. on a 32-bit computer ($2^{31}-1$).
  1835. @d digits=="0","1","2","3","4","5","6","7","8","9"
  1836. @<Cases related to constants...@>=
  1837. digits: begin n:=0;
  1838.   repeat cur_char:=cur_char-"0";
  1839.   if n>=@'1463146314 then err_print('! Constant too big')
  1840. @.Constant too big@>
  1841.   else n:=10*n+cur_char;
  1842.   cur_char:=get_output;
  1843.   until (cur_char>"9")or(cur_char<"0");
  1844.   send_val(n); k:=0;
  1845.   if cur_char="e" then cur_char:="E";
  1846. @^uppercase@>
  1847.   if cur_char="E" then goto get_fraction
  1848.   else goto reswitch;
  1849.   end;
  1850. check_sum: send_val(pool_check_sum);
  1851. octal: begin n:=0; cur_char:="0";
  1852.   repeat cur_char:=cur_char-"0";
  1853.   if n>=@'2000000000 then err_print('! Constant too big')
  1854.   else n:=8*n+cur_char;
  1855.   cur_char:=get_output;
  1856.   until (cur_char>"7")or(cur_char<"0");
  1857.   send_val(n); goto reswitch;
  1858.   end;
  1859. hex: begin n:=0; cur_char:="0";
  1860.   repeat if cur_char>="A" then cur_char:=cur_char+10-"A"
  1861.   else cur_char:=cur_char-"0";
  1862.   if n>=@"8000000 then err_print('! Constant too big')
  1863.   else n:=16*n+cur_char;
  1864.   cur_char:=get_output;
  1865.   until (cur_char>"F")or(cur_char<"0")or@|
  1866.     ((cur_char>"9")and(cur_char<"A"));
  1867.   send_val(n); goto reswitch;
  1868.   end;
  1869. number: send_val(cur_val);
  1870. ".":  begin k:=1; out_contrib[1]:="."; cur_char:=get_output;
  1871.   if cur_char="." then
  1872.     begin out_contrib[2]:="."; send_out(str,2);
  1873.     end
  1874.   else if (cur_char>="0")and(cur_char<="9") then goto get_fraction
  1875.   else  begin send_out(misc,"."); goto reswitch;
  1876.     end;
  1877.   end;
  1878. @ The following code appears at label `|get_fraction|', when we want to
  1879. scan to the end of a real constant. The first |k| characters of a fraction
  1880. have already been placed in |out_contrib|, and |cur_char| is the next character.
  1881. @<Special code...@>=
  1882. repeat if k<line_length then incr(k);
  1883. out_contrib[k]:=cur_char; cur_char:=get_output;
  1884. if (out_contrib[k]="E")and((cur_char="+")or(cur_char="-")) then
  1885. @^uppercase@>
  1886.   begin if k<line_length then incr(k);
  1887.   out_contrib[k]:=cur_char; cur_char:=get_output;
  1888.   end
  1889. else if cur_char="e" then cur_char:="E";
  1890. until (cur_char<>"E")and((cur_char<"0")or(cur_char>"9"));
  1891. if k=line_length then err_print('! Fraction too long');
  1892. @.Fraction too long@>
  1893. send_out(frac,k); goto reswitch
  1894. @ Some \PASCAL\ compilers do not recognize comments in braces, so the
  1895. comments must be delimited by `\.{(*}' and `\.{*)}'.
  1896. @^system dependencies@>
  1897. In such cases the statement `|send_out(misc,"{")|' that appears here should
  1898. be replaced by `\ignorespaces|begin out_contrib[1]:="("; out_contrib[2]:="*";
  1899. send_out(str,2); end|', and a similar change should be made to
  1900. `|send_out(misc,"}")|'.
  1901. @<Cases involving \.{@@\{} and \.{@@\}}@>=
  1902. begin_comment: begin if brace_level=0 then send_out(misc,"{")
  1903.   else send_out(misc,"[");
  1904.   incr(brace_level);
  1905.   end;
  1906. end_comment: if brace_level>0 then
  1907.     begin decr(brace_level);
  1908.     if brace_level=0 then send_out(misc,"}")
  1909.     else send_out(misc,"]");
  1910.     end
  1911.   else err_print('! Extra @@}');
  1912. @.Extra \AT!\}@>
  1913. module_number: begin if brace_level=0 then send_out(misc,"{")
  1914.   else send_out(misc,"[");
  1915.   if cur_val<0 then
  1916.     begin send_out(misc,":"); send_val(-cur_val);
  1917.     end
  1918.   else  begin send_val(cur_val); send_out(misc,":");
  1919.     end;
  1920.   if brace_level=0 then send_out(misc,"}")
  1921.   else send_out(misc,"]");
  1922.   end;
  1923. @ @<Force a line break@>=
  1924. begin send_out(str,0); {normalize the buffer}
  1925. while out_ptr>0 do
  1926.   begin if out_ptr<=line_length then break_ptr:=out_ptr;
  1927.   flush_buffer;
  1928.   end;
  1929. out_state:=misc;
  1930. @* Introduction to the input phase.
  1931. We have now seen that \.{TANGLE} will be able to output the full
  1932. \PASCAL\ program, if we can only get that program into the byte memory in
  1933. the proper format. The input process is something like the output process
  1934. in reverse, since we compress the text as we read it in and we expand it
  1935. as we write it out.
  1936. There are three main input routines. The most interesting is the one that gets
  1937. the next token of a \PASCAL\ text; the other two are used to scan rapidly past
  1938. \TeX\ text in the \.{WEB} source code. One of the latter routines will jump to
  1939. the next token that starts with `\.{@@}', and the other skips to the end
  1940. of a \PASCAL\ comment.
  1941. @ But first we need to consider the low-level routine |get_line|
  1942. that takes care of merging |change_file| into |web_file|. The |get_line|
  1943. procedure also updates the line numbers for error messages.
  1944. @<Globals...@>=
  1945. @!ii:integer; {general purpose |for| loop variable in the outer block}
  1946. @!line:integer; {the number of the current line in the current file}
  1947. @!other_line:integer; {the number of the current line in the input file that
  1948.   is not currently being read}
  1949. @!temp_line:integer; {used when interchanging |line| with |other_line|}
  1950. @!limit:0..buf_size; {the last character position occupied in the buffer}
  1951. @!loc:0..buf_size; {the next character position to be read from the buffer}
  1952. @!input_has_ended: boolean; {if |true|, there is no more input}
  1953. @!changing: boolean; {if |true|, the current line is from |change_file|}
  1954. @ As we change |changing| from |true| to |false| and back again, we must
  1955. remember to swap the values of |line| and |other_line| so that the |err_print|
  1956. routine will be sure to report the correct line number.
  1957. @d change_changing==
  1958.   changing := not changing;
  1959.   temp_line:=other_line; other_line:=line; line:=temp_line
  1960.     {|line @t$\null\BA\null$@> other_line|}
  1961. @ When |changing| is |false|, the next line of |change_file| is kept in
  1962. |change_buffer[0..change_limit]|, for purposes of comparison with the next
  1963. line of |web_file|. After the change file has been completely input, we
  1964. set |change_limit:=0|, so that no further matches will be made.
  1965. @<Globals...@>=
  1966. @!change_buffer:array[0..buf_size] of ASCII_code;
  1967. @!change_limit:0..buf_size; {the last position occupied in |change_buffer|}
  1968. @ Here's a simple function that checks if the two buffers are different.
  1969. @p function lines_dont_match:boolean;
  1970. label exit;
  1971. var k:0..buf_size; {index into the buffers}
  1972. begin lines_dont_match:=true;
  1973. if change_limit<>limit then return;
  1974. if limit>0 then
  1975.   for k:=0 to limit-1 do if change_buffer[k]<>buffer[k] then return;
  1976. lines_dont_match:=false;
  1977. exit: end;
  1978. @ Procedure |prime_the_change_buffer| sets |change_buffer| in preparation
  1979. for the next matching operation. Since blank lines in the change file are
  1980. not used for matching, we have |(change_limit=0)and not changing| if and
  1981. only if the change file is exhausted. This procedure is called only
  1982. when |changing| is true; hence error messages will be reported correctly.
  1983. @p procedure prime_the_change_buffer;
  1984. label continue, done, exit;
  1985. var k:0..buf_size; {index into the buffers}
  1986. begin change_limit:=0; {this value will be used if the change file ends}
  1987. @<Skip over comment lines in the change file; |return| if end of file@>;
  1988. @<Skip to the next nonblank line; |return| if end of file@>;
  1989. @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>;
  1990. exit: end;
  1991. @ While looking for a line that begins with \.{@@x} in the change file,
  1992. we allow lines that begin with \.{@@}, as long as they don't begin with
  1993. \.{@@y} or \.{@@z} (which would probably indicate that the change file is
  1994. fouled up).
  1995. @<Skip over comment lines in the change file...@>=
  1996. loop@+  begin incr(line);
  1997.   if not input_ln(change_file) then return;
  1998.   if limit<2 then goto continue;
  1999.   if buffer[0]<>"@@" then goto continue;
  2000.   if (buffer[1]>="X")and(buffer[1]<="Z") then
  2001.     buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  2002.   if buffer[1]="x" then goto done;
  2003.   if (buffer[1]="y")or(buffer[1]="z") then
  2004.     begin loc:=2; err_print('! Where is the matching @@x?');
  2005. @.Where is the match...@>
  2006.     end;
  2007. continue: end;
  2008. done:
  2009. @ Here we are looking at lines following the \.{@@x}.
  2010. @<Skip to the next nonblank line...@>=
  2011. repeat incr(line);
  2012.   if not input_ln(change_file) then
  2013.     begin err_print('! Change file ended after @@x');
  2014. @.Change file ended...@>
  2015.     return;
  2016.     end;
  2017. until limit>0;
  2018. @ @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>=
  2019. begin change_limit:=limit;
  2020. if limit>0 then for k:=0 to limit-1 do change_buffer[k]:=buffer[k];
  2021. @ The following procedure is used to see if the next change entry should
  2022. go into effect; it is called only when |changing| is false.
  2023. The idea is to test whether or not the current
  2024. contents of |buffer| matches the current contents of |change_buffer|.
  2025. If not, there's nothing more to do; but if so, a change is called for:
  2026. All of the text down to the \.{@@y} is supposed to match. An error
  2027. message is issued if any discrepancy is found. Then the procedure
  2028. prepares to read the next line from |change_file|.
  2029. @p procedure check_change; {switches to |change_file| if the buffers match}
  2030. label exit;
  2031. var n:integer; {the number of discrepancies found}
  2032. @!k:0..buf_size; {index into the buffers}
  2033. begin if lines_dont_match then return;
  2034. n:=0;
  2035. loop@+  begin change_changing; {now it's |true|}
  2036.   incr(line);
  2037.   if not input_ln(change_file) then
  2038.     begin err_print('! Change file ended before @@y');
  2039. @.Change file ended...@>
  2040.     change_limit:=0;  change_changing; {|false| again}
  2041.     return;
  2042.     end;
  2043.   @<If the current line starts with \.{@@y},
  2044.     report any discrepancies and |return|@>;
  2045.   @<Move |buffer| and |limit|...@>;
  2046.   change_changing; {now it's |false|}
  2047.   incr(line);
  2048.   if not input_ln(web_file) then
  2049.     begin err_print('! WEB file ended during a change');
  2050. @.WEB file ended...@>
  2051.     input_has_ended:=true; return;
  2052.     end;
  2053.   if lines_dont_match then incr(n);
  2054.   end;
  2055. exit: end;
  2056. @ @<If the current line starts with \.{@@y}...@>=
  2057. if limit>1 then if buffer[0]="@@" then
  2058.   begin if (buffer[1]>="X")and(buffer[1]<="Z") then
  2059.     buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  2060.   if (buffer[1]="x")or(buffer[1]="z") then
  2061.     begin loc:=2; err_print('! Where is the matching @@y?');
  2062. @.Where is the match...@>
  2063.     end
  2064.   else if buffer[1]="y" then
  2065.     begin if n>0 then
  2066.       begin loc:=2; err_print('! Hmm... ',n:1,
  2067.         ' of the preceding lines failed to match');
  2068. @.Hmm... n of the preceding...@>
  2069.       end;
  2070.     return;
  2071.     end;
  2072.   end
  2073. @ @<Initialize the input system@>=
  2074. open_input; line:=0; other_line:=0;@/
  2075. changing:=true; prime_the_change_buffer; change_changing;@/
  2076. limit:=0; loc:=1; buffer[0]:=" "; input_has_ended:=false;
  2077. @ The |get_line| procedure is called when |loc>limit|; it puts the next
  2078. line of merged input into the buffer and updates the other variables
  2079. appropriately. A space is placed at the right end of the line.
  2080. @p procedure get_line; {inputs the next line}
  2081. label restart;
  2082. begin restart: if changing then
  2083.   @<Read from |change_file| and maybe turn off |changing|@>;
  2084. if not changing then
  2085.   begin @<Read from |web_file| and maybe turn on |changing|@>;
  2086.   if changing then goto restart;
  2087.   end;
  2088. loc:=0; buffer[limit]:=" ";
  2089. @ @<Read from |web_file|...@>=
  2090. begin incr(line);
  2091. if not input_ln(web_file) then input_has_ended:=true
  2092. else if limit=change_limit then
  2093.   if buffer[0]=change_buffer[0] then
  2094.     if change_limit>0 then check_change;
  2095. @ @<Read from |change_file|...@>=
  2096. begin incr(line);
  2097. if not input_ln(change_file) then
  2098.   begin err_print('! Change file ended without @@z');
  2099. @.Change file ended...@>
  2100.   buffer[0]:="@@"; buffer[1]:="z"; limit:=2;
  2101.   end;
  2102. if limit>1 then {check if the change has ended}
  2103.   if buffer[0]="@@" then
  2104.     begin if (buffer[1]>="X")and(buffer[1]<="Z") then
  2105.       buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  2106.     if (buffer[1]="x")or(buffer[1]="y") then
  2107.       begin loc:=2; err_print('! Where is the matching @@z?');
  2108. @.Where is the match...@>
  2109.       end
  2110.     else if buffer[1]="z" then
  2111.       begin prime_the_change_buffer; change_changing;
  2112.       end;
  2113.     end;
  2114. @ At the end of the program, we will tell the user if the change file
  2115. had a line that didn't match any relevant line in |web_file|.
  2116. @<Check that all changes have been read@>=
  2117. if change_limit<>0 then {|changing| is false}
  2118.   begin for ii:=0 to change_limit do buffer[ii]:=change_buffer[ii];
  2119.   limit:=change_limit; changing:=true; line:=other_line; loc:=change_limit;
  2120.   err_print('! Change file entry did not match');
  2121. @.Change file entry did not match@>
  2122.   end
  2123. @ Important milestones are reached during the input phase when certain
  2124. control codes are sensed.
  2125. Control codes in \.{WEB} begin with `\.{@@}', and the next character
  2126. identifies the code. Some of these are of interest only to \.{WEAVE},
  2127. so \.{TANGLE} ignores them; the others are converted by \.{TANGLE} into
  2128. internal code numbers by the |control_code| function below. The ordering
  2129. of these internal code numbers has been chosen to simplify the program logic;
  2130. larger numbers are given to the control codes that denote more significant
  2131. milestones.
  2132. @d ignore=0 {control code of no interest to \.{TANGLE}}
  2133. @d control_text=@'203 {control code for `\.{@@t}', `\.{@@\^}', etc.}
  2134. @d format=@'204 {control code for `\.{@@f}'}
  2135. @d definition=@'205 {control code for `\.{@@d}'}
  2136. @d begin_Pascal=@'206 {control code for `\.{@@p}'}
  2137. @d module_name=@'207 {control code for `\.{@@<}'}
  2138. @d new_module=@'210 {control code for `\.{@@\ }' and `\.{@@*}'}
  2139. @p function control_code(@!c:ASCII_code):eight_bits; {convert |c| after \.{@@}}
  2140. begin case c of
  2141. "@@": control_code:="@@"; {`quoted' at sign}
  2142. "'": control_code:=octal; {precedes octal constant}
  2143. """": control_code:=hex; {precedes hexadecimal constant}
  2144. "$": control_code:=check_sum; {string pool check sum}
  2145. " ",tab_mark: control_code:=new_module; {beginning of a new module}
  2146. "*": begin print('*',module_count+1:1);
  2147.   update_terminal; {print a progress report}
  2148.   control_code:=new_module; {beginning of a new module}
  2149.   end;
  2150. "D","d": control_code:=definition; {macro definition}
  2151. "F","f": control_code:=format; {format definition}
  2152. "{": control_code:=begin_comment; {begin-comment delimiter}
  2153. "}": control_code:=end_comment; {end-comment delimiter}
  2154. "P","p": control_code:=begin_Pascal; {\PASCAL\ text in unnamed module}
  2155. "T","t","^",".",":": control_code:=control_text; {control text to be ignored}
  2156. "&": control_code:=join; {concatenate two tokens}
  2157. "<": control_code:=module_name; {beginning of a module name}
  2158. "=": control_code:=verbatim; {beginning of \PASCAL\ verbatim mode}
  2159. "\": control_code:=force_line; {force a new line in \PASCAL\ output}
  2160. othercases control_code:=ignore {ignore all other cases}
  2161. endcases;
  2162. @ The |skip_ahead| procedure reads through the input at fairly high speed
  2163. until finding the next non-ignorable control code, which it returns.
  2164. @p function skip_ahead:eight_bits; {skip to next control code}
  2165. label done;
  2166. var c:eight_bits; {control code found}
  2167. begin loop begin if loc>limit then
  2168.     begin get_line;
  2169.     if input_has_ended then
  2170.       begin c:=new_module; goto done;
  2171.       end;
  2172.     end;
  2173.   buffer[limit+1]:="@@";
  2174.   while buffer[loc]<>"@@" do incr(loc);
  2175.   if loc<=limit then
  2176.     begin loc:=loc+2; c:=control_code(buffer[loc-1]);
  2177.     if (c<>ignore)or(buffer[loc-1]=">") then goto done;
  2178.     end;
  2179.   end;
  2180. done: skip_ahead:=c;
  2181. @ The |skip_comment| procedure reads through the input at somewhat high speed
  2182. until finding the first unmatched right brace or until coming to the end
  2183. of the file. It ignores characters following `\.\\' characters, since all
  2184. braces that aren't nested are supposed to be hidden in that way. For
  2185. example, consider the process of skipping the first comment below,
  2186. where the string containing the right brace has been typed as \.{\`\\.\\\}\'}
  2187. in the \.{WEB} file.
  2188. @p procedure skip_comment; {skips to next unmatched `\.\}'}
  2189. label exit;
  2190. var bal:eight_bits; {excess of left braces}
  2191. @!c:ASCII_code; {current character}
  2192. begin bal:=0;
  2193. loop@+  begin if loc>limit then
  2194.     begin get_line;
  2195.     if input_has_ended then
  2196.       begin err_print('! Input ended in mid-comment');
  2197. @.Input ended in mid-comment@>
  2198.       return;
  2199.       end;
  2200.     end;
  2201.   c:=buffer[loc]; incr(loc);
  2202.   @<Do special things when |c="@@", "\", "{", "}"|; |return| at end@>;
  2203.   end;
  2204. exit:end;
  2205. @ @<Do special things when |c="@@"...@>=
  2206. if c="@@" then
  2207.   begin c:=buffer[loc];
  2208.   if (c<>" ")and(c<>tab_mark)and(c<>"*")and(c<>"z")and(c<>"Z") then incr(loc)
  2209.   else  begin err_print('! Section ended in mid-comment');
  2210. @.Section ended in mid-comment@>
  2211.     decr(loc); return;
  2212.     end
  2213.   end
  2214. else if (c="\")and(buffer[loc]<>"@@") then incr(loc)
  2215. else if c="{" then incr(bal)
  2216. else if c="}" then
  2217.   begin if bal=0 then return;
  2218.   decr(bal);
  2219.   end
  2220. @* Inputting the next token.
  2221. As stated above, \.{TANGLE}'s most interesting input procedure is the
  2222. |get_next| routine that inputs the next token. However, the procedure
  2223. isn't especially difficult.
  2224. In most cases the tokens output by |get_next| have the form used in
  2225. replacement texts, except that two-byte tokens are not produced.
  2226. An identifier that isn't one letter long is represented by the
  2227. output `|identifier|', and in such a case the global variables
  2228. |id_first| and |id_loc| will have been set to the appropriate values
  2229. needed by the |id_lookup| procedure. A string that begins with a
  2230. double-quote is also considered an |identifier|, and in such a case
  2231. the global variable |double_chars| will also have been set appropriately.
  2232. Control codes produce the corresponding output of the |control_code|
  2233. function above; and if that code is |module_name|, the value of |cur_module|
  2234. will point to the |byte_start| entry for that module name.
  2235. Another global variable, |scanning_hex|, is |true| during the time that
  2236. the letters \.A through \.F should be treated as if they were digits.
  2237. @<Globals...@>=
  2238. @!cur_module: name_pointer; {name of module just scanned}
  2239. @!scanning_hex: boolean; {are we scanning a hexadecimal constant?}
  2240. @ @<Set init...@>=
  2241. scanning_hex:=false;
  2242. @ At the top level, |get_next| is a multi-way switch based on the next
  2243. character in the input buffer. A |new_module| code is inserted at the
  2244. very end of the input file.
  2245. @p function get_next:eight_bits; {produces the next input token}
  2246. label restart,done,found;
  2247. var c:eight_bits; {the current character}
  2248. @!d:eight_bits; {the next character}
  2249. @!j,@!k:0..longest_name; {indices into |mod_text|}
  2250. begin restart: if loc>limit then
  2251.   begin get_line;
  2252.   if input_has_ended then
  2253.     begin c:=new_module; goto found;
  2254.     end;
  2255.   end;
  2256. c:=buffer[loc]; incr(loc);
  2257. if scanning_hex then @<Go to |found| if |c| is a hexadecimal digit,
  2258.   otherwise set |scanning_hex:=false|@>;
  2259. case c of
  2260. "A",up_to("Z"),"a",up_to("z"): @<Get an identifier@>;
  2261. """": @<Get a preprocessed string@>;
  2262. "@@": @<Get control code and possible module name@>;
  2263. @t\4@>@<Compress two-symbol combinations like `\.{:=}'@>@;
  2264. " ",tab_mark: goto restart; {ignore spaces and tabs}
  2265. "{": begin skip_comment; goto restart;
  2266.   end;
  2267. "}": begin err_print('! Extra }'); goto restart;
  2268. @.Extra \}@>
  2269.   end;
  2270. othercases if c>=128 then goto restart {ignore nonstandard characters}
  2271.   else do_nothing
  2272. endcases;
  2273. found:@!debug if trouble_shooting then debug_help;@;@+gubed@/
  2274. get_next:=c;
  2275. @ @<Go to |found| if |c| is a hexadecimal digit...@>=
  2276. if ((c>="0")and(c<="9"))or((c>="A")and(c<="F")) then goto found
  2277. else scanning_hex:=false
  2278. @ Note that the following code substitutes \.{@@\{} and \.{@@\}} for the
  2279. respective combinations `\.{(*}' and `\.{*)}'. Explicit braces should be used
  2280. for \TeX\ comments in \PASCAL\ text.
  2281. @d compress(#)==begin if loc<=limit then begin c:=#; incr(loc); end; end
  2282. @<Compress two-symbol...@>=
  2283. ".": if buffer[loc]="." then compress(double_dot)
  2284.   else if buffer[loc]=")" then compress("]");
  2285. ":": if buffer[loc]="=" then compress(left_arrow);
  2286. "=": if buffer[loc]="=" then compress(equivalence_sign);
  2287. ">": if buffer[loc]="=" then compress(greater_or_equal);
  2288. "<": if buffer[loc]="=" then compress(less_or_equal)
  2289.   else if buffer[loc]=">" then compress(not_equal);
  2290. "(": if buffer[loc]="*" then compress(begin_comment)
  2291.   else if buffer[loc]="." then compress("[");
  2292. "*": if buffer[loc]=")" then compress(end_comment);
  2293. @ We have to look at the preceding character to make sure this isn't part
  2294. of a real constant, before trying to find an identifier starting with
  2295. `\.e' or `\.E'.
  2296. @<Get an identifier@>=
  2297. begin if ((c="e")or(c="E"))and(loc>1) then
  2298.   if (buffer[loc-2]<="9")and(buffer[loc-2]>="0") then c:=0;
  2299. if c<>0 then
  2300.   begin decr(loc); id_first:=loc;
  2301.   repeat incr(loc); d:=buffer[loc];
  2302.   until ((d<"0")or((d>"9")and(d<"A"))or((d>"Z")and(d<"a"))or(d>"z")) and
  2303.     (d<>"_");
  2304.   if loc>id_first+1 then
  2305.     begin c:=identifier; id_loc:=loc;
  2306.     end;
  2307.   end
  2308. else c:="E"; {exponent of a real constant}
  2309. @ A string that starts and ends with double-quote marks is converted into
  2310. an identifier that behaves like a numeric macro by means of the following
  2311. piece of the program.
  2312. @^preprocessed strings@>
  2313. @<Get a preprocessed string@>=
  2314. begin double_chars:=0; id_first:=loc-1;
  2315. repeat d:=buffer[loc]; incr(loc);
  2316.   if (d="""")or(d="@@") then
  2317.     if buffer[loc]=d then
  2318.       begin incr(loc); d:=0; incr(double_chars);
  2319.       end
  2320.     else  begin if d="@@" then err_print('! Double @@ sign missing')
  2321. @.Double \AT! sign missing@>
  2322.       end
  2323.   else if loc>limit then
  2324.     begin err_print('! String constant didn''t end'); d:="""";
  2325. @.String constant didn't end@>
  2326.     end;
  2327. until d="""";
  2328. id_loc:=loc-1; c:=identifier;
  2329. @ After an \.{@@} sign has been scanned, the next character tells us
  2330. whether there is more work to do.
  2331. @<Get control code and possible module name@>=
  2332. begin c:=control_code(buffer[loc]); incr(loc);
  2333. if c=ignore then goto restart
  2334. else if c=hex then scanning_hex:=true
  2335. else if c=module_name then
  2336.   @<Scan the \(module name and make |cur_module| point to it@>
  2337. else if c=control_text then
  2338.   begin repeat c:=skip_ahead;
  2339.   until c<>"@@";
  2340.   if buffer[loc-1]<>">" then
  2341.     err_print('! Improper @@ within control text');
  2342. @.Improper \AT! within control text@>
  2343.   goto restart;
  2344.   end;
  2345. @ @<Scan the \(module name...@>=
  2346. begin @<Put module name into |mod_text[1..k]|@>;
  2347. if k>3 then
  2348.   begin if (mod_text[k]=".")and(mod_text[k-1]=".")and(mod_text[k-2]=".") then
  2349.     cur_module:=prefix_lookup(k-3)
  2350.   else cur_module:=mod_lookup(k);
  2351.   end
  2352. else cur_module:=mod_lookup(k);
  2353. @ Module names are placed into the |mod_text| array with consecutive spaces,
  2354. tabs, and carriage-returns replaced by single spaces. There will be no
  2355. spaces at the beginning or the end. (We set |mod_text[0]:=" "| to facilitate
  2356. this, since the |mod_lookup| routine uses |mod_text[1]| as the first
  2357. character of the name.)
  2358. @<Set init...@>=mod_text[0]:=" ";
  2359. @ @<Put module name...@>=
  2360. k:=0;
  2361. loop@+  begin if loc>limit then
  2362.     begin get_line;
  2363.     if input_has_ended then
  2364.       begin err_print('! Input ended in section name');
  2365. @.Input ended in section name@>
  2366.       goto done;
  2367.       end;
  2368.     end;
  2369.   d:=buffer[loc];
  2370.   @<If end of name, |goto done|@>;
  2371.   incr(loc); if k<longest_name-1 then incr(k);
  2372.   if (d=" ")or(d=tab_mark) then
  2373.     begin d:=" "; if mod_text[k-1]=" " then decr(k);
  2374.     end;
  2375.   mod_text[k]:=d;
  2376.   end;
  2377. done: @<Check for overlong name@>;
  2378. if (mod_text[k]=" ")and(k>0) then decr(k);
  2379. @ @<If end of name,...@>=
  2380. if d="@@" then
  2381.   begin d:=buffer[loc+1];
  2382.   if d=">" then
  2383.     begin loc:=loc+2; goto done;
  2384.     end;
  2385.   if (d=" ")or(d=tab_mark)or(d="*") then
  2386.     begin err_print('! Section name didn''t end'); goto done;
  2387. @.Section name didn't end@>
  2388.     end;
  2389.   incr(k); mod_text[k]:="@@"; incr(loc); {now |d=buffer[loc]| again}
  2390.   end
  2391. @ @<Check for overlong name@>=
  2392. if k>=longest_name-2 then
  2393.   begin print_nl('! Section name too long: ');
  2394. @.Section name too long@>
  2395.   for j:=1 to 25 do print(xchr[mod_text[j]]);
  2396.   print('...'); mark_harmless;
  2397.   end
  2398. @* Scanning a numeric definition.
  2399. When \.{TANGLE} looks at the \PASCAL\ text following the `\.=' of a numeric
  2400. macro definition, it calls on the precedure |scan_numeric(p)|, where |p|
  2401. points to the name that is to be defined. This procedure evaluates the
  2402. right-hand side, which must consist entirely of integer constants and
  2403. defined numeric macros connected with \.+ and \.- signs (no parentheses).
  2404. It also sets the global variable |next_control| to the control code that
  2405. terminated this definition.
  2406. A definition ends with the control codes |definition|, |format|, |module_name|,
  2407. |begin_Pascal|, and |new_module|, all of which can be recognized
  2408. by the fact that they are the largest values |get_next| can return.
  2409. @d end_of_definition(#)==(#>=format)
  2410.   {is |#| a control code ending a definition?}
  2411. @<Global...@>=
  2412. @!next_control:eight_bits; {control code waiting to be acted upon}
  2413. @ The evaluation of a numeric expression makes use of two variables called the
  2414. |accumulator| and the |next_sign|. At the beginning, |accumulator| is zero and
  2415. |next_sign| is $+1$. When a \.+ or \.- is scanned, |next_sign| is multiplied
  2416. by the value of that sign. When a numeric value is scanned, it is multiplied by
  2417. |next_sign| and added to the |accumulator|, then |next_sign| is reset to $+1$.
  2418. @d add_in(#)==begin accumulator:=accumulator+next_sign*(#); next_sign:=+1;
  2419.   end
  2420. @p procedure scan_numeric(@!p:name_pointer); {defines numeric macros}
  2421. label reswitch, done;
  2422. var accumulator:integer; {accumulates sums}
  2423. @!next_sign:-1..+1; {sign to attach to next value}
  2424. @!q:name_pointer; {points to identifiers being evaluated}
  2425. @!val:integer; {constants being evaluated}
  2426. begin @<Set \(|accumulator| to the value of the right-hand side@>;
  2427. if abs(accumulator)>=@'100000 then
  2428.   begin err_print('! Value too big: ',accumulator:1); accumulator:=0;
  2429. @.Value too big@>
  2430.   end;
  2431. equiv[p]:=accumulator+@'100000; {name |p| now is defined to equal |accumulator|}
  2432. @ @<Set \(|accumulator| to the value of the right-hand side@>=
  2433. accumulator:=0; next_sign:=+1;
  2434. loop@+  begin next_control:=get_next;
  2435.   reswitch: case next_control of
  2436.   digits: begin @<Set |val| to value of decimal constant, and
  2437.       set |next_control| to the following token@>;
  2438.     add_in(val); goto reswitch;
  2439.     end;
  2440.   octal: begin @<Set |val| to value of octal constant, and
  2441.       set |next_control| to the following token@>;
  2442.     add_in(val); goto reswitch;
  2443.     end;
  2444.   hex: begin @<Set |val| to value of hexadecimal constant, and
  2445.       set |next_control| to the following token@>;
  2446.     add_in(val); goto reswitch;
  2447.     end;
  2448.   identifier: begin q:=id_lookup(normal);
  2449.     if ilk[q]<>numeric then
  2450.       begin next_control:="*"; goto reswitch; {leads to error}
  2451.       end;
  2452.     add_in(equiv[q]-@'100000);
  2453.     end;
  2454.   "+": do_nothing;
  2455.   "-": next_sign:=-next_sign;
  2456.   format, definition, module_name, begin_Pascal, new_module: goto done;
  2457.   ";": err_print('! Omit semicolon in numeric definition');
  2458. @.Omit semicolon in numeric def...@>
  2459.   othercases @<Signal error, flush rest of the definition@>
  2460.   endcases;
  2461.   end;
  2462. done:
  2463. @ @<Signal error, flush rest...@>=
  2464. begin err_print('! Improper numeric definition will be flushed');
  2465. @.Improper numeric definition...@>
  2466. repeat next_control:=skip_ahead
  2467. until end_of_definition(next_control);
  2468. if next_control=module_name then
  2469.   begin {we want to scan the module name too}
  2470.   loc:=loc-2; next_control:=get_next;
  2471.   end;
  2472. accumulator:=0; goto done;
  2473. @ @<Set |val| to value of decimal...@>=
  2474. val:=0;
  2475. repeat val:=10*val+next_control-"0"; next_control:=get_next;
  2476. until (next_control>"9")or(next_control<"0")
  2477. @ @<Set |val| to value of octal...@>=
  2478. val:=0; next_control:="0";
  2479. repeat val:=8*val+next_control-"0"; next_control:=get_next;
  2480. until (next_control>"7")or(next_control<"0")
  2481. @ @<Set |val| to value of hex...@>=
  2482. val:=0; next_control:="0";
  2483. repeat if next_control>="A" then next_control:=next_control+"0"+10-"A";
  2484. val:=16*val+next_control-"0"; next_control:=get_next;
  2485. until (next_control>"F")or(next_control<"0")or@|
  2486.   ((next_control>"9")and(next_control<"A"))
  2487. @* Scanning a macro definition.
  2488. The rules for generating the replacement texts corresponding to simple
  2489. macros, parametric macros, and \PASCAL\ texts of a module are almost
  2490. identical, so a single procedure is used for all three cases. The
  2491. differences are that
  2492. \yskip\item{a)} The sign |#| denotes a parameter only when it appears
  2493. outside of strings in a parametric macro; otherwise it stands for the
  2494. ASCII character |#|. (This is not used in standard \PASCAL, but some
  2495. \PASCAL s allow, for example, `\.{/\#}' after a certain kind of file name.)
  2496. \item{b)}Module names are not allowed in simple macros or parametric macros;
  2497. in fact, the appearance of a module name terminates such macros and denotes
  2498. the name of the current module.
  2499. \item{c)}The symbols \.{@@d} and \.{@@f} and \.{@@p} are not allowed after
  2500. module names, while they terminate macro definitions.
  2501. @ Therefore there is a procedure |scan_repl| whose parameter |t| specifies
  2502. either |simple| or |parametric| or |module_name|. After |scan_repl| has
  2503. acted, |cur_repl_text| will point to the replacement text just generated, and
  2504. |next_control| will contain the control code that terminated the activity.
  2505. @<Globals...@>=
  2506. @!cur_repl_text:text_pointer; {replacement text formed by |scan_repl|}
  2507. @ @p procedure scan_repl(@!t:eight_bits); {creates a replacement text}
  2508. label continue, done, found, reswitch;
  2509. var a:sixteen_bits; {the current token}
  2510. @!b:ASCII_code; {a character from the buffer}
  2511. @!bal:eight_bits; {left parentheses minus right parentheses}
  2512. begin bal:=0;
  2513. loop@+  begin continue: a:=get_next;
  2514.   case a of
  2515.   "(": incr(bal);
  2516.   ")": if bal=0 then err_print('! Extra )')
  2517. @.Extra )@>
  2518.     else decr(bal);
  2519.   "'": @<Copy a string from the buffer to |tok_mem|@>;
  2520.   "#": if t=parametric then a:=param;
  2521.   @t\4@>@<In cases that |a| is a non-ASCII token (|identifier|,
  2522.   |module_name|, etc.), either process it and change |a| to a byte
  2523.   that should be stored, or |goto continue| if |a| should be ignored,
  2524.   or |goto done| if |a| signals the end of this replacement text@>@;
  2525.   othercases do_nothing
  2526.   endcases;@/
  2527.   app_repl(a); {store |a| in |tok_mem|}
  2528.   end;
  2529. done: next_control:=a;
  2530. @<Make sure the parentheses balance@>;
  2531. if text_ptr>max_texts-zz then overflow('text');
  2532. cur_repl_text:=text_ptr; tok_start[text_ptr+zz]:=tok_ptr[z];
  2533. incr(text_ptr);
  2534. if z=zz-1 then z:=0@+else incr(z);
  2535. @ @<Make sure the parentheses balance@>=
  2536. if bal>0 then
  2537.   begin if bal=1 then err_print('! Missing )')
  2538.   else err_print('! Missing ',bal:1,' )''s');
  2539. @.Missing n )@>
  2540.   while bal>0 do
  2541.     begin app_repl(")"); decr(bal);
  2542.     end;
  2543.   end
  2544. @ @<In cases that |a| is...@>=
  2545. identifier: begin a:=id_lookup(normal); app_repl((a div @'400)+@'200);
  2546.   a:=a mod @'400;
  2547.   end;
  2548. module_name: if t<>module_name then goto done
  2549.   else  begin app_repl((cur_module div @'400)+@'250);
  2550.     a:=cur_module mod @'400;
  2551.     end;
  2552. verbatim: @<Copy verbatim string from the buffer to |tok_mem|@>;
  2553. definition, format, begin_Pascal: if t<>module_name then goto done
  2554.   else  begin err_print('! @@',xchr[buffer[loc-1]],
  2555. @.\AT!p is ignored in Pascal text@>
  2556. @.\AT!d is ignored in Pascal text@>
  2557. @.\AT!f is ignored in Pascal text@>
  2558.       ' is ignored in Pascal text'); goto continue;
  2559.     end;
  2560. new_module: goto done;
  2561. @ @<Copy a string...@>=
  2562. begin b:="'";
  2563. loop@+  begin app_repl(b);
  2564.   if b="@@" then
  2565.     if buffer[loc]="@@" then incr(loc) {store only one \.{@@}}
  2566.     else err_print('! You should double @@ signs in strings');
  2567. @.You should double \AT! signs@>
  2568.   if loc=limit then
  2569.     begin err_print('! String didn''t end');
  2570. @.String didn't end@>
  2571.     buffer[loc]:="'"; buffer[loc+1]:=0;
  2572.     end;
  2573.   b:=buffer[loc]; incr(loc);
  2574.   if b="'" then
  2575.     begin if buffer[loc]<>"'" then goto found
  2576.     else  begin incr(loc); app_repl("'");
  2577.       end;
  2578.     end;
  2579.   end;
  2580. found: end {now |a| holds the final |"'"| that will be stored}
  2581. @ @<Copy verbatim string...@>=
  2582. begin app_repl(verbatim);
  2583. buffer[limit+1]:="@@";
  2584. reswitch: if buffer[loc]="@@" then
  2585.   begin if loc<limit then if buffer[loc+1]="@@" then
  2586.     begin app_repl("@@");
  2587.     loc:=loc+2;
  2588.     goto reswitch;
  2589.     end;
  2590.   end
  2591. else begin app_repl(buffer[loc]);
  2592.   incr(loc);
  2593.   goto reswitch;
  2594.   end;
  2595. if loc>=limit then err_print('! Verbatim string didn''t end')
  2596. @.Verbatim string didn't end@>
  2597. else if buffer[loc+1]<>">" then
  2598.   err_print('! You should double @@ signs in verbatim strings');
  2599. @.You should double \AT! signs@>
  2600. loc:=loc+2;
  2601. end {another |verbatim| byte will be stored, since |a=verbatim|}
  2602. @ The following procedure is used to define a simple or parametric macro,
  2603. just after the `\.{==}' of its definition has been scanned.
  2604. @p procedure define_macro(@!t:eight_bits);
  2605. var p:name_pointer; {the identifier being defined}
  2606. begin p:=id_lookup(t); scan_repl(t);@/
  2607. equiv[p]:=cur_repl_text; text_link[cur_repl_text]:=0;
  2608. @* Scanning a module.
  2609. The |scan_module| procedure starts when `\.{@@\ }' or `\.{@@*}' has been
  2610. sensed in the input, and it proceeds until the end of that module.  It
  2611. uses |module_count| to keep track of the current module number; with luck,
  2612. \.{WEAVE} and \.{TANGLE} will both assign the same numbers to modules.
  2613. @<Globals...@>=
  2614. @!module_count:0..@'27777; {the current module number}
  2615. @ The top level of |scan_module| is trivial.
  2616. @p procedure scan_module;
  2617. label continue, done, exit;
  2618. var p:name_pointer; {module name for the current module}
  2619. begin incr(module_count);
  2620. @<Scan the \(definition part of the current module@>;
  2621. @<Scan the \PASCAL\ part of the current module@>;
  2622. exit: end;
  2623. @ @<Scan the \(definition part...@>=
  2624. next_control:=0;
  2625. loop@+  begin continue: while next_control<=format do
  2626.     begin next_control:=skip_ahead;
  2627.     if next_control=module_name then
  2628.       begin {we want to scan the module name too}
  2629.       loc:=loc-2; next_control:=get_next;
  2630.       end;
  2631.     end;
  2632.   if next_control<>definition then goto done;
  2633.   next_control:=get_next; {get identifier name}
  2634.   if next_control<>identifier then
  2635.     begin err_print('! Definition flushed, must start with ',
  2636. @.Definition flushed...@>
  2637.       'identifier of length > 1'); goto continue;
  2638.     end;
  2639.   next_control:=get_next; {get token after the identifier}
  2640.   if next_control="=" then
  2641.     begin scan_numeric(id_lookup(numeric)); goto continue;
  2642.     end
  2643.   else if next_control=equivalence_sign then
  2644.     begin define_macro(simple); goto continue;
  2645.     end
  2646.   else @<If the next text is `|(#)==|', call |define_macro|
  2647.     and |goto continue|@>;
  2648.   err_print('! Definition flushed since it starts badly');
  2649. @.Definition flushed...@>
  2650.   end;
  2651. done:
  2652. @ @<If the next text is `|(#)==|'...@>=
  2653. if next_control="(" then
  2654.   begin next_control:=get_next;
  2655.   if next_control="#" then
  2656.     begin next_control:=get_next;
  2657.     if next_control=")" then
  2658.       begin next_control:=get_next;
  2659.       if next_control="=" then
  2660.         begin err_print('! Use == for macros');
  2661. @.Use == for macros@>
  2662.         next_control:=equivalence_sign;
  2663.         end;
  2664.       if next_control=equivalence_sign then
  2665.         begin define_macro(parametric); goto continue;
  2666.         end;
  2667.       end;
  2668.     end;
  2669.   end;
  2670. @ @<Scan the \PASCAL...@>=
  2671. case next_control of
  2672. begin_Pascal:p:=0;
  2673. module_name: begin p:=cur_module;
  2674.   @<Check that |=| or |==| follows this module name, otherwise |return|@>;
  2675.   end;
  2676. othercases return
  2677. endcases;@/
  2678. @<Insert the module number into |tok_mem|@>;
  2679. scan_repl(module_name); {now |cur_repl_text| points to the replacement text}
  2680. @<Update the data structure so that the replacement text is accessible@>;
  2681. @ @<Check that |=|...@>=
  2682. repeat next_control:=get_next;
  2683. until next_control<>"+"; {allow optional `\.{+=}'}
  2684. if (next_control<>"=")and(next_control<>equivalence_sign) then
  2685.   begin err_print('! Pascal text flushed, = sign is missing');
  2686. @.Pascal text flushed...@>
  2687.   repeat next_control:=skip_ahead;
  2688.   until next_control=new_module;
  2689.   return;
  2690.   end
  2691. @ @<Insert the module number...@>=
  2692. store_two_bytes(@'150000+module_count); {|@'150000=@'320*@'400|}
  2693. @ @<Update the data...@>=
  2694. if p=0 then {unnamed module}
  2695.   begin text_link[last_unnamed]:=cur_repl_text; last_unnamed:=cur_repl_text;
  2696.   end
  2697. else if equiv[p]=0 then equiv[p]:=cur_repl_text {first module of this name}
  2698. else  begin p:=equiv[p];
  2699.   while text_link[p]<module_flag do p:=text_link[p]; {find end of list}
  2700.   text_link[p]:=cur_repl_text;
  2701.   end;
  2702. text_link[cur_repl_text]:=module_flag;
  2703.   {mark this replacement text as a nonmacro}
  2704. @* Debugging.
  2705. The \PASCAL\ debugger with which \.{TANGLE} was developed allows breakpoints
  2706. to be set, and variables can be read and changed, but procedures cannot be
  2707. executed. Therefore a `|debug_help|' procedure has been inserted in the main
  2708. loops of each phase of the program; when |ddt| and |dd| are set to appropriate
  2709. values, symbolic printouts of various tables will appear.
  2710. The idea is to set a breakpoint inside the |debug_help| routine, at the
  2711. place of `\ignorespaces|breakpoint:|\unskip' below.  Then when
  2712. |debug_help| is to be activated, set |trouble_shooting| equal to |true|.
  2713. The |debug_help| routine will prompt you for values of |ddt| and |dd|,
  2714. discontinuing this when |ddt<=0|; thus you type $2n+1$ integers, ending
  2715. with zero or a negative number. Then control either passes to the
  2716. breakpoint, allowing you to look at and/or change variables (if you typed
  2717. zero), or to exit the routine (if you typed a negative value).
  2718. Another global variable, |debug_cycle|, can be used to skip silently
  2719. past calls on |debug_help|. If you set |debug_cycle>1|, the program stops
  2720. only every |debug_cycle| times |debug_help| is called; however,
  2721. any error stop will set |debug_cycle| to zero.
  2722. @<Globals...@>=
  2723. @!debug@!trouble_shooting:boolean; {is |debug_help| wanted?}
  2724. @!ddt:integer; {operation code for the |debug_help| routine}
  2725. @!dd:integer; {operand in procedures performed by |debug_help|}
  2726. @!debug_cycle:integer; {threshold for |debug_help| stopping}
  2727. @!debug_skipped:integer; {we have skipped this many |debug_help| calls}
  2728. @!term_in:text_file; {the user's terminal as an input file}
  2729. gubed
  2730. @ The debugging routine needs to read from the user's terminal.
  2731. @^system dependencies@>
  2732. @<Set init...@>=
  2733. @!debug trouble_shooting:=true; debug_cycle:=1; debug_skipped:=0;@/
  2734. trouble_shooting:=false; debug_cycle:=99999; {use these when it almost works}
  2735. reset(term_in,'TTY:','/I'); {open |term_in| as the terminal, don't do a |get|}
  2736. gubed
  2737. @ @d breakpoint=888 {place where a breakpoint is desirable}
  2738. @^system dependencies@>
  2739. @p @!debug procedure debug_help; {routine to display various things}
  2740. label breakpoint,exit;
  2741. var k:integer; {index into various arrays}
  2742. begin incr(debug_skipped);
  2743. if debug_skipped<debug_cycle then return;
  2744. debug_skipped:=0;
  2745. loop@+  begin write(term_out,'#'); update_terminal; {prompt}
  2746.   read(term_in,ddt); {read a list of integers}
  2747.   if ddt<0 then return
  2748.   else if ddt=0 then
  2749.     begin goto breakpoint;@\ {go to every label at least once}
  2750.     breakpoint: ddt:=0;@\
  2751.     end
  2752.   else  begin read(term_in,dd);
  2753.     case ddt of
  2754.     1: print_id(dd);
  2755.     2: print_repl(dd);
  2756.     3: for k:=1 to dd do print(xchr[buffer[k]]);
  2757.     4: for k:=1 to dd do print(xchr[mod_text[k]]);
  2758.     5: for k:=1 to out_ptr do print(xchr[out_buf[k]]);
  2759.     6: for k:=1 to dd do print(xchr[out_contrib[k]]);
  2760.     othercases print('?')
  2761.     endcases;
  2762.     end;
  2763.   end;
  2764. exit:end;
  2765. gubed
  2766. @* The main program.
  2767. We have defined plenty of procedures, and it is time to put the last
  2768. pieces of the puzzle in place. Here is where \.{TANGLE} starts, and where
  2769. it ends.
  2770. @^system dependencies@>
  2771. @p begin initialize;
  2772. @<Initialize the input system@>;
  2773. print_ln(banner); {print a ``banner line''}
  2774. @<Phase I: Read all the user's text and compress it into |tok_mem|@>;
  2775. stat for ii:=0 to zz-1 do max_tok_ptr[ii]:=tok_ptr[ii];@+tats@;@/
  2776. @<Phase II:...@>;
  2777. end_of_TANGLE:
  2778. if string_ptr>256 then @<Finish off the string pool file@>;
  2779. stat @<Print statistics about memory usage@>;@+tats@;@/
  2780. @t\4\4@>{here files should be closed if the operating system requires it}
  2781. @<Print the job |history|@>;
  2782. @ @<Phase I:...@>=
  2783. phase_one:=true;
  2784. module_count:=0;
  2785. repeat next_control:=skip_ahead;
  2786. until next_control=new_module;
  2787. while not input_has_ended do scan_module;
  2788. @<Check that all changes have been read@>;
  2789. phase_one:=false;
  2790. @ @<Finish off the string pool file@>=
  2791. begin print_nl(string_ptr-256:1, ' strings written to string pool file.');
  2792. write(pool,'*');
  2793. for ii:=1 to 9 do
  2794.   begin out_buf[ii]:=pool_check_sum mod 10;
  2795.   pool_check_sum:=pool_check_sum div 10;
  2796.   end;
  2797. for ii:=9 downto 1 do write(pool,xchr["0"+out_buf[ii]]);
  2798. write_ln(pool);
  2799. @ @<Glob...@>=
  2800. stat @!wo:0..ww-1; {segment of memory for which statistics are being printed}
  2801. @ @<Print statistics about memory usage@>=
  2802. print_nl('Memory usage statistics:');
  2803. print_nl(name_ptr:1, ' names, ', text_ptr:1, ' replacement texts;');
  2804. print_nl(byte_ptr[0]:1);
  2805. for wo:=1 to ww-1 do print('+',byte_ptr[wo]:1);
  2806. if phase_one then
  2807.   for ii:=0 to zz-1 do max_tok_ptr[ii]:=tok_ptr[ii];
  2808. print(' bytes, ', max_tok_ptr[0]:1);
  2809. for ii:=1 to zz-1 do print('+',max_tok_ptr[ii]:1);
  2810. print(' tokens.');
  2811. @ Some implementations may wish to pass the |history| value to the
  2812. operating system so that it can be used to govern whether or not other
  2813. programs are started. Here we simply report the history to the user.
  2814. @^system dependencies@>
  2815. @<Print the job |history|@>=
  2816. case history of
  2817. spotless: print_nl('(No errors were found.)');
  2818. harmless_message: print_nl('(Did you see the warning message above?)');
  2819. error_message: print_nl('(Pardon me, but I think I spotted something wrong.)');
  2820. fatal_message: print_nl('(That was a fatal error, my friend.)');
  2821. end {there are no other cases}
  2822. @* System-dependent changes.
  2823. This module should be replaced, if necessary, by changes to the program
  2824. that are necessary to make \.{TANGLE} work at a particular installation.
  2825. It is usually best to design your change file so that all changes to
  2826. previous modules preserve the module numbering; then everybody's version
  2827. will be consistent with the printed program. More extensive changes,
  2828. which introduce new modules, can be inserted here; then only the index
  2829. itself will get a new module number.
  2830. @^system dependencies@>
  2831. @* Index.
  2832. Here is a cross-reference table for the \.{TANGLE} processor.
  2833. All modules in which an identifier is
  2834. used are listed with that identifier, except that reserved words are
  2835. indexed only when they appear in format definitions, and the appearances
  2836. of identifiers in module names are not indexed. Underlined entries
  2837. correspond to where the identifier was declared. Error messages and
  2838. a few other things like ``ASCII code'' are indexed here too.
  2839.