Debian Codegraph @

texk/web2c/patgen.web

raw
1 % This program is not copyrighted and can be used freely.
2 % This is PATGEN.WEB in text format, as of August 23, 2004.
3 % Version 1.0 was finished in 1983.
4 % Version 2.0 major revision for `8-bit TeX' (November 8, 1991).
5 % Version 2.1 allows left/right_hypen_min from terminal (April, 1992).
6 % Version 2.2 added `close_in(dictionary)' (August, 1996).
7 % Version 2.3 avoided division by zero - Karl Berry (October, 1996).
8 % Version 2.4 avoided use of uninitialized variables (September, 2009).
9 % A few typos fixed, no version change (April, 2020).
10 % Sorting order fixed, no version change (September, 2024).
11
12 % Here is TeX material that gets inserted after \input webmac
13 \def\hang{\hangindent 3em\indent\ignorespaces}
14 \def\PASCAL{Pascal}
15
16 \def\({} % this is used to make section names sort themselves better
17
18 \def\title{PATGEN}
19 \def\contentspagenumber{45} % should be odd
20 \def\topofcontents{\null
21 \titlefalse % include headline on the contents page
22 \def\rheader{\tenit Appendix\hfil \mainfont\contentspagenumber}
23 \vfill
24 \centerline{\titlefont {\ttitlefont PAT}tern {\ttitlefont GEN}eration
25 program}
26 \vskip 8pt
27 \centerline{\titlefont for the \TeX 82 hyphenator}
28 \vskip 15pt
29 \centerline{(Version 2.4, April 2020)}
30 \vfill}
31 \pageno=\contentspagenumber \advance\pageno by 1
32
33 @* Introduction.
34 This program takes a list of hyphenated words and generates a set of
35 patterns that can be used by the \TeX 82 hyphenation algorithm.
36
37 The patterns consist of strings of letters and digits, where a digit
38 indicates a `hyphenation value' for some intercharacter position. For
39 example, the pattern \.{3t2ion} specifies that if the string \.{tion}
40 occurs in a word, we should assign a hyphenation value of 3 to the
41 position immediately before the \.{t}, and a value of 2 to the position
42 between the \.{t} and the \.{i}.
43
44 To hyphenate a word, we find all patterns that match within the word and
45 determine the hyphenation values for each intercharacter position. If
46 more than one pattern applies to a given position, we take the maximum of
47 the values specified (i.e., the higher value takes priority). If the
48 resulting hyphenation value is odd, this position is a feasible
49 breakpoint; if the value is even or if no value has been specified, we are
50 not allowed to break at this position.
51
52 In order to find quickly the patterns that match in a given word and to
53 compute the associated hyphenation values, the patterns generated by this
54 program are compiled by \.{INITEX} into a compact version of a finite
55 state machine. For further details, see the \TeX 82 source.
56
57 The |banner| string defined here should be changed whenever \.{PATGEN}
58 gets modified.
59
60 @d banner=='This is PATGEN, Version 2.4' {printed when the program starts}
61
62 @ The original version~1 of \.{PATGEN} was written by Frank~M. Liang
63 @^Liang, Franklin Mark@>
64 in 1982; a major revision (version~2) by Peter Breitenlohner in 1991
65 @^Breitenlohner, Peter@>
66 is mostly related to the new features of `8-bit \TeX' (version~3 of
67 \TeX 82). The differences between versions~1 and~2 fall into several
68 categories (all of Liang's algorithms have been left essentially
69 unchanged): (1)~enhancements related to 8-bit \TeX, e.g., the
70 introduction of 8-bit |ASCII_code| values and of \.{\\lefthyphenmin} and
71 \.{\\righthyphenmin}; (2)~a modification of the input and output
72 procedures which should make language specific modifications of this
73 program unnecessary (information about the external representation of
74 all `letters' used by a particular language is obtained from the
75 |translate| file); (3)~removal of ANSI standard \PASCAL\ and range check
76 violations; (4)~removal of uninitialized variables; (5)~minor
77 modifications in order to simplify system-dependent modifications.
78 @^range check violations@>
79
80 @ This program is written in standard \PASCAL, except where it is
81 necessary to use extensions. All places where nonstandard constructions
82 are used have been listed in the index under ``system dependencies.''
83 @!@^system dependencies@>
84
85 The program uses \PASCAL's standard |input| and |output| files to read
86 from and write to the user's terminal.
87
88 @d print(#)==write(output,#)
89 @d print_ln(#)==write_ln(output,#)
90 @d get_input(#)==read(input,#)
91 @d get_input_ln(#)==
92 begin if eoln(input) then read_ln(input);
93 read(input,#);
94 end
95 @#
96 @d end_of_PATGEN=9999
97
98 @p @<Compiler directives@>@/
99 program PATGEN(@!dictionary,@!patterns,@!translate,@!patout);
100 label end_of_PATGEN;
101 const @<Constants in the outer block@>@/
102 type @<Types in the outer block@>@/
103 var @<Globals in the outer block@>@/
104 procedure initialize; {this procedure gets things started properly}
105 var @<Local variables for initialization@>@/
106 begin print_ln(banner);@/
107 @<Set initial values@>@/
108 end;
109
110 @ The patterns are generated in a series of sequential passes through the
111 dictionary. In each pass, we collect count statistics for a particular
112 type of pattern, taking into account the effect of patterns chosen in
113 previous passes. At the end of a pass, the counts are examined and new
114 patterns are selected.
115
116 Patterns are chosen one level at a time, in order of increasing
117 hyphenation value. In the sample run shown below, the parameters
118 |hyph_start| and |hyph_finish| specify the first and last levels,
119 respectively, to be generated.
120
121 Patterns at each level are chosen in order of increasing pattern length
122 (usually starting with length~2). This is controlled by the parameters
123 |pat_start| and |pat_finish| specified at the beginning of each level.
124
125 Furthermore patterns of the same length applying to different
126 intercharacter positions are chosen in separate passes through the
127 dictionary. Since patterns of length $n$ may apply to $n+1$ different
128 positions, choosing a set of patterns of lengths $2$ through $n$ for a
129 given level requires $(n+1)(n+2)/2-3$ passes through the word list.
130
131 At each level, the selection of patterns is controlled by the three
132 parameters |good_wt|, |bad_wt|, and |thresh|. A hyphenating pattern will
133 be selected if |good*good_wt-bad*bad_wt>=thresh|, where |good| and
134 |bad| are the number of times the pattern could and could not be
135 hyphenated, respectively, at a particular point. For inhibiting patterns,
136 |good| is the number of errors inhibited, and |bad| is the number of
137 previously found hyphens inhibited.
138
139 @<Globals...@>=
140 @!pat_start, @!pat_finish: dot_type;
141 @!hyph_start, @!hyph_finish: val_type;
142 @!good_wt, @!bad_wt, @!thresh: integer;
143
144 @ The proper choice of the parameters to achieve a desired degree of
145 hyphenation is discussed in Chapter~4. Below we show part of a sample run
146 of \.{PATGEN}, with the user's inputs underlined.
147 $$\vbox{\halign{\.{#\hfil}\cr
148 $\underline{\smash{\.{ex patgen}}}$\cr
149 DICTIONARY : $\underline{\smash{\.{murray.hyf}}}$\cr
150 PATTERNS : $\underline{\smash{\.{nul:}}}$\cr
151 TRANSLATE : $\underline{\smash{\.{nul:}}}$\cr
152 PATOUT : $\underline{\smash{\.{murray.pat}}}$\cr
153 This is PATGEN, Version 2.0\cr
154 left\_hyphen\_min = 2, right\_hyphen\_min = 3, 26 letters\cr
155 0 patterns read in\cr
156 pattern trie has 256 nodes, trie\_max = 256, 0 outputs\cr
157 hyph\_start, hyph\_finish: $\underline{\.{1 1}}$\cr
158 pat\_start, pat\_finish: $\underline{\.{2 3}}$\cr
159 good weight, bad weight, threshold: $\underline{\.{1 3 3}}$\cr
160 processing dictionary with pat\_len = 2, pat\_dot = 1\cr
161 \cr
162 0 good, 0 bad, 3265 missed\cr
163 0.00 \%, 0.00 \%, 100.00 \%\cr
164 338 patterns, 466 nodes in count trie, triec\_max = 983\cr
165 46 good and 152 bad patterns added (more to come)\cr
166 finding 715 good and 62 bad hyphens, efficiency = 10.72\cr
167 pattern trie has 326 nodes, trie\_max = 509, 2 outputs\cr
168 processing dictionary with pat\_len = 2, pat\_dot = 0\cr
169 \cr
170 \hskip 1.5em ...\cr
171 \cr
172 1592 nodes and 39 outputs deleted\cr
173 total of 220 patterns at hyph\_level 1\cr
174 hyphenate word list? $\underline{\smash{\.{y}}}$\cr
175 writing pattmp.1\cr
176 \cr
177 2529 good, 243 bad, 736 missed\cr
178 77.46 \%, 7.44 \%, 22.54 \%\cr}}$$
179
180 @ Note that before beginning a pattern selection run, a file of existing
181 patterns may be read in. In order for pattern selection to work properly,
182 this file should only contain patterns with hyphenation values less than
183 |hyph_start|. Each word in the dictionary is hyphenated according to the
184 existing set of patterns (including those chosen on previous passes of the
185 current run) before pattern statistics are collected.
186
187 Also, a hyphenated word list may be written out at the end of a run. This
188 list can be read back in as the `dictionary' to continue pattern selection
189 from this point. In addition to ordinary hyphens (|'-'|) the new list
190 will contain two additional kinds of ``hyphens'' between letters, namely
191 hyphens that have been found by previously generated patterns, as well
192 as erroneous hyphens that have been inserted by those patterns. These
193 are represented by the symbols |'*'| and |'.'|, respectively. The three
194 characters |'-'|, |'*'|, and |'.'| are, in fact, just the default values
195 used to represent the three kinds of hyphens, the |translate| file may
196 specify different characters to be used instead of them.
197
198 In addition, a word list can include hyphen weights, both for entire words
199 and for individual hyphen positions. (The syntax for this is explained in
200 the dictionary processing routines.) Thus common words can be weighted
201 more heavily, or, more generally, words can be weighted according to their
202 frequency of occurrence, if such information is available. The use of
203 hyphen weights combined with an appropriate setting of the pattern
204 selection threshold can be used to guarantee hyphenation of certain words
205 or certain hyphen positions within a word.
206
207 @ Below we show the first few lines of a typical word list,
208 before and after generating a level of patterns.
209 $$\vbox{\halign{\tabskip 1in\.{#\hfil}&\.{#\hfil}\cr
210 abil-i-ty& abil*i*ty\cr
211 ab-sence& ab*sence\cr
212 ab-stract& ab*stract\cr
213 ac-a-dem-ic& ac-a-d.em-ic\cr
214 ac-cept& ac*cept\cr
215 ac-cept-able& ac*cept-able\cr
216 ac-cept-ed& ac*cept*ed\cr
217 \hskip 1.5em ...&\hskip 1.5em ...\cr
218 }}$$
219
220 @ We augment \PASCAL 's control structures a bit using |goto|\unskip's
221 and the following symbolic labels.
222
223 @d exit=10 {go here to leave a procedure}
224 @d continue=22 {go here to resume a loop}
225 @d done=30 {go here to exit a loop}
226 @d found=40 {go here when you've found it}
227 @d not_found=41 {go here when you've found something else}
228
229 @ Here are some macros for common programming idioms.
230
231 @d incr(#)==#:=#+1 {increase a variable by unity}
232 @d decr(#)==#:=#-1 {decrease a variable by unity}
233 @#
234 @d Incr_Decr_end(#)==#
235 @d Incr(#)==#:=#+Incr_Decr_end {we use |Incr(a)(b)| to increase \dots}
236 @d Decr(#)==#:=#-Incr_Decr_end {\dots\ and |Decr(a)(b)| to decrease
237 variable |a| by |b|; this can be optimized for some compilers}
238 @#
239 @d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
240 @d do_nothing == {empty statement}
241 @d return==goto exit {terminate a procedure call}
242 @f return==nil
243 @f loop == xclause
244
245 @ In case of serious problems \.{PATGEN} will give up, after issuing an
246 error message about what caused the error. Such errors might be
247 discovered inside of subroutines inside of subroutines, so a \.{WEB}
248 macro called |jump_out| has been introduced. This macro, which transfers
249 control to the label |end_of_PATGEN| at the end of the program, contains
250 the only non-local |@!goto| statement in \.{PATGEN}. Some \PASCAL\
251 compilers do not implement non-local |goto| statements. In such cases
252 the |goto end_of_PATGEN| in the definition of |jump_out| should simply
253 be replaced by a call on some system procedure that quietly terminates
254 the program.
255 @^system dependencies@>
256
257 An overflow stop occurs if \.{PATGEN}'s tables aren't large enough.
258
259 @d jump_out==goto end_of_PATGEN {terminates \.{PATGEN}}
260 @#
261 @d error(#)==begin print_ln(#); jump_out; end
262 @d overflow(#)==error('PATGEN capacity exceeded, sorry [',#,'].')
263 @.PATGEN capacity exceeded ...@>
264
265 @ @<Compiler directives@>=
266 @{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
267 @^system dependencies@>
268
269 @* The character set.
270 Since different \PASCAL\ systems may use different character sets, we use
271 the name |text_char| to stand for the data type of characters appearing in
272 external text files. We also assume that |text_char| consists of the
273 elements |chr(first_text_char)| through |chr(last_text_char)|, inclusive.
274 The definitions below should be adjusted if necessary.
275 @^system dependencies@>
276 @^character set dependencies@>
277
278 Internally, characters will be represented using the type |ASCII_code|.
279 Note, however, that only some of the standard ASCII characters are
280 assigned a fixed |ASCII_code|; all other characters are assigned an
281 |ASCII_code| dynamically when they are first read from the |translate|
282 file specifying the external representation of the `letters' used by a
283 particular language. For the sake of generality the standard version of
284 this program allows for 256 different |ASCII_code| values, but 128 of
285 them would probably suffice for all practical purposes.
286
287 @d first_text_char=0 {ordinal number of the smallest element of |text_char|}
288 @d last_text_char=255 {ordinal number of the largest element of |text_char|}
289 @#
290 @d last_ASCII_code=255 {the highest allowed |ASCII_code| value}
291
292 @<Types...@>=
293 @!text_char=char; {the data type of characters in text files}
294 @!ASCII_code=0..last_ASCII_code; {internal representation of input characters}
295 @!text_file=text;
296
297 @ Some \PASCAL s can store only signed eight-bit quantities (|-128..127|)
298 but not unsigned ones (|0..255|) in one byte. If storage is tight we
299 must, for such \PASCAL s, either restrict |ASCII_code| to the range
300 |0..127| (with some loss of generality) or convert between |ASCII_code|
301 and |packed_ASCII_code| and vice versa by subtracting or adding an
302 offset. (Or we might define |packed_ASCII_code| as |char| and use
303 suitable typecasts for the conversion.) Only the type |packed_ASCII_code|
304 will be used for large arrays and the \.{WEB} macros |si| and |so| will
305 always be used to convert an |ASCII_code| into a |packed_ASCII_code| and
306 vice versa.
307 @^system dependencies@>
308
309 @d min_packed=0 {change this to `$\\{min\_packed}=-128$' when necessary;
310 and don't forget to change the definitions of |si| and |so| below
311 accordingly}
312 @#
313 @d si(#)==# {converts |ASCII_code| to |packed_ASCII_code|}
314 @d so(#)==# {converts |packed_ASCII_code| to |ASCII_code|}
315
316 @<Types...@>=
317 @!packed_ASCII_code=min_packed..last_ASCII_code+min_packed;
318
319 @ We want to make sure that the ``constants'' defined in this program
320 satisfy all the required relations. Some of them are needed to avoid
321 time-consuming checks while processing the dictionary and\slash or to
322 prevent range check and array bound violations.
323 @^range check violations@>
324
325 Here we check that the definitions of |ASCII_code| and
326 |packed_ASCII_code| are consistent with those of |si| and |so|.
327
328 @<Set init...@>=
329 bad:=0;@/
330 if last_ASCII_code<127 then bad:=1;
331 if (si(0)<>min_packed)or(so(min_packed)<>0) then bad:=2;@/
332 @<Check the ``constant'' values for consistency@>@;
333 if bad>0 then error('Bad constants---case ',bad:1);
334 @.Bad constants@>
335
336 @ @<Local variables for init...@>=
337 @!bad:integer;
338 @!i:text_char;
339 @!j:ASCII_code;
340
341 @ We convert between |ASCII_code| and the user's external character set by
342 means of arrays |xord| and |xchr| that are analogous to \PASCAL's |ord|
343 and |chr| functions.
344
345 @<Globals...@>=
346 @!xord: array [text_char] of ASCII_code;
347 {specifies conversion of input characters}
348 @!xchr: array [ASCII_code] of text_char;
349 {specifies conversion of output characters}
350
351 @ The following code initializes the |xchr| array with some of the
352 standard ASCII characters.
353
354 @<Set init...@>=
355 for j:=0 to last_ASCII_code do xchr[j]:=' ';
356 xchr["."]:='.';@/
357 xchr["0"]:='0'; xchr["1"]:='1'; xchr["2"]:='2'; xchr["3"]:='3';
358 xchr["4"]:='4'; xchr["5"]:='5'; xchr["6"]:='6'; xchr["7"]:='7';
359 xchr["8"]:='8'; xchr["9"]:='9';@/
360 xchr["A"]:='A'; xchr["B"]:='B'; xchr["C"]:='C'; xchr["D"]:='D';
361 xchr["E"]:='E'; xchr["F"]:='F'; xchr["G"]:='G'; xchr["H"]:='H';
362 xchr["I"]:='I'; xchr["J"]:='J'; xchr["K"]:='K'; xchr["L"]:='L';
363 xchr["M"]:='M'; xchr["N"]:='N'; xchr["O"]:='O'; xchr["P"]:='P';
364 xchr["Q"]:='Q'; xchr["R"]:='R'; xchr["S"]:='S'; xchr["T"]:='T';
365 xchr["U"]:='U'; xchr["V"]:='V'; xchr["W"]:='W'; xchr["X"]:='X';
366 xchr["Y"]:='Y'; xchr["Z"]:='Z';@/
367 xchr["a"]:='a'; xchr["b"]:='b'; xchr["c"]:='c'; xchr["d"]:='d';
368 xchr["e"]:='e'; xchr["f"]:='f'; xchr["g"]:='g'; xchr["h"]:='h';
369 xchr["i"]:='i'; xchr["j"]:='j'; xchr["k"]:='k'; xchr["l"]:='l';
370 xchr["m"]:='m'; xchr["n"]:='n'; xchr["o"]:='o'; xchr["p"]:='p';
371 xchr["q"]:='q'; xchr["r"]:='r'; xchr["s"]:='s'; xchr["t"]:='t';
372 xchr["u"]:='u'; xchr["v"]:='v'; xchr["w"]:='w'; xchr["x"]:='x';
373 xchr["y"]:='y'; xchr["z"]:='z';
374
375 @ The following system-independent code makes the |xord| array contain a
376 suitable inverse to the information in |xchr|.
377
378 @d invalid_code=0 {|ASCII_code| that should not appear}
379 @d tab_char=@'11 {|ord| of tab character; tab characters seem to be
380 unavoidable with files from UNIX systems}
381 @^system dependencies@>
382 @^character set dependencies@>
383
384 @<Set init...@>=
385 for i:=chr(first_text_char) to chr(last_text_char) do
386 xord[i]:=invalid_code;
387 for j:=0 to last_ASCII_code do xord[xchr[j]]:=j;
388 xord[' ']:=" "; xord[chr(tab_char)]:=" ";
389
390 @ So far each invalid |ASCII_code| has been assigned the character |' '|
391 and all invalid characters have been assigned |ASCII_code=invalid_code|.
392 The |get_ASCII| function, used only while reading the |translate| file,
393 returns the |ASCII_code| corresponding to a character, assigning a new
394 |ASCII_code| first if necessary.
395
396 @d num_ASCII_codes=last_ASCII_code+1 {number of different |ASCII_code| values}
397
398 @p function get_ASCII(@!c:text_char):ASCII_code;
399 label found;
400 var i: ASCII_code;
401 begin i:=xord[c];
402 if i=invalid_code then
403 begin while i<last_ASCII_code do
404 begin incr(i);
405 if (xchr[i]=' ')and(i<>" ") then goto found;
406 end;
407 overflow(num_ASCII_codes:1,' characters');
408 found: xord[c]:=i; xchr[i]:=c;
409 end;
410 get_ASCII:=i;
411 end;
412
413 @ The \TeX 82 hyphenation algorithm operates on `hyphenable words'
414 converted temporarily to lower case, i.e., they may consist of up to
415 255 different `letters' corresponding to \.{\\lccode}s |1..255|. These
416 \.{\\lccode}s could, in principle, be language dependent but this might
417 lead to undesirable results when hyphenating multilingual paragraphs.
418 No more than 245 different letters can occur in hyphenation patterns
419 since the characters |'0'..'9'| and |'.'| play a special r\^^Dole when
420 reading patterns. For the purpose of this program each letter is
421 represented internally by a unique |internal_code>=2| (|internal_code=1|
422 is the |edge_of_word| indicator); |internal_code| values |2..127| will
423 probably suffice for all practical purposes, but we allow the range
424 |2..last_ASCII_code| for the sake of generality. Syntactically
425 |internal_code| and |ASCII_code| are the same, we will use one or the
426 other name according to the semantic context.
427
428 @d edge_of_word=1 {|internal_code| for start and end of a word}
429
430 @<Types...@>=
431 @!internal_code=ASCII_code;
432 @!packed_internal_code=packed_ASCII_code;
433
434 @ Note that an |internal_code| used by this program is in general quite
435 different from the |ASCII_code| (or rather \.{\\lccode}) used by \TeX
436 82. This program allows the input of characters (from the |dictionary|
437 and |patterns| file) corresponding to an |internal_code| in either lower
438 or upper case form; the output (to the |patout| and |pattmp| file) will
439 always be in lower case form.
440
441 Unfortunately there does not (yet?) exist a standardized and widely
442 accepted 8-bit character set (or a unique one-to-one translation between
443 such sets). On the other hand macro expansion takes place in \TeX 82
444 when reading hyphenable words and when reading patterns. Thus the lower
445 and upper case versions of all `letters' used by a particular language
446 can (and for the sake of portability should) be represented entirely in
447 terms of the standard ASCII character set; either directly as characters
448 or via macros (or active characters) with or without arguments. The
449 macro definitions for such a representation will in general be language
450 dependent.
451
452 For the purpose of this program the external representation of the lower
453 and upper case version of a letter (i.e., |internal_code|) consists of a
454 unique sequence of characters (or \\{ASCII\_codes}), the only restriction
455 being that no such sequence must be a subsequence of an other one.
456 Moreover such sequences must not start with |' '|, |'.'|, |'0'..'9'| or
457 with one of the three characters (|'-'|, |'*'|, and |'.'|) representing
458 hyphens in the |dictionary| file; a sequence may, however, end with a
459 mandatory |' '| as, e.g., the sequence |'\ss '|.
460
461 The language dependent values of \.{\\lefthyphenmin} and
462 \.{\\righthyphenmin} as well as the external representation of the lower
463 and upper case letters and their collating sequence are specified in the
464 |translate| file, thus making any language dependent modifications of
465 this program unnecessary. If the |translate| file is empty (or does not
466 exist) the values \.{\\lefthyphenmin=2} and \.{\\righthyphenmin=3} and
467 |internal_code| values |2..27| with the one character external
468 representations |'a'..'z'| and |'A'..'Z'| will be used as defaults.
469
470 Incidentally this program can be used to convert a |dictionary| and
471 |patterns| file from one (``upper case'') to another (``lower case'')
472 external representation of letters.
473
474 @ When reading the |dictionary| (and |patterns|) file sequences of
475 characters must be recognized and converted to their corresponding
476 |internal_code|. This conversion is part of \.{PATGEN}s inner loop and
477 @^inner loop@>
478 must therefore be done as efficient as possible. Thus we will
479 mostly bypass the conversion from character to |ASCII_code| and convert
480 directly to the corresponding |internal_code| using the |xclass|
481 and |xint| arrays. Six types of characters are distinguished by their
482 |xclass|:
483
484 \yskip\hang |space_class| character |' '| terminates a pattern or word.
485
486 \yskip\hang |digit_class| characters |'0'..'9'| are hyphen values for a
487 pattern or hyphen weights for a word; their |xint| is the corresponding
488 numeric value |0..9|.
489
490 \yskip\hang |hyf_class| characters (|'.'|, |'-'|, and |'*'|) are `dots'
491 and indicate hyphens in a word; their |xint| is the corresponding
492 numeric value |err_hyf..found_hyf|.
493
494 \yskip\hang |letter_class| characters represent a letter; their |xint|
495 is the corresponding |internal_code|.
496
497 \yskip\hang |escape_class| characters indicate the start of a
498 multi-character sequence representing a letter.
499
500 \yskip\hang |invalid_class| characters should not occur except as part
501 of multi-character sequences.
502
503 @d space_class=0 {the character |' '|}
504 @d digit_class=1 {the characters |'0'..'9'|}
505 @d hyf_class=2 {the `hyphen' characters (|'.'|, |'-'|, and |'*'|)}
506 @d letter_class=3 {characters representing a letter}
507 @d escape_class=4 {characters that start a multi-character sequence
508 representing a letter}
509 @d invalid_class=5 {characters that normally should not occur}
510 @#
511 @d no_hyf=0 {no hyphen}
512 @d err_hyf=1 {erroneous hyphen}
513 @d is_hyf=2 {hyphen}
514 @d found_hyf=3 {found hyphen}
515
516 @<Types...@>=
517 @!class_type=space_class..invalid_class; {class of a character}
518 @!digit=0..9; {a hyphen weight (or word weight)}
519 @!hyf_type=no_hyf..found_hyf; {type of a hyphen}
520
521 @ In addition we will use the |xext|, |xdig|, and |xdot| arrays to
522 convert from the internal representation to the corresponding
523 characters.
524
525 @<Globals...@>=
526 @!xclass: array [text_char] of class_type;
527 {specifies the class of a character}
528 @!xint: array [text_char] of internal_code;
529 {specifies the |internal_code| for a character}
530 @!xdig: array [0..9] of text_char;
531 {specifies conversion of output characters}
532 @!xext: array [internal_code] of text_char;
533 {specifies conversion of output characters}
534 @!xhyf: array [err_hyf..found_hyf] of text_char;
535 {specifies conversion of output characters}
536
537 @ @<Set init...@>=
538 for i:=chr(first_text_char) to chr(last_text_char) do
539 begin xclass[i]:=invalid_class; xint[i]:=0;
540 end;
541 xclass[' ']:=space_class;
542 for j:=0 to last_ASCII_code do xext[j]:=' ';
543 xext[edge_of_word]:='.';
544 for j:=0 to 9 do
545 begin xdig[j]:=xchr[j+"0"];
546 xclass[xdig[j]]:=digit_class; xint[xdig[j]]:=j;
547 end;
548 xhyf[err_hyf]:='.'; xhyf[is_hyf]:='-'; xhyf[found_hyf]:='*';
549 {default representation for hyphens}
550
551 @ We assume that words use only the letters |cmin+1| through |cmax|.
552 This allows us to save some time on trie operations that involve
553 searching for packed transitions belonging to a particular state.
554
555 @d cmin=edge_of_word
556
557 @<Globals...@>=
558 @!cmax: internal_code; {largest |internal_code| or |ASCII_code|}
559
560 @* Data structures.
561 The main data structure used in this program is a dynamic packed trie.
562 In fact we use two of them, one for the set of patterns selected so far,
563 and one for the patterns being considered in the current pass.
564
565 For a pattern $p_1\ldots p_k$, the information associated with that
566 pattern is accessed by setting |@t$t_1$@>:=trie_root+@t$p_1$@>| and
567 then, for |1<i<=k|, setting |@t$t_i$@>:=trie_link(@t$t_{i-1}$@>)+
568 @t$p_i$@>|; the pattern information is then stored in a location addressed
569 by |@t$t_k$@>|. Since all trie nodes are packed into a single array, in
570 order to distinguish nodes belonging to different trie families, a special
571 field is provided such that |trie_char@t$(t_i)=si(p_i)$@>| for all |i|.
572
573 In addition the trie must support dynamic insertions and deletions. This
574 is done by maintaining a doubly linked list of unoccupied cells and
575 repacking trie families as necessary when insertions are made.
576
577 Each trie node consists of three fields: the character |trie_char|, and
578 the two link fields |trie_link| and |trie_back|. In addition there is a
579 separate boolean array |trie_base_used|. When a node is unoccupied,
580 |trie_char=min_packed| and the link fields point to the next and previous
581 unoccupied nodes, respectively, in the doubly linked list. When a node is
582 occupied, |trie_link| points to the next trie family, and |trie_back|
583 (renamed |trie_outp|) contains the output associated with this transition.
584 The |trie_base_used| bit indicates that some family has been packed at
585 this base location, and is used to prevent two families from being packed
586 at the same location.
587
588 @ The sizes of the pattern tries may have to be adjusted depending
589 on the particular application (i.e., the parameter settings and the
590 size of the dictionary). The sizes below were sufficient to generate
591 the original set of English \TeX 82 hyphenation patterns (file
592 \.{hyphen.tex}).
593
594 @<Constants...@>=
595 @!trie_size=55000; {space for pattern trie}
596 @!triec_size=26000; {space for pattern count trie, must be less than
597 |trie_size| and greater than the number of occurrences of any pattern in
598 the dictionary}
599 @!max_ops=4080; {size of output hash table, should be a multiple of 510}
600 @!max_val=10; {maximum number of levels$+1$, also used to denote bad patterns}
601 @!max_dot=15; {maximum pattern length, also maximum length of external
602 representation of a `letter'}
603 @!max_len=50; {maximum word length}
604 @!max_buf_len=80; {maximum length of input lines, must be at least |max_len|}
605
606 @ @<Check the ``constant'' values for consistency@>=
607 if (triec_size<4096)or(trie_size<triec_size) then bad:=3;
608 if max_ops>trie_size then bad:=4;
609 if max_val>10 then bad:=5;
610 if max_buf_len<max_len then bad:=6;
611
612 @ @<Types...@>=
613 @!q_index=1..last_ASCII_code; {number of transitions in a state}
614 @!val_type=0..max_val; {hyphenation values}
615 @!dot_type=0..max_dot; {dot positions}
616 @!op_type=0..max_ops; {index into output hash table}
617 @!word_index=0..max_len; {index into |word|}
618 @!trie_pointer=0..trie_size;
619 @!triec_pointer=0..triec_size;@/
620 @!op_word=packed record dot: dot_type; val: val_type; op: op_type end;
621
622 @ Trie is actually stored with its components in separate packed arrays,
623 in order to save space and time (although this depends on the computer's
624 word size and the size of the trie pointers).
625
626 @<Globals...@>=
627 @!trie_c: packed array[trie_pointer] of packed_internal_code;
628 @!trie_l, @!trie_r: packed array[trie_pointer] of trie_pointer;
629 @!trie_taken: packed array[trie_pointer] of boolean;
630 @!triec_c: packed array[triec_pointer] of packed_internal_code;
631 @!triec_l, @!triec_r: packed array[triec_pointer] of triec_pointer;
632 @!triec_taken: packed array[triec_pointer] of boolean;
633 @!ops: array[op_type] of op_word; {output hash table}
634
635 @ When some trie state is being worked on, an unpacked version of the
636 state is kept in positions |1..qmax| of the global arrays |trieq_c|,
637 |trieq_l|, and |trieq_r|. The character fields need not be in any
638 particular order.
639
640 @<Globals...@>=
641 @!trieq_c: array[q_index] of internal_code; {character fields of a
642 single trie state}
643 @!trieq_l, @!trieq_r: array[q_index] of trie_pointer; {link fields}
644 @!qmax: q_index; {number of transitions in an unpacked state}
645 @!qmax_thresh: q_index; {controls density of first-fit packing}
646
647 @ Trie fields are accessed using the following macros.
648
649 @d trie_char(#)==trie_c[#]
650 @d trie_link(#)==trie_l[#]
651 @d trie_back(#)==trie_r[#]
652 @d trie_outp(#)==trie_r[#]
653 @d trie_base_used(#)==trie_taken[#]
654 @#
655 @d triec_char(#)==triec_c[#]
656 @d triec_link(#)==triec_l[#]
657 @d triec_back(#)==triec_r[#]
658 @d triec_good(#)==triec_l[#]
659 @d triec_bad(#)==triec_r[#]
660 @d triec_base_used(#)==triec_taken[#]
661 @#
662 @d q_char(#)==trieq_c[#]
663 @d q_link(#)==trieq_l[#]
664 @d q_back(#)==trieq_r[#]
665 @d q_outp(#)==trieq_r[#]
666 @#
667 @d hyf_val(#)==ops[#].val
668 @d hyf_dot(#)==ops[#].dot
669 @d hyf_nxt(#)==ops[#].op
670
671 @* Routines for pattern trie.
672 The pattern trie holds the set of patterns chosen prior to the current
673 pass, including bad or ``hopeless'' patterns at the current level that
674 occur too few times in the dictionary to be of use. Each transition of
675 the trie includes an output field pointing to the hyphenation information
676 associated with this transition.
677
678 @<Globals...@>=
679 @!trie_max: trie_pointer; {maximum occupied trie node}
680 @!trie_bmax: trie_pointer; {maximum base of trie family}
681 @!trie_count: trie_pointer; {number of occupied trie nodes, for space usage
682 statistics}
683 @!op_count: op_type; {number of outputs in hash table}
684
685 @ Initially, the dynamic packed trie has just one state, namely the root,
686 with all transitions present (but with null links). This is convenient
687 because the root will never need to be repacked and also we won't have to
688 check that the base is nonnegative when packing other states.
689 Moreover in many cases we need not check for a vanishing link field:
690 if |trie_link(t)=0| then a subsequent test for
691 |trie_char(trie_link(t)+c)=si(c)| will always fail due to |trie_root=1|.
692
693 @d trie_root=1
694
695 @p procedure init_pattern_trie;
696 var c: internal_code; @!h: op_type;
697 begin for c:=0 to last_ASCII_code do
698 begin trie_char(trie_root+c):=si(c); {indicates node occupied;
699 fake for |c=0|}
700 trie_link(trie_root+c):=0;
701 trie_outp(trie_root+c):=0;
702 trie_base_used(trie_root+c):=false;
703 end;
704 trie_base_used(trie_root):=true;
705 trie_bmax:=trie_root;
706 trie_max:=trie_root+last_ASCII_code;
707 trie_count:=num_ASCII_codes;@/
708 qmax_thresh:=5;@/
709 trie_link(0):=trie_max+1;
710 trie_back(trie_max+1):=0;@/
711 {|trie_link(0)| is used as the head of the doubly linked list of
712 unoccupied cells}
713 for h:=1 to max_ops do hyf_val(h):=0; {clear output hash table}
714 op_count:=0;
715 end;
716
717 @ The |first_fit| procedure finds a hole in the packed trie into which the
718 state in |trieq_c|, |trieq_l|, and |trieq_r| will fit. This is normally
719 done by going through the linked list of unoccupied cells and testing if
720 the state will fit at each position. However if a state has too many
721 transitions (and is therefore unlikely to fit among existing
722 transitions) we don't bother and instead just pack it immediately to the
723 right of the occupied region (starting at |trie_max+1|).
724
725 @p function first_fit: trie_pointer;
726 label found, not_found;
727 var s, @!t: trie_pointer; @!q: q_index;
728 begin @<Set \(|s| to the trie base location at which this state should be
729 packed@>;
730 for q:=1 to qmax do {pack it}
731 begin t:=s+q_char(q);@/
732 trie_link(trie_back(t)):=trie_link(t);
733 trie_back(trie_link(t)):=trie_back(t); {link around
734 filled cell}
735 trie_char(t):=si(q_char(q));
736 trie_link(t):=q_link(q);
737 trie_outp(t):=q_outp(q);
738 if t>trie_max then trie_max:=t;
739 end;
740 trie_base_used(s):=true;
741 first_fit:=s
742 end;
743
744 @ The threshold for large states is initially 5 transitions. If more than
745 one level of patterns is being generated, the threshold is set to 7 on
746 subsequent levels because the pattern trie will be sparser after bad
747 patterns are deleted (see |delete_bad_patterns|).
748
749 @<Set \(|s| to the trie base location at which this state should be packed@>=
750 if qmax>qmax_thresh then t:=trie_back(trie_max+1) @+else t:=0;
751 loop begin t:=trie_link(t); s:=t-q_char(1); {get next unoccupied cell}
752 @<Ensure |trie| linked up to |s+num_ASCII_codes|@>;
753 if trie_base_used(s) then goto not_found;
754 for q:=qmax downto 2 do {check if state fits here}
755 if trie_char(s+q_char(q))<>min_packed then goto not_found;
756 goto found;
757 not_found: end;
758 found:
759
760 @ The trie is only initialized (as a doubly linked list of empty cells) as
761 far as necessary. Here we extend the initialization if necessary, and
762 check for overflow.
763
764 @<Ensure |trie| linked up to |s+num_ASCII_codes|@>=
765 if s>trie_size-num_ASCII_codes then
766 overflow(trie_size:1,' pattern trie nodes');
767 while trie_bmax<s do
768 begin incr(trie_bmax);
769 trie_base_used(trie_bmax):=false;
770 trie_char(trie_bmax+last_ASCII_code):=min_packed;
771 trie_link(trie_bmax+last_ASCII_code):=trie_bmax+num_ASCII_codes;
772 trie_back(trie_bmax+num_ASCII_codes):=trie_bmax+last_ASCII_code;
773 end
774
775 @ The |unpack| procedure finds all transitions associated with the state
776 with base |s|, puts them into the arrays |trieq_c|, |trieq_l|, and
777 |trieq_r|, and sets |qmax| to one more than the number of transitions
778 found. Freed cells are put at the beginning of the free list.
779
780 @p procedure unpack(@!s: trie_pointer);
781 var c: internal_code; @!t: trie_pointer;
782 begin qmax:=1;
783 for c:=cmin to cmax do {search for transitions belonging to this state}
784 begin t:=s+c;
785 if so(trie_char(t))=c then {found one}
786 begin q_char(qmax):=c;
787 q_link(qmax):=trie_link(t);
788 q_outp(qmax):=trie_outp(t);
789 incr(qmax);@/
790 {now free trie node}
791 trie_back(trie_link(0)):=t;
792 trie_link(t):=trie_link(0);
793 trie_link(0):=t;
794 trie_back(t):=0;
795 trie_char(t):=min_packed;
796 end;
797 end;
798 trie_base_used(s):=false;
799 end;
800
801 @ The function |new_trie_op| returns the `opcode' for the output
802 consisting of hyphenation value~|v|, hyphen position |d|, and next output
803 |n|. The hash function used by |new_trie_op| is based on the idea that
804 313/510 is an approximation to the golden ratio [cf.\ {\sl The Art of
805 Computer Programming \bf3} (1973), 510--512]; but the choice is
806 comparatively unimportant in this particular application.
807
808 @p function new_trie_op(@!v: val_type; @!d: dot_type; @!n: op_type): op_type;
809 label exit;
810 var h: op_type;
811 begin h:=((n+313*d+361*v) mod max_ops)+1; {trial hash location}
812 loop begin if hyf_val(h)=0 then {empty position found}
813 begin incr(op_count);
814 if op_count=max_ops then overflow(max_ops:1,' outputs');
815 hyf_val(h):=v; hyf_dot(h):=d; hyf_nxt(h):=n; new_trie_op:=h; return;
816 end;
817 if (hyf_val(h)=v) and (hyf_dot(h)=d) and
818 (hyf_nxt(h)=n) then {already in hash table}
819 begin new_trie_op:=h; return;
820 end;
821 if h>1 then decr(h) @+else h:=max_ops; {try again}
822 end;
823 exit: end;
824
825 @ @<Globals...@>=
826 @!pat: array[dot_type] of internal_code; {current pattern}
827 @!pat_len: dot_type; {pattern length}
828
829 @ Now that we have provided the necessary routines for manipulating the
830 dynamic packed trie, here is a procedure that inserts a pattern of length
831 |pat_len|, stored in the |pat| array, into the pattern trie. It also adds
832 a new output.
833
834 @p procedure insert_pattern(@!val: val_type; @!dot: dot_type);
835 var i: dot_type; @!s, @!t: trie_pointer;
836 begin i:=1;
837 s:=trie_root+pat[i]; t:=trie_link(s);
838 while (t>0) and (i<pat_len) do {follow existing trie}
839 begin incr(i); Incr(t)(pat[i]);
840 if so(trie_char(t))<>pat[i] then
841 @<Insert critical transition, possibly repacking@>;
842 s:=t; t:=trie_link(s);
843 end;
844 q_link(1):=0; q_outp(1):=0; qmax:=1;
845 while i<pat_len do {insert rest of pattern}
846 begin incr(i); q_char(1):=pat[i];
847 t:=first_fit;
848 trie_link(s):=t;
849 s:=t+pat[i];
850 incr(trie_count);
851 end;
852 trie_outp(s):=new_trie_op(val,dot,trie_outp(s));
853 end;
854
855 @ We have accessed a transition not in the trie. We insert it, repacking
856 the state if necessary.
857
858 @<Insert critical transition, possibly repacking@>=
859 begin if trie_char(t)=min_packed then
860 begin {we're lucky, no repacking needed}
861 trie_link(trie_back(t)):=trie_link(t);
862 trie_back(trie_link(t)):=trie_back(t);@/
863 trie_char(t):=si(pat[i]);
864 trie_link(t):=0;
865 trie_outp(t):=0;
866 if t>trie_max then trie_max:=t;
867 end
868 else begin {whoops, have to repack}
869 unpack(t-pat[i]);@/
870 q_char(qmax):=pat[i];
871 q_link(qmax):=0;
872 q_outp(qmax):=0;@/
873 t:=first_fit;
874 trie_link(s):=t;
875 Incr(t)(pat[i]);
876 end;
877 incr(trie_count);
878 end
879
880 @* Routines for pattern count trie.
881 The pattern count trie is used to store the set of patterns considered in
882 the current pass, along with the counts of good and bad instances. The
883 fields of this trie are the same as the pattern trie, except that there is
884 no output field, and leaf nodes are also used to store counts
885 (|triec_good| and |triec_bad|). Except where noted, the following
886 routines are analogous to the pattern trie routines.
887
888 @<Globals...@>=
889 @!triec_max, @!triec_bmax, @!triec_count: triec_pointer; {same as for pattern
890 trie}
891 @!triec_kmax: triec_pointer; {shows growth of trie during pass}
892 @!pat_count: integer; {number of patterns in count trie}
893
894 @ [See |init_pattern_trie|.] The variable |triec_kmax| always contains
895 the size of the count trie rounded up to the next multiple of 4096, and is
896 used to show the growth of the trie during each pass.
897
898 @d triec_root=1
899
900 @p procedure init_count_trie;
901 var c: internal_code;
902 begin for c:=0 to last_ASCII_code do
903 begin triec_char(triec_root+c):=si(c);@/
904 triec_link(triec_root+c):=0;
905 triec_back(triec_root+c):=0;
906 triec_base_used(triec_root+c):=false;
907 end;
908 triec_base_used(triec_root):=true;
909 triec_bmax:=triec_root; triec_max:=triec_root+last_ASCII_code;
910 triec_count:=num_ASCII_codes; triec_kmax:=4096;@/
911 triec_link(0):=triec_max+1; triec_back(triec_max+1):=0;@/
912 pat_count:=0;
913 end;
914
915 @ [See |first_fit|.]
916
917 @p function firstc_fit: triec_pointer;
918 label found, not_found;
919 var a, @!b: triec_pointer; @!q: q_index;
920 begin @<Set \(|b| to the count trie base location at which this state should
921 be packed@>;
922 for q:=1 to qmax do {pack it}
923 begin a:=b+q_char(q);@/
924 triec_link(triec_back(a)):=triec_link(a);
925 triec_back(triec_link(a)):=triec_back(a);@/
926 triec_char(a):=si(q_char(q));
927 triec_link(a):=q_link(q);
928 triec_back(a):=q_back(q);
929 if a>triec_max then triec_max:=a;
930 end;
931 triec_base_used(b):=true;
932 firstc_fit:=b
933 end;
934
935 @ The threshold for attempting a first-fit packing is 3 transitions, which
936 is lower than for the pattern trie because speed is more important here.
937
938 @<Set \(|b| to the count trie base location...@>=
939 if qmax>3 then a:=triec_back(triec_max+1) @+else a:=0;
940 loop begin a:=triec_link(a); b:=a-q_char(1);@/
941 @<Ensure |triec| linked up to |b+num_ASCII_codes|@>;
942 if triec_base_used(b) then goto not_found;
943 for q:=qmax downto 2 do
944 if triec_char(b+q_char(q))<>min_packed then goto not_found;
945 goto found;
946 not_found: end;
947 found:
948
949 @ @<Ensure |triec| linked up to |b+num_ASCII_codes|@>=
950 if b>triec_kmax-num_ASCII_codes then
951 begin if triec_kmax=triec_size then
952 overflow(triec_size:1,' count trie nodes');
953 print(triec_kmax div 1024:1, 'K ');
954 if triec_kmax>triec_size-4096 then triec_kmax:=triec_size
955 else Incr(triec_kmax)(4096);
956 end;
957 while triec_bmax<b do
958 begin incr(triec_bmax);
959 triec_base_used(triec_bmax):=false;
960 triec_char(triec_bmax+last_ASCII_code):=min_packed;
961 triec_link(triec_bmax+last_ASCII_code):=triec_bmax+num_ASCII_codes;
962 triec_back(triec_bmax+num_ASCII_codes):=triec_bmax+last_ASCII_code;
963 end
964
965 @ [See |unpack|.]
966
967 @p procedure unpackc(@!b: triec_pointer);
968 var c: internal_code; @!a: triec_pointer;
969 begin qmax:=1;
970 for c:=cmin to cmax do {search for transitions belonging to this state}
971 begin a:=b+c;
972 if so(triec_char(a))=c then {found one}
973 begin q_char(qmax):=c;
974 q_link(qmax):=triec_link(a);
975 q_back(qmax):=triec_back(a);
976 incr(qmax);@/
977 triec_back(triec_link(0)):=a;
978 triec_link(a):=triec_link(0);
979 triec_link(0):=a; triec_back(a):=0;
980 triec_char(a):=min_packed;
981 end;
982 end;
983 triec_base_used(b):=false;
984 end;
985
986 @ [See |insert_pattern|.] Patterns being inserted into the count trie are
987 always substrings of the current word, so they are contained in the array
988 |word| with length |pat_len| and finishing position |fpos|.
989
990 @p function insertc_pat(@!fpos: word_index): triec_pointer;
991 var spos: word_index; @!a, @!b: triec_pointer;
992 begin spos:=fpos-pat_len; {starting position of pattern}
993 incr(spos); b:=triec_root+word[spos]; a:=triec_link(b);
994 while (a>0) and (spos<fpos) do {follow existing trie}
995 begin incr(spos); Incr(a)(word[spos]);
996 if so(triec_char(a))<>word[spos] then
997 @<Insert critical count transition, possibly repacking@>;
998 b:=a; a:=triec_link(a);
999 end;
1000 q_link(1):=0; q_back(1):=0; qmax:=1;
1001 while spos<fpos do {insert rest of pattern}
1002 begin incr(spos); q_char(1):=word[spos];
1003 a:=firstc_fit;
1004 triec_link(b):=a;
1005 b:=a+word[spos];
1006 incr(triec_count);
1007 end;
1008 insertc_pat:=b;
1009 incr(pat_count);
1010 end;
1011
1012 @ @<Insert critical count transition, possibly repacking@>=
1013 begin if triec_char(a)=min_packed then {lucky}
1014 begin triec_link(triec_back(a)):=triec_link(a);
1015 triec_back(triec_link(a)):=triec_back(a);
1016 triec_char(a):=si(word[spos]);
1017 triec_link(a):=0;
1018 triec_back(a):=0;
1019 if a>triec_max then triec_max:=a;
1020 end
1021 else begin {have to repack}
1022 unpackc(a-word[spos]);@/
1023 q_char(qmax):=word[spos];
1024 q_link(qmax):=0;
1025 q_back(qmax):=0;
1026 a:=firstc_fit;
1027 triec_link(b):=a;
1028 Incr(a)(word[spos]);
1029 end;
1030 incr(triec_count);
1031 end
1032
1033 @* Input and output.
1034 For some \PASCAL\ systems output files must be closed before the program
1035 terminates; it may also be necessary to close input files. Since
1036 standard \PASCAL\ does not provide for this, we use \.{WEB} macros and
1037 will say |close_out(f)| resp.\ |close_in(f)|; these macros should not
1038 produce errors or system messages, even if a file could not be opened
1039 successfully.
1040 @^system dependencies@>
1041
1042 @d close_out(#)==close(#) {close an output file}
1043 @d close_in(#)==do_nothing {close an input file}
1044
1045 @<Globals...@>=
1046 @!dictionary, @!patterns, @!translate, @!patout, @!pattmp: text_file;
1047
1048 @ When reading a line from one of the input files (|dictionary|,
1049 |patterns|, or |translate|) the characters read from that line (padded
1050 with blanks if necessary) are to be placed into the |buf| array. Reading
1051 lines from the |dictionary| file should be as efficient as possible
1052 since this is part of \.{PATGEN}'s ``inner loop''. Standard \PASCAL,
1053 unfortunately, does not provide for this; consequently the \.{WEB} macro
1054 |read_buf| defined below should be optimized if possible. For many
1055 \PASCAL's this can be done with |read_ln(f,buf)| where |buf| is declared
1056 as \PASCAL\ string (i.e., as \&{packed} \&{array} |[1..any]| \&{of}
1057 |char|), for others a string type with dynamic length can be used.
1058 @^inner loop@>@^system dependencies@>
1059
1060 @d read_buf(#)== {reads a line from input file |#| into |buf| array}
1061 begin buf_ptr:=0;
1062 while not eoln(#) do
1063 begin if (buf_ptr>=max_buf_len) then bad_input('Line too long');
1064 @.Line too long@>
1065 incr(buf_ptr); read(#,buf[buf_ptr]);
1066 end;
1067 read_ln(#);
1068 while buf_ptr<max_buf_len do
1069 begin incr(buf_ptr); buf[buf_ptr]:=' ';
1070 end;
1071 end
1072
1073 @<Globals...@>=
1074 @!buf: array[1..max_buf_len] of text_char; {array to hold lines of input}
1075 @!buf_ptr: 0..max_buf_len; {index into |buf|}
1076
1077 @ When an error is caused by bad input data we say |bad_input(#)| in
1078 order to display the contents of the |buf| array before terminating with
1079 an error message.
1080
1081 @d print_buf== {print contents of |buf| array}
1082 begin buf_ptr:=0;
1083 repeat incr(buf_ptr); print(buf[buf_ptr]);
1084 until buf_ptr=max_buf_len;
1085 print_ln(' ');
1086 end
1087 @d bad_input(#)==begin print_buf; error(#); end
1088
1089 @ The |translate| file may specify the values of \.{\\lefthyphenmin} and
1090 \.{\\righthyphenmin} as well as the external representation and
1091 collating sequence of the `letters' used by the language. In addition
1092 replacements may be specified for the characters |'-'|, |'*'|, and |'.'|
1093 representing hyphens in the word list. If the |translate| file is empty
1094 (or does not exist) default values will be used.
1095
1096 @p procedure read_translate;
1097 label done;
1098 var c: text_char;
1099 @!n: integer;
1100 @!j: ASCII_code;
1101 @!bad: boolean;
1102 @!lower: boolean;
1103 @!i: dot_type; @!s, @!t: trie_pointer;
1104 begin imax:=edge_of_word;
1105 reset(translate);
1106 if eof(translate) then
1107 @<Set up default character translation tables@>
1108 else begin read_buf(translate); @<Set up hyphenation data@>;
1109 cmax:=last_ASCII_code-1;
1110 while not eof(translate) do @<Set up representation(s) for a letter@>;
1111 end;
1112 close_in(translate);
1113 print_ln('left_hyphen_min = ',left_hyphen_min:1,
1114 ', right_hyphen_min = ',right_hyphen_min:1,
1115 ', ',imax-edge_of_word:1,' letters');
1116 cmax:=imax;
1117 end;
1118
1119 @ @<Globals...@>=
1120 @!imax: internal_code; {largest |internal_code| assigned so far}
1121 @!left_hyphen_min, @!right_hyphen_min: dot_type;
1122
1123 @ @<Set up default...@>=
1124 begin left_hyphen_min:=2; right_hyphen_min:=3;
1125 for j:="A" to "Z" do
1126 begin incr(imax);
1127 c:=xchr[j+"a"-"A"]; xclass[c]:=letter_class; xint[c]:=imax;
1128 xext[imax]:=c;
1129 c:=xchr[j]; xclass[c]:=letter_class; xint[c]:=imax;
1130 end;
1131 end
1132
1133 @ The first line of the |translate| file must contain the values
1134 of \.{\\lefthyphenmin} and \.{\\righthyphenmin} in columns 1--2 and
1135 3--4. In addition columns~5, 6, and~7 may (optionally) contain
1136 replacements for the default characters |'.'|, |'-'|, and |'*'|
1137 respectively, representing hyphens in the word list.
1138 If the values specified for \.{\\lefthyphenmin} and \.{\\righthyphenmin}
1139 are invalid (e.g., blank) new values are read from the terminal.
1140
1141 @<Set up hyphenation...@>=
1142 bad:=false;
1143 n:=0;
1144 if buf[1]=' ' then do_nothing
1145 else if xclass[buf[1]]=digit_class then n:=xint[buf[1]]@+
1146 else bad:=true;
1147 if xclass[buf[2]]=digit_class then n:=10*n+xint[buf[2]]@+
1148 else bad:=true;
1149 if (n>=1)and(n<max_dot) then left_hyphen_min:=n@+else bad:=true;
1150 n:=0;
1151 if buf[3]=' ' then do_nothing
1152 else if xclass[buf[3]]=digit_class then n:=xint[buf[3]]@+
1153 else bad:=true;
1154 if xclass[buf[4]]=digit_class then n:=10*n+xint[buf[4]]@+
1155 else bad:=true;
1156 if (n>=1)and(n<max_dot) then right_hyphen_min:=n@+
1157 else bad:=true;
1158 if bad then
1159 begin bad:=false;
1160 repeat print('left_hyphen_min, right_hyphen_min: '); get_input(n1,n2);@/
1161 if (n1>=1)and(n1<max_dot)and(n2>=1)and(n2<max_dot) then
1162 begin left_hyphen_min:=n1; right_hyphen_min:=n2;
1163 end
1164 else begin n1:=0;
1165 print_ln('Specify 1<=left_hyphen_min,right_hyphen_min<=',
1166 max_dot-1:1,' !');
1167 end;
1168 until n1>0;
1169 end;
1170 for j:=err_hyf to found_hyf do
1171 begin if buf[j+4]<>' ' then xhyf[j]:=buf[j+4];
1172 if xclass[xhyf[j]]=invalid_class then xclass[xhyf[j]]:=hyf_class@+
1173 else bad:=true;
1174 end;
1175 xclass['.']:=hyf_class; {in case the default has been changed}
1176 if bad then bad_input('Bad hyphenation data')
1177 @.Bad hyphenation data@>
1178
1179 @ Each following line is either a comment or specifies the external
1180 representations for one `letter' used by the language. Comment lines
1181 start with two equal characters (e.g., are blank) and are ignored.
1182 Other lines contain the external representation of the lower case
1183 version and an arbitrary number of `upper case versions' of a letter
1184 preceded and separated by a delimiter and followed by two consecutive
1185 delimiters; the delimiter may be any character not occurring in either
1186 version.
1187
1188 @<Set up repres...@>=
1189 begin read_buf(translate); buf_ptr:=1; lower:=true;
1190 while not bad do {lower and then upper case version}
1191 begin pat_len:=0;
1192 repeat if buf_ptr<max_buf_len then incr(buf_ptr) @+ else bad:=true;
1193 if buf[buf_ptr]=buf[1] then
1194 if pat_len=0 then goto done
1195 else begin if lower then
1196 begin if imax=last_ASCII_code then
1197 begin print_buf; overflow(num_ASCII_codes:1,' letters');
1198 end;
1199 incr(imax); xext[imax]:=xchr[pat[pat_len]];
1200 end;
1201 c:=xchr[pat[1]];
1202 if pat_len=1 then
1203 begin if xclass[c]<>invalid_class then bad:=true;
1204 xclass[c]:=letter_class; xint[c]:=imax;
1205 end
1206 else @<Insert a letter into pattern trie@>;
1207 end
1208 else if pat_len=max_dot then bad:=true
1209 else begin incr(pat_len); pat[pat_len]:=get_ASCII(buf[buf_ptr]);
1210 end;
1211 until (buf[buf_ptr]=buf[1])or bad;
1212 lower:=false;
1213 end;
1214 done: if bad then bad_input('Bad representation');
1215 @.Bad representation@>
1216 end
1217
1218 @ When the (lower or upper case) external representation of a letter
1219 consists of more than one character and the corresponding |ASCII_code|
1220 values have been placed into the |pat| array we store them in
1221 the pattern trie. [See |insert_pattern|.] Since this `external subtrie'
1222 starts at |trie_link(trie_root)| it does not interfere with normal
1223 patterns. The output field of leaf nodes contains the |internal_code|
1224 and the link field distinguishes between lower and upper case letters.
1225
1226 @<Insert a letter...@>=
1227 begin if xclass[c]=invalid_class then xclass[c]:=escape_class;
1228 if xclass[c]<>escape_class then bad:=true;
1229 i:=0; s:=trie_root; t:=trie_link(s);
1230 while (t>trie_root) and (i<pat_len) do {follow existing trie}
1231 begin incr(i); Incr(t)(pat[i]);
1232 if so(trie_char(t))<>pat[i] then
1233 @<Insert critical transition, possibly repacking@>
1234 else if trie_outp(t)>0 then bad:=true;
1235 s:=t; t:=trie_link(s);
1236 end;
1237 if t>trie_root then bad:=true;
1238 q_link(1):=0; q_outp(1):=0; qmax:=1;
1239 while i<pat_len do {insert rest of pattern}
1240 begin incr(i); q_char(1):=pat[i];
1241 t:=first_fit;
1242 trie_link(s):=t;
1243 s:=t+pat[i];
1244 incr(trie_count);
1245 end;
1246 trie_outp(s):=imax;
1247 if not lower then trie_link(s):=trie_root;
1248 end
1249
1250 @ The |get_letter| \.{WEB} macro defined here will be used in
1251 |read_word| and |read_patterns| to obtain the |internal_code|
1252 corresponding to a letter externally represented by a multi-character
1253 sequence (starting with an |escape_class| character).
1254
1255 @d get_letter(#)==
1256 begin t:=trie_root;
1257 loop begin t:=trie_link(t)+xord[c];
1258 if so(trie_char(t))<>xord[c] then bad_input('Bad representation');
1259 @.Bad representation@>
1260 if trie_outp(t)<>0 then
1261 begin #:=trie_outp(t); goto done;
1262 end;
1263 if buf_ptr=max_buf_len then c:=' '
1264 else begin incr(buf_ptr); c:=buf[buf_ptr];
1265 end;
1266 end;
1267 done: end
1268
1269 @ In order to prepare for the output phase we store all but the last of
1270 the \\{ASCII\_codes} of the external representation of each `lower case
1271 letter' in the pattern count trie which is no longer used at that time.
1272 The recursive |find_letters| procedure traverses the `external subtrie'.
1273
1274 @p procedure find_letters(@!b: trie_pointer; @!i: dot_type);@/
1275 {traverse subtries of family |b|; |i| is current depth in trie}
1276 var c: ASCII_code; {a local variable that must be saved on recursive calls}
1277 @!a: trie_pointer; {does not need to be saved}
1278 @!j: dot_type; {loop index}
1279 @!l: triec_pointer;
1280 begin if i=1 then init_count_trie;
1281 for c:=cmin to last_ASCII_code do {find transitions belonging to this family}
1282 begin a:=b+c;
1283 if so(trie_char(a))=c then {found one}
1284 begin pat[i]:=c;
1285 if trie_outp(a)=0 then find_letters(trie_link(a),i+1)
1286 else if trie_link(a)=0 then {this is a lower case letter}
1287 @<Insert external representation for a letter into count trie@>;
1288 end;
1289 end;
1290 end;
1291
1292 @ Starting from |triec_root+trie_outp(a)| we proceed through link fields
1293 and store all \\{ASCII\_codes} except the last one in the count trie;
1294 the last character has already been stored in the |xext| array.
1295
1296 @<Insert external...@>=
1297 begin l:=triec_root+trie_outp(a);
1298 for j:=1 to i-1 do
1299 begin if triec_max=triec_size then
1300 overflow(triec_size:1,' count trie nodes');
1301 incr(triec_max); triec_link(l):=triec_max; l:=triec_max;
1302 triec_char(l):=si(pat[j]);
1303 end;
1304 triec_link(l):=0;
1305 end
1306
1307 @ During the output phase we will say |write_letter(i)(f)| and
1308 |write(f,xext[i])| to write the lower case external representation of
1309 the letter with internal code |i| to file |f|: |xext[i]| is the last
1310 character of the external representation whereas the \.{WEB} macro
1311 |write_letter| defined here writes all preceding characters (if any).
1312
1313 @d write_letter_end(#)==while l>0 do
1314 begin write(#,xchr[so(triec_char(l))]); l:=triec_link(l);
1315 end
1316 @d write_letter(#)==l:=triec_link(triec_root+#); write_letter_end
1317
1318 @* Routines for traversing pattern tries.
1319 At the end of a pass, we traverse the count trie using the following
1320 recursive procedure, selecting good and bad patterns and inserting them
1321 into the pattern trie.
1322
1323 @p procedure traverse_count_trie(@!b: triec_pointer; @!i: dot_type);@/
1324 {traverse subtries of family |b|; |i| is current depth in trie}
1325 var c: internal_code; {a local variable that must be saved on recursive calls}
1326 @!a: triec_pointer; {does not need to be saved}
1327 begin
1328 for c:=cmin to cmax do {find transitions belonging to this family}
1329 begin a:=b+c;
1330 if so(triec_char(a))=c then {found one}
1331 begin pat[i]:=c;
1332 if i<pat_len then traverse_count_trie(triec_link(a),i+1)
1333 else @<Decide what to do with this pattern@>;
1334 end;
1335 end;
1336 end;
1337
1338 @ When we have come to the end of a pattern, |triec_good(a)| and
1339 |triec_bad(a)| contain the number of times this pattern helps or hinders
1340 the cause. We use the counts to determine if this pattern should be
1341 selected, or if it is hopeless, or if we can't decide yet. In the latter
1342 case, we set |more_to_come| true to indicate that there might still be
1343 good patterns extending the current type of patterns.
1344
1345 @<Decide what to do...@>=
1346 if good_wt*triec_good(a)<thresh then {hopeless pattern}
1347 begin insert_pattern(max_val,pat_dot);
1348 incr(bad_pat_count)
1349 end else
1350 if good_wt*triec_good(a)-bad_wt*triec_bad(a)>=thresh then {good pattern}
1351 begin insert_pattern(hyph_level,pat_dot);
1352 incr(good_pat_count);
1353 Incr(good_count)(triec_good(a));
1354 Incr(bad_count)(triec_bad(a));
1355 end else
1356 more_to_come:=true
1357
1358 @ Some global variables are used to accumulate statistics about the
1359 performance of a pass.
1360
1361 @<Globals...@>=
1362 @!good_pat_count, @!bad_pat_count: integer; {number of patterns added at end
1363 of pass}
1364 @!good_count, @!bad_count, @!miss_count: integer; {hyphen counts}
1365 @!level_pattern_count: integer; {number of good patterns at level}
1366 @!more_to_come: boolean;
1367
1368 @ The recursion in |traverse_count_trie| is initiated by the following
1369 procedure, which also prints some statistics about the patterns chosen.
1370 The ``efficiency'' is an estimate of pattern effectiveness.
1371
1372 @d bad_eff==(thresh/good_wt)
1373
1374 @p procedure collect_count_trie;
1375 begin good_pat_count:=0; bad_pat_count:=0;
1376 good_count:=0; bad_count:=0;
1377 more_to_come:=false;
1378 traverse_count_trie(triec_root,1); @/
1379 print(good_pat_count:1,' good and ',
1380 bad_pat_count:1,' bad patterns added');
1381 Incr(level_pattern_count)(good_pat_count);
1382 if more_to_come then print_ln(' (more to come)') @+else print_ln(' ');
1383 print('finding ',good_count:1,' good and ',bad_count:1,' bad hyphens');
1384 if good_pat_count>0 then
1385 print_ln(', efficiency = ',
1386 good_count/(good_pat_count+bad_count/bad_eff):1:2)
1387 else print_ln(' ');
1388 print_ln('pattern trie has ',trie_count:1,' nodes, ',@|
1389 'trie_max = ',trie_max:1,', ',op_count:1,' outputs');
1390 end;
1391
1392 @ At the end of a level, we traverse the pattern trie and delete bad
1393 patterns by removing their outputs. If no output remains, the node is
1394 also deleted.
1395
1396 @p function delete_patterns(@!s: trie_pointer): trie_pointer;@/
1397 {delete bad patterns in subtrie |s|, return 0 if entire subtrie freed,
1398 otherwise |s|}
1399 var c: internal_code; @!t: trie_pointer; @!all_freed: boolean;
1400 {must be saved on recursive calls}
1401 @!h, @!n: op_type; {do not need to be saved}
1402 begin all_freed:=true;
1403 for c:=cmin to cmax do {find transitions belonging to this family}
1404 begin t:=s+c;
1405 if so(trie_char(t))=c then
1406 begin @<Link around bad outputs@>;
1407 if trie_link(t)>0 then
1408 trie_link(t):=delete_patterns(trie_link(t));
1409 if (trie_link(t)>0) or (trie_outp(t)>0) or (s=trie_root) then
1410 all_freed:=false
1411 else
1412 @<Deallocate this node@>;
1413 end;
1414 end;
1415 if all_freed then {entire state is freed}
1416 begin trie_base_used(s):=false;
1417 s:=0;
1418 end;
1419 delete_patterns:=s;
1420 end;
1421
1422 @ @<Link around bad outputs@>=
1423 begin h:=0;
1424 hyf_nxt(0):=trie_outp(t);
1425 n:=hyf_nxt(0);
1426 while n>0 do
1427 begin if hyf_val(n)=max_val then hyf_nxt(h):=hyf_nxt(n)
1428 else h:=n;
1429 n:=hyf_nxt(h);
1430 end;
1431 trie_outp(t):=hyf_nxt(0);
1432 end
1433
1434 @ Cells freed by |delete_patterns| are put at the end of the free list.
1435
1436 @<Deallocate this node@>=
1437 begin trie_link(trie_back(trie_max+1)):=t;
1438 trie_back(t):=trie_back(trie_max+1);
1439 trie_link(t):=trie_max+1;
1440 trie_back(trie_max+1):=t;
1441 trie_char(t):=min_packed;@/
1442 decr(trie_count);
1443 end
1444
1445 @ The recursion in |delete_patterns| is initiated by the following
1446 procedure, which also prints statistics about the number of nodes deleted,
1447 and zeros bad outputs in the hash table. Note that the hash table may
1448 become somewhat disorganized when more levels are added, but this defect
1449 isn't serious.
1450
1451 @p procedure delete_bad_patterns;
1452 var old_op_count: op_type;
1453 @!old_trie_count: trie_pointer;
1454 @!t: trie_pointer; @!h: op_type;
1455 begin old_op_count:=op_count;
1456 old_trie_count:=trie_count;@/
1457 t:=delete_patterns(trie_root);
1458 for h:=1 to max_ops do
1459 if hyf_val(h)=max_val then
1460 begin hyf_val(h):=0; decr(op_count);
1461 end;
1462 print_ln(old_trie_count-trie_count:1,' nodes and ',@|
1463 old_op_count-op_count:1,' outputs deleted');
1464 qmax_thresh:=7; {pattern trie will be sparser because of deleted
1465 patterns}
1466 end;
1467
1468 @ After all patterns have been generated, we will traverse the pattern
1469 trie and output all patterns. Note that if a pattern appears more than
1470 once, only the maximum value at each position will be output.
1471
1472 @p procedure output_patterns(@!s: trie_pointer; @!pat_len: dot_type);@/
1473 {output patterns in subtrie |s|; |pat_len| is current depth in trie}
1474 var c: internal_code; {must be saved on recursive calls}
1475 @!t: trie_pointer; @!h: op_type; @!d: dot_type;@/
1476 @!l: triec_pointer; {for |write_letter|}
1477 begin for c:=cmin to cmax do
1478 begin t:=s+c;
1479 if so(trie_char(t))=c then
1480 begin pat[pat_len]:=c;
1481 h:=trie_outp(t);
1482 if h>0 then @<Output this pattern@>;
1483 if trie_link(t)>0 then output_patterns(trie_link(t),pat_len+1);
1484 end;
1485 end;
1486 end;
1487
1488 @ @<Output this pattern@>=
1489 begin for d:=0 to pat_len do hval[d]:=0;
1490 repeat d:=hyf_dot(h);
1491 if hval[d]<hyf_val(h) then hval[d]:=hyf_val(h);
1492 h:=hyf_nxt(h);
1493 until h=0;
1494 if hval[0]>0 then write(patout,xdig[hval[0]]);
1495 for d:=1 to pat_len do
1496 begin write_letter(pat[d])(patout); write(patout,xext[pat[d]]);
1497 if hval[d]>0 then write(patout,xdig[hval[d]]);
1498 end;
1499 write_ln(patout);
1500 end
1501
1502 @* Dictionary processing routines.
1503 The procedures in this section are the ``inner loop'' of the pattern
1504 generation process. To speed the program up, key parts of these routines
1505 could be coded in machine language.
1506 @^inner loop@>
1507
1508 @<Globals...@>=
1509 @!word: array[word_index] of internal_code; {current word}
1510 @!dots: array[word_index] of hyf_type; {current hyphens}
1511 @!dotw: array[word_index] of digit; {dot weights}
1512 @!hval: array[word_index] of val_type; {hyphenation values}
1513 @!no_more: array[word_index] of boolean; {positions `knocked out'}
1514 @!wlen: word_index; {length of current word}
1515 @!word_wt: digit; {global word weight}
1516 @!wt_chg: boolean; {indicates |word_wt| has changed}
1517
1518 @ The words in the |dictionary| consist of the `letters' used by the
1519 language. ``Dots'' between letters can be one of four possibilities:
1520 |'-'| indicating a hyphen, |'*'| indicating a found hyphen, |'.'|
1521 indicating an error, or nothing; these are represented internally by the
1522 four values |is_hyf|, |found_hyf|, |err_hyf|, and |no_hyf| respectively.
1523 When reading a word we will, however, convert |err_hyf| into |no_hyf|
1524 and |found_hyf| into |is_hyf| thus ignoring whether a hyphen has or
1525 has not been found by a previous set of patterns.
1526
1527 @<Prepare to read dictionary@>=
1528 xclass['.']:=invalid_class; {in case the default has been changed}
1529 xclass[xhyf[err_hyf]]:=hyf_class; xint[xhyf[err_hyf]]:=no_hyf;
1530 xclass[xhyf[is_hyf]]:=hyf_class; xint[xhyf[is_hyf]]:=is_hyf;
1531 xclass[xhyf[found_hyf]]:=hyf_class; xint[xhyf[found_hyf]]:=is_hyf;
1532
1533 @ Furthermore single-digit word weights are allowed. A digit at
1534 the beginning of a word indicates a global word weight that is to be
1535 applied to all following words (until the next global word weight). A
1536 digit at some intercharacter position indicates a weight for that position
1537 only.
1538
1539 The |read_word| procedure scans a line of input representing a word,
1540 and places the letters into the array |word|, with |word[1]=word[wlen]=
1541 edge_of_word|. The dot appearing between |word[dpos]| and |word[dpos+1]|
1542 is placed in |dots[dpos]|, and the corresponding dot weight in
1543 |dotw[dpos]|.
1544
1545 @p procedure read_word;
1546 label done, found;
1547 var c: text_char;
1548 @!t: trie_pointer;
1549 begin read_buf(dictionary);
1550 word[1]:=edge_of_word; wlen:=1; buf_ptr:=0;
1551 repeat incr(buf_ptr); c:=buf[buf_ptr];
1552 case xclass[c] of
1553 space_class: goto found;
1554 digit_class:
1555 if wlen=1 then {global word weight}
1556 begin if xint[c]<>word_wt then wt_chg:=true;
1557 word_wt:=xint[c];
1558 end
1559 else dotw[wlen]:=xint[c]; {dot weight}
1560 hyf_class: dots[wlen]:=xint[c]; {record the dot |c|}
1561 letter_class: {record the letter |c|}
1562 begin incr(wlen);
1563 if wlen=max_len then
1564 begin print_buf; overflow('word length=',max_len:1);
1565 end;
1566 word[wlen]:=xint[c]; dots[wlen]:=no_hyf; dotw[wlen]:=word_wt;
1567 end;
1568 escape_class: {record a multi-character sequence starting with |c|}
1569 begin incr(wlen);
1570 if wlen=max_len then
1571 begin print_buf; overflow('word length=',max_len:1);
1572 end;
1573 get_letter(word[wlen]); dots[wlen]:=no_hyf; dotw[wlen]:=word_wt;
1574 end;
1575 invalid_class: bad_input('Bad character');
1576 @.Bad character@>
1577 end;
1578 until buf_ptr=max_buf_len;
1579 found: incr(wlen); word[wlen]:=edge_of_word;
1580 end;
1581
1582 @ Here is a procedure that uses the existing patterns to hyphenate the
1583 current word. The hyphenation value applying between the characters
1584 |word[dpos]| and |word[dpos+1]| is stored in |hval[dpos]|.
1585
1586 In addition, |no_more[dpos]| is set to |true| if this position is
1587 ``knocked out'' by either a good or bad pattern at this level. That is,
1588 if the pattern with current length and hyphen position is a superstring of
1589 either a good or bad pattern at this level, then we don't need to collect
1590 count statistics for the pattern because it can't possibly be chosen in
1591 this pass. Thus we don't even need to insert such patterns into the count
1592 trie, which saves a good deal of space.
1593
1594 @p procedure hyphenate;
1595 label done;
1596 var spos, @!dpos, @!fpos: word_index;
1597 @!t: trie_pointer; @!h: op_type; @!v: val_type;
1598 begin
1599 for spos:=wlen-hyf_max downto 0 do
1600 begin no_more[spos]:=false; hval[spos]:=0;
1601 fpos:=spos+1; t:=trie_root+word[fpos];
1602 repeat h:=trie_outp(t);
1603 while h>0 do @<Store output |h| in the |hval| and
1604 |no_more| arrays, and advance |h|@>;
1605 t:=trie_link(t);
1606 if t=0 then goto done;
1607 incr(fpos); Incr(t)(word[fpos]);
1608 until so(trie_char(t))<>word[fpos];
1609 done:
1610 end;
1611 end;
1612
1613 @ In order to avoid unnecessary test (and range check violations) the
1614 globals |hyf_min|, |hyf_max|, and |hyf_len| are set up such that only
1615 positions from |hyf_min| up to |wlen-hyf_max| of the |word| array need
1616 to be checked, and that words with |wlen<hyf_len| need not to be checked
1617 at all.
1618
1619 @<Globals...@>=
1620 @!hyf_min, @!hyf_max, @!hyf_len: word_index; {limits for legal hyphens}
1621
1622 @ @<Prepare to read dictionary@>=
1623 hyf_min:=left_hyphen_min+1; hyf_max:=right_hyphen_min+1;
1624 hyf_len:=hyf_min+hyf_max;
1625
1626 @ @<Store output |h| in the |hval| and |no_more| arrays, and advance |h|@>=
1627 begin dpos:=spos+hyf_dot(h);
1628 v:=hyf_val(h);
1629 if (v<max_val) and (hval[dpos]<v) then hval[dpos]:=v;
1630 if (v>=hyph_level) then {check if position knocked out}
1631 if ((fpos-pat_len)<=(dpos-pat_dot))and((dpos-pat_dot)<=spos) then
1632 no_more[dpos]:=true;
1633 h:=hyf_nxt(h);
1634 end
1635
1636 @ The |change_dots| procedure updates the |dots| array representing the
1637 printing values of the hyphens. Initially, hyphens (and correctly
1638 found hyphens) in the word list are represented by |is_hyf| whereas
1639 non-hyphen positions (and erroneous hyphens) are represented by |no_hyf|.
1640 Here these values are increased by one for each hyphen found by the
1641 current patterns, thus changing |no_hyf| into |err_hyf| and |is_hyf|
1642 into |found_hyf|. The routine also collects statistics about the number
1643 of good, bad, and missed hyphens.
1644
1645 @d incr_wt(#)==Incr(#)(dotw[dpos])
1646
1647 @p procedure change_dots;
1648 var dpos: word_index;
1649 begin for dpos:=wlen-hyf_max downto hyf_min do
1650 begin if odd(hval[dpos]) then incr(dots[dpos]);
1651 if dots[dpos]=found_hyf then incr_wt(good_count)
1652 else if dots[dpos]=err_hyf then incr_wt(bad_count)
1653 else if dots[dpos]=is_hyf then incr_wt(miss_count);
1654 end;
1655 end;
1656
1657 @ The following procedure outputs the word as hyphenated by the current
1658 patterns, including any word weights. Hyphens inhibited by the values of
1659 \.{\\lefthyphenmin} and \.{\\righthyphenmin} are output as well.
1660
1661 @p procedure output_hyphenated_word;
1662 var dpos: word_index;@/
1663 @!l: triec_pointer; {for |write_letter|}
1664 begin if wt_chg then {output global word weight}
1665 begin write(pattmp,xdig[word_wt]); wt_chg:=false
1666 end;
1667 for dpos:=2 to wlen-2 do
1668 begin write_letter(word[dpos])(pattmp); write(pattmp,xext[word[dpos]]);
1669 if dots[dpos]<>no_hyf then write(pattmp,xhyf[dots[dpos]]);
1670 if dotw[dpos]<>word_wt then write(pattmp,xdig[dotw[dpos]]);
1671 end;
1672 write_letter(word[wlen-1])(pattmp); write_ln(pattmp,xext[word[wlen-1]]);
1673 end;
1674
1675 @ For each dot position in the current word, the |do_word| routine first
1676 checks to see if we need to consider it. It might be knocked out or a dot
1677 we don't care about. That is, when considering hyphenating patterns, for
1678 example, we don't need to count hyphens already found. If a relevant dot
1679 is found, we increment the count in the count trie for the corresponding
1680 pattern, inserting it first if necessary. At this point of the program
1681 range check violations may occur if these counts are incremented beyond
1682 |triec_max|; it would, however, be too expensive to prevent this.
1683 @^range check violations@>
1684
1685 @p procedure do_word;
1686 label continue, done;
1687 var spos, @!dpos, @!fpos: word_index; @!a: triec_pointer;
1688 @!goodp: boolean;
1689 begin for dpos:=wlen-dot_max downto dot_min do
1690 begin spos:=dpos-pat_dot;
1691 fpos:=spos+pat_len;
1692 @<Check this dot position and |goto continue| if don't care@>;
1693 incr(spos); a:=triec_root+word[spos];
1694 while spos<fpos do
1695 begin {follow existing count trie}
1696 incr(spos);
1697 a:=triec_link(a)+word[spos];
1698 if so(triec_char(a))<>word[spos] then
1699 begin {insert new count pattern}
1700 a:=insertc_pat(fpos);
1701 goto done;
1702 end;
1703 end;
1704 done: if goodp then incr_wt(triec_good(a))
1705 @+else incr_wt(triec_bad(a));
1706 continue:
1707 end;
1708 end;
1709
1710 @ The globals |good_dot| and |bad_dot| will be set to |is_hyf| and
1711 |no_hyf|, or |err_hyf| and |found_hyf|, depending on whether the current
1712 level is odd or even, respectively. The globals |dot_min|, |dot_max|,
1713 and |dot_len| are analogous to |hyf_min|, |hyf_max|, and |hyf_len|
1714 defined earlier.
1715
1716 @<Globals...@>=
1717 @!good_dot, @!bad_dot: hyf_type; {good and bad hyphens at current level}
1718 @!dot_min, @!dot_max, @!dot_len: word_index; {limits for legal dots}
1719
1720 @ @<Prepare to read dictionary@>=
1721 if procesp then
1722 begin dot_min:=pat_dot; dot_max:=pat_len-pat_dot;
1723 if dot_min<hyf_min then dot_min:=hyf_min;
1724 if dot_max<hyf_max then dot_max:=hyf_max;
1725 dot_len:=dot_min+dot_max;
1726 if odd(hyph_level) then
1727 begin good_dot:=is_hyf; bad_dot:=no_hyf;
1728 end
1729 else begin good_dot:=err_hyf; bad_dot:=found_hyf;
1730 end;
1731 end;
1732
1733 @ If the dot position |dpos| is out of bounds, knocked out, or a ``don't
1734 care'', we skip this position. Otherwise we set the flag |goodp|
1735 indicating whether this is a good or bad dot.
1736
1737 @<Check this dot position...@>=
1738 if no_more[dpos] then goto continue;
1739 if dots[dpos]=good_dot then goodp:=true else
1740 if dots[dpos]=bad_dot then goodp:=false else goto continue;
1741
1742 @ If |hyphp| is set to |true|, |do_dictionary| will write out a copy of
1743 the dictionary as hyphenated by the current set of patterns. If |procesp|
1744 is set to |true|, |do_dictionary| will collect pattern statistics for
1745 patterns with length |pat_len| and hyphen position |pat_dot|, at level
1746 |hyph_level|.
1747
1748 @<Globals...@>=
1749 @!procesp, @!hyphp: boolean;
1750 @!pat_dot: dot_type; {hyphen position, measured from beginning of pattern}
1751 @!hyph_level: val_type; {hyphenation level}
1752 @!filnam: packed array[1..8] of char; {for |pattmp|}
1753
1754 @ The following procedure makes a pass through the word list, and also
1755 prints out statistics about number of hyphens found and storage used by
1756 the count trie.
1757
1758 @p procedure do_dictionary;
1759 begin good_count:=0; bad_count:=0; miss_count:=0;
1760 word_wt:=1; wt_chg:=false;
1761 reset(dictionary);@/
1762 @<Prepare to read dictionary@>@;@/
1763 if procesp then
1764 begin init_count_trie;
1765 print_ln('processing dictionary with pat_len = ',pat_len:1,
1766 ', pat_dot = ',pat_dot:1);
1767 end;
1768 if hyphp then
1769 begin filnam:='pattmp. ';
1770 filnam[8]:=xdig[hyph_level];
1771 rewrite(pattmp,filnam);
1772 print_ln('writing pattmp.', xdig[hyph_level]);
1773 end;
1774 @<Process words until end of file@>;@/
1775 close_in(dictionary);@/
1776 print_ln(' ');
1777 print_ln(good_count:1,' good, ',bad_count:1,' bad, ',
1778 miss_count:1,' missed');
1779 if (good_count+miss_count)>0 then
1780 print_ln((100*good_count/(good_count+miss_count)):1:2,' %, ',
1781 (100*bad_count/(good_count+miss_count)):1:2,' %, ',
1782 (100*miss_count/(good_count+miss_count)):1:2,' %');
1783 if procesp then
1784 print_ln(pat_count:1,' patterns, ',triec_count:1,
1785 ' nodes in count trie, ','triec_max = ',triec_max:1);
1786 if hyphp then close_out(pattmp);
1787 end;
1788
1789 @ @<Process words...@>=
1790 while not eof(dictionary) do
1791 begin read_word;
1792 if wlen>=hyf_len then {short words are never hyphenated}
1793 begin hyphenate; change_dots;
1794 end;
1795 if hyphp then if wlen>2 then output_hyphenated_word;
1796 {empty words are ignored}
1797 if procesp then if wlen>=dot_len then do_word;
1798 end
1799
1800 @* Reading patterns.
1801 Before beginning a run, we can read in a file of existing patterns. This
1802 is useful for extending a previous pattern selection run to get some more
1803 levels. (Since these runs are quite time-consuming, it is convenient to
1804 choose patterns one level at a time, pausing to look at the results of the
1805 previous level, and possibly amending the dictionary.)
1806
1807 @p procedure read_patterns;
1808 label done, found;
1809 var c: text_char;
1810 @!d: digit;
1811 @!i: dot_type;
1812 @!t: trie_pointer;
1813 begin xclass['.']:=letter_class; xint['.']:=edge_of_word;
1814 level_pattern_count:=0; max_pat:=0;
1815 reset(patterns);
1816 while not eof(patterns) do
1817 begin read_buf(patterns);
1818 incr(level_pattern_count);@/
1819 @<Get pattern and dots and |goto found|@>;
1820 found: @<Insert pattern@>;
1821 end;
1822 close_in(patterns);
1823 print_ln(level_pattern_count:1,' patterns read in');@/
1824 print_ln('pattern trie has ',trie_count:1,' nodes, ',@|
1825 'trie_max = ',trie_max:1,', ',op_count:1,' outputs');
1826 end;
1827
1828 @ The global variable |max_pat| keeps track of the largest hyphenation
1829 value found in any pattern.
1830
1831 @<Globals...@>=
1832 @!max_pat: val_type;
1833
1834 @ When a new pattern has been input into |buf|, we extract the letters of
1835 the pattern, and insert the hyphenation values (digits) into the |hval|
1836 array.
1837
1838 @<Get pattern...@>=
1839 pat_len:=0; buf_ptr:=0; hval[0]:=0;
1840 repeat incr(buf_ptr); c:=buf[buf_ptr];
1841 case xclass[c] of
1842 space_class: goto found;
1843 digit_class:
1844 begin d:=xint[c];
1845 if d>=max_val then bad_input('Bad hyphenation value');
1846 @.Bad hyphenation value@>
1847 if d>max_pat then max_pat:=d;
1848 hval[pat_len]:=d;
1849 end;
1850 letter_class:
1851 begin incr(pat_len); hval[pat_len]:=0; pat[pat_len]:=xint[c];
1852 end;
1853 escape_class: {record a multi-character sequence starting with |c|}
1854 begin incr(pat_len); hval[pat_len]:=0; get_letter(pat[pat_len]);
1855 end;
1856 hyf_class, invalid_class: bad_input('Bad character');
1857 @.Bad character@>
1858 end;
1859 until buf_ptr=max_buf_len
1860
1861 @ Then we insert the pattern for each non-vanishing hyphenation value.
1862 In addition we check that |edge_of_word| (i.e., |'.'|) occurs only as
1863 first or last character; otherwise we would have to perform a time
1864 consuming test for the end of a word in the |hyphenate| procedure.
1865
1866 @<Insert pattern@>=
1867 if pat_len>0 then {avoid spurious patterns}
1868 for i:=0 to pat_len do
1869 begin if hval[i]<>0 then insert_pattern(hval[i],i);
1870 if i>1 then if i<pat_len then if pat[i]=edge_of_word then
1871 bad_input('Bad edge_of_word');
1872 @.Bad edge_of_word@>
1873 end
1874
1875 @* The main program.
1876 This is where \.{PATGEN} actually starts. We initialize the pattern trie,
1877 get |hyph_level| and |pat_len| limits from the terminal, and generate
1878 patterns.
1879
1880 @p begin initialize;
1881 init_pattern_trie;
1882 read_translate;
1883 read_patterns;
1884 procesp:=true; hyphp:=false;@/
1885 repeat print('hyph_start, hyph_finish: '); get_input(n1,n2);@/
1886 if (n1>=1)and(n1<max_val)and(n2>=1)and(n2<max_val) then
1887 begin hyph_start:=n1; hyph_finish:=n2;
1888 end
1889 else begin n1:=0;
1890 print_ln('Specify 1<=hyph_start,hyph_finish<=',max_val-1:1,' !');
1891 end;
1892 until n1>0;
1893 hyph_level:=max_pat; {in case |hyph_finish<hyph_start|}
1894 for i:=hyph_start to hyph_finish do
1895 begin hyph_level:=i; level_pattern_count:=0;
1896 if hyph_level>hyph_start then print_ln(' ')
1897 else if hyph_start<=max_pat then
1898 print_ln('Largest hyphenation value ',max_pat:1,
1899 ' in patterns should be less than hyph_start');@/
1900 @.Largest hyphenation value@>
1901 repeat print('pat_start, pat_finish: '); get_input(n1,n2);@/
1902 if (n1>=1)and(n1<=n2)and(n2<=max_dot) then
1903 begin pat_start:=n1; pat_finish:=n2;
1904 end
1905 else begin n1:=0;
1906 print_ln('Specify 1<=pat_start<=pat_finish<=',max_dot:1,' !');
1907 end;
1908 until n1>0;
1909 repeat print('good weight, bad weight, threshold: ');
1910 get_input(n1,n2,n3);@/
1911 if (n1>=1)and(n2>=1)and(n3>=1) then
1912 begin good_wt:=n1; bad_wt:=n2; thresh:=n3;
1913 end
1914 else begin n1:=0;
1915 print_ln('Specify good weight, bad weight, threshold>=1 !');
1916 end;
1917 until n1>0;
1918 @<Generate a level@>;
1919 delete_bad_patterns;
1920 print_ln('total of ',level_pattern_count:1,
1921 ' patterns at hyph_level ',hyph_level:1);
1922 end;
1923 find_letters(trie_link(trie_root),1); {prepare for output}
1924 rewrite(patout);
1925 output_patterns(trie_root,1);
1926 close_out(patout);@/
1927 @<Make final pass to hyphenate word list@>;
1928 end_of_PATGEN:
1929 end.
1930
1931 @ The patterns of a given length (at a given level) are chosen with dot
1932 positions ordered in an ``organ-pipe'' fashion. For example, for
1933 |pat_len=4| we choose patterns for different dot positions in the order 2,
1934 1, 3, 0, 4. The variable |dot1| controls this iteration in a clever
1935 manner.
1936
1937 @<Globals...@>=
1938 @!n1, @!n2, @!n3: integer; {accumulators}
1939 @!i: val_type; {loop index: hyphenation level}
1940 @!j: dot_type; {loop index: pattern length}
1941 @!k: dot_type; {loop index: hyphen position}
1942 @!dot1: dot_type;
1943 @!more_this_level: array[dot_type] of boolean;
1944
1945 @ The array |more_this_level| remembers which positions are permanently
1946 ``knocked out''. That is, if there aren't any possible good patterns
1947 remaining at a certain dot position, we don't need to consider longer
1948 patterns at this level containing that position.
1949
1950 @<Generate a level@>=
1951 for k:=0 to max_dot do more_this_level[k]:=true;
1952 for j:=pat_start to pat_finish do
1953 begin pat_len:=j; pat_dot:=pat_len div 2; dot1:=pat_dot*2;
1954 repeat pat_dot:=dot1-pat_dot; dot1:=pat_len*2-dot1-1;
1955 if more_this_level[pat_dot] then
1956 begin do_dictionary; collect_count_trie;
1957 more_this_level[pat_dot]:=more_to_come;
1958 end;
1959 until pat_dot=pat_len;
1960 for k:=max_dot downto 1 do
1961 if not more_this_level[k-1] then more_this_level[k]:=false;
1962 end
1963
1964 @ When all patterns have been found, the user has a chance to see what
1965 they do. The resulting \.{pattmp} file can be used as the new
1966 `dictionary' if we want to continue pattern generation from this point.
1967
1968 @<Make final pass to hyphenate word list@>=
1969 procesp:=false; hyphp:=true;@/
1970 print('hyphenate word list? ');
1971 get_input_ln(buf[1]);
1972 if (buf[1]='Y') or (buf[1]='y') then do_dictionary
1973
1974 @* System-dependent changes.
1975 This section should be replaced, if necessary, by changes to the program
1976 that are necessary to make \.{PATGEN} work at a particular installation.
1977 It is usually best to design your change file so that all changes to
1978 previous sections preserve the section numbering; then everybody's version
1979 will be consistent with the printed program. More extensive changes,
1980 which introduce new sections, can be inserted here; then only the index
1981 itself will get a new section number.
1982 @^system dependencies@>
1983
1984 @* Index.
1985 Pointers to error messages appear here together with the section numbers
1986 where each ident\-i\-fier is used.