1 % $Id: mp.web,v 1.8 2005/08/24 10:54:02 taco Exp $
2 % MetaPost, by John Hobby. Public domain.
4 % Much of this program was copied with permission from MF.web Version 1.9
5 % It interprets a language very similar to D.E. Knuth's METAFONT, but with
6 % changes designed to make it more suitable for PostScript output.
8 % TeX is a trademark of the American Mathematical Society.
9 % METAFONT is a trademark of Addison-Wesley Publishing Company.
10 % PostScript is a trademark of Adobe Systems Incorporated.
12 % Here is TeX material that gets inserted after \input webmac
13 \def\hang{\hangindent 3em\noindent\ignorespaces}
14 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
17 \def\ph{\hbox{Pascal-H}}
18 \def\psqrt#1{\sqrt{\mathstrut#1}}
20 \def\pct!{{\char`\%}} % percent sign in ordinary text
21 \font\tenlogo=logo10 % font used for the METAFONT logo
23 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
24 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
25 \def\[#1]{#1.} % from pascal web
26 \def\<#1>{$\langle#1\rangle$}
27 \def\section{\mathhexbox278}
28 \let\swap=\leftrightarrow
29 \def\round{\mathop{\rm round}\nolimits}
30 \mathchardef\vb="026A % synonym for `\|'
32 \def\(#1){} % this is used to make section names sort themselves better
33 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
35 \def\glob{15} % this should be the section number of "<Global...>"
36 \def\gglob{23, 28} % this should be the next two sections of "<Global...>"
41 This is \MP, a graphics-language processor based on D. E. Knuth's \MF.
43 The main purpose of the following program is to explain the algorithms of \MP\
44 as clearly as possible. As a result, the program will not necessarily be very
45 efficient when a particular \PASCAL\ compiler has translated it into a
46 particular machine language. However, the program has been written so that it
47 can be tuned to run efficiently in a wide variety of operating environments
48 by making comparatively few changes. Such flexibility is possible because
49 the documentation that follows is written in the \.{WEB} language, which is
50 at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
51 to \PASCAL\ is able to introduce most of the necessary refinements.
52 Semi-automatic translation to other languages is also feasible, because the
53 program below does not make extensive use of features that are peculiar to
56 A large piece of software like \MP\ has inherent complexity that cannot
57 be reduced below a certain level of difficulty, although each individual
58 part is fairly simple by itself. The \.{WEB} language is intended to make
59 the algorithms as readable as possible, by reflecting the way the
60 individual program pieces fit together and by providing the
61 cross-references that connect different parts. Detailed comments about
62 what is going on, and about why things were done in certain ways, have
63 been liberally sprinkled throughout the program. These comments explain
64 features of the implementation, but they rarely attempt to explain the
65 \MP\ language itself, since the reader is supposed to be familiar with
66 {\sl The {\logos METAFONT\/}book} as well as the manual
68 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
69 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
70 AT\AM T Bell Laboratories.
72 @ The present implementation is a preliminary version, but the possibilities
73 for new features are limited by the desire to remain as nearly compatible
74 with \MF\ as possible.
76 On the other hand, the \.{WEB} description can be extended without changing
77 the core of the program, and it has been designed so that such
78 extensions are not extremely difficult to make.
79 The |banner| string defined here should be changed whenever \MP\
80 undergoes any modifications, so that it will be clear which version of
81 \MP\ might be the guilty party when a problem arises.
83 @^system dependencies@>
85 @d banner "This is MetaPost, Version 1.002" /* printed when \MP\ starts */
86 @d metapost_version "1.002"
87 @d mplib_version "0.10"
88 @d version_string " (Cweb version 0.10)"
90 @ Different \PASCAL s have slightly different conventions, and the present
92 program is expressed in a version of \PASCAL\ that D. E. Knuth used for \MF.
93 Constructions that apply to
94 this particular compiler, which we shall call \ph, should help the
95 reader see how to make an appropriate interface for other systems
96 if necessary. (\ph\ is Charles Hedrick's modification of a compiler
97 @^Hedrick, Charles Locke@>
98 for the DECsystem-10 that was originally developed at the University of
99 Hamburg; cf.\ {\sl SOFTWARE---Practice \AM\ Experience \bf6} (1976),
100 29--42. The \MP\ program below is intended to be adaptable, without
101 extensive changes, to most other versions of \PASCAL\ and commonly used
102 \PASCAL-to-C translators, so it does not fully
104 use the admirable features of \ph. Indeed, a conscious effort has been
105 made here to avoid using several idiosyncratic features of standard
106 \PASCAL\ itself, so that most of the code can be translated mechanically
107 into other high-level languages. For example, the `\&{with}' and `\\{new}'
108 features are not used, nor are pointer types, set types, or enumerated
109 scalar types; there are no `\&{var}' parameters, except in the case of files;
110 there are no tag fields on variant records; there are no |real| variables;
111 no procedures are declared local to other procedures.)
113 The portions of this program that involve system-dependent code, where
114 changes might be necessary because of differences between \PASCAL\ compilers
115 and/or differences between
116 operating systems, can be identified by looking at the sections whose
117 numbers are listed under `system dependencies' in the index. Furthermore,
118 the index entries for `dirty \PASCAL' list all places where the restrictions
119 of \PASCAL\ have not been followed perfectly, for one reason or another.
120 @^system dependencies@>
123 @ The program begins with a normal \PASCAL\ program heading, whose
124 components will be filled in later, using the conventions of \.{WEB}.
126 For example, the portion of the program called `\X\glob:Global
127 variables\X' below will be replaced by a sequence of variable declarations
128 that starts in $\section\glob$ of this documentation. In this way, we are able
129 to define each individual global variable when we are prepared to
130 understand what it means; we do not have to define all of the globals at
131 once. Cross references in $\section\glob$, where it says ``See also
132 sections \gglob, \dots,'' also make it possible to look at the set of
133 all global variables, if desired. Similar remarks apply to the other
134 portions of the program heading.
136 Actually the heading shown here is not quite normal: The |program| line
137 does not mention any |output| file, because \ph\ would ask the \MP\ user
138 to specify a file name if |output| were specified here.
139 @^system dependencies@>
145 typedef struct MP_instance * MP;
147 typedef struct MP_options {
150 @<Exported function headers@>
154 typedef struct psout_data_struct * psout_data;
156 typedef signed int integer;
158 @<Types in the outer block@>;
159 @<Constants in the outer block@>
160 # ifndef LIBAVL_ALLOCATOR
161 # define LIBAVL_ALLOCATOR
162 struct libavl_allocator {
163 void *(*libavl_malloc) (struct libavl_allocator *, size_t libavl_size);
164 void (*libavl_free) (struct libavl_allocator *, void *libavl_block);
167 typedef struct MP_instance {
170 @<Internal library declarations@>
178 #include <unistd.h> /* for access() */
179 #include <time.h> /* for struct tm \& co */
181 #include "mpmp.h" /* internal header */
182 #include "mppsout.h" /* internal header */
185 @<Basic printing procedures@>
186 @<Error handling procedures@>
188 @ Here are the functions that set up the \MP\ instance.
191 @<Declare |mp_reallocate| functions@>;
192 struct MP_options *mp_options (void);
193 MP mp_new (struct MP_options *opt);
196 struct MP_options *mp_options (void) {
197 struct MP_options *opt;
198 opt = malloc(sizeof(MP_options));
200 memset (opt,0,sizeof(MP_options));
204 MP mp_new (struct MP_options *opt) {
206 mp = xmalloc(1,sizeof(MP_instance));
207 @<Set |ini_version|@>;
208 @<Setup the non-local jump buffer in |mp_new|@>;
209 @<Allocate or initialize variables@>
210 if (opt->main_memory>mp->mem_max)
211 mp_reallocate_memory(mp,opt->main_memory);
212 mp_reallocate_paths(mp,1000);
213 mp_reallocate_fonts(mp,8);
215 mp->term_out = stdout;
218 void mp_free (MP mp) {
219 int k; /* loop variable */
220 @<Dealloc variables@>
225 void mp_do_initialize ( MP mp) {
226 @<Local variables for initialization@>
227 @<Set initial values of key variables@>
229 int mp_initialize (MP mp) { /* this procedure gets things started properly */
230 mp->history=mp_fatal_error_stop; /* in case we quit during initialization */
231 @<Install and test the non-local jump buffer@>;
232 t_open_out; /* open the terminal for output */
233 @<Check the ``constant'' values...@>;
235 fprintf(stdout,"Ouch---my internal constants have been clobbered!\n"
236 "---case %i",(int)mp->bad);
240 mp_do_initialize(mp); /* erase preloaded mem */
241 if (mp->ini_version) {
242 @<Run inimpost commands@>;
244 @<Initialize the output routines@>;
245 @<Get the first line of input and prepare to start@>;
247 mp_init_map_file(mp, mp->troff_mode);
248 mp->history=mp_spotless; /* ready to go! */
249 if (mp->troff_mode) {
250 mp->internal[mp_gtroffmode]=unity;
251 mp->internal[mp_prologues]=unity;
253 if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
254 mp->cur_sym=mp->start_sym; mp_back_input(mp);
260 @<Exported function headers@>=
261 extern struct MP_options *mp_options (void);
262 extern MP mp_new (struct MP_options *opt) ;
263 extern void mp_free (MP mp);
264 extern int mp_initialize (MP mp);
267 void mp_do_initialize (MP mp);
270 @ The overall \MP\ program begins with the heading just shown, after which
271 comes a bunch of procedure declarations and function declarations.
272 Finally we will get to the main program, which begins with the
273 comment `|start_here|'. If you want to skip down to the
274 main program now, you can look up `|start_here|' in the index.
275 But the author suggests that the best way to understand this program
276 is to follow pretty much the order of \MP's components as they appear in the
277 \.{WEB} description you are now reading, since the present ordering is
278 intended to combine the advantages of the ``bottom up'' and ``top down''
279 approaches to the problem of understanding a somewhat complicated system.
281 @ Some of the code below is intended to be used only when diagnosing the
282 strange behavior that sometimes occurs when \MP\ is being installed or
283 when system wizards are fooling around with \MP\ without quite knowing
284 what they are doing. Such code will not normally be compiled; it is
285 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
287 @ This program has two important variations: (1) There is a long and slow
288 version called \.{INIMP}, which does the extra calculations needed to
290 initialize \MP's internal tables; and (2)~there is a shorter and faster
291 production version, which cuts the initialization to a bare minimum.
293 Which is which is decided at runtime.
295 @ The following parameters can be changed at compile time to extend or
296 reduce \MP's capacity. They may have different values in \.{INIMP} and
297 in production versions of \MP.
299 @^system dependencies@>
302 #define file_name_size 255 /* file names shouldn't be longer than this */
303 #define bistack_size 1500 /* size of stack for bisection algorithms;
304 should probably be left at this value */
306 @ Like the preceding parameters, the following quantities can be changed
307 at compile time to extend or reduce \MP's capacity. But if they are changed,
308 it is necessary to rerun the initialization program \.{INIMP}
310 to generate new tables for the production \MP\ program.
311 One can't simply make helter-skelter changes to the following constants,
312 since certain rather complex initialization
313 numbers are computed from them.
316 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
317 int pool_size; /* maximum number of characters in strings, including all
318 error messages and help texts, and the names of all identifiers */
319 int error_line; /* width of context lines on terminal error messages */
320 int half_error_line; /* width of first lines of contexts in terminal
321 error messages; should be between 30 and |error_line-15| */
322 int max_print_line; /* width of longest text lines output; should be at least 60 */
323 int mem_max; /* greatest index in \MP's internal |mem| array;
324 must be strictly less than |max_halfword|;
325 must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
326 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
327 must not be greater than |mem_max| */
328 int hash_size; /* maximum number of symbolic tokens,
329 must be less than |max_halfword-3*param_size| */
330 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
331 int param_size; /* maximum number of simultaneous macro parameters */
332 int max_in_open; /* maximum number of input files and error insertions that
333 can be going on simultaneously */
335 @ @<Option variables@>=
346 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
351 set_value(mp->error_line,opt->error_line,79);
352 set_value(mp->half_error_line,opt->half_error_line,50);
353 set_value(mp->max_print_line,opt->max_print_line,79);
356 set_value(mp->hash_size,opt->hash_size,9500);
357 set_value(mp->hash_prime,opt->hash_prime,7919);
358 set_value(mp->param_size,opt->param_size,150);
359 set_value(mp->max_in_open,opt->max_in_open,10);
362 @ In case somebody has inadvertently made bad settings of the ``constants,''
363 \MP\ checks them using a global variable called |bad|.
365 This is the first of many sections of \MP\ where global variables are
369 integer bad; /* is some ``constant'' wrong? */
371 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
372 or something similar. (We can't do that until |max_halfword| has been defined.)
374 @<Check the ``constant'' values for consistency@>=
376 if ( (mp->half_error_line<30)||(mp->half_error_line>mp->error_line-15) ) mp->bad=1;
377 if ( mp->max_print_line<60 ) mp->bad=2;
378 if ( mp->mem_top<=1100 ) mp->bad=4;
379 if (mp->hash_prime>mp->hash_size ) mp->bad=5;
381 @ Labels are given symbolic names by the following definitions, so that
382 occasional |goto| statements will be meaningful. We insert the label
383 `|exit|:' just before the `\ignorespaces|end|\unskip' of a procedure in
384 which we have used the `|return|' statement defined below; the label
385 `|restart|' is occasionally used at the very beginning of a procedure; and
386 the label `|reswitch|' is occasionally used just prior to a |case|
387 statement in which some cases change the conditions and we wish to branch
388 to the newly applicable case. Loops that are set up with the |loop|
389 construction defined below are commonly exited by going to `|done|' or to
390 `|found|' or to `|not_found|', and they are sometimes repeated by going to
391 `|continue|'. If two or more parts of a subroutine start differently but
392 end up the same, the shared code may be gathered together at
395 Incidentally, this program never declares a label that isn't actually used,
396 because some fussy \PASCAL\ compilers will complain about redundant labels.
398 @d label_exit 10 /* go here to leave a procedure */
399 @d restart 20 /* go here to start a procedure again */
400 @d reswitch 21 /* go here to start a case statement again */
401 @d continue 22 /* go here to resume a loop */
402 @d done 30 /* go here to exit a loop */
403 @d done1 31 /* like |done|, when there is more than one loop */
404 @d done2 32 /* for exiting the second loop in a long block */
405 @d done3 33 /* for exiting the third loop in a very long block */
406 @d done4 34 /* for exiting the fourth loop in an extremely long block */
407 @d done5 35 /* for exiting the fifth loop in an immense block */
408 @d done6 36 /* for exiting the sixth loop in a block */
409 @d found 40 /* go here when you've found it */
410 @d found1 41 /* like |found|, when there's more than one per routine */
411 @d found2 42 /* like |found|, when there's more than two per routine */
412 @d found3 43 /* like |found|, when there's more than three per routine */
413 @d not_found 45 /* go here when you've found nothing */
414 @d common_ending 50 /* go here when you want to merge with another branch */
416 @ Here are some macros for common programming idioms.
418 @d incr(A) (A)=(A)+1 /* increase a variable by unity */
419 @d decr(A) (A)=(A)-1 /* decrease a variable by unity */
420 @d negate(A) (A)=-(A) /* change the sign of a variable */
421 @d double(A) (A)=(A)+(A)
424 @d do_nothing /* empty statement */
425 @d Return goto exit /* terminate a procedure call */
426 @f return nil /* \.{WEB} will henceforth say |return| instead of \\{return} */
428 @* \[2] The character set.
429 In order to make \MP\ readily portable to a wide variety of
430 computers, all of its input text is converted to an internal eight-bit
431 code that includes standard ASCII, the ``American Standard Code for
432 Information Interchange.'' This conversion is done immediately when each
433 character is read in. Conversely, characters are converted from ASCII to
434 the user's external representation just before they are output to a
438 Such an internal code is relevant to users of \MP\ only with respect to
439 the \&{char} and \&{ASCII} operations, and the comparison of strings.
441 @ Characters of text that have been converted to \MP's internal form
442 are said to be of type |ASCII_code|, which is a subrange of the integers.
445 typedef unsigned char ASCII_code; /* eight-bit numbers */
447 @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
448 character sets were common, so it did not make provision for lowercase
449 letters. Nowadays, of course, we need to deal with both capital and small
450 letters in a convenient way, especially in a program for font design;
451 so the present specification of \MP\ has been written under the assumption
452 that the \PASCAL\ compiler and run-time system permit the use of text files
453 with more than 64 distinguishable characters. More precisely, we assume that
454 the character set contains at least the letters and symbols associated
455 with ASCII codes 040 through 0176; all of these characters are now
456 available on most computer terminals.
458 Since we are dealing with more characters than were present in the first
459 \PASCAL\ compilers, we have to decide what to call the associated data
460 type. Some \PASCAL s use the original name |char| for the
461 characters in text files, even though there now are more than 64 such
462 characters, while other \PASCAL s consider |char| to be a 64-element
463 subrange of a larger data type that has some other name.
465 In order to accommodate this difference, we shall use the name |text_char|
466 to stand for the data type of the characters that are converted to and
467 from |ASCII_code| when they are input and output. We shall also assume
468 that |text_char| consists of the elements |chr(first_text_char)| through
469 |chr(last_text_char)|, inclusive. The following definitions should be
470 adjusted if necessary.
471 @^system dependencies@>
473 @d first_text_char 0 /* ordinal number of the smallest element of |text_char| */
474 @d last_text_char 255 /* ordinal number of the largest element of |text_char| */
477 typedef unsigned char text_char; /* the data type of characters in text files */
479 @ @<Local variables for init...@>=
482 @ The \MP\ processor converts between ASCII code and
483 the user's external character set by means of arrays |xord| and |xchr|
484 that are analogous to \PASCAL's |ord| and |chr| functions.
486 @d xchr(A) mp->xchr[(A)]
487 @d xord(A) mp->xord[(A)]
490 ASCII_code xord[256]; /* specifies conversion of input characters */
491 text_char xchr[256]; /* specifies conversion of output characters */
493 @ The core system assumes all 8-bit is acceptable. If it is not,
494 a change file has to alter the below section.
495 @^system dependencies@>
497 Additionally, people with extended character sets can
498 assign codes arbitrarily, giving an |xchr| equivalent to whatever
499 characters the users of \MP\ are allowed to have in their input files.
500 Appropriate changes to \MP's |char_class| table should then be made.
501 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
502 codes, called the |char_class|.) Such changes make portability of programs
503 more difficult, so they should be introduced cautiously if at all.
504 @^character set dependencies@>
505 @^system dependencies@>
508 for (i=0;i<=0377;i++) { xchr(i)=i; }
510 @ The following system-independent code makes the |xord| array contain a
511 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
512 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
513 |j| or more; hence, standard ASCII code numbers will be used instead of
514 codes below 040 in case there is a coincidence.
517 for (i=first_text_char;i<=last_text_char;i++) {
520 for (i=0200;i<=0377;i++) { xord(xchr(i))=i;}
521 for (i=0;i<=0176;i++) { xord(xchr(i))=i;}
523 @* \[3] Input and output.
524 The bane of portability is the fact that different operating systems treat
525 input and output quite differently, perhaps because computer scientists
526 have not given sufficient attention to this problem. People have felt somehow
527 that input and output are not part of ``real'' programming. Well, it is true
528 that some kinds of programming are more fun than others. With existing
529 input/output conventions being so diverse and so messy, the only sources of
530 joy in such parts of the code are the rare occasions when one can find a
531 way to make the program a little less bad than it might have been. We have
532 two choices, either to attack I/O now and get it over with, or to postpone
533 I/O until near the end. Neither prospect is very attractive, so let's
536 The basic operations we need to do are (1)~inputting and outputting of
537 text, to or from a file or the user's terminal; (2)~inputting and
538 outputting of eight-bit bytes, to or from a file; (3)~instructing the
539 operating system to initiate (``open'') or to terminate (``close'') input or
540 output from a specified file; (4)~testing whether the end of an input
541 file has been reached; (5)~display of bits on the user's screen.
542 The bit-display operation will be discussed in a later section; we shall
543 deal here only with more traditional kinds of I/O.
545 @ Finding files happens in a slightly roundabout fashion: the \MP\
546 instance object contains a field that holds a function pointer that finds a
547 file, and returns its name, or NULL. For this, it receives three
548 parameters: the non-qualified name |fname|, the intended |fopen|
549 operation type |fmode|, and the type of the file |ftype|.
551 The file types that are passed on in |ftype| can be used to
552 differentiate file searches if a library like kpathsea is used,
553 the fopen mode is passed along for the same reason.
556 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
558 @ @<Exported types@>=
560 mp_filetype_program = 1, /* \MP\ language input */
561 mp_filetype_log, /* the log file */
562 mp_filetype_postscript, /* the postscript output */
563 mp_filetype_text, /* text files for readfrom and writeto primitives */
564 mp_filetype_memfile, /* memory dumps */
565 mp_filetype_metrics, /* TeX font metric files */
566 mp_filetype_fontmap, /* PostScript font mapping files */
567 mp_filetype_font, /* PostScript type1 font programs */
568 mp_filetype_encoding, /* PostScript font encoding files */
570 typedef char *(*mp_file_finder)(char *, char *, int);
573 mp_file_finder find_file;
575 @ @<Option variables@>=
576 mp_file_finder find_file;
578 @ The default function for finding files is |mp_find_file|. It is
579 pretty stupid: it will only find files in the current directory.
582 char *mp_find_file (char *fname, char *fmode, int ftype) {
583 if (fmode[0] != 'r' || access (fname,R_OK) || ftype)
584 return strdup(fname);
588 @ This has to be done very early on, so it is best to put it in with
589 the |mp_new| allocations
591 @d set_callback_option(A) do { mp->A = mp_##A;
592 if (opt->A!=NULL) mp->A = opt->A;
595 @<Allocate or initialize ...@>=
596 set_callback_option(find_file);
598 @ Because |mp_find_file| is used so early, it has to be in the helpers
602 char *mp_find_file (char *fname, char *fmode, int ftype) ;
604 @ The function to open files can now be very short.
607 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype) {
608 char *s = (mp->find_file)(fname,fmode,ftype);
610 FILE *f = fopen(s, fmode);
617 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
620 char name_of_file[file_name_size+1]; /* the name of a system file */
621 int name_length;/* this many characters are actually
622 relevant in |name_of_file| (the rest are blank) */
623 boolean print_found_names; /* configuration parameter */
625 @ @<Option variables@>=
626 int print_found_names; /* configuration parameter */
628 @ If this parameter is true, the terminal and log will report the found
629 file names for input files instead of the requested ones.
630 It is off by default because it creates an extra filename lookup.
632 @<Allocate or initialize ...@>=
633 mp->print_found_names = (opt->print_found_names>0 ? true : false);
635 @ \MP's file-opening procedures return |false| if no file identified by
636 |name_of_file| could be opened.
638 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
639 It is not used for opening a mem file for read, because that file name
643 if (mp->print_found_names) {
644 char *s = (mp->find_file)(mp->name_of_file,A,ftype);
646 *f = mp_open_file(mp,mp->name_of_file,A, ftype);
647 strncpy(mp->name_of_file,s,file_name_size);
653 *f = mp_open_file(mp,mp->name_of_file,A, ftype);
656 return (*f ? true : false)
659 boolean mp_a_open_in (MP mp, FILE **f, int ftype) {
660 /* open a text file for input */
664 boolean mp_w_open_in (MP mp, FILE **f) {
665 /* open a word file for input */
666 *f = mp_open_file(mp,mp->name_of_file,"rb",mp_filetype_memfile);
667 return (*f ? true : false);
670 boolean mp_a_open_out (MP mp, FILE **f, int ftype) {
671 /* open a text file for output */
675 boolean mp_b_open_out (MP mp, FILE **f, int ftype) {
676 /* open a binary file for output */
680 boolean mp_w_open_out (MP mp, FILE**f) {
681 /* open a word file for output */
682 int ftype = mp_filetype_memfile;
687 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype);
689 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
690 procedures, so we don't have to make any other special arrangements for
691 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
692 The treatment of text input is more difficult, however, because
693 of the necessary translation to |ASCII_code| values.
694 \MP's conventions should be efficient, and they should
695 blend nicely with the user's operating environment.
697 @ Input from text files is read one line at a time, using a routine called
698 |input_ln|. This function is defined in terms of global variables called
699 |buffer|, |first|, and |last| that will be described in detail later; for
700 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
701 values, and that |first| and |last| are indices into this array
702 representing the beginning and ending of a line of text.
705 size_t buf_size; /* maximum number of characters simultaneously present in
706 current lines of open files */
707 ASCII_code *buffer; /* lines of characters being read */
708 size_t first; /* the first unused position in |buffer| */
709 size_t last; /* end of the line just input to |buffer| */
710 size_t max_buf_stack; /* largest index used in |buffer| */
712 @ @<Allocate or initialize ...@>=
714 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
716 @ @<Dealloc variables@>=
720 void mp_reallocate_buffer(MP mp, size_t l) {
722 if (l>max_halfword) {
723 mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
725 buffer = xmalloc((l+1),sizeof(ASCII_code));
726 memcpy(buffer,mp->buffer,(mp->buf_size+1));
728 mp->buffer = buffer ;
732 @ The |input_ln| function brings the next line of input from the specified
733 field into available positions of the buffer array and returns the value
734 |true|, unless the file has already been entirely read, in which case it
735 returns |false| and sets |last:=first|. In general, the |ASCII_code|
736 numbers that represent the next line of the file are input into
737 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
738 global variable |last| is set equal to |first| plus the length of the
739 line. Trailing blanks are removed from the line; thus, either |last=first|
740 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
743 An overflow error is given, however, if the normal actions of |input_ln|
744 would make |last>=buf_size|; this is done so that other parts of \MP\
745 can safely look at the contents of |buffer[last+1]| without overstepping
746 the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
747 |first<buf_size| will always hold, so that there is always room for an
750 The variable |max_buf_stack|, which is used to keep track of how large
751 the |buf_size| parameter must be to accommodate the present job, is
752 also kept up to date by |input_ln|.
754 If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
755 before looking at the first character of the line; this skips over
756 an |eoln| that was in |f^|. The procedure does not do a |get| when it
757 reaches the end of the line; therefore it can be used to acquire input
758 from the user's terminal as well as from ordinary text files.
760 Standard \PASCAL\ says that a file should have |eoln| immediately
761 before |eof|, but \MP\ needs only a weaker restriction: If |eof|
762 occurs in the middle of a line, the system function |eoln| should return
763 a |true| result (even though |f^| will be undefined).
766 boolean mp_input_ln (MP mp,FILE * f, boolean bypass_eoln) {
767 /* inputs the next line or returns |false| */
768 int last_nonblank; /* |last| with trailing blanks removed */
774 if (c!='\n' && c!='\r') {
778 /* input the first character of the line into |f^| */
779 mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
783 last_nonblank=mp->first;
784 while (c!=EOF && c!='\n' && c!='\r') {
785 if ( mp->last>=mp->max_buf_stack ) {
786 mp->max_buf_stack=mp->last+1;
787 if ( mp->max_buf_stack==mp->buf_size ) {
788 mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
791 mp->buffer[mp->last]=xord(c);
793 if ( mp->buffer[mp->last-1]!=' ' )
794 last_nonblank=mp->last;
800 mp->last=last_nonblank;
804 @ The user's terminal acts essentially like other files of text, except
805 that it is used both for input and for output. When the terminal is
806 considered an input file, the file variable is called |term_in|, and when it
807 is considered an output file the file variable is |term_out|.
808 @^system dependencies@>
811 FILE * term_in; /* the terminal as an input file */
812 FILE * term_out; /* the terminal as an output file */
814 @ Here is how to open the terminal files. In the default configuration,
815 nothing happens except that the command line (if there is one) is copied
816 to the input buffer. The variable |command_line| will be filled by the
817 |main| procedure. The copying can not be done earlier in the program
818 logic because in the |INI| version, the |buffer| is also used for primitive
821 @^system dependencies@>
823 @d t_open_out /* open the terminal for text output */
824 @d t_open_in do { /* open the terminal for text input */
825 if (mp->command_line!=NULL) {
826 mp->last = strlen(mp->command_line);
827 strncpy((char *)mp->buffer,mp->command_line,mp->last);
828 xfree(mp->command_line);
835 @ @<Option variables@>=
838 @ @<Allocate or initialize ...@>=
839 mp->command_line = opt->command_line;
841 @ Sometimes it is necessary to synchronize the input/output mixture that
842 happens on the user's terminal, and three system-dependent
843 procedures are used for this
844 purpose. The first of these, |update_terminal|, is called when we want
845 to make sure that everything we have output to the terminal so far has
846 actually left the computer's internal buffers and been sent.
847 The second, |clear_terminal|, is called when we wish to cancel any
848 input that the user may have typed ahead (since we are about to
849 issue an unexpected error message). The third, |wake_up_terminal|,
850 is supposed to revive the terminal if the user has disabled it by
851 some instruction to the operating system. The following macros show how
852 these operations can be specified in \ph:
853 @^system dependencies@>
855 @d update_terminal fflush(mp->term_out) /* empty the terminal output buffer */
856 @d clear_terminal do_nothing /* clear the terminal input buffer */
857 @d wake_up_terminal fflush(mp->term_out) /* cancel the user's cancellation of output */
859 @ We need a special routine to read the first line of \MP\ input from
860 the user's terminal. This line is different because it is read before we
861 have opened the transcript file; there is sort of a ``chicken and
862 egg'' problem here. If the user types `\.{input cmr10}' on the first
863 line, or if some macro invoked by that line does such an \.{input},
864 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
865 commands are performed during the first line of terminal input, the transcript
866 file will acquire its default name `\.{mpout.log}'. (The transcript file
867 will not contain error messages generated by the first line before the
868 first \.{input} command.)
870 The first line is even more special if we are lucky enough to have an operating
871 system that treats \MP\ differently from a run-of-the-mill \PASCAL\ object
872 program. It's nice to let the user start running a \MP\ job by typing
873 a command line like `\.{MP cmr10}'; in such a case, \MP\ will operate
874 as if the first line of input were `\.{cmr10}', i.e., the first line will
875 consist of the remainder of the command line, after the part that invoked \MP.
877 @ Different systems have different ways to get started. But regardless of
878 what conventions are adopted, the routine that initializes the terminal
879 should satisfy the following specifications:
881 \yskip\textindent{1)}It should open file |term_in| for input from the
882 terminal. (The file |term_out| will already be open for output to the
885 \textindent{2)}If the user has given a command line, this line should be
886 considered the first line of terminal input. Otherwise the
887 user should be prompted with `\.{**}', and the first line of input
888 should be whatever is typed in response.
890 \textindent{3)}The first line of input, which might or might not be a
891 command line, should appear in locations |first| to |last-1| of the
894 \textindent{4)}The global variable |loc| should be set so that the
895 character to be read next by \MP\ is in |buffer[loc]|. This
896 character should not be blank, and we should have |loc<last|.
898 \yskip\noindent(It may be necessary to prompt the user several times
899 before a non-blank line comes in. The prompt is `\.{**}' instead of the
900 later `\.*' because the meaning is slightly different: `\.{input}' need
901 not be typed immediately after~`\.{**}'.)
903 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
905 @ The following program does the required initialization
906 without retrieving a possible command line.
907 It should be clear how to modify this routine to deal with command lines,
908 if the system permits them.
909 @^system dependencies@>
912 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
919 wake_up_terminal; fprintf(mp->term_out,"**"); update_terminal;
921 if ( ! mp_input_ln(mp, mp->term_in,true) ) { /* this shouldn't happen */
922 fprintf(mp->term_out,"\n! End of file on the terminal... why?");
923 @.End of file on the terminal@>
927 while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') )
929 if ( loc<(int)mp->last ) {
930 return true; /* return unless the line was all blank */
932 fprintf(mp->term_out,"Please type the name of your input file.\n");
937 boolean mp_init_terminal (MP mp) ;
940 @* \[4] String handling.
941 Symbolic token names and diagnostic messages are variable-length strings
942 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
943 mechanism, \MP\ does all of its string processing by homegrown methods.
945 \MP\ uses strings more extensively than \MF\ does, but the necessary
946 operations can still be handled with a fairly simple data structure.
947 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
948 of the strings, and the array |str_start| contains indices of the starting
949 points of each string. Strings are referred to by integer numbers, so that
950 string number |s| comprises the characters |str_pool[j]| for
951 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|. The string pool
952 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
953 location. The first string number not currently in use is |str_ptr|
954 and |next_str[str_ptr]| begins a list of free string numbers. String
955 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
956 string currently being constructed.
958 String numbers 0 to 255 are reserved for strings that correspond to single
959 ASCII characters. This is in accordance with the conventions of \.{WEB},
961 which converts single-character strings into the ASCII code number of the
962 single character involved, while it converts other strings into integers
963 and builds a string pool file. Thus, when the string constant \.{"."} appears
964 in the program below, \.{WEB} converts it into the integer 46, which is the
965 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
966 into some integer greater than~255. String number 46 will presumably be the
967 single character `\..'\thinspace; but some ASCII codes have no standard visible
968 representation, and \MP\ may need to be able to print an arbitrary
969 ASCII character, so the first 256 strings are used to specify exactly what
970 should be printed for each of the 256 possibilities.
973 typedef int pool_pointer; /* for variables that point into |str_pool| */
974 typedef int str_number; /* for variables that point into |str_start| */
977 ASCII_code *str_pool; /* the characters */
978 pool_pointer *str_start; /* the starting pointers */
979 str_number *next_str; /* for linking strings in order */
980 pool_pointer pool_ptr; /* first unused position in |str_pool| */
981 str_number str_ptr; /* number of the current string being created */
982 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
983 str_number init_str_use; /* the initial number of strings in use */
984 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
985 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
987 @ @<Allocate or initialize ...@>=
988 mp->str_pool = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
989 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
990 mp->next_str = xmalloc ((mp->max_strings+1),sizeof(str_number));
992 @ @<Dealloc variables@>=
994 xfree(mp->str_start);
997 @ Most printing is done from |char *|s, but sometimes not. Here are
998 functions that convert an internal string into a |char *| for use
999 by the printing routines, and vice versa.
1001 @d str(A) mp_str(mp,A)
1002 @d rts(A) mp_rts(mp,A)
1005 int mp_xstrcmp (const char *a, const char *b);
1006 char * mp_str (MP mp, str_number s);
1009 str_number mp_rts (MP mp, char *s);
1010 str_number mp_make_string (MP mp);
1012 @ The attempt to catch interrupted strings that is in |mp_rts|, is not
1013 very good: it does not handle nesting over more than one level.
1016 int mp_xstrcmp (const char *a, const char *b) {
1017 if (a==NULL && b==NULL)
1027 char * mp_str (MP mp, str_number ss) {
1030 if (ss==mp->str_ptr) {
1034 s = xmalloc(len+1,sizeof(char));
1035 strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1040 str_number mp_rts (MP mp, char *s) {
1041 int r; /* the new string */
1042 int old; /* a possible string in progress */
1046 } else if (strlen(s)==1) {
1050 str_room((integer)strlen(s));
1051 if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1052 old = mp_make_string(mp);
1057 r = mp_make_string(mp);
1059 str_room(length(old));
1060 while (i<length(old)) {
1061 append_char((mp->str_start[old]+i));
1063 mp_flush_string(mp,old);
1069 @ Except for |strs_used_up|, the following string statistics are only
1070 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1074 integer strs_used_up; /* strings in use or unused but not reclaimed */
1075 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1076 integer strs_in_use; /* total number of strings actually in use */
1077 integer max_pl_used; /* maximum |pool_in_use| so far */
1078 integer max_strs_used; /* maximum |strs_in_use| so far */
1080 @ Several of the elementary string operations are performed using \.{WEB}
1081 macros instead of \PASCAL\ procedures, because many of the
1082 operations are done quite frequently and we want to avoid the
1083 overhead of procedure calls. For example, here is
1084 a simple macro that computes the length of a string.
1087 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1089 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1091 @ The length of the current string is called |cur_length|. If we decide that
1092 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1093 |cur_length| becomes zero.
1095 @d cur_length (mp->pool_ptr - mp->str_start[mp->str_ptr])
1096 @d flush_cur_string mp->pool_ptr=mp->str_start[mp->str_ptr]
1098 @ Strings are created by appending character codes to |str_pool|.
1099 The |append_char| macro, defined here, does not check to see if the
1100 value of |pool_ptr| has gotten too high; this test is supposed to be
1101 made before |append_char| is used.
1103 To test if there is room to append |l| more characters to |str_pool|,
1104 we shall write |str_room(l)|, which tries to make sure there is enough room
1105 by compacting the string pool if necessary. If this does not work,
1106 |do_compaction| aborts \MP\ and gives an apologetic error message.
1108 @d append_char(A) /* put |ASCII_code| \# at the end of |str_pool| */
1109 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1111 @d str_room(A) /* make sure that the pool hasn't overflowed */
1112 { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1113 if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1114 else mp->max_pool_ptr=mp->pool_ptr+(A); }
1117 @ The following routine is similar to |str_room(1)| but it uses the
1118 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1119 string space is exhausted.
1121 @<Declare the procedure called |unit_str_room|@>=
1122 void mp_unit_str_room (MP mp);
1125 void mp_unit_str_room (MP mp) {
1126 if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1127 if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1130 @ \MP's string expressions are implemented in a brute-force way: Every
1131 new string or substring that is needed is simply copied into the string pool.
1132 Space is eventually reclaimed by a procedure called |do_compaction| with
1133 the aid of a simple system system of reference counts.
1134 @^reference counts@>
1136 The number of references to string number |s| will be |str_ref[s]|. The
1137 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1138 positive number of references; such strings will never be recycled. If
1139 a string is ever referred to more than 126 times, simultaneously, we
1140 put it in this category. Hence a single byte suffices to store each |str_ref|.
1142 @d max_str_ref 127 /* ``infinite'' number of references */
1143 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1149 @ @<Allocate or initialize ...@>=
1150 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1152 @ @<Dealloc variables@>=
1155 @ Here's what we do when a string reference disappears:
1157 @d delete_str_ref(A) {
1158 if ( mp->str_ref[(A)]<max_str_ref ) {
1159 if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]);
1160 else mp_flush_string(mp, (A));
1164 @<Declare the procedure called |flush_string|@>=
1165 void mp_flush_string (MP mp,str_number s) ;
1168 @ We can't flush the first set of static strings at all, so there
1169 is no point in trying
1172 void mp_flush_string (MP mp,str_number s) {
1174 mp->pool_in_use=mp->pool_in_use-length(s);
1175 decr(mp->strs_in_use);
1176 if ( mp->next_str[s]!=mp->str_ptr ) {
1180 decr(mp->strs_used_up);
1182 mp->pool_ptr=mp->str_start[mp->str_ptr];
1186 @ C literals cannot be simply added, they need to be set so they can't
1189 @d intern(A) mp_intern(mp,(A))
1192 str_number mp_intern (MP mp, char *s) {
1195 mp->str_ref[r] = max_str_ref;
1200 str_number mp_intern (MP mp, char *s);
1203 @ Once a sequence of characters has been appended to |str_pool|, it
1204 officially becomes a string when the function |make_string| is called.
1205 This function returns the identification number of the new string as its
1208 When getting the next unused string number from the linked list, we pretend
1210 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1211 are linked sequentially even though the |next_str| entries have not been
1212 initialized yet. We never allow |str_ptr| to reach |mp->max_strings|;
1213 |do_compaction| is responsible for making sure of this.
1216 @<Declare the procedure called |do_compaction|@>;
1217 @<Declare the procedure called |unit_str_room|@>;
1218 str_number mp_make_string (MP mp);
1221 str_number mp_make_string (MP mp) { /* current string enters the pool */
1222 str_number s; /* the new string */
1225 mp->str_ptr=mp->next_str[s];
1226 if ( mp->str_ptr>mp->max_str_ptr ) {
1227 if ( mp->str_ptr==mp->max_strings ) {
1229 mp_do_compaction(mp, 0);
1233 if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1234 @:this can't happen s}{\quad \.s@>
1236 mp->max_str_ptr=mp->str_ptr;
1237 mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1241 mp->str_start[mp->str_ptr]=mp->pool_ptr;
1242 incr(mp->strs_used_up);
1243 incr(mp->strs_in_use);
1244 mp->pool_in_use=mp->pool_in_use+length(s);
1245 if ( mp->pool_in_use>mp->max_pl_used )
1246 mp->max_pl_used=mp->pool_in_use;
1247 if ( mp->strs_in_use>mp->max_strs_used )
1248 mp->max_strs_used=mp->strs_in_use;
1252 @ The most interesting string operation is string pool compaction. The idea
1253 is to recover unused space in the |str_pool| array by recopying the strings
1254 to close the gaps created when some strings become unused. All string
1255 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1256 numbers after |str_ptr|. If this fails to free enough pool space we issue an
1257 |overflow| error unless |needed=mp->pool_size|. Calling |do_compaction|
1258 with |needed=mp->pool_size| supresses all overflow tests.
1260 The compaction process starts with |last_fixed_str| because all lower numbered
1261 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1264 str_number last_fixed_str; /* last permanently allocated string */
1265 str_number fixed_str_use; /* number of permanently allocated strings */
1267 @ @<Declare the procedure called |do_compaction|@>=
1268 void mp_do_compaction (MP mp, pool_pointer needed) ;
1271 void mp_do_compaction (MP mp, pool_pointer needed) {
1272 str_number str_use; /* a count of strings in use */
1273 str_number r,s,t; /* strings being manipulated */
1274 pool_pointer p,q; /* destination and source for copying string characters */
1275 @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1276 r=mp->last_fixed_str;
1279 while ( s!=mp->str_ptr ) {
1280 while ( mp->str_ref[s]==0 ) {
1281 @<Advance |s| and add the old |s| to the list of free string numbers;
1282 then |break| if |s=str_ptr|@>;
1284 r=s; s=mp->next_str[s];
1286 @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1287 after the end of the string@>;
1289 @<Move the current string back so that it starts at |p|@>;
1290 if ( needed<mp->pool_size ) {
1291 @<Make sure that there is room for another string with |needed| characters@>;
1293 @<Account for the compaction and make sure the statistics agree with the
1295 mp->strs_used_up=str_use;
1298 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1299 t=mp->next_str[mp->last_fixed_str];
1300 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1301 incr(mp->fixed_str_use);
1302 mp->last_fixed_str=t;
1305 str_use=mp->fixed_str_use
1307 @ Because of the way |flush_string| has been written, it should never be
1308 necessary to |break| here. The extra line of code seems worthwhile to
1309 preserve the generality of |do_compaction|.
1311 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1316 mp->next_str[t]=mp->next_str[mp->str_ptr];
1317 mp->next_str[mp->str_ptr]=t;
1318 if ( s==mp->str_ptr ) break;
1321 @ The string currently starts at |str_start[r]| and ends just before
1322 |str_start[s]|. We don't change |str_start[s]| because it might be needed
1323 to locate the next string.
1325 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1328 while ( q<mp->str_start[s] ) {
1329 mp->str_pool[p]=mp->str_pool[q];
1333 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated. When
1334 we do this, anything between them should be moved.
1336 @ @<Move the current string back so that it starts at |p|@>=
1337 q=mp->str_start[mp->str_ptr];
1338 mp->str_start[mp->str_ptr]=p;
1339 while ( q<mp->pool_ptr ) {
1340 mp->str_pool[p]=mp->str_pool[q];
1345 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1347 @<Make sure that there is room for another string with |needed| char...@>=
1348 if ( str_use>=mp->max_strings-1 )
1349 mp_reallocate_strings (mp,str_use);
1350 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1351 mp_reallocate_pool(mp, mp->pool_ptr+needed);
1352 mp->max_pool_ptr=mp->pool_ptr+needed;
1356 void mp_reallocate_strings (MP mp, str_number str_use) ;
1357 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1360 void mp_reallocate_strings (MP mp, str_number str_use) {
1361 while ( str_use>=mp->max_strings-1 ) {
1362 int l = mp->max_strings + (mp->max_strings>>2);
1363 XREALLOC (mp->str_ref, l, int);
1364 XREALLOC (mp->str_start, l, pool_pointer);
1365 XREALLOC (mp->next_str, l, str_number);
1366 mp->max_strings = l;
1369 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1370 while ( needed>mp->pool_size ) {
1371 int l = mp->pool_size + (mp->pool_size>>2);
1372 XREALLOC (mp->str_pool, l, ASCII_code);
1377 @ @<Account for the compaction and make sure the statistics agree with...@>=
1378 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1379 mp_confusion(mp, "string");
1380 @:this can't happen string}{\quad string@>
1381 incr(mp->pact_count);
1382 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1383 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1385 s=mp->str_ptr; t=str_use;
1386 while ( s<=mp->max_str_ptr ){
1387 if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1388 incr(t); s=mp->next_str[s];
1390 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1393 @ A few more global variables are needed to keep track of statistics when
1394 |stat| $\ldots$ |tats| blocks are not commented out.
1397 integer pact_count; /* number of string pool compactions so far */
1398 integer pact_chars; /* total number of characters moved during compactions */
1399 integer pact_strs; /* total number of strings moved during compactions */
1401 @ @<Initialize compaction statistics@>=
1406 @ The following subroutine compares string |s| with another string of the
1407 same length that appears in |buffer| starting at position |k|;
1408 the result is |true| if and only if the strings are equal.
1411 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1412 /* test equality of strings */
1413 pool_pointer j; /* running index */
1415 while ( j<str_stop(s) ) {
1416 if ( mp->str_pool[j++]!=mp->buffer[k++] )
1422 @ Here is a similar routine, but it compares two strings in the string pool,
1423 and it does not assume that they have the same length. If the first string
1424 is lexicographically greater than, less than, or equal to the second,
1425 the result is respectively positive, negative, or zero.
1428 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1429 /* test equality of strings */
1430 pool_pointer j,k; /* running indices */
1431 integer ls,lt; /* lengths */
1432 integer l; /* length remaining to test */
1433 ls=length(s); lt=length(t);
1434 if ( ls<=lt ) l=ls; else l=lt;
1435 j=mp->str_start[s]; k=mp->str_start[t];
1437 if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1438 return (mp->str_pool[j]-mp->str_pool[k]);
1445 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1446 and |str_ptr| are computed by the \.{INIMP} program, based in part
1447 on the information that \.{WEB} has output while processing \MP.
1452 void mp_get_strings_started (MP mp) {
1453 /* initializes the string pool,
1454 but returns |false| if something goes wrong */
1455 int k; /* small indices or counters */
1456 str_number g; /* a new string */
1457 mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1460 mp->pool_in_use=0; mp->strs_in_use=0;
1461 mp->max_pl_used=0; mp->max_strs_used=0;
1462 @<Initialize compaction statistics@>;
1464 @<Make the first 256 strings@>;
1465 g=mp_make_string(mp); /* string 256 == "" */
1466 mp->str_ref[g]=max_str_ref;
1467 mp->last_fixed_str=mp->str_ptr-1;
1468 mp->fixed_str_use=mp->str_ptr;
1473 void mp_get_strings_started (MP mp);
1475 @ The first 256 strings will consist of a single character only.
1477 @<Make the first 256...@>=
1478 for (k=0;k<=255;k++) {
1480 g=mp_make_string(mp);
1481 mp->str_ref[g]=max_str_ref;
1484 @ The first 128 strings will contain 95 standard ASCII characters, and the
1485 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1486 unless a system-dependent change is made here. Installations that have
1487 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1488 would like string 032 to be printed as the single character 032 instead
1489 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1490 even people with an extended character set will want to represent string
1491 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1492 to produce visible strings instead of tabs or line-feeds or carriage-returns
1493 or bell-rings or characters that are treated anomalously in text files.
1495 Unprintable characters of codes 128--255 are, similarly, rendered
1496 \.{\^\^80}--\.{\^\^ff}.
1498 The boolean expression defined here should be |true| unless \MP\ internal
1499 code number~|k| corresponds to a non-troublesome visible symbol in the
1500 local character set.
1501 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1502 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1504 @^character set dependencies@>
1505 @^system dependencies@>
1507 @<Character |k| cannot be printed@>=
1510 @* \[5] On-line and off-line printing.
1511 Messages that are sent to a user's terminal and to the transcript-log file
1512 are produced by several `|print|' procedures. These procedures will
1513 direct their output to a variety of places, based on the setting of
1514 the global variable |selector|, which has the following possible
1518 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1521 \hang |log_only|, prints only on the transcript file.
1523 \hang |term_only|, prints only on the terminal.
1525 \hang |no_print|, doesn't print at all. This is used only in rare cases
1526 before the transcript file is open.
1528 \hang |ps_file_only| prints only on the \ps\ output file.
1530 \hang |pseudo|, puts output into a cyclic buffer that is used
1531 by the |show_context| routine; when we get to that routine we shall discuss
1532 the reasoning behind this curious mode.
1534 \hang |new_string|, appends the output to the current string in the
1537 \hang |>=write_file| prints on one of the files used for the \&{write}
1538 @:write_}{\&{write} primitive@>
1542 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1543 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1544 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|. These
1545 relations are not used when |selector| could be |pseudo|, |new_string|,
1546 or |ps_file_only|. We need not check for unprintable characters when
1549 Four additional global variables, |tally|, |term_offset|, |file_offset|,
1550 and |ps_offset| record the number of characters that have been printed
1551 since they were most recently cleared to zero. We use |tally| to record
1552 the length of (possibly very long) stretches of printing; |term_offset|,
1553 |file_offset|, and |ps_offset|, on the other hand, keep track of how many
1554 characters have appeared so far on the current line that has been output
1555 to the terminal, the transcript file, or the \ps\ output file, respectively.
1557 @d new_string 0 /* printing is deflected to the string pool */
1558 @d ps_file_only 1 /* printing goes to the \ps\ output file */
1559 @d pseudo 2 /* special |selector| setting for |show_context| */
1560 @d no_print 3 /* |selector| setting that makes data disappear */
1561 @d term_only 4 /* printing is destined for the terminal only */
1562 @d log_only 5 /* printing is destined for the transcript file only */
1563 @d term_and_log 6 /* normal |selector| setting */
1564 @d write_file 7 /* first write file selector */
1567 FILE * log_file; /* transcript of \MP\ session */
1568 FILE * ps_file; /* the generic font output goes here */
1569 unsigned int selector; /* where to print a message */
1570 unsigned char dig[23]; /* digits in a number being output */
1571 integer tally; /* the number of characters recently printed */
1572 unsigned int term_offset;
1573 /* the number of characters on the current terminal line */
1574 unsigned int file_offset;
1575 /* the number of characters on the current file line */
1577 /* the number of characters on the current \ps\ file line */
1578 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1579 integer trick_count; /* threshold for pseudoprinting, explained later */
1580 integer first_count; /* another variable for pseudoprinting */
1582 @ @<Allocate or initialize ...@>=
1583 memset(mp->dig,0,23);
1584 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1586 @ @<Dealloc variables@>=
1587 xfree(mp->trick_buf);
1589 @ @<Initialize the output routines@>=
1590 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; mp->ps_offset=0;
1592 @ Macro abbreviations for output to the terminal and to the log file are
1593 defined here for convenience. Some systems need special conventions
1594 for terminal output, and it is possible to adhere to those conventions
1595 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1596 @^system dependencies@>
1598 @d wterm(A) fprintf(mp->term_out,"%s",(A))
1599 @d wterm_chr(A)fprintf(mp->term_out,"%c",(A))
1600 @d wterm_ln(A) fprintf(mp->term_out,"\n%s",(A))
1601 @d wterm_cr fprintf(mp->term_out,"\n")
1602 @d wlog(A) fprintf(mp->log_file,"%s",(A))
1603 @d wlog_chr(A) fprintf(mp->log_file,"%c",(A))
1604 @d wlog_ln(A) fprintf(mp->log_file,"\n%s",(A))
1605 @d wlog_cr fprintf(mp->log_file, "\n")
1606 @d wps(A) fprintf(mp->ps_file,"%s",(A))
1607 @d wps_chr(A) fprintf(mp->ps_file,"%c",(A))
1608 @d wps_ln(A) fprintf(mp->ps_file,,"\n%s",(A))
1609 @d wps_cr fprintf(mp->ps_file,"\n")
1611 @ To end a line of text output, we call |print_ln|. Cases |0..max_write_files|
1612 use an array |wr_file| that will be declared later.
1614 @d mp_print_text(A) mp_print_str(mp,text((A)))
1617 void mp_print_ln (MP mp);
1618 void mp_print_visible_char (MP mp, ASCII_code s);
1619 void mp_print_char (MP mp, ASCII_code k);
1620 void mp_print (MP mp, char *s);
1621 void mp_print_str (MP mp, str_number s);
1622 void mp_print_nl (MP mp, char *s);
1623 void mp_print_two (MP mp,scaled x, scaled y) ;
1624 void mp_print_scaled (MP mp,scaled s);
1626 @ @<Basic print...@>=
1627 void mp_print_ln (MP mp) { /* prints an end-of-line */
1628 switch (mp->selector) {
1631 mp->term_offset=0; mp->file_offset=0;
1634 wlog_cr; mp->file_offset=0;
1637 wterm_cr; mp->term_offset=0;
1640 wps_cr; mp->ps_offset=0;
1647 fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1649 } /* note that |tally| is not affected */
1651 @ The |print_visible_char| procedure sends one character to the desired
1652 destination, using the |xchr| array to map it into an external character
1653 compatible with |input_ln|. (It assumes that it is always called with
1654 a visible ASCII character.) All printing comes through |print_ln| or
1655 |print_char|, which ultimately calls |print_visible_char|, hence these
1656 routines are the ones that limit lines to at most |max_print_line| characters.
1657 But we must make an exception for the \ps\ output file since it is not safe
1658 to cut up lines arbitrarily in \ps.
1660 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1661 |do_compaction| and |do_compaction| can call the error routines. Actually,
1662 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1664 @<Basic printing...@>=
1665 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1666 switch (mp->selector) {
1668 wterm_chr(xchr(s)); wlog_chr(xchr(s));
1669 incr(mp->term_offset); incr(mp->file_offset);
1670 if ( mp->term_offset==(unsigned)mp->max_print_line ) {
1671 wterm_cr; mp->term_offset=0;
1673 if ( mp->file_offset==(unsigned)mp->max_print_line ) {
1674 wlog_cr; mp->file_offset=0;
1678 wlog_chr(xchr(s)); incr(mp->file_offset);
1679 if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1682 wterm_chr(xchr(s)); incr(mp->term_offset);
1683 if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1687 wps_cr; mp->ps_offset=0;
1689 wps_chr(xchr(s)); incr(mp->ps_offset);
1695 if ( mp->tally<mp->trick_count )
1696 mp->trick_buf[mp->tally % mp->error_line]=s;
1699 if ( mp->pool_ptr>=mp->max_pool_ptr ) {
1700 mp_unit_str_room(mp);
1701 if ( mp->pool_ptr>=mp->pool_size )
1702 goto DONE; /* drop characters if string space is full */
1707 fprintf(mp->wr_file[(mp->selector-write_file)],"%c",xchr(s));
1713 @ The |print_char| procedure sends one character to the desired destination.
1714 File names and string expressions might contain |ASCII_code| values that
1715 can't be printed using |print_visible_char|. These characters will be
1716 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1717 (This procedure assumes that it is safe to bypass all checks for unprintable
1718 characters when |selector| is in the range |0..max_write_files-1| or when
1719 |selector=ps_file_only|. In the former case the user might want to write
1720 unprintable characters, and in the latter case the \ps\ printing routines
1721 check their arguments themselves before calling |print_char| or |print|.)
1723 @d print_lc_hex(A) do { l=(A);
1724 mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1727 @<Basic printing...@>=
1728 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1729 int l; /* small index or counter */
1730 if ( mp->selector<pseudo || mp->selector>=write_file) {
1731 mp_print_visible_char(mp, k);
1732 } else if ( @<Character |k| cannot be printed@> ) {
1735 mp_print_visible_char(mp, k+0100);
1736 } else if ( k<0200 ) {
1737 mp_print_visible_char(mp, k-0100);
1739 print_lc_hex(k / 16);
1740 print_lc_hex(k % 16);
1743 mp_print_visible_char(mp, k);
1747 @ An entire string is output by calling |print|. Note that if we are outputting
1748 the single standard ASCII character \.c, we could call |print("c")|, since
1749 |"c"=99| is the number of a single-character string, as explained above. But
1750 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1751 routine when it knows that this is safe. (The present implementation
1752 assumes that it is always safe to print a visible ASCII character.)
1753 @^system dependencies@>
1756 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1759 mp_print_char(mp, ss[j]); incr(j);
1765 void mp_print (MP mp, char *ss) {
1766 mp_do_print(mp, ss, strlen(ss));
1768 void mp_print_str (MP mp, str_number s) {
1769 pool_pointer j; /* current character code position */
1770 if ( (s<0)||(s>mp->max_str_ptr) ) {
1771 mp_do_print(mp,"???",3); /* this can't happen */
1775 mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1779 @ Here is the very first thing that \MP\ prints: a headline that identifies
1780 the version number and base name. The |term_offset| variable is temporarily
1781 incorrect, but the discrepancy is not serious since we assume that the banner
1782 and mem identifier together will occupy at most |max_print_line|
1783 character positions.
1785 @<Initialize the output...@>=
1787 wterm (version_string);
1788 if (mp->mem_ident!=NULL)
1789 mp_print(mp,mp->mem_ident);
1793 @ The procedure |print_nl| is like |print|, but it makes sure that the
1794 string appears at the beginning of a new line.
1797 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1798 switch(mp->selector) {
1800 if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1803 if ( mp->file_offset>0 ) mp_print_ln(mp);
1806 if ( mp->term_offset>0 ) mp_print_ln(mp);
1809 if ( mp->ps_offset>0 ) mp_print_ln(mp);
1815 } /* there are no other cases */
1819 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1822 void mp_print_the_digs (MP mp, eight_bits k) {
1823 /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1825 decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1829 @ The following procedure, which prints out the decimal representation of a
1830 given integer |n|, has been written carefully so that it works properly
1831 if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
1832 to negative arguments, since such operations are not implemented consistently
1833 by all \PASCAL\ compilers.
1836 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1837 integer m; /* used to negate |n| in possibly dangerous cases */
1838 int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1840 mp_print_char(mp, '-');
1841 if ( n>-100000000 ) {
1844 m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1848 mp->dig[0]=0; incr(n);
1853 mp->dig[k]=n % 10; n=n / 10; incr(k);
1855 mp_print_the_digs(mp, k);
1859 void mp_print_int (MP mp,integer n);
1861 @ \MP\ also makes use of a trivial procedure to print two digits. The
1862 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1865 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1867 mp_print_char(mp, '0'+(n / 10));
1868 mp_print_char(mp, '0'+(n % 10));
1873 void mp_print_dd (MP mp,integer n);
1875 @ Here is a procedure that asks the user to type a line of input,
1876 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1877 The input is placed into locations |first| through |last-1| of the
1878 |buffer| array, and echoed on the transcript file if appropriate.
1880 This procedure is never called when |interaction<mp_scroll_mode|.
1882 @d prompt_input(A) do {
1883 wake_up_terminal; mp_print(mp, (A)); mp_term_input(mp);
1884 } while (0) /* prints a string and gets a line of input */
1887 void mp_term_input (MP mp) { /* gets a line from the terminal */
1888 size_t k; /* index into |buffer| */
1889 update_terminal; /* Now the user sees the prompt for sure */
1890 if (!mp_input_ln(mp, mp->term_in,true))
1891 mp_fatal_error(mp, "End of file on the terminal!");
1892 @.End of file on the terminal@>
1893 mp->term_offset=0; /* the user's line ended with \<\rm return> */
1894 decr(mp->selector); /* prepare to echo the input */
1895 if ( mp->last!=mp->first ) {
1896 for (k=mp->first;k<=mp->last-1;k++) {
1897 mp_print_char(mp, mp->buffer[k]);
1901 mp->buffer[mp->last]='%';
1902 incr(mp->selector); /* restore previous status */
1905 @* \[6] Reporting errors.
1906 When something anomalous is detected, \MP\ typically does something like this:
1907 $$\vbox{\halign{#\hfil\cr
1908 |print_err("Something anomalous has been detected");|\cr
1909 |help3("This is the first line of my offer to help.")|\cr
1910 |("This is the second line. I'm trying to")|\cr
1911 |("explain the best way for you to proceed.");|\cr
1913 A two-line help message would be given using |help2|, etc.; these informal
1914 helps should use simple vocabulary that complements the words used in the
1915 official error message that was printed. (Outside the U.S.A., the help
1916 messages should preferably be translated into the local vernacular. Each
1917 line of help is at most 60 characters long, in the present implementation,
1918 so that |max_print_line| will not be exceeded.)
1920 The |print_err| procedure supplies a `\.!' before the official message,
1921 and makes sure that the terminal is awake if a stop is going to occur.
1922 The |error| procedure supplies a `\..' after the official message, then it
1923 shows the location of the error; and if |interaction=error_stop_mode|,
1924 it also enters into a dialog with the user, during which time the help
1925 message may be printed.
1926 @^system dependencies@>
1928 @ The global variable |interaction| has four settings, representing increasing
1929 amounts of user interaction:
1932 enum mp_interaction_mode {
1933 mp_unspecified_mode=0, /* extra value for command-line switch */
1934 mp_batch_mode, /* omits all stops and omits terminal output */
1935 mp_nonstop_mode, /* omits all stops */
1936 mp_scroll_mode, /* omits error stops */
1937 mp_error_stop_mode, /* stops at every opportunity to interact */
1941 int interaction; /* current level of interaction */
1943 @ @<Option variables@>=
1944 int interaction; /* current level of interaction */
1946 @ Set it here so it can be overwritten by the commandline
1948 @<Allocate or initialize ...@>=
1949 mp->interaction=opt->interaction;
1950 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode)
1951 mp->interaction=mp_error_stop_mode;
1952 if (mp->interaction<mp_unspecified_mode)
1953 mp->interaction=mp_batch_mode;
1957 @d print_err(A) mp_print_err(mp,(A))
1960 void mp_print_err(MP mp, char * A);
1963 void mp_print_err(MP mp, char * A) {
1964 if ( mp->interaction==mp_error_stop_mode )
1966 mp_print_nl(mp, "! ");
1972 @ \MP\ is careful not to call |error| when the print |selector| setting
1973 might be unusual. The only possible values of |selector| at the time of
1976 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1977 and |log_file| not yet open);
1979 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1981 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1983 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1985 @<Initialize the print |selector| based on |interaction|@>=
1986 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1988 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1989 routine is active when |error| is called; this ensures that |get_next|
1990 will never be called recursively.
1993 The global variable |history| records the worst level of error that
1994 has been detected. It has four possible values: |spotless|, |warning_issued|,
1995 |error_message_issued|, and |fatal_error_stop|.
1997 Another global variable, |error_count|, is increased by one when an
1998 |error| occurs without an interactive dialog, and it is reset to zero at
1999 the end of every statement. If |error_count| reaches 100, \MP\ decides
2000 that there is no point in continuing further.
2003 enum mp_history_states {
2004 mp_spotless=0, /* |history| value when nothing has been amiss yet */
2005 mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
2006 mp_error_message_issued, /* |history| value when |error| has been called */
2007 mp_fatal_error_stop, /* |history| value when termination was premature */
2011 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2012 int history; /* has the source input been clean so far? */
2013 int error_count; /* the number of scrolled errors since the last statement ended */
2015 @ The value of |history| is initially |fatal_error_stop|, but it will
2016 be changed to |spotless| if \MP\ survives the initialization process.
2018 @<Allocate or ...@>=
2019 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
2021 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2022 error procedures near the beginning of the program. But the error procedures
2023 in turn use some other procedures, which need to be declared |forward|
2024 before we get to |error| itself.
2026 It is possible for |error| to be called recursively if some error arises
2027 when |get_next| is being used to delete a token, and/or if some fatal error
2028 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2030 is never more than two levels deep.
2033 void mp_get_next (MP mp);
2034 void mp_term_input (MP mp);
2035 void mp_show_context (MP mp);
2036 void mp_begin_file_reading (MP mp);
2037 void mp_open_log_file (MP mp);
2038 void mp_clear_for_error_prompt (MP mp);
2039 void mp_debug_help (MP mp);
2040 @<Declare the procedure called |flush_string|@>
2043 void mp_normalize_selector (MP mp);
2045 @ Individual lines of help are recorded in the array |help_line|, which
2046 contains entries in positions |0..(help_ptr-1)|. They should be printed
2047 in reverse order, i.e., with |help_line[0]| appearing last.
2049 @d hlp1(A) mp->help_line[0]=(A); }
2050 @d hlp2(A) mp->help_line[1]=(A); hlp1
2051 @d hlp3(A) mp->help_line[2]=(A); hlp2
2052 @d hlp4(A) mp->help_line[3]=(A); hlp3
2053 @d hlp5(A) mp->help_line[4]=(A); hlp4
2054 @d hlp6(A) mp->help_line[5]=(A); hlp5
2055 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2056 @d help1 { mp->help_ptr=1; hlp1 /* use this with one help line */
2057 @d help2 { mp->help_ptr=2; hlp2 /* use this with two help lines */
2058 @d help3 { mp->help_ptr=3; hlp3 /* use this with three help lines */
2059 @d help4 { mp->help_ptr=4; hlp4 /* use this with four help lines */
2060 @d help5 { mp->help_ptr=5; hlp5 /* use this with five help lines */
2061 @d help6 { mp->help_ptr=6; hlp6 /* use this with six help lines */
2064 char * help_line[6]; /* helps for the next |error| */
2065 unsigned int help_ptr; /* the number of help lines present */
2066 boolean use_err_help; /* should the |err_help| string be shown? */
2067 str_number err_help; /* a string set up by \&{errhelp} */
2068 str_number filename_template; /* a string set up by \&{filenametemplate} */
2070 @ @<Allocate or ...@>=
2071 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2073 @ The |jump_out| procedure just cuts across all active procedure levels and
2074 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2075 whole program. It is used when there is no recovery from a particular error.
2077 The program uses a |jump_buf| to handle this, this is initialized at three
2078 spots: the start of |mp_new|, the start of |mp_initialize|, and the start
2079 of |mp_run|. Those are the only library enty points.
2081 @^system dependencies@>
2086 @ @<Install and test the non-local jump buffer@>=
2087 if (setjmp(mp->jump_buf) != 0) return mp->history;
2089 @ @<Setup the non-local jump buffer in |mp_new|@>=
2090 if (setjmp(mp->jump_buf) != 0) return NULL;
2092 @ If |mp->internal| is zero, then a crash occured during initialization,
2093 and it is not safe to run |mp_close_files_and_terminate|.
2096 void mp_jump_out (MP mp) {
2097 if(mp->internal!=NULL)
2098 mp_close_files_and_terminate(mp);
2099 longjmp(mp->jump_buf,1);
2102 @ Here now is the general |error| routine.
2105 void mp_error (MP mp) { /* completes the job of error reporting */
2106 ASCII_code c; /* what the user types */
2107 integer s1,s2,s3; /* used to save global variables when deleting tokens */
2108 pool_pointer j; /* character position being printed */
2109 if ( mp->history<mp_error_message_issued ) mp->history=mp_error_message_issued;
2110 mp_print_char(mp, '.'); mp_show_context(mp);
2111 if ( mp->interaction==mp_error_stop_mode ) {
2112 @<Get user's advice and |return|@>;
2114 incr(mp->error_count);
2115 if ( mp->error_count==100 ) {
2116 mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2117 @.That makes 100 errors...@>
2118 mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2120 @<Put help message on the transcript file@>;
2122 void mp_warn (MP mp, char *msg) {
2123 int saved_selector = mp->selector;
2124 mp_normalize_selector(mp);
2125 mp_print_nl(mp,"Warning: ");
2127 mp->selector = saved_selector;
2130 @ @<Exported function ...@>=
2131 void mp_error (MP mp);
2132 void mp_warn (MP mp, char *msg);
2135 @ @<Get user's advice...@>=
2138 mp_clear_for_error_prompt(mp); prompt_input("? ");
2140 if ( mp->last==mp->first ) return;
2141 c=mp->buffer[mp->first];
2142 if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2143 @<Interpret code |c| and |return| if done@>;
2146 @ It is desirable to provide an `\.E' option here that gives the user
2147 an easy way to return from \MP\ to the system editor, with the offending
2148 line ready to be edited. But such an extension requires some system
2149 wizardry, so the present implementation simply types out the name of the
2151 edited and the relevant line number.
2152 @^system dependencies@>
2155 typedef void (*mp_run_editor_command)(MP, char *, int);
2158 mp_run_editor_command run_editor;
2160 @ @<Option variables@>=
2161 mp_run_editor_command run_editor;
2163 @ @<Allocate or initialize ...@>=
2164 set_callback_option(run_editor);
2167 void mp_run_editor (MP mp, char *fname, int fline);
2169 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2170 mp_print_nl(mp, "You want to edit file ");
2171 @.You want to edit file x@>
2172 mp_print(mp, fname);
2173 mp_print(mp, " at line ");
2174 mp_print_int(mp, fline);
2175 mp->interaction=mp_scroll_mode;
2180 There is a secret `\.D' option available when the debugging routines haven't
2184 @<Interpret code |c| and |return| if done@>=
2186 case '0': case '1': case '2': case '3': case '4':
2187 case '5': case '6': case '7': case '8': case '9':
2188 if ( mp->deletions_allowed ) {
2189 @<Delete |c-"0"| tokens and |continue|@>;
2194 mp_debug_help(mp); continue;
2198 if ( mp->file_ptr>0 ){
2199 (mp->run_editor)(mp,
2200 str(mp->input_stack[mp->file_ptr].name_field),
2205 @<Print the help information and |continue|@>;
2208 @<Introduce new material from the terminal and |return|@>;
2210 case 'Q': case 'R': case 'S':
2211 @<Change the interaction level and |return|@>;
2214 mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2219 @<Print the menu of available options@>
2221 @ @<Print the menu...@>=
2223 mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2224 @.Type <return> to proceed...@>
2225 mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2226 mp_print_nl(mp, "I to insert something, ");
2227 if ( mp->file_ptr>0 )
2228 mp_print(mp, "E to edit your file,");
2229 if ( mp->deletions_allowed )
2230 mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2231 mp_print_nl(mp, "H for help, X to quit.");
2234 @ Here the author of \MP\ apologizes for making use of the numerical
2235 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2236 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2237 @^Knuth, Donald Ervin@>
2239 @<Change the interaction...@>=
2241 mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2242 mp_print(mp, "OK, entering ");
2244 case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2245 case 'R': mp_print(mp, "nonstopmode"); break;
2246 case 'S': mp_print(mp, "scrollmode"); break;
2247 } /* there are no other cases */
2248 mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2251 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2252 contain the material inserted by the user; otherwise another prompt will
2253 be given. In order to understand this part of the program fully, you need
2254 to be familiar with \MP's input stacks.
2256 @<Introduce new material...@>=
2258 mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2259 if ( mp->last>mp->first+1 ) {
2260 loc=mp->first+1; mp->buffer[mp->first]=' ';
2262 prompt_input("insert>"); loc=mp->first;
2265 mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2268 @ We allow deletion of up to 99 tokens at a time.
2270 @<Delete |c-"0"| tokens...@>=
2272 s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2273 if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2274 c=c*10+mp->buffer[mp->first+1]-'0'*11;
2278 mp_get_next(mp); /* one-level recursive call of |error| is possible */
2279 @<Decrease the string reference count, if the current token is a string@>;
2282 mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2283 help2("I have just deleted some text, as you asked.")
2284 ("You can now delete more, or insert, or whatever.");
2285 mp_show_context(mp);
2289 @ @<Print the help info...@>=
2291 if ( mp->use_err_help ) {
2292 @<Print the string |err_help|, possibly on several lines@>;
2293 mp->use_err_help=false;
2295 if ( mp->help_ptr==0 ) {
2296 help2("Sorry, I don't know how to help in this situation.")
2297 ("Maybe you should try asking a human?");
2300 decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2301 } while (mp->help_ptr!=0);
2303 help4("Sorry, I already gave what help I could...")
2304 ("Maybe you should try asking a human?")
2305 ("An error might have occurred before I noticed any problems.")
2306 ("``If all else fails, read the instructions.''");
2310 @ @<Print the string |err_help|, possibly on several lines@>=
2311 j=mp->str_start[mp->err_help];
2312 while ( j<str_stop(mp->err_help) ) {
2313 if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2314 else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2315 else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2316 else { incr(j); mp_print_char(mp, '%'); };
2320 @ @<Put help message on the transcript file@>=
2321 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2322 if ( mp->use_err_help ) {
2323 mp_print_nl(mp, "");
2324 @<Print the string |err_help|, possibly on several lines@>;
2326 while ( mp->help_ptr>0 ){
2327 decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2331 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2334 @ In anomalous cases, the print selector might be in an unknown state;
2335 the following subroutine is called to fix things just enough to keep
2336 running a bit longer.
2339 void mp_normalize_selector (MP mp) {
2340 if ( mp->log_opened ) mp->selector=term_and_log;
2341 else mp->selector=term_only;
2342 if ( mp->job_name==NULL ) mp_open_log_file(mp);
2343 if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2346 @ The following procedure prints \MP's last words before dying.
2348 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2349 mp->interaction=mp_scroll_mode; /* no more interaction */
2350 if ( mp->log_opened ) mp_error(mp);
2351 /* if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); */
2352 mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2356 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2357 mp_normalize_selector(mp);
2358 print_err("Emergency stop"); help1(s); succumb;
2362 @ @<Exported function ...@>=
2363 void mp_fatal_error (MP mp, char *s);
2366 @ Here is the most dreaded error message.
2369 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2370 mp_normalize_selector(mp);
2371 print_err("MetaPost capacity exceeded, sorry [");
2372 @.MetaPost capacity exceeded ...@>
2373 mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2374 help2("If you really absolutely need more capacity,")
2375 ("you can ask a wizard to enlarge me.");
2380 void mp_overflow (MP mp, char *s, integer n);
2382 @ The program might sometime run completely amok, at which point there is
2383 no choice but to stop. If no previous error has been detected, that's bad
2384 news; a message is printed that is really intended for the \MP\
2385 maintenance person instead of the user (unless the user has been
2386 particularly diabolical). The index entries for `this can't happen' may
2387 help to pinpoint the problem.
2390 @<Internal library ...@>=
2391 void mp_confusion (MP mp,char *s);
2393 @ @<Error hand...@>=
2394 void mp_confusion (MP mp,char *s) {
2395 /* consistency check violated; |s| tells where */
2396 mp_normalize_selector(mp);
2397 if ( mp->history<mp_error_message_issued ) {
2398 print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2399 @.This can't happen@>
2400 help1("I'm broken. Please show this to someone who can fix can fix");
2402 print_err("I can\'t go on meeting you like this");
2403 @.I can't go on...@>
2404 help2("One of your faux pas seems to have wounded me deeply...")
2405 ("in fact, I'm barely conscious. Please fix it and try again.");
2410 @ Users occasionally want to interrupt \MP\ while it's running.
2411 If the \PASCAL\ runtime system allows this, one can implement
2412 a routine that sets the global variable |interrupt| to some nonzero value
2413 when such an interrupt is signaled. Otherwise there is probably at least
2414 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2415 @^system dependencies@>
2418 @d check_interrupt { if ( mp->interrupt!=0 )
2419 mp_pause_for_instructions(mp); }
2422 integer interrupt; /* should \MP\ pause for instructions? */
2423 boolean OK_to_interrupt; /* should interrupts be observed? */
2425 @ @<Allocate or ...@>=
2426 mp->interrupt=0; mp->OK_to_interrupt=true;
2428 @ When an interrupt has been detected, the program goes into its
2429 highest interaction level and lets the user have the full flexibility of
2430 the |error| routine. \MP\ checks for interrupts only at times when it is
2434 void mp_pause_for_instructions (MP mp) {
2435 if ( mp->OK_to_interrupt ) {
2436 mp->interaction=mp_error_stop_mode;
2437 if ( (mp->selector==log_only)||(mp->selector==no_print) )
2439 print_err("Interruption");
2442 ("Try to insert some instructions for me (e.g.,`I show x'),")
2443 ("unless you just want to quit by typing `X'.");
2444 mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2449 @ Many of \MP's error messages state that a missing token has been
2450 inserted behind the scenes. We can save string space and program space
2451 by putting this common code into a subroutine.
2454 void mp_missing_err (MP mp, char *s) {
2455 print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2456 @.Missing...inserted@>
2459 @* \[7] Arithmetic with scaled numbers.
2460 The principal computations performed by \MP\ are done entirely in terms of
2461 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2462 program can be carried out in exactly the same way on a wide variety of
2463 computers, including some small ones.
2466 But \PASCAL\ does not define the |div|
2467 operation in the case of negative dividends; for example, the result of
2468 |(-2*n-1) div 2| is |-(n+1)| on some computers and |-n| on others.
2469 There are two principal types of arithmetic: ``translation-preserving,''
2470 in which the identity |(a+q*b)div b=(a div b)+q| is valid; and
2471 ``negation-preserving,'' in which |(-a)div b=-(a div b)|. This leads to
2472 two \MP s, which can produce different results, although the differences
2473 should be negligible when the language is being used properly.
2474 The \TeX\ processor has been defined carefully so that both varieties
2475 of arithmetic will produce identical output, but it would be too
2476 inefficient to constrain \MP\ in a similar way.
2478 @d el_gordo 017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2480 @ One of \MP's most common operations is the calculation of
2481 $\lfloor{a+b\over2}\rfloor$,
2482 the midpoint of two given integers |a| and~|b|. The only decent way to do
2483 this in \PASCAL\ is to write `|(a+b) div 2|'; but on most machines it is
2484 far more efficient to calculate `|(a+b)| right shifted one bit'.
2486 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2487 in this program. If \MP\ is being implemented with languages that permit
2488 binary shifting, the |half| macro should be changed to make this operation
2489 as efficient as possible. Since some languages have shift operators that can
2490 only be trusted to work on positive numbers, there is also a macro |halfp|
2491 that is used only when the quantity being halved is known to be positive
2494 @d half(A) ((A) / 2)
2495 @d halfp(A) ((A) / 2)
2497 @ A single computation might use several subroutine calls, and it is
2498 desirable to avoid producing multiple error messages in case of arithmetic
2499 overflow. So the routines below set the global variable |arith_error| to |true|
2500 instead of reporting errors directly to the user.
2503 boolean arith_error; /* has arithmetic overflow occurred recently? */
2505 @ @<Allocate or ...@>=
2506 mp->arith_error=false;
2508 @ At crucial points the program will say |check_arith|, to test if
2509 an arithmetic error has been detected.
2511 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2514 void mp_clear_arith (MP mp) {
2515 print_err("Arithmetic overflow");
2516 @.Arithmetic overflow@>
2517 help4("Uh, oh. A little while ago one of the quantities that I was")
2518 ("computing got too large, so I'm afraid your answers will be")
2519 ("somewhat askew. You'll probably have to adopt different")
2520 ("tactics next time. But I shall try to carry on anyway.");
2522 mp->arith_error=false;
2525 @ Addition is not always checked to make sure that it doesn't overflow,
2526 but in places where overflow isn't too unlikely the |slow_add| routine
2529 @c integer mp_slow_add (MP mp,integer x, integer y) {
2531 if ( y<=el_gordo-x ) {
2534 mp->arith_error=true;
2537 } else if ( -y<=el_gordo+x ) {
2540 mp->arith_error=true;
2545 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2546 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2547 positions from the right end of a binary computer word.
2549 @d quarter_unit 040000 /* $2^{14}$, represents 0.250000 */
2550 @d half_unit 0100000 /* $2^{15}$, represents 0.50000 */
2551 @d three_quarter_unit 0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2552 @d unity 0200000 /* $2^{16}$, represents 1.00000 */
2553 @d two 0400000 /* $2^{17}$, represents 2.00000 */
2554 @d three 0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2557 typedef integer scaled; /* this type is used for scaled integers */
2558 typedef unsigned char small_number; /* this type is self-explanatory */
2560 @ The following function is used to create a scaled integer from a given decimal
2561 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2562 given in |dig[i]|, and the calculation produces a correctly rounded result.
2565 scaled mp_round_decimals (MP mp,small_number k) {
2566 /* converts a decimal fraction */
2567 integer a = 0; /* the accumulator */
2569 a=(a+mp->dig[k]*two) / 10;
2574 @ Conversely, here is a procedure analogous to |print_int|. If the output
2575 of this procedure is subsequently read by \MP\ and converted by the
2576 |round_decimals| routine above, it turns out that the original value will
2577 be reproduced exactly. A decimal point is printed only if the value is
2578 not an integer. If there is more than one way to print the result with
2579 the optimum number of digits following the decimal point, the closest
2580 possible value is given.
2582 The invariant relation in the \&{repeat} loop is that a sequence of
2583 decimal digits yet to be printed will yield the original number if and only if
2584 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2585 We can stop if and only if $f=0$ satisfies this condition; the loop will
2586 terminate before $s$ can possibly become zero.
2588 @<Basic printing...@>=
2589 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five digits */
2590 scaled delta; /* amount of allowable inaccuracy */
2592 mp_print_char(mp, '-');
2593 negate(s); /* print the sign, if negative */
2595 mp_print_int(mp, s / unity); /* print the integer part */
2599 mp_print_char(mp, '.');
2602 s=s+0100000-(delta / 2); /* round the final digit */
2603 mp_print_char(mp, '0'+(s / unity));
2610 @ We often want to print two scaled quantities in parentheses,
2611 separated by a comma.
2613 @<Basic printing...@>=
2614 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2615 mp_print_char(mp, '(');
2616 mp_print_scaled(mp, x);
2617 mp_print_char(mp, ',');
2618 mp_print_scaled(mp, y);
2619 mp_print_char(mp, ')');
2622 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2623 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2624 arithmetic with 28~significant bits of precision. A |fraction| denotes
2625 a scaled integer whose binary point is assumed to be 28 bit positions
2628 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2629 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2630 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2631 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2632 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2635 typedef integer fraction; /* this type is used for scaled fractions */
2637 @ In fact, the two sorts of scaling discussed above aren't quite
2638 sufficient; \MP\ has yet another, used internally to keep track of angles
2639 in units of $2^{-20}$ degrees.
2641 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2642 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2643 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2644 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2647 typedef integer angle; /* this type is used for scaled angles */
2649 @ The |make_fraction| routine produces the |fraction| equivalent of
2650 |p/q|, given integers |p| and~|q|; it computes the integer
2651 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2652 positive. If |p| and |q| are both of the same scaled type |t|,
2653 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2654 and it's also possible to use the subroutine ``backwards,'' using
2655 the relation |make_fraction(t,fraction)=t| between scaled types.
2657 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2658 sets |arith_error:=true|. Most of \MP's internal computations have
2659 been designed to avoid this sort of error.
2661 If this subroutine were programmed in assembly language on a typical
2662 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2663 double-precision product can often be input to a fixed-point division
2664 instruction. But when we are restricted to \PASCAL\ arithmetic it
2665 is necessary either to resort to multiple-precision maneuvering
2666 or to use a simple but slow iteration. The multiple-precision technique
2667 would be about three times faster than the code adopted here, but it
2668 would be comparatively long and tricky, involving about sixteen
2669 additional multiplications and divisions.
2671 This operation is part of \MP's ``inner loop''; indeed, it will
2672 consume nearly 10\pct! of the running time (exclusive of input and output)
2673 if the code below is left unchanged. A machine-dependent recoding
2674 will therefore make \MP\ run faster. The present implementation
2675 is highly portable, but slow; it avoids multiplication and division
2676 except in the initial stage. System wizards should be careful to
2677 replace it with a routine that is guaranteed to produce identical
2678 results in all cases.
2679 @^system dependencies@>
2681 As noted below, a few more routines should also be replaced by machine-dependent
2682 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2683 such changes aren't advisable; simplicity and robustness are
2684 preferable to trickery, unless the cost is too high.
2688 fraction mp_make_fraction (MP mp,integer p, integer q);
2689 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2691 @ If FIXPT is not defined, we need these preprocessor values
2693 @d ELGORDO 0x7fffffff
2694 @d TWEXP31 2147483648.0
2695 @d TWEXP28 268435456.0
2697 @d TWEXP_16 (1.0/65536.0)
2698 @d TWEXP_28 (1.0/268435456.0)
2702 fraction mp_make_fraction (MP mp,integer p, integer q) {
2704 integer f; /* the fraction bits, with a leading 1 bit */
2705 integer n; /* the integer part of $\vert p/q\vert$ */
2706 integer be_careful; /* disables certain compiler optimizations */
2707 boolean negative = false; /* should the result be negated? */
2709 negate(p); negative=true;
2713 if ( q==0 ) mp_confusion(mp, '/');
2715 @:this can't happen /}{\quad \./@>
2716 negate(q); negative = ! negative;
2720 mp->arith_error=true;
2721 return ( negative ? -el_gordo : el_gordo);
2723 n=(n-1)*fraction_one;
2724 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2725 return (negative ? (-(f+n)) : (f+n));
2731 if (q==0) mp_confusion(mp,'/');
2733 d = TWEXP28 * (double)p /(double)q;
2736 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2738 if (d==i && ( ((q>0 ? -q : q)&077777)
2739 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2742 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2744 if (d==i && ( ((q>0 ? q : -q)&077777)
2745 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2751 @ The |repeat| loop here preserves the following invariant relations
2752 between |f|, |p|, and~|q|:
2753 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2754 $p_0$ is the original value of~$p$.
2756 Notice that the computation specifies
2757 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2758 Let us hope that optimizing compilers do not miss this point; a
2759 special variable |be_careful| is used to emphasize the necessary
2760 order of computation. Optimizing compilers should keep |be_careful|
2761 in a register, not store it in memory.
2764 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2768 be_careful=p-q; p=be_careful+p;
2774 } while (f<fraction_one);
2776 if ( be_careful+p>=0 ) incr(f);
2779 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2780 given integer~|q| by a fraction~|f|. When the operands are positive, it
2781 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2784 This routine is even more ``inner loopy'' than |make_fraction|;
2785 the present implementation consumes almost 20\pct! of \MP's computation
2786 time during typical jobs, so a machine-language substitute is advisable.
2787 @^inner loop@> @^system dependencies@>
2790 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2794 integer mp_take_fraction (MP mp,integer q, fraction f) {
2795 integer p; /* the fraction so far */
2796 boolean negative; /* should the result be negated? */
2797 integer n; /* additional multiple of $q$ */
2798 integer be_careful; /* disables certain compiler optimizations */
2799 @<Reduce to the case that |f>=0| and |q>0|@>;
2800 if ( f<fraction_one ) {
2803 n=f / fraction_one; f=f % fraction_one;
2804 if ( q<=el_gordo / n ) {
2807 mp->arith_error=true; n=el_gordo;
2811 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2812 be_careful=n-el_gordo;
2813 if ( be_careful+p>0 ){
2814 mp->arith_error=true; n=el_gordo-p;
2821 integer mp_take_fraction (MP mp,integer p, fraction q) {
2824 d = (double)p * (double)q * TWEXP_28;
2828 if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2829 mp->arith_error = true;
2833 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2837 if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2838 mp->arith_error = true;
2842 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2848 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2852 negate( f); negative=true;
2855 negate(q); negative=! negative;
2858 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2859 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2860 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2863 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2864 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2865 if ( q<fraction_four ) {
2867 if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2872 if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2878 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2879 analogous to |take_fraction| but with a different scaling.
2880 Given positive operands, |take_scaled|
2881 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2883 Once again it is a good idea to use a machine-language replacement if
2884 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2885 when the Computer Modern fonts are being generated.
2890 integer mp_take_scaled (MP mp,integer q, scaled f) {
2891 integer p; /* the fraction so far */
2892 boolean negative; /* should the result be negated? */
2893 integer n; /* additional multiple of $q$ */
2894 integer be_careful; /* disables certain compiler optimizations */
2895 @<Reduce to the case that |f>=0| and |q>0|@>;
2899 n=f / unity; f=f % unity;
2900 if ( q<=el_gordo / n ) {
2903 mp->arith_error=true; n=el_gordo;
2907 @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2908 be_careful=n-el_gordo;
2909 if ( be_careful+p>0 ) {
2910 mp->arith_error=true; n=el_gordo-p;
2912 return ( negative ?(-(n+p)) :(n+p));
2914 integer mp_take_scaled (MP mp,integer p, scaled q) {
2917 d = (double)p * (double)q * TWEXP_16;
2921 if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2922 mp->arith_error = true;
2926 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2930 if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2931 mp->arith_error = true;
2935 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2941 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2942 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2944 if ( q<fraction_four ) {
2946 p = (odd(f) ? halfp(p+q) : halfp(p));
2951 p = (odd(f) ? p+halfp(q-p) : halfp(p));
2956 @ For completeness, there's also |make_scaled|, which computes a
2957 quotient as a |scaled| number instead of as a |fraction|.
2958 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2959 operands are positive. \ (This procedure is not used especially often,
2960 so it is not part of \MP's inner loop.)
2962 @<Internal library ...@>=
2963 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2966 scaled mp_make_scaled (MP mp,integer p, integer q) {
2968 integer f; /* the fraction bits, with a leading 1 bit */
2969 integer n; /* the integer part of $\vert p/q\vert$ */
2970 boolean negative; /* should the result be negated? */
2971 integer be_careful; /* disables certain compiler optimizations */
2972 if ( p>=0 ) negative=false;
2973 else { negate(p); negative=true; };
2976 if ( q==0 ) mp_confusion(mp, "/");
2977 @:this can't happen /}{\quad \./@>
2979 negate(q); negative=! negative;
2983 mp->arith_error=true;
2984 return (negative ? (-el_gordo) : el_gordo);
2987 @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2988 return ( negative ? (-(f+n)) :(f+n));
2994 if (q==0) mp_confusion(mp,"/");
2996 d = TWEXP16 * (double)p /(double)q;
2999 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
3001 if (d==i && ( ((q>0 ? -q : q)&077777)
3002 * (((i&037777)<<1)-1) & 04000)!=0) --i;
3005 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
3007 if (d==i && ( ((q>0 ? q : -q)&077777)
3008 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
3014 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
3017 be_careful=p-q; p=be_careful+p;
3018 if ( p>=0 ) f=f+f+1;
3019 else { f+=f; p=p+q; };
3022 if ( be_careful+p>=0 ) incr(f)
3024 @ Here is a typical example of how the routines above can be used.
3025 It computes the function
3026 $${1\over3\tau}f(\theta,\phi)=
3027 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3028 (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3029 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3030 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3031 fudge factor for placing the first control point of a curve that starts
3032 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3033 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3035 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3036 (It's a sum of eight terms whose absolute values can be bounded using
3037 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3038 is positive; and since the tension $\tau$ is constrained to be at least
3039 $3\over4$, the numerator is less than $16\over3$. The denominator is
3040 nonnegative and at most~6. Hence the fixed-point calculations below
3041 are guaranteed to stay within the bounds of a 32-bit computer word.
3043 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3044 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3045 $\sin\phi$, and $\cos\phi$, respectively.
3048 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3049 fraction cf, scaled t) {
3050 integer acc,num,denom; /* registers for intermediate calculations */
3051 acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3052 acc=mp_take_fraction(mp, acc,ct-cf);
3053 num=fraction_two+mp_take_fraction(mp, acc,379625062);
3054 /* $2^{28}\sqrt2\approx379625062.497$ */
3055 denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3056 /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3057 $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3058 if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3059 /* |make_scaled(fraction,scaled)=fraction| */
3060 if ( num / 4>=denom )
3061 return fraction_four;
3063 return mp_make_fraction(mp, num, denom);
3066 @ The following somewhat different subroutine tests rigorously if $ab$ is
3067 greater than, equal to, or less than~$cd$,
3068 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3069 The result is $+1$, 0, or~$-1$ in the three respective cases.
3071 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3074 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3075 integer q,r; /* temporary registers */
3076 @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3078 q = a / d; r = c / b;
3080 return ( q>r ? 1 : -1);
3081 q = a % d; r = c % b;
3084 if ( q==0 ) return -1;
3086 } /* now |a>d>0| and |c>b>0| */
3089 @ @<Reduce to the case that |a...@>=
3090 if ( a<0 ) { negate(a); negate(b); };
3091 if ( c<0 ) { negate(c); negate(d); };
3094 if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3098 return ( a==0 ? 0 : -1);
3099 q=a; a=c; c=q; q=-b; b=-d; d=q;
3100 } else if ( b<=0 ) {
3101 if ( b<0 ) if ( a>0 ) return -1;
3102 return (c==0 ? 0 : -1);
3105 @ We conclude this set of elementary routines with some simple rounding
3106 and truncation operations.
3108 @<Internal library declarations@>=
3109 #define mp_floor_scaled(M,i) ((i)&(-65536))
3110 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3111 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3114 @* \[8] Algebraic and transcendental functions.
3115 \MP\ computes all of the necessary special functions from scratch, without
3116 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3118 @ To get the square root of a |scaled| number |x|, we want to calculate
3119 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3120 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3121 determines $s$ by an iterative method that maintains the invariant
3122 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3123 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3124 might, however, be zero at the start of the first iteration.
3127 scaled mp_square_rt (MP mp,scaled x) ;
3130 scaled mp_square_rt (MP mp,scaled x) {
3131 small_number k; /* iteration control counter */
3132 integer y,q; /* registers for intermediate calculations */
3134 @<Handle square root of zero or negative argument@>;
3137 while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3140 if ( x<fraction_four ) y=0;
3141 else { x=x-fraction_four; y=1; };
3143 @<Decrease |k| by 1, maintaining the invariant
3144 relations between |x|, |y|, and~|q|@>;
3150 @ @<Handle square root of zero...@>=
3153 print_err("Square root of ");
3154 @.Square root...replaced by 0@>
3155 mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3156 help2("Since I don't take square roots of negative numbers,")
3157 ("I'm zeroing this one. Proceed, with fingers crossed.");
3163 @ @<Decrease |k| by 1, maintaining...@>=
3165 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3166 x=x-fraction_four; incr(y);
3168 x+=x; y=y+y-q; q+=q;
3169 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3170 if ( y>q ){ y=y-q; q=q+2; }
3171 else if ( y<=0 ) { q=q-2; y=y+q; };
3174 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3175 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3176 @^Moler, Cleve Barry@>
3177 @^Morrison, Donald Ross@>
3178 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3179 in such a way that their Pythagorean sum remains invariant, while the
3180 smaller argument decreases.
3182 @<Internal library ...@>=
3183 integer mp_pyth_add (MP mp,integer a, integer b);
3187 integer mp_pyth_add (MP mp,integer a, integer b) {
3188 fraction r; /* register used to transform |a| and |b| */
3189 boolean big; /* is the result dangerously near $2^{31}$? */
3191 if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3193 if ( a<fraction_two ) {
3196 a=a / 4; b=b / 4; big=true;
3197 }; /* we reduced the precision to avoid arithmetic overflow */
3198 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3200 if ( a<fraction_two ) {
3203 mp->arith_error=true; a=el_gordo;
3210 @ The key idea here is to reflect the vector $(a,b)$ about the
3211 line through $(a,b/2)$.
3213 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3215 r=mp_make_fraction(mp, b,a);
3216 r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3218 r=mp_make_fraction(mp, r,fraction_four+r);
3219 a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3223 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3224 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3227 integer mp_pyth_sub (MP mp,integer a, integer b) {
3228 fraction r; /* register used to transform |a| and |b| */
3229 boolean big; /* is the input dangerously near $2^{31}$? */
3232 @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3234 if ( a<fraction_four ) {
3237 a=halfp(a); b=halfp(b); big=true;
3239 @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3240 if ( big ) double(a);
3245 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3247 r=mp_make_fraction(mp, b,a);
3248 r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3250 r=mp_make_fraction(mp, r,fraction_four-r);
3251 a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3254 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3257 print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3258 mp_print(mp, "+-+"); mp_print_scaled(mp, b);
3259 mp_print(mp, " has been replaced by 0");
3261 help2("Since I don't take square roots of negative numbers,")
3262 ("I'm zeroing this one. Proceed, with fingers crossed.");
3268 @ The subroutines for logarithm and exponential involve two tables.
3269 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3270 a bit more calculation, which the author claims to have done correctly:
3271 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3272 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3275 @d two_to_the(A) (1<<(A))
3278 static const integer spec_log[29] = { 0, /* special logarithms */
3279 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3280 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3281 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3283 @ @<Local variables for initialization@>=
3284 integer k; /* all-purpose loop index */
3287 @ Here is the routine that calculates $2^8$ times the natural logarithm
3288 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3289 when |x| is a given positive integer.
3291 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3292 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3293 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3294 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3295 during the calculation, and sixteen auxiliary bits to extend |y| are
3296 kept in~|z| during the initial argument reduction. (We add
3297 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3298 not become negative; also, the actual amount subtracted from~|y| is~96,
3299 not~100, because we want to add~4 for rounding before the final division by~8.)
3302 scaled mp_m_log (MP mp,scaled x) {
3303 integer y,z; /* auxiliary registers */
3304 integer k; /* iteration counter */
3306 @<Handle non-positive logarithm@>;
3308 y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3309 z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3310 while ( x<fraction_four ) {
3311 double(x); y-=93032639; z-=48782;
3312 } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3313 y=y+(z / unity); k=2;
3314 while ( x>fraction_four+4 ) {
3315 @<Increase |k| until |x| can be multiplied by a
3316 factor of $2^{-k}$, and adjust $y$ accordingly@>;
3322 @ @<Increase |k| until |x| can...@>=
3324 z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3325 while ( x<fraction_four+z ) { z=halfp(z+1); incr(k); };
3326 y+=spec_log[k]; x-=z;
3329 @ @<Handle non-positive logarithm@>=
3331 print_err("Logarithm of ");
3332 @.Logarithm...replaced by 0@>
3333 mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3334 help2("Since I don't take logs of non-positive numbers,")
3335 ("I'm zeroing this one. Proceed, with fingers crossed.");
3340 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3341 when |x| is |scaled|. The result is an integer approximation to
3342 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3345 scaled mp_m_exp (MP mp,scaled x) {
3346 small_number k; /* loop control index */
3347 integer y,z; /* auxiliary registers */
3348 if ( x>174436200 ) {
3349 /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3350 mp->arith_error=true;
3352 } else if ( x<-197694359 ) {
3353 /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3357 z=-8*x; y=04000000; /* $y=2^{20}$ */
3359 if ( x<=127919879 ) {
3361 /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3363 z=8*(174436200-x); /* |z| is always nonnegative */
3367 @<Multiply |y| by $\exp(-z/2^{27})$@>;
3369 return ((y+8) / 16);
3375 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3376 to multiplying |y| by $1-2^{-k}$.
3378 A subtle point (which had to be checked) was that if $x=127919879$, the
3379 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3380 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3381 and by~16 when |k=27|.
3383 @<Multiply |y| by...@>=
3386 while ( z>=spec_log[k] ) {
3388 y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3393 @ The trigonometric subroutines use an auxiliary table such that
3394 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3395 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$
3398 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058,
3399 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667,
3400 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3402 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3403 returns the |angle| whose tangent points in the direction $(x,y)$.
3404 This subroutine first determines the correct octant, then solves the
3405 problem for |0<=y<=x|, then converts the result appropriately to
3406 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3407 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3408 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3410 The octants are represented in a ``Gray code,'' since that turns out
3411 to be computationally simplest.
3417 @d second_octant (first_octant+switch_x_and_y)
3418 @d third_octant (first_octant+switch_x_and_y+negate_x)
3419 @d fourth_octant (first_octant+negate_x)
3420 @d fifth_octant (first_octant+negate_x+negate_y)
3421 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3422 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3423 @d eighth_octant (first_octant+negate_y)
3426 angle mp_n_arg (MP mp,integer x, integer y) {
3427 angle z; /* auxiliary register */
3428 integer t; /* temporary storage */
3429 small_number k; /* loop counter */
3430 int octant; /* octant code */
3432 octant=first_octant;
3434 negate(x); octant=first_octant+negate_x;
3437 negate(y); octant=octant+negate_y;
3440 t=y; y=x; x=t; octant=octant+switch_x_and_y;
3443 @<Handle undefined arg@>;
3445 @<Set variable |z| to the arg of $(x,y)$@>;
3446 @<Return an appropriate answer based on |z| and |octant|@>;
3450 @ @<Handle undefined arg@>=
3452 print_err("angle(0,0) is taken as zero");
3453 @.angle(0,0)...zero@>
3454 help2("The `angle' between two identical points is undefined.")
3455 ("I'm zeroing this one. Proceed, with fingers crossed.");
3460 @ @<Return an appropriate answer...@>=
3462 case first_octant: return z;
3463 case second_octant: return (ninety_deg-z);
3464 case third_octant: return (ninety_deg+z);
3465 case fourth_octant: return (one_eighty_deg-z);
3466 case fifth_octant: return (z-one_eighty_deg);
3467 case sixth_octant: return (-z-ninety_deg);
3468 case seventh_octant: return (z-ninety_deg);
3469 case eighth_octant: return (-z);
3470 }; /* there are no other cases */
3473 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3474 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3477 @<Set variable |z| to the arg...@>=
3478 while ( x>=fraction_two ) {
3479 x=halfp(x); y=halfp(y);
3483 while ( x<fraction_one ) {
3486 @<Increase |z| to the arg of $(x,y)$@>;
3489 @ During the calculations of this section, variables |x| and~|y|
3490 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3491 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3492 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3493 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3494 coordinates whose angle has decreased by~$\phi$; in the special case
3495 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3496 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3497 @^Meggitt, John E.@>
3498 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3500 The initial value of |x| will be multiplied by at most
3501 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3502 there is no chance of integer overflow.
3504 @<Increase |z|...@>=
3509 z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3514 if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3517 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3518 and cosine of that angle. The results of this routine are
3519 stored in global integer variables |n_sin| and |n_cos|.
3522 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3524 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3525 the purpose of |n_sin_cos(z)| is to set
3526 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3527 for some rather large number~|r|. The maximum of |x| and |y|
3528 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3529 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3532 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3534 small_number k; /* loop control variable */
3535 int q; /* specifies the quadrant */
3536 fraction r; /* magnitude of |(x,y)| */
3537 integer x,y,t; /* temporary registers */
3538 while ( z<0 ) z=z+three_sixty_deg;
3539 z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3540 q=z / forty_five_deg; z=z % forty_five_deg;
3541 x=fraction_one; y=x;
3542 if ( ! odd(q) ) z=forty_five_deg-z;
3543 @<Subtract angle |z| from |(x,y)|@>;
3544 @<Convert |(x,y)| to the octant determined by~|q|@>;
3545 r=mp_pyth_add(mp, x,y);
3546 mp->n_cos=mp_make_fraction(mp, x,r);
3547 mp->n_sin=mp_make_fraction(mp, y,r);
3550 @ In this case the octants are numbered sequentially.
3552 @<Convert |(x,...@>=
3555 case 1: t=x; x=y; y=t; break;
3556 case 2: t=x; x=-y; y=t; break;
3557 case 3: negate(x); break;
3558 case 4: negate(x); negate(y); break;
3559 case 5: t=x; x=-y; y=-t; break;
3560 case 6: t=x; x=y; y=-t; break;
3561 case 7: negate(y); break;
3562 } /* there are no other cases */
3564 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3565 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3566 that this loop is guaranteed to terminate before the (nonexistent) value
3567 |spec_atan[27]| would be required.
3569 @<Subtract angle |z|...@>=
3572 if ( z>=spec_atan[k] ) {
3573 z=z-spec_atan[k]; t=x;
3574 x=t+y / two_to_the(k);
3575 y=y-t / two_to_the(k);
3579 if ( y<0 ) y=0 /* this precaution may never be needed */
3581 @ And now let's complete our collection of numeric utility routines
3582 by considering random number generation.
3583 \MP\ generates pseudo-random numbers with the additive scheme recommended
3584 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3585 results are random fractions between 0 and |fraction_one-1|, inclusive.
3587 There's an auxiliary array |randoms| that contains 55 pseudo-random
3588 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3589 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3590 The global variable |j_random| tells which element has most recently
3592 The global variable |sys_random_seed| was introduced in version 0.9,
3593 for the sole reason of stressing the fact that the initial value of the
3594 random seed is system-dependant. The pascal code below will initialize
3595 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this
3596 is not good enough on modern fast machines that are capable of running
3597 multiple MetaPost processes within the same second.
3598 @^system dependencies@>
3601 fraction randoms[55]; /* the last 55 random values generated */
3602 int j_random; /* the number of unused |randoms| */
3603 scaled sys_random_seed; /* the default random seed */
3605 @ @<Exported types@>=
3606 typedef int (*mp_get_random_seed_command)(MP mp);
3609 mp_get_random_seed_command get_random_seed;
3611 @ @<Option variables@>=
3612 mp_get_random_seed_command get_random_seed;
3614 @ @<Allocate or initialize ...@>=
3615 set_callback_option(get_random_seed);
3617 @ @<Internal library declarations@>=
3618 int mp_get_random_seed (MP mp);
3621 int mp_get_random_seed (MP mp) {
3622 return (mp->internal[mp_time] / unity)+mp->internal[mp_day];
3625 @ To consume a random fraction, the program below will say `|next_random|'
3626 and then it will fetch |randoms[j_random]|.
3628 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3629 else decr(mp->j_random); }
3632 void mp_new_randoms (MP mp) {
3633 int k; /* index into |randoms| */
3634 fraction x; /* accumulator */
3635 for (k=0;k<=23;k++) {
3636 x=mp->randoms[k]-mp->randoms[k+31];
3637 if ( x<0 ) x=x+fraction_one;
3640 for (k=24;k<= 54;k++){
3641 x=mp->randoms[k]-mp->randoms[k-24];
3642 if ( x<0 ) x=x+fraction_one;
3649 void mp_init_randoms (MP mp,scaled seed);
3651 @ To initialize the |randoms| table, we call the following routine.
3654 void mp_init_randoms (MP mp,scaled seed) {
3655 fraction j,jj,k; /* more or less random integers */
3656 int i; /* index into |randoms| */
3658 while ( j>=fraction_one ) j=halfp(j);
3660 for (i=0;i<=54;i++ ){
3662 if ( k<0 ) k=k+fraction_one;
3663 mp->randoms[(i*21)% 55]=j;
3667 mp_new_randoms(mp); /* ``warm up'' the array */
3670 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3671 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3673 Note that the call of |take_fraction| will produce the values 0 and~|x|
3674 with about half the probability that it will produce any other particular
3675 values between 0 and~|x|, because it rounds its answers.
3678 scaled mp_unif_rand (MP mp,scaled x) {
3679 scaled y; /* trial value */
3680 next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3681 if ( y==abs(x) ) return 0;
3682 else if ( x>0 ) return y;
3686 @ Finally, a normal deviate with mean zero and unit standard deviation
3687 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3688 {\sl The Art of Computer Programming\/}).
3691 scaled mp_norm_rand (MP mp) {
3692 integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3696 x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3697 /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3698 next_random; u=mp->randoms[mp->j_random];
3699 } while (abs(x)>=u);
3700 x=mp_make_fraction(mp, x,u);
3701 l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3702 } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3706 @* \[9] Packed data.
3707 In order to make efficient use of storage space, \MP\ bases its major data
3708 structures on a |memory_word|, which contains either a (signed) integer,
3709 possibly scaled, or a small number of fields that are one half or one
3710 quarter of the size used for storing integers.
3712 If |x| is a variable of type |memory_word|, it contains up to four
3713 fields that can be referred to as follows:
3714 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3715 |x|&.|int|&(an |integer|)\cr
3716 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3717 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3718 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3720 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3721 &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3722 This is somewhat cumbersome to write, and not very readable either, but
3723 macros will be used to make the notation shorter and more transparent.
3724 The code below gives a formal definition of |memory_word| and
3725 its subsidiary types, using packed variant records. \MP\ makes no
3726 assumptions about the relative positions of the fields within a word.
3728 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3729 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3731 @ Here are the inequalities that the quarterword and halfword values
3732 must satisfy (or rather, the inequalities that they mustn't satisfy):
3734 @<Check the ``constant''...@>=
3735 if (mp->ini_version) {
3736 if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3738 if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3740 if ( max_quarterword<255 ) mp->bad=9;
3741 if ( max_halfword<65535 ) mp->bad=10;
3742 if ( max_quarterword>max_halfword ) mp->bad=11;
3743 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3744 if ( mp->max_strings>max_halfword ) mp->bad=13;
3746 @ The macros |qi| and |qo| are used for input to and output
3747 from quarterwords. These are legacy macros.
3748 @^system dependencies@>
3750 @d qo(A) (A) /* to read eight bits from a quarterword */
3751 @d qi(A) (A) /* to store eight bits in a quarterword */
3753 @ The reader should study the following definitions closely:
3754 @^system dependencies@>
3756 @d sc cint /* |scaled| data is equivalent to |integer| */
3759 typedef short quarterword; /* 1/4 of a word */
3760 typedef int halfword; /* 1/2 of a word */
3765 struct { /* Make B0,B1 overlap the most significant bytes of LH. */
3772 quarterword B2, B3, B0, B1;
3787 @ When debugging, we may want to print a |memory_word| without knowing
3788 what type it is; so we print it in all modes.
3789 @^dirty \PASCAL@>@^debugging@>
3792 void mp_print_word (MP mp,memory_word w) {
3793 /* prints |w| in all ways */
3794 mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3795 mp_print_scaled(mp, w.sc); mp_print_char(mp, ' ');
3796 mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3797 mp_print_int(mp, w.hh.lh); mp_print_char(mp, '=');
3798 mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3799 mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';');
3800 mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3801 mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':');
3802 mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3803 mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':');
3804 mp_print_int(mp, w.qqqq.b3);
3808 @* \[10] Dynamic memory allocation.
3810 The \MP\ system does nearly all of its own memory allocation, so that it
3811 can readily be transported into environments that do not have automatic
3812 facilities for strings, garbage collection, etc., and so that it can be in
3813 control of what error messages the user receives. The dynamic storage
3814 requirements of \MP\ are handled by providing a large array |mem| in
3815 which consecutive blocks of words are used as nodes by the \MP\ routines.
3817 Pointer variables are indices into this array, or into another array
3818 called |eqtb| that will be explained later. A pointer variable might
3819 also be a special flag that lies outside the bounds of |mem|, so we
3820 allow pointers to assume any |halfword| value. The minimum memory
3821 index represents a null pointer.
3823 @d null 0 /* the null pointer */
3824 @d mp_void (null+1) /* a null pointer different from |null| */
3828 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3830 @ The |mem| array is divided into two regions that are allocated separately,
3831 but the dividing line between these two regions is not fixed; they grow
3832 together until finding their ``natural'' size in a particular job.
3833 Locations less than or equal to |lo_mem_max| are used for storing
3834 variable-length records consisting of two or more words each. This region
3835 is maintained using an algorithm similar to the one described in exercise
3836 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3837 appears in the allocated nodes; the program is responsible for knowing the
3838 relevant size when a node is freed. Locations greater than or equal to
3839 |hi_mem_min| are used for storing one-word records; a conventional
3840 \.{AVAIL} stack is used for allocation in this region.
3842 Locations of |mem| between |0| and |mem_top| may be dumped as part
3843 of preloaded format files, by the \.{INIMP} preprocessor.
3845 Production versions of \MP\ may extend the memory at the top end in order to
3846 provide more space; these locations, between |mem_top| and |mem_max|,
3847 are always used for single-word nodes.
3849 The key pointers that govern |mem| allocation have a prescribed order:
3850 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3853 memory_word *mem; /* the big dynamic storage area */
3854 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3855 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3859 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3860 @d xrealloc(P,A,B) mp_xrealloc(mp,P,A,B)
3861 @d xmalloc(A,B) mp_xmalloc(mp,A,B)
3862 @d xstrdup(A) mp_xstrdup(mp,A)
3863 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3865 @<Declare helpers@>=
3866 void mp_xfree (void *x);
3867 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3868 void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3869 char *mp_xstrdup(MP mp, const char *s);
3871 @ The |max_size_test| guards against overflow, on the assumption that
3872 |size_t| is at least 31bits wide.
3874 @d max_size_test 0x7FFFFFFF
3877 void mp_xfree (void *x) {
3878 if (x!=NULL) free(x);
3880 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3882 if ((max_size_test/size)<nmem) {
3883 fprintf(stderr,"Memory size overflow!\n");
3884 mp->history =mp_fatal_error_stop; mp_jump_out(mp);
3886 w = realloc (p,(nmem*size));
3888 fprintf(stderr,"Out of memory!\n");
3889 mp->history =mp_fatal_error_stop; mp_jump_out(mp);
3893 void *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3895 if ((max_size_test/size)<nmem) {
3896 fprintf(stderr,"Memory size overflow!\n");
3897 mp->history =mp_fatal_error_stop; mp_jump_out(mp);
3899 w = malloc (nmem*size);
3901 fprintf(stderr,"Out of memory!\n");
3902 mp->history =mp_fatal_error_stop; mp_jump_out(mp);
3906 char *mp_xstrdup(MP mp, const char *s) {
3912 fprintf(stderr,"Out of memory!\n");
3913 mp->history =mp_fatal_error_stop; mp_jump_out(mp);
3920 @<Allocate or initialize ...@>=
3921 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3922 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
3924 @ @<Dealloc variables@>=
3927 @ Users who wish to study the memory requirements of particular applications can
3928 can use optional special features that keep track of current and
3929 maximum memory usage. When code between the delimiters |stat| $\ldots$
3930 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3931 report these statistics when |mp_tracing_stats| is positive.
3934 integer var_used; integer dyn_used; /* how much memory is in use */
3936 @ Let's consider the one-word memory region first, since it's the
3937 simplest. The pointer variable |mem_end| holds the highest-numbered location
3938 of |mem| that has ever been used. The free locations of |mem| that
3939 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3940 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3941 and |rh| fields of |mem[p]| when it is of this type. The single-word
3942 free locations form a linked list
3943 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3944 terminated by |null|.
3946 @d link(A) mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3947 @d info(A) mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3950 pointer avail; /* head of the list of available one-word nodes */
3951 pointer mem_end; /* the last one-word node used in |mem| */
3953 @ If one-word memory is exhausted, it might mean that the user has forgotten
3954 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3955 later that try to help pinpoint the trouble.
3958 @<Declare the procedure called |show_token_list|@>;
3959 @<Declare the procedure called |runaway|@>
3961 @ The function |get_avail| returns a pointer to a new one-word node whose
3962 |link| field is null. However, \MP\ will halt if there is no more room left.
3966 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3967 pointer p; /* the new node being got */
3968 p=mp->avail; /* get top location in the |avail| stack */
3970 mp->avail=link(mp->avail); /* and pop it off */
3971 } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3972 incr(mp->mem_end); p=mp->mem_end;
3974 decr(mp->hi_mem_min); p=mp->hi_mem_min;
3975 if ( mp->hi_mem_min<=mp->lo_mem_max ) {
3976 mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3977 mp_overflow(mp, "main memory size",mp->mem_max);
3978 /* quit; all one-word nodes are busy */
3979 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3982 link(p)=null; /* provide an oft-desired initialization of the new node */
3983 incr(mp->dyn_used);/* maintain statistics */
3987 @ Conversely, a one-word node is recycled by calling |free_avail|.
3989 @d free_avail(A) /* single-word node liberation */
3990 { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used); }
3992 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3993 overhead at the expense of extra programming. This macro is used in
3994 the places that would otherwise account for the most calls of |get_avail|.
3997 @d fast_get_avail(A) {
3998 (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
3999 if ( (A)==null ) { (A)=mp_get_avail(mp); }
4000 else { mp->avail=link((A)); link((A))=null; incr(mp->dyn_used); }
4003 @ The available-space list that keeps track of the variable-size portion
4004 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
4005 pointed to by the roving pointer |rover|.
4007 Each empty node has size 2 or more; the first word contains the special
4008 value |max_halfword| in its |link| field and the size in its |info| field;
4009 the second word contains the two pointers for double linking.
4011 Each nonempty node also has size 2 or more. Its first word is of type
4012 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
4013 Otherwise there is complete flexibility with respect to the contents
4014 of its other fields and its other words.
4016 (We require |mem_max<max_halfword| because terrible things can happen
4017 when |max_halfword| appears in the |link| field of a nonempty node.)
4019 @d empty_flag max_halfword /* the |link| of an empty variable-size node */
4020 @d is_empty(A) (link((A))==empty_flag) /* tests for empty node */
4021 @d node_size info /* the size field in empty variable-size nodes */
4022 @d llink(A) info((A)+1) /* left link in doubly-linked list of empty nodes */
4023 @d rlink(A) link((A)+1) /* right link in doubly-linked list of empty nodes */
4026 pointer rover; /* points to some node in the list of empties */
4028 @ A call to |get_node| with argument |s| returns a pointer to a new node
4029 of size~|s|, which must be 2~or more. The |link| field of the first word
4030 of this new node is set to null. An overflow stop occurs if no suitable
4033 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4034 areas and returns the value |max_halfword|.
4037 pointer mp_get_node (MP mp,integer s) ;
4040 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4041 pointer p; /* the node currently under inspection */
4042 pointer q; /* the node physically after node |p| */
4043 integer r; /* the newly allocated node, or a candidate for this honor */
4044 integer t,tt; /* temporary registers */
4047 p=mp->rover; /* start at some free node in the ring */
4049 @<Try to allocate within node |p| and its physical successors,
4050 and |goto found| if allocation was possible@>;
4051 if (rlink(p)==null || rlink(p)==p) {
4052 print_err("Free list garbled");
4053 help3("I found an entry in the list of free nodes that links")
4054 ("badly. I will try to ignore the broken link, but something")
4055 ("is seriously amiss. It is wise to warn the maintainers.")
4059 p=rlink(p); /* move to the next node in the ring */
4060 } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4061 if ( s==010000000000 ) {
4062 return max_halfword;
4064 if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4065 if ( mp->lo_mem_max+2<=max_halfword ) {
4066 @<Grow more variable-size memory and |goto restart|@>;
4069 mp_overflow(mp, "main memory size",mp->mem_max);
4070 /* sorry, nothing satisfactory is left */
4071 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4073 link(r)=null; /* this node is now nonempty */
4074 mp->var_used+=s; /* maintain usage statistics */
4078 @ The lower part of |mem| grows by 1000 words at a time, unless
4079 we are very close to going under. When it grows, we simply link
4080 a new node into the available-space list. This method of controlled
4081 growth helps to keep the |mem| usage consecutive when \MP\ is
4082 implemented on ``virtual memory'' systems.
4085 @<Grow more variable-size memory and |goto restart|@>=
4087 if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4088 t=mp->lo_mem_max+1000;
4090 t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2;
4091 /* |lo_mem_max+2<=t<hi_mem_min| */
4093 if ( t>max_halfword ) t=max_halfword;
4094 p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4095 rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag;
4096 node_size(q)=t-mp->lo_mem_max;
4097 mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4102 @ @<Try to allocate...@>=
4103 q=p+node_size(p); /* find the physical successor */
4104 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4105 t=rlink(q); tt=llink(q);
4107 if ( q==mp->rover ) mp->rover=t;
4108 llink(t)=tt; rlink(tt)=t;
4113 @<Allocate from the top of node |p| and |goto found|@>;
4116 if ( rlink(p)!=p ) {
4117 @<Allocate entire node |p| and |goto found|@>;
4120 node_size(p)=q-p /* reset the size in case it grew */
4122 @ @<Allocate from the top...@>=
4124 node_size(p)=r-p; /* store the remaining size */
4125 mp->rover=p; /* start searching here next time */
4129 @ Here we delete node |p| from the ring, and let |rover| rove around.
4131 @<Allocate entire...@>=
4133 mp->rover=rlink(p); t=llink(p);
4134 llink(mp->rover)=t; rlink(t)=mp->rover;
4138 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4139 the operation |free_node(p,s)| will make its words available, by inserting
4140 |p| as a new empty node just before where |rover| now points.
4143 void mp_free_node (MP mp, pointer p, halfword s) ;
4146 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4148 pointer q; /* |llink(rover)| */
4149 node_size(p)=s; link(p)=empty_flag;
4151 q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4152 llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4153 mp->var_used-=s; /* maintain statistics */
4156 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4157 available space list. The list is probably very short at such times, so a
4158 simple insertion sort is used. The smallest available location will be
4159 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4162 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4164 pointer p,q,r; /* indices into |mem| */
4165 pointer old_rover; /* initial |rover| setting */
4166 p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4167 p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4168 while ( p!=old_rover ) {
4169 @<Sort |p| into the list starting at |rover|
4170 and advance |p| to |rlink(p)|@>;
4173 while ( rlink(p)!=max_halfword ) {
4174 llink(rlink(p))=p; p=rlink(p);
4176 rlink(p)=mp->rover; llink(mp->rover)=p;
4179 @ The following |while| loop is guaranteed to
4180 terminate, since the list that starts at
4181 |rover| ends with |max_halfword| during the sorting procedure.
4184 if ( p<mp->rover ) {
4185 q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4188 while ( rlink(q)<p ) q=rlink(q);
4189 r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4192 @* \[11] Memory layout.
4193 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4194 more efficient than dynamic allocation when we can get away with it. For
4195 example, locations |0| to |1| are always used to store a
4196 two-word dummy token whose second word is zero.
4197 The following macro definitions accomplish the static allocation by giving
4198 symbolic names to the fixed positions. Static variable-size nodes appear
4199 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4200 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4202 @d null_dash (2) /* the first two words are reserved for a null value */
4203 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4204 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4205 @d temp_val (zero_val+2) /* two words for a temporary value node */
4206 @d end_attr temp_val /* we use |end_attr+2| only */
4207 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4208 @d test_pen (inf_val+2)
4209 /* nine words for a pen used when testing the turning number */
4210 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4211 @d lo_mem_stat_max (bad_vardef+1) /* largest statically
4212 allocated word in the variable-size |mem| */
4214 @d sentinel mp->mem_top /* end of sorted lists */
4215 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4216 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4217 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4218 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4219 the one-word |mem| */
4221 @ The following code gets the dynamic part of |mem| off to a good start,
4222 when \MP\ is initializing itself the slow way.
4224 @<Initialize table entries (done by \.{INIMP} only)@>=
4225 @^data structure assumptions@>
4226 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4227 link(mp->rover)=empty_flag;
4228 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4229 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4230 mp->lo_mem_max=mp->rover+1000;
4231 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4232 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4233 mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4235 mp->avail=null; mp->mem_end=mp->mem_top;
4236 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4237 mp->var_used=lo_mem_stat_max+1;
4238 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min); /* initialize statistics */
4239 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4241 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4242 nodes that starts at a given position, until coming to |sentinel| or a
4243 pointer that is not in the one-word region. Another procedure,
4244 |flush_node_list|, frees an entire linked list of one-word and two-word
4245 nodes, until coming to a |null| pointer.
4249 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes available */
4250 pointer q,r; /* list traversers */
4251 if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) {
4256 if ( r<mp->hi_mem_min ) break;
4257 } while (r!=sentinel);
4258 /* now |q| is the last node on the list */
4259 link(q)=mp->avail; mp->avail=p;
4263 void mp_flush_node_list (MP mp,pointer p) {
4264 pointer q; /* the node being recycled */
4267 if ( q<mp->hi_mem_min )
4268 mp_free_node(mp, q,2);
4274 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4275 For example, some pointers might be wrong, or some ``dead'' nodes might not
4276 have been freed when the last reference to them disappeared. Procedures
4277 |check_mem| and |search_mem| are available to help diagnose such
4278 problems. These procedures make use of two arrays called |free| and
4279 |was_free| that are present only if \MP's debugging routines have
4280 been included. (You may want to decrease the size of |mem| while you
4284 Because |boolean|s are typedef-d as ints, it is better to use
4285 unsigned chars here.
4288 unsigned char *free; /* free cells */
4289 unsigned char *was_free; /* previously free cells */
4290 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4291 /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4292 boolean panicking; /* do we want to check memory constantly? */
4294 @ @<Allocate or initialize ...@>=
4295 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4296 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4298 @ @<Dealloc variables@>=
4300 xfree(mp->was_free);
4302 @ @<Allocate or ...@>=
4303 mp->was_mem_end=0; /* indicate that everything was previously free */
4304 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4305 mp->panicking=false;
4307 @ @<Declare |mp_reallocate| functions@>=
4308 void mp_reallocate_memory(MP mp, int l) ;
4311 void mp_reallocate_memory(MP mp, int l) {
4312 XREALLOC(mp->free, l, unsigned char);
4313 XREALLOC(mp->was_free, l, unsigned char);
4315 int newarea = l-mp->mem_max;
4316 XREALLOC(mp->mem, l, memory_word);
4317 memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4319 XREALLOC(mp->mem, l, memory_word);
4320 memset(mp->mem,0,sizeof(memory_word)*(l+1));
4323 if (mp->ini_version)
4329 @ Procedure |check_mem| makes sure that the available space lists of
4330 |mem| are well formed, and it optionally prints out all locations
4331 that are reserved now but were free the last time this procedure was called.
4334 void mp_check_mem (MP mp,boolean print_locs ) {
4335 pointer p,q,r; /* current locations of interest in |mem| */
4336 boolean clobbered; /* is something amiss? */
4337 for (p=0;p<=mp->lo_mem_max;p++) {
4338 mp->free[p]=false; /* you can probably do this faster */
4340 for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4341 mp->free[p]=false; /* ditto */
4343 @<Check single-word |avail| list@>;
4344 @<Check variable-size |avail| list@>;
4345 @<Check flags of unavailable nodes@>;
4346 @<Check the list of linear dependencies@>;
4348 @<Print newly busy locations@>;
4350 memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4351 mp->was_mem_end=mp->mem_end;
4352 mp->was_lo_max=mp->lo_mem_max;
4353 mp->was_hi_min=mp->hi_mem_min;
4356 @ @<Check single-word...@>=
4357 p=mp->avail; q=null; clobbered=false;
4359 if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4360 else if ( mp->free[p] ) clobbered=true;
4362 mp_print_nl(mp, "AVAIL list clobbered at ");
4363 @.AVAIL list clobbered...@>
4364 mp_print_int(mp, q); break;
4366 mp->free[p]=true; q=p; p=link(q);
4369 @ @<Check variable-size...@>=
4370 p=mp->rover; q=null; clobbered=false;
4372 if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4373 else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4374 else if ( !(is_empty(p))||(node_size(p)<2)||
4375 (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4377 mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4378 @.Double-AVAIL list clobbered...@>
4379 mp_print_int(mp, q); break;
4381 for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4382 if ( mp->free[q] ) {
4383 mp_print_nl(mp, "Doubly free location at ");
4384 @.Doubly free location...@>
4385 mp_print_int(mp, q); break;
4390 } while (p!=mp->rover)
4393 @ @<Check flags...@>=
4395 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4396 if ( is_empty(p) ) {
4397 mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4400 while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4401 while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4404 @ @<Print newly busy...@>=
4406 @<Do intialization required before printing new busy locations@>;
4407 mp_print_nl(mp, "New busy locs:");
4409 for (p=0;p<= mp->lo_mem_max;p++ ) {
4410 if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4411 @<Indicate that |p| is a new busy location@>;
4414 for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4415 if ( ! mp->free[p] &&
4416 ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4417 @<Indicate that |p| is a new busy location@>;
4420 @<Finish printing new busy locations@>;
4423 @ There might be many new busy locations so we are careful to print contiguous
4424 blocks compactly. During this operation |q| is the last new busy location and
4425 |r| is the start of the block containing |q|.
4427 @<Indicate that |p| is a new busy location@>=
4431 mp_print(mp, ".."); mp_print_int(mp, q);
4433 mp_print_char(mp, ' '); mp_print_int(mp, p);
4439 @ @<Do intialization required before printing new busy locations@>=
4440 q=mp->mem_max; r=mp->mem_max
4442 @ @<Finish printing new busy locations@>=
4444 mp_print(mp, ".."); mp_print_int(mp, q);
4447 @ The |search_mem| procedure attempts to answer the question ``Who points
4448 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4449 that might not be of type |two_halves|. Strictly speaking, this is
4451 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
4452 point to |p| purely by coincidence). But for debugging purposes, we want
4453 to rule out the places that do {\sl not\/} point to |p|, so a few false
4454 drops are tolerable.
4457 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4458 integer q; /* current position being searched */
4459 for (q=0;q<=mp->lo_mem_max;q++) {
4461 mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4464 mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4467 for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4469 mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4472 mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4475 @<Search |eqtb| for equivalents equal to |p|@>;
4478 @* \[12] The command codes.
4479 Before we can go much further, we need to define symbolic names for the internal
4480 code numbers that represent the various commands obeyed by \MP. These codes
4481 are somewhat arbitrary, but not completely so. For example,
4482 some codes have been made adjacent so that |case| statements in the
4483 program need not consider cases that are widely spaced, or so that |case|
4484 statements can be replaced by |if| statements. A command can begin an
4485 expression if and only if its code lies between |min_primary_command| and
4486 |max_primary_command|, inclusive. The first token of a statement that doesn't
4487 begin with an expression has a command code between |min_command| and
4488 |max_statement_command|, inclusive. Anything less than |min_command| is
4489 eliminated during macro expansions, and anything no more than |max_pre_command|
4490 is eliminated when expanding \TeX\ material. Ranges such as
4491 |min_secondary_command..max_secondary_command| are used when parsing
4492 expressions, but the relative ordering within such a range is generally not
4495 The ordering of the highest-numbered commands
4496 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4497 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4498 for the smallest two commands. The ordering is also important in the ranges
4499 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4501 At any rate, here is the list, for future reference.
4503 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4504 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4505 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4506 @d max_pre_command mpx_break
4507 @d if_test 4 /* conditional text (\&{if}) */
4508 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4509 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4510 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4511 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4512 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4513 @d relax 10 /* do nothing (\.{\char`\\}) */
4514 @d scan_tokens 11 /* put a string into the input buffer */
4515 @d expand_after 12 /* look ahead one token */
4516 @d defined_macro 13 /* a macro defined by the user */
4517 @d min_command (defined_macro+1)
4518 @d save_command 14 /* save a list of tokens (\&{save}) */
4519 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4520 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4521 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4522 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4523 @d ship_out_command 19 /* output a character (\&{shipout}) */
4524 @d add_to_command 20 /* add to edges (\&{addto}) */
4525 @d bounds_command 21 /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4526 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4527 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4528 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4529 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4530 @d random_seed 26 /* initialize random number generator (\&{randomseed}) */
4531 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4532 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4533 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4534 @d special_command 30 /* output special info (\&{special})
4535 or font map info (\&{fontmapfile}, \&{fontmapline}) */
4536 @d write_command 31 /* write text to a file (\&{write}) */
4537 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4538 @d max_statement_command type_name
4539 @d min_primary_command type_name
4540 @d left_delimiter 33 /* the left delimiter of a matching pair */
4541 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4542 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4543 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4544 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4545 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4546 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4547 @d capsule_token 40 /* a value that has been put into a token list */
4548 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4549 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4550 @d min_suffix_token internal_quantity
4551 @d tag_token 43 /* a symbolic token without a primitive meaning */
4552 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4553 @d max_suffix_token numeric_token
4554 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4555 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4556 @d min_tertiary_command plus_or_minus
4557 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4558 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4559 @d max_tertiary_command tertiary_binary
4560 @d left_brace 48 /* the operator `\.{\char`\{}' */
4561 @d min_expression_command left_brace
4562 @d path_join 49 /* the operator `\.{..}' */
4563 @d ampersand 50 /* the operator `\.\&' */
4564 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4565 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4566 @d equals 53 /* the operator `\.=' */
4567 @d max_expression_command equals
4568 @d and_command 54 /* the operator `\&{and}' */
4569 @d min_secondary_command and_command
4570 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4571 @d slash 56 /* the operator `\./' */
4572 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4573 @d max_secondary_command secondary_binary
4574 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4575 @d controls 59 /* specify control points explicitly (\&{controls}) */
4576 @d tension 60 /* specify tension between knots (\&{tension}) */
4577 @d at_least 61 /* bounded tension value (\&{atleast}) */
4578 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4579 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4580 @d right_delimiter 64 /* the right delimiter of a matching pair */
4581 @d left_bracket 65 /* the operator `\.[' */
4582 @d right_bracket 66 /* the operator `\.]' */
4583 @d right_brace 67 /* the operator `\.{\char`\}}' */
4584 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4586 /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4587 @d of_token 70 /* the operator `\&{of}' */
4588 @d to_token 71 /* the operator `\&{to}' */
4589 @d step_token 72 /* the operator `\&{step}' */
4590 @d until_token 73 /* the operator `\&{until}' */
4591 @d within_token 74 /* the operator `\&{within}' */
4592 @d lig_kern_token 75
4593 /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4594 @d assignment 76 /* the operator `\.{:=}' */
4595 @d skip_to 77 /* the operation `\&{skipto}' */
4596 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4597 @d double_colon 79 /* the operator `\.{::}' */
4598 @d colon 80 /* the operator `\.:' */
4600 @d comma 81 /* the operator `\.,', must be |colon+1| */
4601 @d end_of_statement (mp->cur_cmd>comma)
4602 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4603 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4604 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4605 @d max_command_code stop
4606 @d outer_tag (max_command_code+1) /* protection code added to command code */
4609 typedef int command_code;
4611 @ Variables and capsules in \MP\ have a variety of ``types,''
4612 distinguished by the code numbers defined here. These numbers are also
4613 not completely arbitrary. Things that get expanded must have types
4614 |>mp_independent|; a type remaining after expansion is numeric if and only if
4615 its code number is at least |numeric_type|; objects containing numeric
4616 parts must have types between |transform_type| and |pair_type|;
4617 all other types must be smaller than |transform_type|; and among the types
4618 that are not unknown or vacuous, the smallest two must be |boolean_type|
4619 and |string_type| in that order.
4621 @d undefined 0 /* no type has been declared */
4622 @d unknown_tag 1 /* this constant is added to certain type codes below */
4623 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4624 case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4627 enum mp_variable_type {
4628 mp_vacuous=1, /* no expression was present */
4629 mp_boolean_type, /* \&{boolean} with a known value */
4631 mp_string_type, /* \&{string} with a known value */
4633 mp_pen_type, /* \&{pen} with a known value */
4635 mp_path_type, /* \&{path} with a known value */
4637 mp_picture_type, /* \&{picture} with a known value */
4639 mp_transform_type, /* \&{transform} variable or capsule */
4640 mp_color_type, /* \&{color} variable or capsule */
4641 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4642 mp_pair_type, /* \&{pair} variable or capsule */
4643 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4644 mp_known, /* \&{numeric} with a known value */
4645 mp_dependent, /* a linear combination with |fraction| coefficients */
4646 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4647 mp_independent, /* \&{numeric} with unknown value */
4648 mp_token_list, /* variable name or suffix argument or text argument */
4649 mp_structured, /* variable with subscripts and attributes */
4650 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4651 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4655 void mp_print_type (MP mp,small_number t) ;
4657 @ @<Basic printing procedures@>=
4658 void mp_print_type (MP mp,small_number t) {
4660 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4661 case mp_boolean_type:mp_print(mp, "boolean"); break;
4662 case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4663 case mp_string_type:mp_print(mp, "string"); break;
4664 case mp_unknown_string:mp_print(mp, "unknown string"); break;
4665 case mp_pen_type:mp_print(mp, "pen"); break;
4666 case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4667 case mp_path_type:mp_print(mp, "path"); break;
4668 case mp_unknown_path:mp_print(mp, "unknown path"); break;
4669 case mp_picture_type:mp_print(mp, "picture"); break;
4670 case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4671 case mp_transform_type:mp_print(mp, "transform"); break;
4672 case mp_color_type:mp_print(mp, "color"); break;
4673 case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4674 case mp_pair_type:mp_print(mp, "pair"); break;
4675 case mp_known:mp_print(mp, "known numeric"); break;
4676 case mp_dependent:mp_print(mp, "dependent"); break;
4677 case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4678 case mp_numeric_type:mp_print(mp, "numeric"); break;
4679 case mp_independent:mp_print(mp, "independent"); break;
4680 case mp_token_list:mp_print(mp, "token list"); break;
4681 case mp_structured:mp_print(mp, "mp_structured"); break;
4682 case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4683 case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4684 default: mp_print(mp, "undefined"); break;
4688 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4689 as well as a |type|. The possibilities for |name_type| are defined
4690 here; they will be explained in more detail later.
4694 mp_root=0, /* |name_type| at the top level of a variable */
4695 mp_saved_root, /* same, when the variable has been saved */
4696 mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4697 mp_subscr, /* |name_type| in a subscript node */
4698 mp_attr, /* |name_type| in an attribute node */
4699 mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4700 mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4701 mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4702 mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4703 mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4704 mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4705 mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4706 mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4707 mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4708 mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4709 mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4710 mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4711 mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4712 mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4713 mp_capsule, /* |name_type| in stashed-away subexpressions */
4714 mp_token /* |name_type| in a numeric token or string token */
4717 @ Primitive operations that produce values have a secondary identification
4718 code in addition to their command code; it's something like genera and species.
4719 For example, `\.*' has the command code |primary_binary|, and its
4720 secondary identification is |times|. The secondary codes start at 30 so that
4721 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4722 are used as operators as well as type identifications. The relative values
4723 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4724 and |filled_op..bounded_op|. The restrictions are that
4725 |and_op-false_code=or_op-true_code|, that the ordering of
4726 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4727 and the ordering of |filled_op..bounded_op| must match that of the code
4728 values they test for.
4730 @d true_code 30 /* operation code for \.{true} */
4731 @d false_code 31 /* operation code for \.{false} */
4732 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4733 @d null_pen_code 33 /* operation code for \.{nullpen} */
4734 @d job_name_op 34 /* operation code for \.{jobname} */
4735 @d read_string_op 35 /* operation code for \.{readstring} */
4736 @d pen_circle 36 /* operation code for \.{pencircle} */
4737 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4738 @d read_from_op 38 /* operation code for \.{readfrom} */
4739 @d close_from_op 39 /* operation code for \.{closefrom} */
4740 @d odd_op 40 /* operation code for \.{odd} */
4741 @d known_op 41 /* operation code for \.{known} */
4742 @d unknown_op 42 /* operation code for \.{unknown} */
4743 @d not_op 43 /* operation code for \.{not} */
4744 @d decimal 44 /* operation code for \.{decimal} */
4745 @d reverse 45 /* operation code for \.{reverse} */
4746 @d make_path_op 46 /* operation code for \.{makepath} */
4747 @d make_pen_op 47 /* operation code for \.{makepen} */
4748 @d oct_op 48 /* operation code for \.{oct} */
4749 @d hex_op 49 /* operation code for \.{hex} */
4750 @d ASCII_op 50 /* operation code for \.{ASCII} */
4751 @d char_op 51 /* operation code for \.{char} */
4752 @d length_op 52 /* operation code for \.{length} */
4753 @d turning_op 53 /* operation code for \.{turningnumber} */
4754 @d color_model_part 54 /* operation code for \.{colormodel} */
4755 @d x_part 55 /* operation code for \.{xpart} */
4756 @d y_part 56 /* operation code for \.{ypart} */
4757 @d xx_part 57 /* operation code for \.{xxpart} */
4758 @d xy_part 58 /* operation code for \.{xypart} */
4759 @d yx_part 59 /* operation code for \.{yxpart} */
4760 @d yy_part 60 /* operation code for \.{yypart} */
4761 @d red_part 61 /* operation code for \.{redpart} */
4762 @d green_part 62 /* operation code for \.{greenpart} */
4763 @d blue_part 63 /* operation code for \.{bluepart} */
4764 @d cyan_part 64 /* operation code for \.{cyanpart} */
4765 @d magenta_part 65 /* operation code for \.{magentapart} */
4766 @d yellow_part 66 /* operation code for \.{yellowpart} */
4767 @d black_part 67 /* operation code for \.{blackpart} */
4768 @d grey_part 68 /* operation code for \.{greypart} */
4769 @d font_part 69 /* operation code for \.{fontpart} */
4770 @d text_part 70 /* operation code for \.{textpart} */
4771 @d path_part 71 /* operation code for \.{pathpart} */
4772 @d pen_part 72 /* operation code for \.{penpart} */
4773 @d dash_part 73 /* operation code for \.{dashpart} */
4774 @d sqrt_op 74 /* operation code for \.{sqrt} */
4775 @d m_exp_op 75 /* operation code for \.{mexp} */
4776 @d m_log_op 76 /* operation code for \.{mlog} */
4777 @d sin_d_op 77 /* operation code for \.{sind} */
4778 @d cos_d_op 78 /* operation code for \.{cosd} */
4779 @d floor_op 79 /* operation code for \.{floor} */
4780 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4781 @d char_exists_op 81 /* operation code for \.{charexists} */
4782 @d font_size 82 /* operation code for \.{fontsize} */
4783 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4784 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4785 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4786 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4787 @d arc_length 87 /* operation code for \.{arclength} */
4788 @d angle_op 88 /* operation code for \.{angle} */
4789 @d cycle_op 89 /* operation code for \.{cycle} */
4790 @d filled_op 90 /* operation code for \.{filled} */
4791 @d stroked_op 91 /* operation code for \.{stroked} */
4792 @d textual_op 92 /* operation code for \.{textual} */
4793 @d clipped_op 93 /* operation code for \.{clipped} */
4794 @d bounded_op 94 /* operation code for \.{bounded} */
4795 @d plus 95 /* operation code for \.+ */
4796 @d minus 96 /* operation code for \.- */
4797 @d times 97 /* operation code for \.* */
4798 @d over 98 /* operation code for \./ */
4799 @d pythag_add 99 /* operation code for \.{++} */
4800 @d pythag_sub 100 /* operation code for \.{+-+} */
4801 @d or_op 101 /* operation code for \.{or} */
4802 @d and_op 102 /* operation code for \.{and} */
4803 @d less_than 103 /* operation code for \.< */
4804 @d less_or_equal 104 /* operation code for \.{<=} */
4805 @d greater_than 105 /* operation code for \.> */
4806 @d greater_or_equal 106 /* operation code for \.{>=} */
4807 @d equal_to 107 /* operation code for \.= */
4808 @d unequal_to 108 /* operation code for \.{<>} */
4809 @d concatenate 109 /* operation code for \.\& */
4810 @d rotated_by 110 /* operation code for \.{rotated} */
4811 @d slanted_by 111 /* operation code for \.{slanted} */
4812 @d scaled_by 112 /* operation code for \.{scaled} */
4813 @d shifted_by 113 /* operation code for \.{shifted} */
4814 @d transformed_by 114 /* operation code for \.{transformed} */
4815 @d x_scaled 115 /* operation code for \.{xscaled} */
4816 @d y_scaled 116 /* operation code for \.{yscaled} */
4817 @d z_scaled 117 /* operation code for \.{zscaled} */
4818 @d in_font 118 /* operation code for \.{infont} */
4819 @d intersect 119 /* operation code for \.{intersectiontimes} */
4820 @d double_dot 120 /* operation code for improper \.{..} */
4821 @d substring_of 121 /* operation code for \.{substring} */
4822 @d min_of substring_of
4823 @d subpath_of 122 /* operation code for \.{subpath} */
4824 @d direction_time_of 123 /* operation code for \.{directiontime} */
4825 @d point_of 124 /* operation code for \.{point} */
4826 @d precontrol_of 125 /* operation code for \.{precontrol} */
4827 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4828 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4829 @d arc_time_of 128 /* operation code for \.{arctime} */
4830 @d mp_version 129 /* operation code for \.{mpversion} */
4831 @d envelope_of 130 /* operation code for \{.envelope} */
4833 @c void mp_print_op (MP mp,quarterword c) {
4834 if (c<=mp_numeric_type ) {
4835 mp_print_type(mp, c);
4838 case true_code:mp_print(mp, "true"); break;
4839 case false_code:mp_print(mp, "false"); break;
4840 case null_picture_code:mp_print(mp, "nullpicture"); break;
4841 case null_pen_code:mp_print(mp, "nullpen"); break;
4842 case job_name_op:mp_print(mp, "jobname"); break;
4843 case read_string_op:mp_print(mp, "readstring"); break;
4844 case pen_circle:mp_print(mp, "pencircle"); break;
4845 case normal_deviate:mp_print(mp, "normaldeviate"); break;
4846 case read_from_op:mp_print(mp, "readfrom"); break;
4847 case close_from_op:mp_print(mp, "closefrom"); break;
4848 case odd_op:mp_print(mp, "odd"); break;
4849 case known_op:mp_print(mp, "known"); break;
4850 case unknown_op:mp_print(mp, "unknown"); break;
4851 case not_op:mp_print(mp, "not"); break;
4852 case decimal:mp_print(mp, "decimal"); break;
4853 case reverse:mp_print(mp, "reverse"); break;
4854 case make_path_op:mp_print(mp, "makepath"); break;
4855 case make_pen_op:mp_print(mp, "makepen"); break;
4856 case oct_op:mp_print(mp, "oct"); break;
4857 case hex_op:mp_print(mp, "hex"); break;
4858 case ASCII_op:mp_print(mp, "ASCII"); break;
4859 case char_op:mp_print(mp, "char"); break;
4860 case length_op:mp_print(mp, "length"); break;
4861 case turning_op:mp_print(mp, "turningnumber"); break;
4862 case x_part:mp_print(mp, "xpart"); break;
4863 case y_part:mp_print(mp, "ypart"); break;
4864 case xx_part:mp_print(mp, "xxpart"); break;
4865 case xy_part:mp_print(mp, "xypart"); break;
4866 case yx_part:mp_print(mp, "yxpart"); break;
4867 case yy_part:mp_print(mp, "yypart"); break;
4868 case red_part:mp_print(mp, "redpart"); break;
4869 case green_part:mp_print(mp, "greenpart"); break;
4870 case blue_part:mp_print(mp, "bluepart"); break;
4871 case cyan_part:mp_print(mp, "cyanpart"); break;
4872 case magenta_part:mp_print(mp, "magentapart"); break;
4873 case yellow_part:mp_print(mp, "yellowpart"); break;
4874 case black_part:mp_print(mp, "blackpart"); break;
4875 case grey_part:mp_print(mp, "greypart"); break;
4876 case color_model_part:mp_print(mp, "colormodel"); break;
4877 case font_part:mp_print(mp, "fontpart"); break;
4878 case text_part:mp_print(mp, "textpart"); break;
4879 case path_part:mp_print(mp, "pathpart"); break;
4880 case pen_part:mp_print(mp, "penpart"); break;
4881 case dash_part:mp_print(mp, "dashpart"); break;
4882 case sqrt_op:mp_print(mp, "sqrt"); break;
4883 case m_exp_op:mp_print(mp, "mexp"); break;
4884 case m_log_op:mp_print(mp, "mlog"); break;
4885 case sin_d_op:mp_print(mp, "sind"); break;
4886 case cos_d_op:mp_print(mp, "cosd"); break;
4887 case floor_op:mp_print(mp, "floor"); break;
4888 case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4889 case char_exists_op:mp_print(mp, "charexists"); break;
4890 case font_size:mp_print(mp, "fontsize"); break;
4891 case ll_corner_op:mp_print(mp, "llcorner"); break;
4892 case lr_corner_op:mp_print(mp, "lrcorner"); break;
4893 case ul_corner_op:mp_print(mp, "ulcorner"); break;
4894 case ur_corner_op:mp_print(mp, "urcorner"); break;
4895 case arc_length:mp_print(mp, "arclength"); break;
4896 case angle_op:mp_print(mp, "angle"); break;
4897 case cycle_op:mp_print(mp, "cycle"); break;
4898 case filled_op:mp_print(mp, "filled"); break;
4899 case stroked_op:mp_print(mp, "stroked"); break;
4900 case textual_op:mp_print(mp, "textual"); break;
4901 case clipped_op:mp_print(mp, "clipped"); break;
4902 case bounded_op:mp_print(mp, "bounded"); break;
4903 case plus:mp_print_char(mp, '+'); break;
4904 case minus:mp_print_char(mp, '-'); break;
4905 case times:mp_print_char(mp, '*'); break;
4906 case over:mp_print_char(mp, '/'); break;
4907 case pythag_add:mp_print(mp, "++"); break;
4908 case pythag_sub:mp_print(mp, "+-+"); break;
4909 case or_op:mp_print(mp, "or"); break;
4910 case and_op:mp_print(mp, "and"); break;
4911 case less_than:mp_print_char(mp, '<'); break;
4912 case less_or_equal:mp_print(mp, "<="); break;
4913 case greater_than:mp_print_char(mp, '>'); break;
4914 case greater_or_equal:mp_print(mp, ">="); break;
4915 case equal_to:mp_print_char(mp, '='); break;
4916 case unequal_to:mp_print(mp, "<>"); break;
4917 case concatenate:mp_print(mp, "&"); break;
4918 case rotated_by:mp_print(mp, "rotated"); break;
4919 case slanted_by:mp_print(mp, "slanted"); break;
4920 case scaled_by:mp_print(mp, "scaled"); break;
4921 case shifted_by:mp_print(mp, "shifted"); break;
4922 case transformed_by:mp_print(mp, "transformed"); break;
4923 case x_scaled:mp_print(mp, "xscaled"); break;
4924 case y_scaled:mp_print(mp, "yscaled"); break;
4925 case z_scaled:mp_print(mp, "zscaled"); break;
4926 case in_font:mp_print(mp, "infont"); break;
4927 case intersect:mp_print(mp, "intersectiontimes"); break;
4928 case substring_of:mp_print(mp, "substring"); break;
4929 case subpath_of:mp_print(mp, "subpath"); break;
4930 case direction_time_of:mp_print(mp, "directiontime"); break;
4931 case point_of:mp_print(mp, "point"); break;
4932 case precontrol_of:mp_print(mp, "precontrol"); break;
4933 case postcontrol_of:mp_print(mp, "postcontrol"); break;
4934 case pen_offset_of:mp_print(mp, "penoffset"); break;
4935 case arc_time_of:mp_print(mp, "arctime"); break;
4936 case mp_version:mp_print(mp, "mpversion"); break;
4937 case envelope_of:mp_print(mp, "envelope"); break;
4938 default: mp_print(mp, ".."); break;
4943 @ \MP\ also has a bunch of internal parameters that a user might want to
4944 fuss with. Every such parameter has an identifying code number, defined here.
4947 enum mp_given_internal {
4948 mp_tracing_titles=1, /* show titles online when they appear */
4949 mp_tracing_equations, /* show each variable when it becomes known */
4950 mp_tracing_capsules, /* show capsules too */
4951 mp_tracing_choices, /* show the control points chosen for paths */
4952 mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
4953 mp_tracing_commands, /* show commands and operations before they are performed */
4954 mp_tracing_restores, /* show when a variable or internal is restored */
4955 mp_tracing_macros, /* show macros before they are expanded */
4956 mp_tracing_output, /* show digitized edges as they are output */
4957 mp_tracing_stats, /* show memory usage at end of job */
4958 mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
4959 mp_tracing_online, /* show long diagnostics on terminal and in the log file */
4960 mp_year, /* the current year (e.g., 1984) */
4961 mp_month, /* the current month (e.g, 3 $\equiv$ March) */
4962 mp_day, /* the current day of the month */
4963 mp_time, /* the number of minutes past midnight when this job started */
4964 mp_char_code, /* the number of the next character to be output */
4965 mp_char_ext, /* the extension code of the next character to be output */
4966 mp_char_wd, /* the width of the next character to be output */
4967 mp_char_ht, /* the height of the next character to be output */
4968 mp_char_dp, /* the depth of the next character to be output */
4969 mp_char_ic, /* the italic correction of the next character to be output */
4970 mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
4971 mp_pausing, /* positive to display lines on the terminal before they are read */
4972 mp_showstopping, /* positive to stop after each \&{show} command */
4973 mp_fontmaking, /* positive if font metric output is to be produced */
4974 mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4975 mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
4976 mp_miterlimit, /* controls miter length as in \ps */
4977 mp_warning_check, /* controls error message when variable value is large */
4978 mp_boundary_char, /* the right boundary character for ligatures */
4979 mp_prologues, /* positive to output conforming PostScript using built-in fonts */
4980 mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4981 mp_default_color_model, /* the default color model for unspecified items */
4982 mp_restore_clip_color,
4983 mp_procset, /* wether or not create PostScript command shortcuts */
4984 mp_gtroffmode, /* whether the user specified |-troff| on the command line */
4989 @d max_given_internal mp_gtroffmode
4992 scaled *internal; /* the values of internal quantities */
4993 char **int_name; /* their names */
4994 int int_ptr; /* the maximum internal quantity defined so far */
4995 int max_internal; /* current maximum number of internal quantities */
4998 @ @<Option variables@>=
5001 @ @<Allocate or initialize ...@>=
5002 mp->max_internal=2*max_given_internal;
5003 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
5004 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
5005 mp->troff_mode=(opt->troff_mode>0 ? true : false);
5007 @ @<Exported function ...@>=
5008 int mp_troff_mode(MP mp);
5011 int mp_troff_mode(MP mp) { return mp->troff_mode; }
5013 @ @<Set initial ...@>=
5014 for (k=0;k<= mp->max_internal; k++ ) {
5016 mp->int_name[k]=NULL;
5018 mp->int_ptr=max_given_internal;
5020 @ The symbolic names for internal quantities are put into \MP's hash table
5021 by using a routine called |primitive|, which will be defined later. Let us
5022 enter them now, so that we don't have to list all those names again
5025 @<Put each of \MP's primitives into the hash table@>=
5026 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5027 @:tracingtitles_}{\&{tracingtitles} primitive@>
5028 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5029 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5030 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5031 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5032 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5033 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5034 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5035 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5036 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5037 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5038 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5039 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5040 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5041 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5042 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5043 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5044 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5045 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5046 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5047 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5048 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5049 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5050 mp_primitive(mp, "year",internal_quantity,mp_year);
5051 @:mp_year_}{\&{year} primitive@>
5052 mp_primitive(mp, "month",internal_quantity,mp_month);
5053 @:mp_month_}{\&{month} primitive@>
5054 mp_primitive(mp, "day",internal_quantity,mp_day);
5055 @:mp_day_}{\&{day} primitive@>
5056 mp_primitive(mp, "time",internal_quantity,mp_time);
5057 @:time_}{\&{time} primitive@>
5058 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5059 @:mp_char_code_}{\&{charcode} primitive@>
5060 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5061 @:mp_char_ext_}{\&{charext} primitive@>
5062 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5063 @:mp_char_wd_}{\&{charwd} primitive@>
5064 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5065 @:mp_char_ht_}{\&{charht} primitive@>
5066 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5067 @:mp_char_dp_}{\&{chardp} primitive@>
5068 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5069 @:mp_char_ic_}{\&{charic} primitive@>
5070 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5071 @:mp_design_size_}{\&{designsize} primitive@>
5072 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5073 @:mp_pausing_}{\&{pausing} primitive@>
5074 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5075 @:mp_showstopping_}{\&{showstopping} primitive@>
5076 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5077 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5078 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5079 @:mp_linejoin_}{\&{linejoin} primitive@>
5080 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5081 @:mp_linecap_}{\&{linecap} primitive@>
5082 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5083 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5084 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5085 @:mp_warning_check_}{\&{warningcheck} primitive@>
5086 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5087 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5088 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5089 @:mp_prologues_}{\&{prologues} primitive@>
5090 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5091 @:mp_true_corners_}{\&{truecorners} primitive@>
5092 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5093 @:mp_procset_}{\&{mpprocset} primitive@>
5094 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5095 @:troffmode_}{\&{troffmode} primitive@>
5096 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5097 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5098 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5099 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5101 @ Colors can be specified in four color models. In the special
5102 case of |no_model|, MetaPost does not output any color operator to
5103 the postscript output.
5105 Note: these values are passed directly on to |with_option|. This only
5106 works because the other possible values passed to |with_option| are
5107 8 and 10 respectively (from |with_pen| and |with_picture|).
5109 There is a first state, that is only used for |gs_colormodel|. It flags
5110 the fact that there has not been any kind of color specification by
5111 the user so far in the game.
5114 enum mp_color_model {
5119 mp_uninitialized_model=9,
5123 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5124 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5125 mp->internal[mp_restore_clip_color]=unity;
5127 @ Well, we do have to list the names one more time, for use in symbolic
5130 @<Initialize table...@>=
5131 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5132 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5133 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5134 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5135 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5136 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5137 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5138 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5139 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5140 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5141 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5142 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5143 mp->int_name[mp_year]=xstrdup("year");
5144 mp->int_name[mp_month]=xstrdup("month");
5145 mp->int_name[mp_day]=xstrdup("day");
5146 mp->int_name[mp_time]=xstrdup("time");
5147 mp->int_name[mp_char_code]=xstrdup("charcode");
5148 mp->int_name[mp_char_ext]=xstrdup("charext");
5149 mp->int_name[mp_char_wd]=xstrdup("charwd");
5150 mp->int_name[mp_char_ht]=xstrdup("charht");
5151 mp->int_name[mp_char_dp]=xstrdup("chardp");
5152 mp->int_name[mp_char_ic]=xstrdup("charic");
5153 mp->int_name[mp_design_size]=xstrdup("designsize");
5154 mp->int_name[mp_pausing]=xstrdup("pausing");
5155 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5156 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5157 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5158 mp->int_name[mp_linecap]=xstrdup("linecap");
5159 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5160 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5161 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5162 mp->int_name[mp_prologues]=xstrdup("prologues");
5163 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5164 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5165 mp->int_name[mp_procset]=xstrdup("mpprocset");
5166 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5167 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5169 @ The following procedure, which is called just before \MP\ initializes its
5170 input and output, establishes the initial values of the date and time.
5171 @^system dependencies@>
5173 Note that the values are |scaled| integers. Hence \MP\ can no longer
5174 be used after the year 32767.
5177 void mp_fix_date_and_time (MP mp) {
5178 time_t clock = time ((time_t *) 0);
5179 struct tm *tmptr = localtime (&clock);
5180 mp->internal[mp_time]=
5181 (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5182 mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5183 mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5184 mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5188 void mp_fix_date_and_time (MP mp) ;
5190 @ \MP\ is occasionally supposed to print diagnostic information that
5191 goes only into the transcript file, unless |mp_tracing_online| is positive.
5192 Now that we have defined |mp_tracing_online| we can define
5193 two routines that adjust the destination of print commands:
5196 void mp_begin_diagnostic (MP mp) ;
5197 void mp_end_diagnostic (MP mp,boolean blank_line);
5198 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5200 @ @<Basic printing...@>=
5201 @<Declare a function called |true_line|@>;
5202 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5203 mp->old_setting=mp->selector;
5204 if ( mp->selector==ps_file_only ) mp->selector=mp->non_ps_setting;
5205 if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){
5207 if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5211 void mp_end_diagnostic (MP mp,boolean blank_line) {
5212 /* restore proper conditions after tracing */
5213 mp_print_nl(mp, "");
5214 if ( blank_line ) mp_print_ln(mp);
5215 mp->selector=mp->old_setting;
5218 @ The global variable |non_ps_setting| is initialized when it is time to print
5222 unsigned int old_setting;
5223 unsigned int non_ps_setting;
5225 @ We will occasionally use |begin_diagnostic| in connection with line-number
5226 printing, as follows. (The parameter |s| is typically |"Path"| or
5227 |"Cycle spec"|, etc.)
5229 @<Basic printing...@>=
5230 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) {
5231 mp_begin_diagnostic(mp);
5232 if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5233 mp_print(mp, " at line ");
5234 mp_print_int(mp, mp_true_line(mp));
5235 mp_print(mp, t); mp_print_char(mp, ':');
5238 @ The 256 |ASCII_code| characters are grouped into classes by means of
5239 the |char_class| table. Individual class numbers have no semantic
5240 or syntactic significance, except in a few instances defined here.
5241 There's also |max_class|, which can be used as a basis for additional
5242 class numbers in nonstandard extensions of \MP.
5244 @d digit_class 0 /* the class number of \.{0123456789} */
5245 @d period_class 1 /* the class number of `\..' */
5246 @d space_class 2 /* the class number of spaces and nonstandard characters */
5247 @d percent_class 3 /* the class number of `\.\%' */
5248 @d string_class 4 /* the class number of `\."' */
5249 @d right_paren_class 8 /* the class number of `\.)' */
5250 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5251 @d letter_class 9 /* letters and the underline character */
5252 @d left_bracket_class 17 /* `\.[' */
5253 @d right_bracket_class 18 /* `\.]' */
5254 @d invalid_class 20 /* bad character in the input */
5255 @d max_class 20 /* the largest class number */
5258 int char_class[256]; /* the class numbers */
5260 @ If changes are made to accommodate non-ASCII character sets, they should
5261 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5262 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5263 @^system dependencies@>
5265 @<Set initial ...@>=
5266 for (k='0';k<='9';k++)
5267 mp->char_class[k]=digit_class;
5268 mp->char_class['.']=period_class;
5269 mp->char_class[' ']=space_class;
5270 mp->char_class['%']=percent_class;
5271 mp->char_class['"']=string_class;
5272 mp->char_class[',']=5;
5273 mp->char_class[';']=6;
5274 mp->char_class['(']=7;
5275 mp->char_class[')']=right_paren_class;
5276 for (k='A';k<= 'Z';k++ )
5277 mp->char_class[k]=letter_class;
5278 for (k='a';k<='z';k++)
5279 mp->char_class[k]=letter_class;
5280 mp->char_class['_']=letter_class;
5281 mp->char_class['<']=10;
5282 mp->char_class['=']=10;
5283 mp->char_class['>']=10;
5284 mp->char_class[':']=10;
5285 mp->char_class['|']=10;
5286 mp->char_class['`']=11;
5287 mp->char_class['\'']=11;
5288 mp->char_class['+']=12;
5289 mp->char_class['-']=12;
5290 mp->char_class['/']=13;
5291 mp->char_class['*']=13;
5292 mp->char_class['\\']=13;
5293 mp->char_class['!']=14;
5294 mp->char_class['?']=14;
5295 mp->char_class['#']=15;
5296 mp->char_class['&']=15;
5297 mp->char_class['@@']=15;
5298 mp->char_class['$']=15;
5299 mp->char_class['^']=16;
5300 mp->char_class['~']=16;
5301 mp->char_class['[']=left_bracket_class;
5302 mp->char_class[']']=right_bracket_class;
5303 mp->char_class['{']=19;
5304 mp->char_class['}']=19;
5306 mp->char_class[k]=invalid_class;
5307 mp->char_class['\t']=space_class;
5308 mp->char_class['\f']=space_class;
5309 for (k=127;k<=255;k++)
5310 mp->char_class[k]=invalid_class;
5312 @* \[13] The hash table.
5313 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5314 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5315 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5316 table, it is never removed.
5318 The actual sequence of characters forming a symbolic token is
5319 stored in the |str_pool| array together with all the other strings. An
5320 auxiliary array |hash| consists of items with two halfword fields per
5321 word. The first of these, called |next(p)|, points to the next identifier
5322 belonging to the same coalesced list as the identifier corresponding to~|p|;
5323 and the other, called |text(p)|, points to the |str_start| entry for
5324 |p|'s identifier. If position~|p| of the hash table is empty, we have
5325 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5326 hash list, we have |next(p)=0|.
5328 An auxiliary pointer variable called |hash_used| is maintained in such a
5329 way that all locations |p>=hash_used| are nonempty. The global variable
5330 |st_count| tells how many symbolic tokens have been defined, if statistics
5333 The first 256 locations of |hash| are reserved for symbols of length one.
5335 There's a parallel array called |eqtb| that contains the current equivalent
5336 values of each symbolic token. The entries of this array consist of
5337 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5338 piece of information that qualifies the |eq_type|).
5340 @d next(A) mp->hash[(A)].lh /* link for coalesced lists */
5341 @d text(A) mp->hash[(A)].rh /* string number for symbolic token name */
5342 @d eq_type(A) mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5343 @d equiv(A) mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5344 @d hash_base 257 /* hashing actually starts here */
5345 @d hash_is_full (mp->hash_used==hash_base) /* are all positions occupied? */
5348 pointer hash_used; /* allocation pointer for |hash| */
5349 integer st_count; /* total number of known identifiers */
5351 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5352 since they are used in error recovery.
5354 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5355 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5356 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5357 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5358 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5359 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5360 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5361 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5362 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5363 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5364 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5365 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5366 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5367 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5368 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5369 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5370 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5373 two_halves *hash; /* the hash table */
5374 two_halves *eqtb; /* the equivalents */
5376 @ @<Allocate or initialize ...@>=
5377 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5378 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5380 @ @<Dealloc variables@>=
5385 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5386 for (k=2;k<=hash_end;k++) {
5387 mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5390 @ @<Initialize table entries...@>=
5391 mp->hash_used=frozen_inaccessible; /* nothing is used */
5393 text(frozen_bad_vardef)=intern("a bad variable");
5394 text(frozen_etex)=intern("etex");
5395 text(frozen_mpx_break)=intern("mpxbreak");
5396 text(frozen_fi)=intern("fi");
5397 text(frozen_end_group)=intern("endgroup");
5398 text(frozen_end_def)=intern("enddef");
5399 text(frozen_end_for)=intern("endfor");
5400 text(frozen_semicolon)=intern(";");
5401 text(frozen_colon)=intern(":");
5402 text(frozen_slash)=intern("/");
5403 text(frozen_left_bracket)=intern("[");
5404 text(frozen_right_delimiter)=intern(")");
5405 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5406 eq_type(frozen_right_delimiter)=right_delimiter;
5408 @ @<Check the ``constant'' values...@>=
5409 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5411 @ Here is the subroutine that searches the hash table for an identifier
5412 that matches a given string of length~|l| appearing in |buffer[j..
5413 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5414 will always be found, and the corresponding hash table address
5418 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5419 integer h; /* hash code */
5420 pointer p; /* index in |hash| array */
5421 pointer k; /* index in |buffer| array */
5423 @<Treat special case of length 1 and |break|@>;
5425 @<Compute the hash code |h|@>;
5426 p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5428 if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j))
5431 @<Insert a new symbolic token after |p|, then
5432 make |p| point to it and |break|@>;
5439 @ @<Treat special case of length 1...@>=
5440 p=mp->buffer[j]+1; text(p)=p-1; return p;
5443 @ @<Insert a new symbolic...@>=
5448 mp_overflow(mp, "hash size",mp->hash_size);
5449 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5450 decr(mp->hash_used);
5451 } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5452 next(p)=mp->hash_used;
5456 for (k=j;k<=j+l-1;k++) {
5457 append_char(mp->buffer[k]);
5459 text(p)=mp_make_string(mp);
5460 mp->str_ref[text(p)]=max_str_ref;
5466 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5467 should be a prime number. The theory of hashing tells us to expect fewer
5468 than two table probes, on the average, when the search is successful.
5469 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5470 @^Vitter, Jeffrey Scott@>
5472 @<Compute the hash code |h|@>=
5474 for (k=j+1;k<=j+l-1;k++){
5475 h=h+h+mp->buffer[k];
5476 while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5479 @ @<Search |eqtb| for equivalents equal to |p|@>=
5480 for (q=1;q<=hash_end;q++) {
5481 if ( equiv(q)==p ) {
5482 mp_print_nl(mp, "EQUIV(");
5483 mp_print_int(mp, q);
5484 mp_print_char(mp, ')');
5488 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5489 table, together with their command code (which will be the |eq_type|)
5490 and an operand (which will be the |equiv|). The |primitive| procedure
5491 does this, in a way that no \MP\ user can. The global value |cur_sym|
5492 contains the new |eqtb| pointer after |primitive| has acted.
5495 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5496 pool_pointer k; /* index into |str_pool| */
5497 small_number j; /* index into |buffer| */
5498 small_number l; /* length of the string */
5501 k=mp->str_start[s]; l=str_stop(s)-k;
5502 /* we will move |s| into the (empty) |buffer| */
5503 for (j=0;j<=l-1;j++) {
5504 mp->buffer[j]=mp->str_pool[k+j];
5506 mp->cur_sym=mp_id_lookup(mp, 0,l);
5507 if ( s>=256 ) { /* we don't want to have the string twice */
5508 mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5510 eq_type(mp->cur_sym)=c;
5511 equiv(mp->cur_sym)=o;
5515 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5516 by their |eq_type| alone. These primitives are loaded into the hash table
5519 @<Put each of \MP's primitives into the hash table@>=
5520 mp_primitive(mp, "..",path_join,0);
5521 @:.._}{\.{..} primitive@>
5522 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5523 @:[ }{\.{[} primitive@>
5524 mp_primitive(mp, "]",right_bracket,0);
5525 @:] }{\.{]} primitive@>
5526 mp_primitive(mp, "}",right_brace,0);
5527 @:]]}{\.{\char`\}} primitive@>
5528 mp_primitive(mp, "{",left_brace,0);
5529 @:][}{\.{\char`\{} primitive@>
5530 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5531 @:: }{\.{:} primitive@>
5532 mp_primitive(mp, "::",double_colon,0);
5533 @::: }{\.{::} primitive@>
5534 mp_primitive(mp, "||:",bchar_label,0);
5535 @:::: }{\.{\char'174\char'174:} primitive@>
5536 mp_primitive(mp, ":=",assignment,0);
5537 @::=_}{\.{:=} primitive@>
5538 mp_primitive(mp, ",",comma,0);
5539 @:, }{\., primitive@>
5540 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5541 @:; }{\.; primitive@>
5542 mp_primitive(mp, "\\",relax,0);
5543 @:]]\\}{\.{\char`\\} primitive@>
5545 mp_primitive(mp, "addto",add_to_command,0);
5546 @:add_to_}{\&{addto} primitive@>
5547 mp_primitive(mp, "atleast",at_least,0);
5548 @:at_least_}{\&{atleast} primitive@>
5549 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5550 @:begin_group_}{\&{begingroup} primitive@>
5551 mp_primitive(mp, "controls",controls,0);
5552 @:controls_}{\&{controls} primitive@>
5553 mp_primitive(mp, "curl",curl_command,0);
5554 @:curl_}{\&{curl} primitive@>
5555 mp_primitive(mp, "delimiters",delimiters,0);
5556 @:delimiters_}{\&{delimiters} primitive@>
5557 mp_primitive(mp, "endgroup",end_group,0);
5558 mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5559 @:endgroup_}{\&{endgroup} primitive@>
5560 mp_primitive(mp, "everyjob",every_job_command,0);
5561 @:every_job_}{\&{everyjob} primitive@>
5562 mp_primitive(mp, "exitif",exit_test,0);
5563 @:exit_if_}{\&{exitif} primitive@>
5564 mp_primitive(mp, "expandafter",expand_after,0);
5565 @:expand_after_}{\&{expandafter} primitive@>
5566 mp_primitive(mp, "interim",interim_command,0);
5567 @:interim_}{\&{interim} primitive@>
5568 mp_primitive(mp, "let",let_command,0);
5569 @:let_}{\&{let} primitive@>
5570 mp_primitive(mp, "newinternal",new_internal,0);
5571 @:new_internal_}{\&{newinternal} primitive@>
5572 mp_primitive(mp, "of",of_token,0);
5573 @:of_}{\&{of} primitive@>
5574 mp_primitive(mp, "randomseed",random_seed,0);
5575 @:random_seed_}{\&{randomseed} primitive@>
5576 mp_primitive(mp, "save",save_command,0);
5577 @:save_}{\&{save} primitive@>
5578 mp_primitive(mp, "scantokens",scan_tokens,0);
5579 @:scan_tokens_}{\&{scantokens} primitive@>
5580 mp_primitive(mp, "shipout",ship_out_command,0);
5581 @:ship_out_}{\&{shipout} primitive@>
5582 mp_primitive(mp, "skipto",skip_to,0);
5583 @:skip_to_}{\&{skipto} primitive@>
5584 mp_primitive(mp, "special",special_command,0);
5585 @:special}{\&{special} primitive@>
5586 mp_primitive(mp, "fontmapfile",special_command,1);
5587 @:fontmapfile}{\&{fontmapfile} primitive@>
5588 mp_primitive(mp, "fontmapline",special_command,2);
5589 @:fontmapline}{\&{fontmapline} primitive@>
5590 mp_primitive(mp, "step",step_token,0);
5591 @:step_}{\&{step} primitive@>
5592 mp_primitive(mp, "str",str_op,0);
5593 @:str_}{\&{str} primitive@>
5594 mp_primitive(mp, "tension",tension,0);
5595 @:tension_}{\&{tension} primitive@>
5596 mp_primitive(mp, "to",to_token,0);
5597 @:to_}{\&{to} primitive@>
5598 mp_primitive(mp, "until",until_token,0);
5599 @:until_}{\&{until} primitive@>
5600 mp_primitive(mp, "within",within_token,0);
5601 @:within_}{\&{within} primitive@>
5602 mp_primitive(mp, "write",write_command,0);
5603 @:write_}{\&{write} primitive@>
5605 @ Each primitive has a corresponding inverse, so that it is possible to
5606 display the cryptic numeric contents of |eqtb| in symbolic form.
5607 Every call of |primitive| in this program is therefore accompanied by some
5608 straightforward code that forms part of the |print_cmd_mod| routine
5611 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5612 case add_to_command:mp_print(mp, "addto"); break;
5613 case assignment:mp_print(mp, ":="); break;
5614 case at_least:mp_print(mp, "atleast"); break;
5615 case bchar_label:mp_print(mp, "||:"); break;
5616 case begin_group:mp_print(mp, "begingroup"); break;
5617 case colon:mp_print(mp, ":"); break;
5618 case comma:mp_print(mp, ","); break;
5619 case controls:mp_print(mp, "controls"); break;
5620 case curl_command:mp_print(mp, "curl"); break;
5621 case delimiters:mp_print(mp, "delimiters"); break;
5622 case double_colon:mp_print(mp, "::"); break;
5623 case end_group:mp_print(mp, "endgroup"); break;
5624 case every_job_command:mp_print(mp, "everyjob"); break;
5625 case exit_test:mp_print(mp, "exitif"); break;
5626 case expand_after:mp_print(mp, "expandafter"); break;
5627 case interim_command:mp_print(mp, "interim"); break;
5628 case left_brace:mp_print(mp, "{"); break;
5629 case left_bracket:mp_print(mp, "["); break;
5630 case let_command:mp_print(mp, "let"); break;
5631 case new_internal:mp_print(mp, "newinternal"); break;
5632 case of_token:mp_print(mp, "of"); break;
5633 case path_join:mp_print(mp, ".."); break;
5634 case random_seed:mp_print(mp, "randomseed"); break;
5635 case relax:mp_print_char(mp, '\\'); break;
5636 case right_brace:mp_print(mp, "}"); break;
5637 case right_bracket:mp_print(mp, "]"); break;
5638 case save_command:mp_print(mp, "save"); break;
5639 case scan_tokens:mp_print(mp, "scantokens"); break;
5640 case semicolon:mp_print(mp, ";"); break;
5641 case ship_out_command:mp_print(mp, "shipout"); break;
5642 case skip_to:mp_print(mp, "skipto"); break;
5643 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5644 if ( m==1 ) mp_print(mp, "fontmapfile"); else
5645 mp_print(mp, "special"); break;
5646 case step_token:mp_print(mp, "step"); break;
5647 case str_op:mp_print(mp, "str"); break;
5648 case tension:mp_print(mp, "tension"); break;
5649 case to_token:mp_print(mp, "to"); break;
5650 case until_token:mp_print(mp, "until"); break;
5651 case within_token:mp_print(mp, "within"); break;
5652 case write_command:mp_print(mp, "write"); break;
5654 @ We will deal with the other primitives later, at some point in the program
5655 where their |eq_type| and |equiv| values are more meaningful. For example,
5656 the primitives for macro definitions will be loaded when we consider the
5657 routines that define macros.
5658 It is easy to find where each particular
5659 primitive was treated by looking in the index at the end; for example, the
5660 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5662 @* \[14] Token lists.
5663 A \MP\ token is either symbolic or numeric or a string, or it denotes
5664 a macro parameter or capsule; so there are five corresponding ways to encode it
5666 internally: (1)~A symbolic token whose hash code is~|p|
5667 is represented by the number |p|, in the |info| field of a single-word
5668 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5669 represented in a two-word node of~|mem|; the |type| field is |known|,
5670 the |name_type| field is |token|, and the |value| field holds~|v|.
5671 The fact that this token appears in a two-word node rather than a
5672 one-word node is, of course, clear from the node address.
5673 (3)~A string token is also represented in a two-word node; the |type|
5674 field is |mp_string_type|, the |name_type| field is |token|, and the
5675 |value| field holds the corresponding |str_number|. (4)~Capsules have
5676 |name_type=capsule|, and their |type| and |value| fields represent
5677 arbitrary values (in ways to be explained later). (5)~Macro parameters
5678 are like symbolic tokens in that they appear in |info| fields of
5679 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5680 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5681 by |text_base+k| if it is of type \&{text}. (Here |0<=k<param_size|.)
5682 Actual values of these parameters are kept in a separate stack, as we will
5683 see later. The constants |expr_base|, |suffix_base|, and |text_base| are,
5684 of course, chosen so that there will be no confusion between symbolic
5685 tokens and parameters of various types.
5688 the `\\{type}' field of a node has nothing to do with ``type'' in a
5689 printer's sense. It's curious that the same word is used in such different ways.
5691 @d type(A) mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5692 @d name_type(A) mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5693 @d token_node_size 2 /* the number of words in a large token node */
5694 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5695 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5696 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5697 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5698 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5700 @<Check the ``constant''...@>=
5701 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5703 @ We have set aside a two word node beginning at |null| so that we can have
5704 |value(null)=0|. We will make use of this coincidence later.
5706 @<Initialize table entries...@>=
5707 link(null)=null; value(null)=0;
5709 @ A numeric token is created by the following trivial routine.
5712 pointer mp_new_num_tok (MP mp,scaled v) {
5713 pointer p; /* the new node */
5714 p=mp_get_node(mp, token_node_size); value(p)=v;
5715 type(p)=mp_known; name_type(p)=mp_token;
5719 @ A token list is a singly linked list of nodes in |mem|, where
5720 each node contains a token and a link. Here's a subroutine that gets rid
5721 of a token list when it is no longer needed.
5724 void mp_token_recycle (MP mp);
5727 @c void mp_flush_token_list (MP mp,pointer p) {
5728 pointer q; /* the node being recycled */
5731 if ( q>=mp->hi_mem_min ) {
5735 case mp_vacuous: case mp_boolean_type: case mp_known:
5737 case mp_string_type:
5738 delete_str_ref(value(q));
5740 case unknown_types: case mp_pen_type: case mp_path_type:
5741 case mp_picture_type: case mp_pair_type: case mp_color_type:
5742 case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5743 case mp_proto_dependent: case mp_independent:
5744 mp->g_pointer=q; mp_token_recycle(mp);
5746 default: mp_confusion(mp, "token");
5747 @:this can't happen token}{\quad token@>
5749 mp_free_node(mp, q,token_node_size);
5754 @ The procedure |show_token_list|, which prints a symbolic form of
5755 the token list that starts at a given node |p|, illustrates these
5756 conventions. The token list being displayed should not begin with a reference
5757 count. However, the procedure is intended to be fairly robust, so that if the
5758 memory links are awry or if |p| is not really a pointer to a token list,
5759 almost nothing catastrophic can happen.
5761 An additional parameter |q| is also given; this parameter is either null
5762 or it points to a node in the token list where a certain magic computation
5763 takes place that will be explained later. (Basically, |q| is non-null when
5764 we are printing the two-line context information at the time of an error
5765 message; |q| marks the place corresponding to where the second line
5768 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5769 of printing exceeds a given limit~|l|; the length of printing upon entry is
5770 assumed to be a given amount called |null_tally|. (Note that
5771 |show_token_list| sometimes uses itself recursively to print
5772 variable names within a capsule.)
5775 Unusual entries are printed in the form of all-caps tokens
5776 preceded by a space, e.g., `\.{\char`\ BAD}'.
5779 void mp_print_capsule (MP mp);
5781 @ @<Declare the procedure called |show_token_list|@>=
5782 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5783 integer null_tally) ;
5786 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5787 integer null_tally) {
5788 small_number class,c; /* the |char_class| of previous and new tokens */
5789 integer r,v; /* temporary registers */
5790 class=percent_class;
5791 mp->tally=null_tally;
5792 while ( (p!=null) && (mp->tally<l) ) {
5794 @<Do magic computation@>;
5795 @<Display token |p| and set |c| to its class;
5796 but |return| if there are problems@>;
5800 mp_print(mp, " ETC.");
5805 @ @<Display token |p| and set |c| to its class...@>=
5806 c=letter_class; /* the default */
5807 if ( (p<0)||(p>mp->mem_end) ) {
5808 mp_print(mp, " CLOBBERED"); return;
5811 if ( p<mp->hi_mem_min ) {
5812 @<Display two-word token@>;
5815 if ( r>=expr_base ) {
5816 @<Display a parameter token@>;
5820 @<Display a collective subscript@>
5822 mp_print(mp, " IMPOSSIBLE");
5827 if ( (r<0)||(r>mp->max_str_ptr) ) {
5828 mp_print(mp, " NONEXISTENT");
5831 @<Print string |r| as a symbolic token
5832 and set |c| to its class@>;
5838 @ @<Display two-word token@>=
5839 if ( name_type(p)==mp_token ) {
5840 if ( type(p)==mp_known ) {
5841 @<Display a numeric token@>;
5842 } else if ( type(p)!=mp_string_type ) {
5843 mp_print(mp, " BAD");
5846 mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5849 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5850 mp_print(mp, " BAD");
5852 mp->g_pointer=p; mp_print_capsule(mp); c=right_paren_class;
5855 @ @<Display a numeric token@>=
5856 if ( class==digit_class )
5857 mp_print_char(mp, ' ');
5860 if ( class==left_bracket_class )
5861 mp_print_char(mp, ' ');
5862 mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5863 c=right_bracket_class;
5865 mp_print_scaled(mp, v); c=digit_class;
5869 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5870 But we will see later (in the |print_variable_name| routine) that
5871 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5873 @<Display a collective subscript@>=
5875 if ( class==left_bracket_class )
5876 mp_print_char(mp, ' ');
5877 mp_print(mp, "[]"); c=right_bracket_class;
5880 @ @<Display a parameter token@>=
5882 if ( r<suffix_base ) {
5883 mp_print(mp, "(EXPR"); r=r-(expr_base);
5885 } else if ( r<text_base ) {
5886 mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5889 mp_print(mp, "(TEXT"); r=r-(text_base);
5892 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5896 @ @<Print string |r| as a symbolic token...@>=
5898 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5901 case letter_class:mp_print_char(mp, '.'); break;
5902 case isolated_classes: break;
5903 default: mp_print_char(mp, ' '); break;
5906 mp_print_str(mp, r);
5909 @ The following procedures have been declared |forward| with no parameters,
5910 because the author dislikes \PASCAL's convention about |forward| procedures
5911 with parameters. It was necessary to do something, because |show_token_list|
5912 is recursive (although the recursion is limited to one level), and because
5913 |flush_token_list| is syntactically (but not semantically) recursive.
5916 @<Declare miscellaneous procedures that were declared |forward|@>=
5917 void mp_print_capsule (MP mp) {
5918 mp_print_char(mp, '('); mp_print_exp(mp, mp->g_pointer,0); mp_print_char(mp, ')');
5921 void mp_token_recycle (MP mp) {
5922 mp_recycle_value(mp, mp->g_pointer);
5926 pointer g_pointer; /* (global) parameter to the |forward| procedures */
5928 @ Macro definitions are kept in \MP's memory in the form of token lists
5929 that have a few extra one-word nodes at the beginning.
5931 The first node contains a reference count that is used to tell when the
5932 list is no longer needed. To emphasize the fact that a reference count is
5933 present, we shall refer to the |info| field of this special node as the
5935 @^reference counts@>
5937 The next node or nodes after the reference count serve to describe the
5938 formal parameters. They either contain a code word that specifies all
5939 of the parameters, or they contain zero or more parameter tokens followed
5940 by the code `|general_macro|'.
5943 /* reference count preceding a macro definition or picture header */
5944 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5945 @d general_macro 0 /* preface to a macro defined with a parameter list */
5946 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5947 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5948 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5949 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5950 @d of_macro 5 /* preface to a macro with
5951 undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5952 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5953 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5956 void mp_delete_mac_ref (MP mp,pointer p) {
5957 /* |p| points to the reference count of a macro list that is
5958 losing one reference */
5959 if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5960 else decr(ref_count(p));
5963 @ The following subroutine displays a macro, given a pointer to its
5967 @<Declare the procedure called |print_cmd_mod|@>;
5968 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5969 pointer r; /* temporary storage */
5970 p=link(p); /* bypass the reference count */
5971 while ( info(p)>text_macro ){
5972 r=link(p); link(p)=null;
5973 mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5974 if ( l>0 ) l=l-mp->tally; else return;
5975 } /* control printing of `\.{ETC.}' */
5979 case general_macro:mp_print(mp, "->"); break;
5981 case primary_macro: case secondary_macro: case tertiary_macro:
5982 mp_print_char(mp, '<');
5983 mp_print_cmd_mod(mp, param_type,info(p));
5984 mp_print(mp, ">->");
5986 case expr_macro:mp_print(mp, "<expr>->"); break;
5987 case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5988 case suffix_macro:mp_print(mp, "<suffix>->"); break;
5989 case text_macro:mp_print(mp, "<text>->"); break;
5990 } /* there are no other cases */
5991 mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5994 @* \[15] Data structures for variables.
5995 The variables of \MP\ programs can be simple, like `\.x', or they can
5996 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5997 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5998 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
5999 things are represented inside of the computer.
6001 Each variable value occupies two consecutive words, either in a two-word
6002 node called a value node, or as a two-word subfield of a larger node. One
6003 of those two words is called the |value| field; it is an integer,
6004 containing either a |scaled| numeric value or the representation of some
6005 other type of quantity. (It might also be subdivided into halfwords, in
6006 which case it is referred to by other names instead of |value|.) The other
6007 word is broken into subfields called |type|, |name_type|, and |link|. The
6008 |type| field is a quarterword that specifies the variable's type, and
6009 |name_type| is a quarterword from which \MP\ can reconstruct the
6010 variable's name (sometimes by using the |link| field as well). Thus, only
6011 1.25 words are actually devoted to the value itself; the other
6012 three-quarters of a word are overhead, but they aren't wasted because they
6013 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
6015 In this section we shall be concerned only with the structural aspects of
6016 variables, not their values. Later parts of the program will change the
6017 |type| and |value| fields, but we shall treat those fields as black boxes
6018 whose contents should not be touched.
6020 However, if the |type| field is |mp_structured|, there is no |value| field,
6021 and the second word is broken into two pointer fields called |attr_head|
6022 and |subscr_head|. Those fields point to additional nodes that
6023 contain structural information, as we shall see.
6025 @d subscr_head_loc(A) (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
6026 @d attr_head(A) info(subscr_head_loc((A))) /* pointer to attribute info */
6027 @d subscr_head(A) link(subscr_head_loc((A))) /* pointer to subscript info */
6028 @d value_node_size 2 /* the number of words in a value node */
6030 @ An attribute node is three words long. Two of these words contain |type|
6031 and |value| fields as described above, and the third word contains
6032 additional information: There is an |attr_loc| field, which contains the
6033 hash address of the token that names this attribute; and there's also a
6034 |parent| field, which points to the value node of |mp_structured| type at the
6035 next higher level (i.e., at the level to which this attribute is
6036 subsidiary). The |name_type| in an attribute node is `|attr|'. The
6037 |link| field points to the next attribute with the same parent; these are
6038 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
6039 final attribute node links to the constant |end_attr|, whose |attr_loc|
6040 field is greater than any legal hash address. The |attr_head| in the
6041 parent points to a node whose |name_type| is |mp_structured_root|; this
6042 node represents the null attribute, i.e., the variable that is relevant
6043 when no attributes are attached to the parent. The |attr_head| node is either
6044 a value node, a subscript node, or an attribute node, depending on what
6045 the parent would be if it were not structured; but the subscript and
6046 attribute fields are ignored, so it effectively contains only the data of
6047 a value node. The |link| field in this special node points to an attribute
6048 node whose |attr_loc| field is zero; the latter node represents a collective
6049 subscript `\.{[]}' attached to the parent, and its |link| field points to
6050 the first non-special attribute node (or to |end_attr| if there are none).
6052 A subscript node likewise occupies three words, with |type| and |value| fields
6053 plus extra information; its |name_type| is |subscr|. In this case the
6054 third word is called the |subscript| field, which is a |scaled| integer.
6055 The |link| field points to the subscript node with the next larger
6056 subscript, if any; otherwise the |link| points to the attribute node
6057 for collective subscripts at this level. We have seen that the latter node
6058 contains an upward pointer, so that the parent can be deduced.
6060 The |name_type| in a parent-less value node is |root|, and the |link|
6061 is the hash address of the token that names this value.
6063 In other words, variables have a hierarchical structure that includes
6064 enough threads running around so that the program is able to move easily
6065 between siblings, parents, and children. An example should be helpful:
6066 (The reader is advised to draw a picture while reading the following
6067 description, since that will help to firm up the ideas.)
6068 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6069 and `\.{x20b}' have been mentioned in a user's program, where
6070 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6071 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6072 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6073 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
6074 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6075 node and |r| to a subscript node. (Are you still following this? Use
6076 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6077 |type(q)| and |value(q)|; furthermore
6078 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6079 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6080 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6081 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6082 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
6083 numeric, because |qq| represents `\.{x[]}' with no further attributes),
6084 |name_type(qq)=mp_structured_root|, and
6085 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6086 an attribute node representing `\.{x[][]}', which has never yet
6087 occurred; its |type| field is |undefined|, and its |value| field is
6088 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6089 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6090 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6091 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6092 (Maybe colored lines will help untangle your picture.)
6093 Node |r| is a subscript node with |type| and |value|
6094 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6095 and |link(r)=r1| is another subscript node. To complete the picture,
6096 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6097 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6098 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6099 and we finish things off with three more nodes
6100 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6101 with a larger sheet of paper.) The value of variable \.{x20b}
6102 appears in node~|qqq2|, as you can well imagine.
6104 If the example in the previous paragraph doesn't make things crystal
6105 clear, a glance at some of the simpler subroutines below will reveal how
6106 things work out in practice.
6108 The only really unusual thing about these conventions is the use of
6109 collective subscript attributes. The idea is to avoid repeating a lot of
6110 type information when many elements of an array are identical macros
6111 (for which distinct values need not be stored) or when they don't have
6112 all of the possible attributes. Branches of the structure below collective
6113 subscript attributes do not carry actual values except for macro identifiers;
6114 branches of the structure below subscript nodes do not carry significant
6115 information in their collective subscript attributes.
6117 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6118 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6119 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6120 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6121 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6122 @d attr_node_size 3 /* the number of words in an attribute node */
6123 @d subscr_node_size 3 /* the number of words in a subscript node */
6124 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6126 @<Initialize table...@>=
6127 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6129 @ Variables of type \&{pair} will have values that point to four-word
6130 nodes containing two numeric values. The first of these values has
6131 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6132 the |link| in the first points back to the node whose |value| points
6133 to this four-word node.
6135 Variables of type \&{transform} are similar, but in this case their
6136 |value| points to a 12-word node containing six values, identified by
6137 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6138 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6139 Finally, variables of type \&{color} have three values in six words
6140 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6142 When an entire structured variable is saved, the |root| indication
6143 is temporarily replaced by |saved_root|.
6145 Some variables have no name; they just are used for temporary storage
6146 while expressions are being evaluated. We call them {\sl capsules}.
6148 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6149 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6150 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6151 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6152 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6153 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6154 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6155 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6156 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6157 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6158 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6159 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6160 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6161 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6163 @d pair_node_size 4 /* the number of words in a pair node */
6164 @d transform_node_size 12 /* the number of words in a transform node */
6165 @d color_node_size 6 /* the number of words in a color node */
6166 @d cmykcolor_node_size 8 /* the number of words in a color node */
6169 small_number big_node_size[mp_pair_type+1];
6170 small_number sector0[mp_pair_type+1];
6171 small_number sector_offset[mp_black_part_sector+1];
6173 @ The |sector0| array gives for each big node type, |name_type| values
6174 for its first subfield; the |sector_offset| array gives for each
6175 |name_type| value, the offset from the first subfield in words;
6176 and the |big_node_size| array gives the size in words for each type of
6180 mp->big_node_size[mp_transform_type]=transform_node_size;
6181 mp->big_node_size[mp_pair_type]=pair_node_size;
6182 mp->big_node_size[mp_color_type]=color_node_size;
6183 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6184 mp->sector0[mp_transform_type]=mp_x_part_sector;
6185 mp->sector0[mp_pair_type]=mp_x_part_sector;
6186 mp->sector0[mp_color_type]=mp_red_part_sector;
6187 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6188 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6189 mp->sector_offset[k]=2*(k-mp_x_part_sector);
6191 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6192 mp->sector_offset[k]=2*(k-mp_red_part_sector);
6194 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6195 mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6198 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6199 procedure call |init_big_node(p)| will allocate a pair or transform node
6200 for~|p|. The individual parts of such nodes are initially of type
6204 void mp_init_big_node (MP mp,pointer p) {
6205 pointer q; /* the new node */
6206 small_number s; /* its size */
6207 s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6210 @<Make variable |q+s| newly independent@>;
6211 name_type(q+s)=halfp(s)+mp->sector0[type(p)];
6214 link(q)=p; value(p)=q;
6217 @ The |id_transform| function creates a capsule for the
6218 identity transformation.
6221 pointer mp_id_transform (MP mp) {
6222 pointer p,q,r; /* list manipulation registers */
6223 p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6224 name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6225 r=q+transform_node_size;
6228 type(r)=mp_known; value(r)=0;
6230 value(xx_part_loc(q))=unity;
6231 value(yy_part_loc(q))=unity;
6235 @ Tokens are of type |tag_token| when they first appear, but they point
6236 to |null| until they are first used as the root of a variable.
6237 The following subroutine establishes the root node on such grand occasions.
6240 void mp_new_root (MP mp,pointer x) {
6241 pointer p; /* the new node */
6242 p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6243 link(p)=x; equiv(x)=p;
6246 @ These conventions for variable representation are illustrated by the
6247 |print_variable_name| routine, which displays the full name of a
6248 variable given only a pointer to its two-word value packet.
6251 void mp_print_variable_name (MP mp, pointer p);
6254 void mp_print_variable_name (MP mp, pointer p) {
6255 pointer q; /* a token list that will name the variable's suffix */
6256 pointer r; /* temporary for token list creation */
6257 while ( name_type(p)>=mp_x_part_sector ) {
6258 @<Preface the output with a part specifier; |return| in the
6259 case of a capsule@>;
6262 while ( name_type(p)>mp_saved_root ) {
6263 @<Ascend one level, pushing a token onto list |q|
6264 and replacing |p| by its parent@>;
6266 r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6267 if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6269 mp_show_token_list(mp, r,null,el_gordo,mp->tally);
6270 mp_flush_token_list(mp, r);
6273 @ @<Ascend one level, pushing a token onto list |q|...@>=
6275 if ( name_type(p)==mp_subscr ) {
6276 r=mp_new_num_tok(mp, subscript(p));
6279 } while (name_type(p)!=mp_attr);
6280 } else if ( name_type(p)==mp_structured_root ) {
6281 p=link(p); goto FOUND;
6283 if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6284 @:this can't happen var}{\quad var@>
6285 r=mp_get_avail(mp); info(r)=attr_loc(p);
6292 @ @<Preface the output with a part specifier...@>=
6293 { switch (name_type(p)) {
6294 case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6295 case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6296 case mp_xx_part_sector: mp_print(mp, "xx"); break;
6297 case mp_xy_part_sector: mp_print(mp, "xy"); break;
6298 case mp_yx_part_sector: mp_print(mp, "yx"); break;
6299 case mp_yy_part_sector: mp_print(mp, "yy"); break;
6300 case mp_red_part_sector: mp_print(mp, "red"); break;
6301 case mp_green_part_sector: mp_print(mp, "green"); break;
6302 case mp_blue_part_sector: mp_print(mp, "blue"); break;
6303 case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6304 case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6305 case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6306 case mp_black_part_sector: mp_print(mp, "black"); break;
6307 case mp_grey_part_sector: mp_print(mp, "grey"); break;
6309 mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6312 } /* there are no other cases */
6313 mp_print(mp, "part ");
6314 p=link(p-mp->sector_offset[name_type(p)]);
6317 @ The |interesting| function returns |true| if a given variable is not
6318 in a capsule, or if the user wants to trace capsules.
6321 boolean mp_interesting (MP mp,pointer p) {
6322 small_number t; /* a |name_type| */
6323 if ( mp->internal[mp_tracing_capsules]>0 ) {
6327 if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6328 t=name_type(link(p-mp->sector_offset[t]));
6329 return (t!=mp_capsule);
6333 @ Now here is a subroutine that converts an unstructured type into an
6334 equivalent structured type, by inserting a |mp_structured| node that is
6335 capable of growing. This operation is done only when |name_type(p)=root|,
6336 |subscr|, or |attr|.
6338 The procedure returns a pointer to the new node that has taken node~|p|'s
6339 place in the structure. Node~|p| itself does not move, nor are its
6340 |value| or |type| fields changed in any way.
6343 pointer mp_new_structure (MP mp,pointer p) {
6344 pointer q,r=0; /* list manipulation registers */
6345 switch (name_type(p)) {
6347 q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6350 @<Link a new subscript node |r| in place of node |p|@>;
6353 @<Link a new attribute node |r| in place of node |p|@>;
6356 mp_confusion(mp, "struct");
6357 @:this can't happen struct}{\quad struct@>
6360 link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6361 attr_head(r)=p; name_type(p)=mp_structured_root;
6362 q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6363 parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6364 attr_loc(q)=collective_subscript;
6368 @ @<Link a new subscript node |r| in place of node |p|@>=
6373 } while (name_type(q)!=mp_attr);
6374 q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6378 r=mp_get_node(mp, subscr_node_size);
6379 link(q)=r; subscript(r)=subscript(p);
6382 @ If the attribute is |collective_subscript|, there are two pointers to
6383 node~|p|, so we must change both of them.
6385 @<Link a new attribute node |r| in place of node |p|@>=
6387 q=parent(p); r=attr_head(q);
6391 r=mp_get_node(mp, attr_node_size); link(q)=r;
6392 mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6393 if ( attr_loc(p)==collective_subscript ) {
6394 q=subscr_head_loc(parent(p));
6395 while ( link(q)!=p ) q=link(q);
6400 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6401 list of suffixes; it returns a pointer to the corresponding two-word
6402 value. For example, if |t| points to token \.x followed by a numeric
6403 token containing the value~7, |find_variable| finds where the value of
6404 \.{x7} is stored in memory. This may seem a simple task, and it
6405 usually is, except when \.{x7} has never been referenced before.
6406 Indeed, \.x may never have even been subscripted before; complexities
6407 arise with respect to updating the collective subscript information.
6409 If a macro type is detected anywhere along path~|t|, or if the first
6410 item on |t| isn't a |tag_token|, the value |null| is returned.
6411 Otherwise |p| will be a non-null pointer to a node such that
6412 |undefined<type(p)<mp_structured|.
6414 @d abort_find { return null; }
6417 pointer mp_find_variable (MP mp,pointer t) {
6418 pointer p,q,r,s; /* nodes in the ``value'' line */
6419 pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6420 integer n; /* subscript or attribute */
6421 memory_word save_word; /* temporary storage for a word of |mem| */
6423 p=info(t); t=link(t);
6424 if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6425 if ( equiv(p)==null ) mp_new_root(mp, p);
6428 @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6429 if ( t<mp->hi_mem_min ) {
6430 @<Descend one level for the subscript |value(t)|@>
6432 @<Descend one level for the attribute |info(t)|@>;
6436 if ( type(pp)>=mp_structured ) {
6437 if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6439 if ( type(p)==mp_structured ) p=attr_head(p);
6440 if ( type(p)==undefined ) {
6441 if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6442 type(p)=type(pp); value(p)=null;
6447 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6448 |pp|~stays in the collective line while |p|~goes through actual subscript
6451 @<Make sure that both nodes |p| and |pp|...@>=
6452 if ( type(pp)!=mp_structured ) {
6453 if ( type(pp)>mp_structured ) abort_find;
6454 ss=mp_new_structure(mp, pp);
6457 }; /* now |type(pp)=mp_structured| */
6458 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6459 p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6461 @ We want this part of the program to be reasonably fast, in case there are
6463 lots of subscripts at the same level of the data structure. Therefore
6464 we store an ``infinite'' value in the word that appears at the end of the
6465 subscript list, even though that word isn't part of a subscript node.
6467 @<Descend one level for the subscript |value(t)|@>=
6470 pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6471 q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6472 subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6475 } while (n>subscript(s));
6476 if ( n==subscript(s) ) {
6479 p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6480 subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6482 mp->mem[subscript_loc(q)]=save_word;
6485 @ @<Descend one level for the attribute |info(t)|@>=
6491 } while (n>attr_loc(ss));
6492 if ( n<attr_loc(ss) ) {
6493 qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6494 attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6495 parent(qq)=pp; ss=qq;
6500 pp=ss; s=attr_head(p);
6503 } while (n>attr_loc(s));
6504 if ( n==attr_loc(s) ) {
6507 q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6508 attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6514 @ Variables lose their former values when they appear in a type declaration,
6515 or when they are defined to be macros or \&{let} equal to something else.
6516 A subroutine will be defined later that recycles the storage associated
6517 with any particular |type| or |value|; our goal now is to study a higher
6518 level process called |flush_variable|, which selectively frees parts of a
6521 This routine has some complexity because of examples such as
6522 `\hbox{\tt numeric x[]a[]b}'
6523 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6524 `\hbox{\tt vardef x[]a[]=...}'
6525 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6526 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6527 to handle such examples is to use recursion; so that's what we~do.
6530 Parameter |p| points to the root information of the variable;
6531 parameter |t| points to a list of one-word nodes that represent
6532 suffixes, with |info=collective_subscript| for subscripts.
6535 @<Declare subroutines for printing expressions@>
6536 @<Declare basic dependency-list subroutines@>
6537 @<Declare the recycling subroutines@>
6538 void mp_flush_cur_exp (MP mp,scaled v) ;
6539 @<Declare the procedure called |flush_below_variable|@>
6542 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6543 pointer q,r; /* list manipulation */
6544 halfword n; /* attribute to match */
6546 if ( type(p)!=mp_structured ) return;
6547 n=info(t); t=link(t);
6548 if ( n==collective_subscript ) {
6549 r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6550 while ( name_type(q)==mp_subscr ){
6551 mp_flush_variable(mp, q,t,discard_suffixes);
6553 if ( type(q)==mp_structured ) r=q;
6554 else { link(r)=link(q); mp_free_node(mp, q,subscr_node_size); }
6564 } while (attr_loc(p)<n);
6565 if ( attr_loc(p)!=n ) return;
6567 if ( discard_suffixes ) {
6568 mp_flush_below_variable(mp, p);
6570 if ( type(p)==mp_structured ) p=attr_head(p);
6571 mp_recycle_value(mp, p);
6575 @ The next procedure is simpler; it wipes out everything but |p| itself,
6576 which becomes undefined.
6578 @<Declare the procedure called |flush_below_variable|@>=
6579 void mp_flush_below_variable (MP mp, pointer p);
6582 void mp_flush_below_variable (MP mp,pointer p) {
6583 pointer q,r; /* list manipulation registers */
6584 if ( type(p)!=mp_structured ) {
6585 mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6588 while ( name_type(q)==mp_subscr ) {
6589 mp_flush_below_variable(mp, q); r=q; q=link(q);
6590 mp_free_node(mp, r,subscr_node_size);
6592 r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6593 if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6594 else mp_free_node(mp, r,subscr_node_size);
6595 /* we assume that |subscr_node_size=attr_node_size| */
6597 mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6598 } while (q!=end_attr);
6603 @ Just before assigning a new value to a variable, we will recycle the
6604 old value and make the old value undefined. The |und_type| routine
6605 determines what type of undefined value should be given, based on
6606 the current type before recycling.
6609 small_number mp_und_type (MP mp,pointer p) {
6611 case undefined: case mp_vacuous:
6613 case mp_boolean_type: case mp_unknown_boolean:
6614 return mp_unknown_boolean;
6615 case mp_string_type: case mp_unknown_string:
6616 return mp_unknown_string;
6617 case mp_pen_type: case mp_unknown_pen:
6618 return mp_unknown_pen;
6619 case mp_path_type: case mp_unknown_path:
6620 return mp_unknown_path;
6621 case mp_picture_type: case mp_unknown_picture:
6622 return mp_unknown_picture;
6623 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6624 case mp_pair_type: case mp_numeric_type:
6626 case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6627 return mp_numeric_type;
6628 } /* there are no other cases */
6632 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6633 of a symbolic token. It must remove any variable structure or macro
6634 definition that is currently attached to that symbol. If the |saving|
6635 parameter is true, a subsidiary structure is saved instead of destroyed.
6638 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6639 pointer q; /* |equiv(p)| */
6641 switch (eq_type(p) % outer_tag) {
6643 case secondary_primary_macro:
6644 case tertiary_secondary_macro:
6645 case expression_tertiary_macro:
6646 if ( ! saving ) mp_delete_mac_ref(mp, q);
6651 name_type(q)=mp_saved_root;
6653 mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size);
6660 mp->eqtb[p]=mp->eqtb[frozen_undefined];
6663 @* \[16] Saving and restoring equivalents.
6664 The nested structure given by \&{begingroup} and \&{endgroup}
6665 allows |eqtb| entries to be saved and restored, so that temporary changes
6666 can be made without difficulty. When the user requests a current value to
6667 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6668 \&{endgroup} ultimately causes the old values to be removed from the save
6669 stack and put back in their former places.
6671 The save stack is a linked list containing three kinds of entries,
6672 distinguished by their |info| fields. If |p| points to a saved item,
6676 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6677 such an item to the save stack and each \&{endgroup} cuts back the stack
6678 until the most recent such entry has been removed.
6681 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6682 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6683 commands or suitable \&{interim} commands.
6686 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6687 integer to be restored to internal parameter number~|q|. Such entries
6688 are generated by \&{interim} commands.
6691 The global variable |save_ptr| points to the top item on the save stack.
6693 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6694 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6695 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6696 link((A))=mp->save_ptr; mp->save_ptr=(A);
6700 pointer save_ptr; /* the most recently saved item */
6702 @ @<Set init...@>=mp->save_ptr=null;
6704 @ The |save_variable| routine is given a hash address |q|; it salts this
6705 address in the save stack, together with its current equivalent,
6706 then makes token~|q| behave as though it were brand new.
6708 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6709 things from the stack when the program is not inside a group, so there's
6710 no point in wasting the space.
6712 @c void mp_save_variable (MP mp,pointer q) {
6713 pointer p; /* temporary register */
6714 if ( mp->save_ptr!=null ){
6715 p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6716 saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6718 mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6721 @ Similarly, |save_internal| is given the location |q| of an internal
6722 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6725 @c void mp_save_internal (MP mp,halfword q) {
6726 pointer p; /* new item for the save stack */
6727 if ( mp->save_ptr!=null ){
6728 p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6729 link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6733 @ At the end of a group, the |unsave| routine restores all of the saved
6734 equivalents in reverse order. This routine will be called only when there
6735 is at least one boundary item on the save stack.
6738 void mp_unsave (MP mp) {
6739 pointer q; /* index to saved item */
6740 pointer p; /* temporary register */
6741 while ( info(mp->save_ptr)!=0 ) {
6742 q=info(mp->save_ptr);
6744 if ( mp->internal[mp_tracing_restores]>0 ) {
6745 mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6746 mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6747 mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6748 mp_end_diagnostic(mp, false);
6750 mp->internal[q-(hash_end)]=value(mp->save_ptr);
6752 if ( mp->internal[mp_tracing_restores]>0 ) {
6753 mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6754 mp_print_text(q); mp_print_char(mp, '}');
6755 mp_end_diagnostic(mp, false);
6757 mp_clear_symbol(mp, q,false);
6758 mp->eqtb[q]=saved_equiv(mp->save_ptr);
6759 if ( eq_type(q) % outer_tag==tag_token ) {
6761 if ( p!=null ) name_type(p)=mp_root;
6764 p=link(mp->save_ptr);
6765 mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6767 p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6770 @* \[17] Data structures for paths.
6771 When a \MP\ user specifies a path, \MP\ will create a list of knots
6772 and control points for the associated cubic spline curves. If the
6773 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6774 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6775 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6776 @:Bezier}{B\'ezier, Pierre Etienne@>
6777 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6778 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6781 There is a 8-word node for each knot $z_k$, containing one word of
6782 control information and six words for the |x| and |y| coordinates of
6783 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6784 |left_type| and |right_type| fields, which each occupy a quarter of
6785 the first word in the node; they specify properties of the curve as it
6786 enters and leaves the knot. There's also a halfword |link| field,
6787 which points to the following knot, and a final supplementary word (of
6788 which only a quarter is used).
6790 If the path is a closed contour, knots 0 and |n| are identical;
6791 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6792 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6793 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6794 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6796 @d left_type(A) mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6797 @d right_type(A) mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6798 @d x_coord(A) mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6799 @d y_coord(A) mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6800 @d left_x(A) mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6801 @d left_y(A) mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6802 @d right_x(A) mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6803 @d right_y(A) mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6804 @d x_loc(A) ((A)+1) /* where the |x| coordinate is stored in a knot */
6805 @d y_loc(A) ((A)+2) /* where the |y| coordinate is stored in a knot */
6806 @d knot_coord(A) mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6807 @d left_coord(A) mp->mem[(A)+2].sc
6808 /* coordinate of previous control point given |x_loc| or |y_loc| */
6809 @d right_coord(A) mp->mem[(A)+4].sc
6810 /* coordinate of next control point given |x_loc| or |y_loc| */
6811 @d knot_node_size 8 /* number of words in a knot node */
6815 mp_endpoint=0, /* |left_type| at path beginning and |right_type| at path end */
6816 mp_explicit, /* |left_type| or |right_type| when control points are known */
6817 mp_given, /* |left_type| or |right_type| when a direction is given */
6818 mp_curl, /* |left_type| or |right_type| when a curl is desired */
6819 mp_open, /* |left_type| or |right_type| when \MP\ should choose the direction */
6823 @ Before the B\'ezier control points have been calculated, the memory
6824 space they will ultimately occupy is taken up by information that can be
6825 used to compute them. There are four cases:
6828 \textindent{$\bullet$} If |right_type=mp_open|, the curve should leave
6829 the knot in the same direction it entered; \MP\ will figure out a
6833 \textindent{$\bullet$} If |right_type=mp_curl|, the curve should leave the
6834 knot in a direction depending on the angle at which it enters the next
6835 knot and on the curl parameter stored in |right_curl|.
6838 \textindent{$\bullet$} If |right_type=mp_given|, the curve should leave the
6839 knot in a nonzero direction stored as an |angle| in |right_given|.
6842 \textindent{$\bullet$} If |right_type=mp_explicit|, the B\'ezier control
6843 point for leaving this knot has already been computed; it is in the
6844 |right_x| and |right_y| fields.
6847 The rules for |left_type| are similar, but they refer to the curve entering
6848 the knot, and to \\{left} fields instead of \\{right} fields.
6850 Non-|explicit| control points will be chosen based on ``tension'' parameters
6851 in the |left_tension| and |right_tension| fields. The
6852 `\&{atleast}' option is represented by negative tension values.
6853 @:at_least_}{\&{atleast} primitive@>
6855 For example, the \MP\ path specification
6856 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6858 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6860 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6861 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6862 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6864 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6865 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6866 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6867 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6868 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6869 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6870 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6871 Of course, this example is more complicated than anything a normal user
6874 These types must satisfy certain restrictions because of the form of \MP's
6876 (i)~|open| type never appears in the same node together with |endpoint|,
6878 (ii)~The |right_type| of a node is |explicit| if and only if the
6879 |left_type| of the following node is |explicit|.
6880 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6882 @d left_curl left_x /* curl information when entering this knot */
6883 @d left_given left_x /* given direction when entering this knot */
6884 @d left_tension left_y /* tension information when entering this knot */
6885 @d right_curl right_x /* curl information when leaving this knot */
6886 @d right_given right_x /* given direction when leaving this knot */
6887 @d right_tension right_y /* tension information when leaving this knot */
6889 @ Knots can be user-supplied, or they can be created by program code,
6890 like the |split_cubic| function, or |copy_path|. The distinction is
6891 needed for the cleanup routine that runs after |split_cubic|, because
6892 it should only delete knots it has previously inserted, and never
6893 anything that was user-supplied. In order to be able to differentiate
6894 one knot from another, we will set |originator(p):=mp_metapost_user| when
6895 it appeared in the actual metapost program, and
6896 |originator(p):=mp_program_code| in all other cases.
6898 @d originator(A) mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6902 mp_program_code=0, /* not created by a user */
6903 mp_metapost_user, /* created by a user */
6906 @ Here is a routine that prints a given knot list
6907 in symbolic form. It illustrates the conventions discussed above,
6908 and checks for anomalies that might arise while \MP\ is being debugged.
6910 @<Declare subroutines for printing expressions@>=
6911 void mp_pr_path (MP mp,pointer h);
6914 void mp_pr_path (MP mp,pointer h) {
6915 pointer p,q; /* for list traversal */
6919 if ( (p==null)||(q==null) ) {
6920 mp_print_nl(mp, "???"); return; /* this won't happen */
6923 @<Print information for adjacent knots |p| and |q|@>;
6926 if ( (p!=h)||(left_type(h)!=mp_endpoint) ) {
6927 @<Print two dots, followed by |given| or |curl| if present@>;
6930 if ( left_type(h)!=mp_endpoint )
6931 mp_print(mp, "cycle");
6934 @ @<Print information for adjacent knots...@>=
6935 mp_print_two(mp, x_coord(p),y_coord(p));
6936 switch (right_type(p)) {
6938 if ( left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6940 if ( (left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6944 @<Print control points between |p| and |q|, then |goto done1|@>;
6947 @<Print information for a curve that begins |open|@>;
6951 @<Print information for a curve that begins |curl| or |given|@>;
6954 mp_print(mp, "???"); /* can't happen */
6958 if ( left_type(q)<=mp_explicit ) {
6959 mp_print(mp, "..control?"); /* can't happen */
6961 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6962 @<Print tension between |p| and |q|@>;
6965 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6966 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6968 @<Print two dots...@>=
6970 mp_print_nl(mp, " ..");
6971 if ( left_type(p)==mp_given ) {
6972 mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6973 mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6974 mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6975 } else if ( left_type(p)==mp_curl ){
6976 mp_print(mp, "{curl ");
6977 mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6981 @ @<Print tension between |p| and |q|@>=
6983 mp_print(mp, "..tension ");
6984 if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6985 mp_print_scaled(mp, abs(right_tension(p)));
6986 if ( right_tension(p)!=left_tension(q) ){
6987 mp_print(mp, " and ");
6988 if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6989 mp_print_scaled(mp, abs(left_tension(q)));
6993 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6995 mp_print(mp, "..controls ");
6996 mp_print_two(mp, right_x(p),right_y(p));
6997 mp_print(mp, " and ");
6998 if ( left_type(q)!=mp_explicit ) {
6999 mp_print(mp, "??"); /* can't happen */
7002 mp_print_two(mp, left_x(q),left_y(q));
7007 @ @<Print information for a curve that begins |open|@>=
7008 if ( (left_type(p)!=mp_explicit)&&(left_type(p)!=mp_open) ) {
7009 mp_print(mp, "{open?}"); /* can't happen */
7013 @ A curl of 1 is shown explicitly, so that the user sees clearly that
7014 \MP's default curl is present.
7016 The code here uses the fact that |left_curl==left_given| and
7017 |right_curl==right_given|.
7019 @<Print information for a curve that begins |curl|...@>=
7021 if ( left_type(p)==mp_open )
7022 mp_print(mp, "??"); /* can't happen */
7024 if ( right_type(p)==mp_curl ) {
7025 mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
7027 mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
7028 mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
7029 mp_print_scaled(mp, mp->n_sin);
7031 mp_print_char(mp, '}');
7034 @ It is convenient to have another version of |pr_path| that prints the path
7035 as a diagnostic message.
7037 @<Declare subroutines for printing expressions@>=
7038 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) {
7039 mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
7042 mp_end_diagnostic(mp, true);
7045 @ If we want to duplicate a knot node, we can say |copy_knot|:
7048 pointer mp_copy_knot (MP mp,pointer p) {
7049 pointer q; /* the copy */
7050 int k; /* runs through the words of a knot node */
7051 q=mp_get_node(mp, knot_node_size);
7052 for (k=0;k<knot_node_size;k++) {
7053 mp->mem[q+k]=mp->mem[p+k];
7055 originator(q)=originator(p);
7059 @ The |copy_path| routine makes a clone of a given path.
7062 pointer mp_copy_path (MP mp, pointer p) {
7063 pointer q,pp,qq; /* for list manipulation */
7064 q=mp_copy_knot(mp, p);
7067 link(qq)=mp_copy_knot(mp, pp);
7076 @ Just before |ship_out|, knot lists are exported for printing.
7078 @d gr_left_type(A) (A)->left_type_field
7079 @d gr_right_type(A) (A)->right_type_field
7080 @d gr_x_coord(A) (A)->x_coord_field
7081 @d gr_y_coord(A) (A)->y_coord_field
7082 @d gr_left_x(A) (A)->left_x_field
7083 @d gr_left_y(A) (A)->left_y_field
7084 @d gr_right_x(A) (A)->right_x_field
7085 @d gr_right_y(A) (A)->right_y_field
7086 @d gr_next_knot(A) (A)->next_field
7087 @d gr_originator(A) (A)->originator_field
7090 struct mp_knot *mp_export_knot (MP mp,pointer p) {
7091 struct mp_knot *q; /* the copy */
7094 q = mp_xmalloc(mp, 1, sizeof (struct mp_knot));
7095 memset(q,0,sizeof (struct mp_knot));
7096 gr_left_type(q) = left_type(p);
7097 gr_right_type(q) = right_type(p);
7098 gr_x_coord(q) = x_coord(p);
7099 gr_y_coord(q) = y_coord(p);
7100 gr_left_x(q) = left_x(p);
7101 gr_left_y(q) = left_y(p);
7102 gr_right_x(q) = right_x(p);
7103 gr_right_y(q) = right_y(p);
7104 gr_originator(q) = originator(p);
7108 @ The |export_knot_list| routine therefore also makes a clone
7112 struct mp_knot *mp_export_knot_list (MP mp, pointer p) {
7113 struct mp_knot *q, *qq; /* for list manipulation */
7114 pointer pp; /* for list manipulation */
7117 q=mp_export_knot(mp, p);
7120 gr_next_knot(qq)=mp_export_knot(mp, pp);
7121 qq=gr_next_knot(qq);
7129 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7130 returns a pointer to the first node of the copy, if the path is a cycle,
7131 but to the final node of a non-cyclic copy. The global
7132 variable |path_tail| will point to the final node of the original path;
7133 this trick makes it easier to implement `\&{doublepath}'.
7135 All node types are assumed to be |endpoint| or |explicit| only.
7138 pointer mp_htap_ypoc (MP mp,pointer p) {
7139 pointer q,pp,qq,rr; /* for list manipulation */
7140 q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7143 right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7144 x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7145 right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7146 left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7147 originator(qq)=originator(pp);
7148 if ( link(pp)==p ) {
7149 link(q)=qq; mp->path_tail=pp; return q;
7151 rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7156 pointer path_tail; /* the node that links to the beginning of a path */
7158 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7159 calling the following subroutine.
7161 @<Declare the recycling subroutines@>=
7162 void mp_toss_knot_list (MP mp,pointer p) ;
7165 void mp_toss_knot_list (MP mp,pointer p) {
7166 pointer q; /* the node being freed */
7167 pointer r; /* the next node */
7171 mp_free_node(mp, q,knot_node_size); q=r;
7175 @* \[18] Choosing control points.
7176 Now we must actually delve into one of \MP's more difficult routines,
7177 the |make_choices| procedure that chooses angles and control points for
7178 the splines of a curve when the user has not specified them explicitly.
7179 The parameter to |make_choices| points to a list of knots and
7180 path information, as described above.
7182 A path decomposes into independent segments at ``breakpoint'' knots,
7183 which are knots whose left and right angles are both prespecified in
7184 some way (i.e., their |left_type| and |right_type| aren't both open).
7187 @<Declare the procedure called |solve_choices|@>;
7188 void mp_make_choices (MP mp,pointer knots) {
7189 pointer h; /* the first breakpoint */
7190 pointer p,q; /* consecutive breakpoints being processed */
7191 @<Other local variables for |make_choices|@>;
7192 check_arith; /* make sure that |arith_error=false| */
7193 if ( mp->internal[mp_tracing_choices]>0 )
7194 mp_print_path(mp, knots,", before choices",true);
7195 @<If consecutive knots are equal, join them explicitly@>;
7196 @<Find the first breakpoint, |h|, on the path;
7197 insert an artificial breakpoint if the path is an unbroken cycle@>;
7200 @<Fill in the control points between |p| and the next breakpoint,
7201 then advance |p| to that breakpoint@>;
7203 if ( mp->internal[mp_tracing_choices]>0 )
7204 mp_print_path(mp, knots,", after choices",true);
7205 if ( mp->arith_error ) {
7206 @<Report an unexpected problem during the choice-making@>;
7210 @ @<Report an unexpected problem during the choice...@>=
7212 print_err("Some number got too big");
7213 @.Some number got too big@>
7214 help2("The path that I just computed is out of range.")
7215 ("So it will probably look funny. Proceed, for a laugh.");
7216 mp_put_get_error(mp); mp->arith_error=false;
7219 @ Two knots in a row with the same coordinates will always be joined
7220 by an explicit ``curve'' whose control points are identical with the
7223 @<If consecutive knots are equal, join them explicitly@>=
7227 if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>mp_explicit ) {
7228 right_type(p)=mp_explicit;
7229 if ( left_type(p)==mp_open ) {
7230 left_type(p)=mp_curl; left_curl(p)=unity;
7232 left_type(q)=mp_explicit;
7233 if ( right_type(q)==mp_open ) {
7234 right_type(q)=mp_curl; right_curl(q)=unity;
7236 right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7237 right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7242 @ If there are no breakpoints, it is necessary to compute the direction
7243 angles around an entire cycle. In this case the |left_type| of the first
7244 node is temporarily changed to |end_cycle|.
7246 @<Find the first breakpoint, |h|, on the path...@>=
7249 if ( left_type(h)!=mp_open ) break;
7250 if ( right_type(h)!=mp_open ) break;
7253 left_type(h)=mp_end_cycle; break;
7257 @ If |right_type(p)<given| and |q=link(p)|, we must have
7258 |right_type(p)=left_type(q)=mp_explicit| or |endpoint|.
7260 @<Fill in the control points between |p| and the next breakpoint...@>=
7262 if ( right_type(p)>=mp_given ) {
7263 while ( (left_type(q)==mp_open)&&(right_type(q)==mp_open) ) q=link(q);
7264 @<Fill in the control information between
7265 consecutive breakpoints |p| and |q|@>;
7266 } else if ( right_type(p)==mp_endpoint ) {
7267 @<Give reasonable values for the unused control points between |p| and~|q|@>;
7271 @ This step makes it possible to transform an explicitly computed path without
7272 checking the |left_type| and |right_type| fields.
7274 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7276 right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7277 left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7280 @ Before we can go further into the way choices are made, we need to
7281 consider the underlying theory. The basic ideas implemented in |make_choices|
7282 are due to John Hobby, who introduced the notion of ``mock curvature''
7283 @^Hobby, John Douglas@>
7284 at a knot. Angles are chosen so that they preserve mock curvature when
7285 a knot is passed, and this has been found to produce excellent results.
7287 It is convenient to introduce some notations that simplify the necessary
7288 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7289 between knots |k| and |k+1|; and let
7290 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7291 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7292 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7293 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7294 $$\eqalign{z_k^+&=z_k+
7295 \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7297 \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7298 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7299 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7300 corresponding ``offset angles.'' These angles satisfy the condition
7301 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7302 whenever the curve leaves an intermediate knot~|k| in the direction that
7305 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7306 the curve at its beginning and ending points. This means that
7307 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7308 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7309 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7310 z\k^-,z\k^{\phantom+};t)$
7313 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7314 \qquad{\rm and}\qquad
7315 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7316 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7318 approximation to this true curvature that arises in the limit for
7319 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7320 The standard velocity function satisfies
7321 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7322 hence the mock curvatures are respectively
7323 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7324 \qquad{\rm and}\qquad
7325 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7327 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7328 determines $\phi_k$ when $\theta_k$ is known, so the task of
7329 angle selection is essentially to choose appropriate values for each
7330 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7331 from $(**)$, we obtain a system of linear equations of the form
7332 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7334 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7335 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7336 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7337 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7338 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7339 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7340 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7341 hence they have a unique solution. Moreover, in most cases the tensions
7342 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7343 solution numerically stable, and there is an exponential damping
7344 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7345 a factor of~$O(2^{-j})$.
7347 @ However, we still must consider the angles at the starting and ending
7348 knots of a non-cyclic path. These angles might be given explicitly, or
7349 they might be specified implicitly in terms of an amount of ``curl.''
7351 Let's assume that angles need to be determined for a non-cyclic path
7352 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7353 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7354 have been given for $0<k<n$, and it will be convenient to introduce
7355 equations of the same form for $k=0$ and $k=n$, where
7356 $$A_0=B_0=C_n=D_n=0.$$
7357 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7358 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7359 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7360 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7361 mock curvature at $z_1$; i.e.,
7362 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7363 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7364 This equation simplifies to
7365 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7366 \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7367 -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7368 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7369 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7370 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7371 hence the linear equations remain nonsingular.
7373 Similar considerations apply at the right end, when the final angle $\phi_n$
7374 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7375 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7377 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7378 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7379 \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7381 When |make_choices| chooses angles, it must compute the coefficients of
7382 these linear equations, then solve the equations. To compute the coefficients,
7383 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7384 When the equations are solved, the chosen directions $\theta_k$ are put
7385 back into the form of control points by essentially computing sines and
7388 @ OK, we are ready to make the hard choices of |make_choices|.
7389 Most of the work is relegated to an auxiliary procedure
7390 called |solve_choices|, which has been introduced to keep
7391 |make_choices| from being extremely long.
7393 @<Fill in the control information between...@>=
7394 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7395 set $n$ to the length of the path@>;
7396 @<Remove |open| types at the breakpoints@>;
7397 mp_solve_choices(mp, p,q,n)
7399 @ It's convenient to precompute quantities that will be needed several
7400 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7401 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7402 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7403 and $z\k-z_k$ will be stored in |psi[k]|.
7406 int path_size; /* maximum number of knots between breakpoints of a path */
7409 scaled *delta; /* knot differences */
7410 angle *psi; /* turning angles */
7412 @ @<Allocate or initialize ...@>=
7418 @ @<Dealloc variables@>=
7424 @ @<Other local variables for |make_choices|@>=
7425 int k,n; /* current and final knot numbers */
7426 pointer s,t; /* registers for list traversal */
7427 scaled delx,dely; /* directions where |open| meets |explicit| */
7428 fraction sine,cosine; /* trig functions of various angles */
7430 @ @<Calculate the turning angles...@>=
7433 k=0; s=p; n=mp->path_size;
7436 mp->delta_x[k]=x_coord(t)-x_coord(s);
7437 mp->delta_y[k]=y_coord(t)-y_coord(s);
7438 mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7440 sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7441 cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7442 mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7443 mp_take_fraction(mp, mp->delta_y[k],sine),
7444 mp_take_fraction(mp, mp->delta_y[k],cosine)-
7445 mp_take_fraction(mp, mp->delta_x[k],sine));
7448 if ( k==mp->path_size ) {
7449 mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7450 goto RESTART; /* retry, loop size has changed */
7453 } while (!((k>=n)&&(left_type(s)!=mp_end_cycle)));
7454 if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7457 @ When we get to this point of the code, |right_type(p)| is either
7458 |given| or |curl| or |open|. If it is |open|, we must have
7459 |left_type(p)=mp_end_cycle| or |left_type(p)=mp_explicit|. In the latter
7460 case, the |open| type is converted to |given|; however, if the
7461 velocity coming into this knot is zero, the |open| type is
7462 converted to a |curl|, since we don't know the incoming direction.
7464 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7465 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7467 @<Remove |open| types at the breakpoints@>=
7468 if ( left_type(q)==mp_open ) {
7469 delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7470 if ( (delx==0)&&(dely==0) ) {
7471 left_type(q)=mp_curl; left_curl(q)=unity;
7473 left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7476 if ( (right_type(p)==mp_open)&&(left_type(p)==mp_explicit) ) {
7477 delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7478 if ( (delx==0)&&(dely==0) ) {
7479 right_type(p)=mp_curl; right_curl(p)=unity;
7481 right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7485 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7486 and exactly one of the breakpoints involves a curl. The simplest case occurs
7487 when |n=1| and there is a curl at both breakpoints; then we simply draw
7490 But before coding up the simple cases, we might as well face the general case,
7491 since we must deal with it sooner or later, and since the general case
7492 is likely to give some insight into the way simple cases can be handled best.
7494 When there is no cycle, the linear equations to be solved form a tridiagonal
7495 system, and we can apply the standard technique of Gaussian elimination
7496 to convert that system to a sequence of equations of the form
7497 $$\theta_0+u_0\theta_1=v_0,\quad
7498 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7499 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7501 It is possible to do this diagonalization while generating the equations.
7502 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7503 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7505 The procedure is slightly more complex when there is a cycle, but the
7506 basic idea will be nearly the same. In the cyclic case the right-hand
7507 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7508 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7509 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7510 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7511 eliminate the $w$'s from the system, after which the solution can be
7514 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7515 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7516 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7517 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7520 angle *theta; /* values of $\theta_k$ */
7521 fraction *uu; /* values of $u_k$ */
7522 angle *vv; /* values of $v_k$ */
7523 fraction *ww; /* values of $w_k$ */
7525 @ @<Allocate or initialize ...@>=
7531 @ @<Dealloc variables@>=
7537 @ @<Declare |mp_reallocate| functions@>=
7538 void mp_reallocate_paths (MP mp, int l);
7541 void mp_reallocate_paths (MP mp, int l) {
7542 XREALLOC (mp->delta_x, l, scaled);
7543 XREALLOC (mp->delta_y, l, scaled);
7544 XREALLOC (mp->delta, l, scaled);
7545 XREALLOC (mp->psi, l, angle);
7546 XREALLOC (mp->theta, l, angle);
7547 XREALLOC (mp->uu, l, fraction);
7548 XREALLOC (mp->vv, l, angle);
7549 XREALLOC (mp->ww, l, fraction);
7553 @ Our immediate problem is to get the ball rolling by setting up the
7554 first equation or by realizing that no equations are needed, and to fit
7555 this initialization into a framework suitable for the overall computation.
7557 @<Declare the procedure called |solve_choices|@>=
7558 @<Declare subroutines needed by |solve_choices|@>;
7559 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7560 int k; /* current knot number */
7561 pointer r,s,t; /* registers for list traversal */
7562 @<Other local variables for |solve_choices|@>;
7567 @<Get the linear equations started; or |return|
7568 with the control points in place, if linear equations
7571 switch (left_type(s)) {
7572 case mp_end_cycle: case mp_open:
7573 @<Set up equation to match mock curvatures
7574 at $z_k$; then |goto found| with $\theta_n$
7575 adjusted to equal $\theta_0$, if a cycle has ended@>;
7578 @<Set up equation for a curl at $\theta_n$
7582 @<Calculate the given value of $\theta_n$
7585 } /* there are no other cases */
7590 @<Finish choosing angles and assigning control points@>;
7593 @ On the first time through the loop, we have |k=0| and |r| is not yet
7594 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7596 @<Get the linear equations started...@>=
7597 switch (right_type(s)) {
7599 if ( left_type(t)==mp_given ) {
7600 @<Reduce to simple case of two givens and |return|@>
7602 @<Set up the equation for a given value of $\theta_0$@>;
7606 if ( left_type(t)==mp_curl ) {
7607 @<Reduce to simple case of straight line and |return|@>
7609 @<Set up the equation for a curl at $\theta_0$@>;
7613 mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7614 /* this begins a cycle */
7616 } /* there are no other cases */
7618 @ The general equation that specifies equality of mock curvature at $z_k$ is
7619 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7620 as derived above. We want to combine this with the already-derived equation
7621 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7623 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7625 $$(B_k-u_{k-1}A_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k-A_kv_{k-1}
7626 -A_kw_{k-1}\theta_0$$
7627 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7628 fixed-point arithmetic, avoiding the chance of overflow while retaining
7631 The calculations will be performed in several registers that
7632 provide temporary storage for intermediate quantities.
7634 @<Other local variables for |solve_choices|@>=
7635 fraction aa,bb,cc,ff,acc; /* temporary registers */
7636 scaled dd,ee; /* likewise, but |scaled| */
7637 scaled lt,rt; /* tension values */
7639 @ @<Set up equation to match mock curvatures...@>=
7640 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7641 $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7642 and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7643 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7644 mp->uu[k]=mp_take_fraction(mp, ff,bb);
7645 @<Calculate the values of $v_k$ and $w_k$@>;
7646 if ( left_type(s)==mp_end_cycle ) {
7647 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7651 @ Since tension values are never less than 3/4, the values |aa| and
7652 |bb| computed here are never more than 4/5.
7654 @<Calculate the values $\\{aa}=...@>=
7655 if ( abs(right_tension(r))==unity) {
7656 aa=fraction_half; dd=2*mp->delta[k];
7658 aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7659 dd=mp_take_fraction(mp, mp->delta[k],
7660 fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7662 if ( abs(left_tension(t))==unity ){
7663 bb=fraction_half; ee=2*mp->delta[k-1];
7665 bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7666 ee=mp_take_fraction(mp, mp->delta[k-1],
7667 fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7669 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7671 @ The ratio to be calculated in this step can be written in the form
7672 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7673 \\{cc}\cdot\\{dd},$$
7674 because of the quantities just calculated. The values of |dd| and |ee|
7675 will not be needed after this step has been performed.
7677 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7678 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7679 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7681 ff=mp_make_fraction(mp, lt,rt);
7682 ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7683 dd=mp_take_fraction(mp, dd,ff);
7685 ff=mp_make_fraction(mp, rt,lt);
7686 ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7687 ee=mp_take_fraction(mp, ee,ff);
7690 ff=mp_make_fraction(mp, ee,ee+dd)
7692 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7693 equation was specified by a curl. In that case we must use a special
7694 method of computation to prevent overflow.
7696 Fortunately, the calculations turn out to be even simpler in this ``hard''
7697 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7698 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7700 @<Calculate the values of $v_k$ and $w_k$@>=
7701 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7702 if ( right_type(r)==mp_curl ) {
7704 mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7706 ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7707 $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7708 acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7709 ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7710 mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7711 if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7712 else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7715 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7716 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7717 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7718 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7721 The idea in the following code is to observe that
7722 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7723 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7724 -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7725 so we can solve for $\theta_n=\theta_0$.
7727 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7729 aa=0; bb=fraction_one; /* we have |k=n| */
7732 aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7733 bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7734 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7735 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7736 mp->theta[n]=aa; mp->vv[0]=aa;
7737 for (k=1;k<=n-1;k++) {
7738 mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7743 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7744 if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7746 @<Calculate the given value of $\theta_n$...@>=
7748 mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7749 reduce_angle(mp->theta[n]);
7753 @ @<Set up the equation for a given value of $\theta_0$@>=
7755 mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7756 reduce_angle(mp->vv[0]);
7757 mp->uu[0]=0; mp->ww[0]=0;
7760 @ @<Set up the equation for a curl at $\theta_0$@>=
7761 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7762 if ( (rt==unity)&&(lt==unity) )
7763 mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7765 mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7766 mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7769 @ @<Set up equation for a curl at $\theta_n$...@>=
7770 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7771 if ( (rt==unity)&&(lt==unity) )
7772 ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7774 ff=mp_curl_ratio(mp, cc,lt,rt);
7775 mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7776 fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7780 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7781 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7782 a somewhat tedious program to calculate
7783 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7784 \alpha^3\gamma+(3-\beta)\beta^2},$$
7785 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7786 is necessary only if the curl and tension are both large.)
7787 The values of $\alpha$ and $\beta$ will be at most~4/3.
7789 @<Declare subroutines needed by |solve_choices|@>=
7790 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension,
7792 fraction alpha,beta,num,denom,ff; /* registers */
7793 alpha=mp_make_fraction(mp, unity,a_tension);
7794 beta=mp_make_fraction(mp, unity,b_tension);
7795 if ( alpha<=beta ) {
7796 ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7797 gamma=mp_take_fraction(mp, gamma,ff);
7798 beta=beta / 010000; /* convert |fraction| to |scaled| */
7799 denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7800 num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7802 ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7803 beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7804 denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7805 /* $1365\approx 2^{12}/3$ */
7806 num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7808 if ( num>=denom+denom+denom+denom ) return fraction_four;
7809 else return mp_make_fraction(mp, num,denom);
7812 @ We're in the home stretch now.
7814 @<Finish choosing angles and assigning control points@>=
7815 for (k=n-1;k>=0;k--) {
7816 mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7821 mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7822 mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7823 mp_set_controls(mp, s,t,k);
7827 @ The |set_controls| routine actually puts the control points into
7828 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7829 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7830 $\cos\phi$ needed in this calculation.
7836 fraction cf; /* sines and cosines */
7838 @ @<Declare subroutines needed by |solve_choices|@>=
7839 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7840 fraction rr,ss; /* velocities, divided by thrice the tension */
7841 scaled lt,rt; /* tensions */
7842 fraction sine; /* $\sin(\theta+\phi)$ */
7843 lt=abs(left_tension(q)); rt=abs(right_tension(p));
7844 rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7845 ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7846 if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7847 @<Decrease the velocities,
7848 if necessary, to stay inside the bounding triangle@>;
7850 right_x(p)=x_coord(p)+mp_take_fraction(mp,
7851 mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7852 mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7853 right_y(p)=y_coord(p)+mp_take_fraction(mp,
7854 mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7855 mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7856 left_x(q)=x_coord(q)-mp_take_fraction(mp,
7857 mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7858 mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7859 left_y(q)=y_coord(q)-mp_take_fraction(mp,
7860 mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7861 mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7862 right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7865 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7866 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7867 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7868 there is no ``bounding triangle.''
7869 @:at_least_}{\&{atleast} primitive@>
7871 @<Decrease the velocities, if necessary...@>=
7872 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7873 sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7874 mp_take_fraction(mp, abs(mp->sf),mp->ct);
7876 sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7877 if ( right_tension(p)<0 )
7878 if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7879 rr=mp_make_fraction(mp, abs(mp->sf),sine);
7880 if ( left_tension(q)<0 )
7881 if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7882 ss=mp_make_fraction(mp, abs(mp->st),sine);
7886 @ Only the simple cases remain to be handled.
7888 @<Reduce to simple case of two givens and |return|@>=
7890 aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7891 mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7892 mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7893 mp_set_controls(mp, p,q,0); return;
7896 @ @<Reduce to simple case of straight line and |return|@>=
7898 right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7899 lt=abs(left_tension(q)); rt=abs(right_tension(p));
7901 if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7902 else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7903 if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7904 else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7906 ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7907 right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7908 right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7911 if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7912 else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7913 if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7914 else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7916 ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7917 left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7918 left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7923 @* \[19] Measuring paths.
7924 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7925 allow the user to measure the bounding box of anything that can go into a
7926 picture. It's easy to get rough bounds on the $x$ and $y$ extent of a path
7927 by just finding the bounding box of the knots and the control points. We
7928 need a more accurate version of the bounding box, but we can still use the
7929 easy estimate to save time by focusing on the interesting parts of the path.
7931 @ Computing an accurate bounding box involves a theme that will come up again
7932 and again. Given a Bernshte{\u\i}n polynomial
7933 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7934 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7935 we can conveniently bisect its range as follows:
7938 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7941 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7942 |0<=k<n-j|, for |0<=j<n|.
7946 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7947 =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7948 This formula gives us the coefficients of polynomials to use over the ranges
7949 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7951 @ Now here's a subroutine that's handy for all sorts of path computations:
7952 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7953 returns the unique |fraction| value |t| between 0 and~1 at which
7954 $B(a,b,c;t)$ changes from positive to negative, or returns
7955 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7956 is already negative at |t=0|), |crossing_point| returns the value zero.
7958 @d no_crossing { return (fraction_one+1); }
7959 @d one_crossing { return fraction_one; }
7960 @d zero_crossing { return 0; }
7961 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7963 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7964 integer d; /* recursive counter */
7965 integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7966 if ( a<0 ) zero_crossing;
7969 if ( c>0 ) { no_crossing; }
7970 else if ( (a==0)&&(b==0) ) { no_crossing;}
7971 else { one_crossing; }
7973 if ( a==0 ) zero_crossing;
7974 } else if ( a==0 ) {
7975 if ( b<=0 ) zero_crossing;
7977 @<Use bisection to find the crossing point, if one exists@>;
7980 @ The general bisection method is quite simple when $n=2$, hence
7981 |crossing_point| does not take much time. At each stage in the
7982 recursion we have a subinterval defined by |l| and~|j| such that
7983 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7984 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7986 It is convenient for purposes of calculation to combine the values
7987 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7988 of bisection then corresponds simply to doubling $d$ and possibly
7989 adding~1. Furthermore it proves to be convenient to modify
7990 our previous conventions for bisection slightly, maintaining the
7991 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7992 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7993 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7995 The following code maintains the invariant relations
7996 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7997 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7998 it has been constructed in such a way that no arithmetic overflow
7999 will occur if the inputs satisfy
8000 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
8002 @<Use bisection to find the crossing point...@>=
8003 d=1; x0=a; x1=a-b; x2=b-c;
8014 if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
8018 } while (d<fraction_one);
8019 return (d-fraction_one)
8021 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
8022 a cubic corresponding to the |fraction| value~|t|.
8024 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
8025 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
8027 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
8029 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
8030 scaled x1,x2,x3; /* intermediate values */
8031 x1=t_of_the_way(knot_coord(p),right_coord(p));
8032 x2=t_of_the_way(right_coord(p),left_coord(q));
8033 x3=t_of_the_way(left_coord(q),knot_coord(q));
8034 x1=t_of_the_way(x1,x2);
8035 x2=t_of_the_way(x2,x3);
8036 return t_of_the_way(x1,x2);
8039 @ The actual bounding box information is stored in global variables.
8040 Since it is convenient to address the $x$ and $y$ information
8041 separately, we define arrays indexed by |x_code..y_code| and use
8042 macros to give them more convenient names.
8046 mp_x_code=0, /* index for |minx| and |maxx| */
8047 mp_y_code /* index for |miny| and |maxy| */
8051 @d minx mp->bbmin[mp_x_code]
8052 @d maxx mp->bbmax[mp_x_code]
8053 @d miny mp->bbmin[mp_y_code]
8054 @d maxy mp->bbmax[mp_y_code]
8057 scaled bbmin[mp_y_code+1];
8058 scaled bbmax[mp_y_code+1];
8059 /* the result of procedures that compute bounding box information */
8061 @ Now we're ready for the key part of the bounding box computation.
8062 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
8063 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
8064 \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
8066 for $0<t\le1$. In other words, the procedure adjusts the bounds to
8067 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8068 The |c| parameter is |x_code| or |y_code|.
8070 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
8071 boolean wavy; /* whether we need to look for extremes */
8072 scaled del1,del2,del3,del,dmax; /* proportional to the control
8073 points of a quadratic derived from a cubic */
8074 fraction t,tt; /* where a quadratic crosses zero */
8075 scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8077 @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8078 @<Check the control points against the bounding box and set |wavy:=true|
8079 if any of them lie outside@>;
8081 del1=right_coord(p)-knot_coord(p);
8082 del2=left_coord(q)-right_coord(p);
8083 del3=knot_coord(q)-left_coord(q);
8084 @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8085 also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8087 negate(del1); negate(del2); negate(del3);
8089 t=mp_crossing_point(mp, del1,del2,del3);
8090 if ( t<fraction_one ) {
8091 @<Test the extremes of the cubic against the bounding box@>;
8096 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8097 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8098 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8100 @ @<Check the control points against the bounding box and set...@>=
8102 if ( mp->bbmin[c]<=right_coord(p) )
8103 if ( right_coord(p)<=mp->bbmax[c] )
8104 if ( mp->bbmin[c]<=left_coord(q) )
8105 if ( left_coord(q)<=mp->bbmax[c] )
8108 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8109 section. We just set |del=0| in that case.
8111 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8112 if ( del1!=0 ) del=del1;
8113 else if ( del2!=0 ) del=del2;
8117 if ( abs(del2)>dmax ) dmax=abs(del2);
8118 if ( abs(del3)>dmax ) dmax=abs(del3);
8119 while ( dmax<fraction_half ) {
8120 dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8124 @ Since |crossing_point| has tried to choose |t| so that
8125 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8126 slope, the value of |del2| computed below should not be positive.
8127 But rounding error could make it slightly positive in which case we
8128 must cut it to zero to avoid confusion.
8130 @<Test the extremes of the cubic against the bounding box@>=
8132 x=mp_eval_cubic(mp, p,q,t);
8133 @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8134 del2=t_of_the_way(del2,del3);
8135 /* now |0,del2,del3| represent the derivative on the remaining interval */
8136 if ( del2>0 ) del2=0;
8137 tt=mp_crossing_point(mp, 0,-del2,-del3);
8138 if ( tt<fraction_one ) {
8139 @<Test the second extreme against the bounding box@>;
8143 @ @<Test the second extreme against the bounding box@>=
8145 x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8146 @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8149 @ Finding the bounding box of a path is basically a matter of applying
8150 |bound_cubic| twice for each pair of adjacent knots.
8152 @c void mp_path_bbox (MP mp,pointer h) {
8153 pointer p,q; /* a pair of adjacent knots */
8154 minx=x_coord(h); miny=y_coord(h);
8155 maxx=minx; maxy=miny;
8158 if ( right_type(p)==mp_endpoint ) return;
8160 mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8161 mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8166 @ Another important way to measure a path is to find its arc length. This
8167 is best done by using the general bisection algorithm to subdivide the path
8168 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8171 Since the arc length is the integral with respect to time of the magnitude of
8172 the velocity, it is natural to use Simpson's rule for the approximation.
8174 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8175 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8176 for the arc length of a path of length~1. For a cubic spline
8177 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8178 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$. Hence the arc length
8180 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8182 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8183 is the result of the bisection algorithm.
8185 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8186 This could be done via the theoretical error bound for Simpson's rule,
8188 but this is impractical because it requires an estimate of the fourth
8189 derivative of the quantity being integrated. It is much easier to just perform
8190 a bisection step and see how much the arc length estimate changes. Since the
8191 error for Simpson's rule is proportional to the fourth power of the sample
8192 spacing, the remaining error is typically about $1\over16$ of the amount of
8193 the change. We say ``typically'' because the error has a pseudo-random behavior
8194 that could cause the two estimates to agree when each contain large errors.
8196 To protect against disasters such as undetected cusps, the bisection process
8197 should always continue until all the $dz_i$ vectors belong to a single
8198 $90^\circ$ sector. This ensures that no point on the spline can have velocity
8199 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8200 If such a spline happens to produce an erroneous arc length estimate that
8201 is little changed by bisection, the amount of the error is likely to be fairly
8202 small. We will try to arrange things so that freak accidents of this type do
8203 not destroy the inverse relationship between the \&{arclength} and
8204 \&{arctime} operations.
8205 @:arclength_}{\&{arclength} primitive@>
8206 @:arctime_}{\&{arctime} primitive@>
8208 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8210 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8211 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8212 returns the time when the arc length reaches |a_goal| if there is such a time.
8213 Thus the return value is either an arc length less than |a_goal| or, if the
8214 arc length would be at least |a_goal|, it returns a time value decreased by
8215 |two|. This allows the caller to use the sign of the result to distinguish
8216 between arc lengths and time values. On certain types of overflow, it is
8217 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8218 Otherwise, the result is always less than |a_goal|.
8220 Rather than halving the control point coordinates on each recursive call to
8221 |arc_test|, it is better to keep them proportional to velocity on the original
8222 curve and halve the results instead. This means that recursive calls can
8223 potentially use larger error tolerances in their arc length estimates. How
8224 much larger depends on to what extent the errors behave as though they are
8225 independent of each other. To save computing time, we use optimistic assumptions
8226 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8229 In addition to the tolerance parameter, |arc_test| should also have parameters
8230 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8231 ${1\over3}\vb\dot B(1)\vb$. These quantities are relatively expensive to compute
8232 and they are needed in different instances of |arc_test|.
8234 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8235 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1,
8236 scaled dx2, scaled dy2, scaled v0, scaled v02,
8237 scaled v2, scaled a_goal, scaled tol) {
8238 boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8239 scaled dx01, dy01, dx12, dy12, dx02, dy02; /* bisection results */
8241 /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8242 scaled arc; /* best arc length estimate before recursion */
8243 @<Other local variables in |arc_test|@>;
8244 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8246 @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8247 set |arc_test| and |return|@>;
8248 @<Test if the control points are confined to one quadrant or rotating them
8249 $45^\circ$ would put them in one quadrant. Then set |simple| appropriately@>;
8250 if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8251 if ( arc < a_goal ) {
8254 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8255 that time minus |two|@>;
8258 @<Use one or two recursive calls to compute the |arc_test| function@>;
8262 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8263 calls, but $1.5$ is an adequate approximation. It is best to avoid using
8264 |make_fraction| in this inner loop.
8267 @<Use one or two recursive calls to compute the |arc_test| function@>=
8269 @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8270 large as possible@>;
8271 tol = tol + halfp(tol);
8272 a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002,
8273 halfp(v02), a_new, tol);
8275 return (-halfp(two-a));
8277 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8278 b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8279 halfp(v02), v022, v2, a_new, tol);
8281 return (-halfp(-b) - half_unit);
8283 return (a + half(b-a));
8287 @ @<Other local variables in |arc_test|@>=
8288 scaled a,b; /* results of recursive calls */
8289 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8291 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8292 a_aux = el_gordo - a_goal;
8293 if ( a_goal > a_aux ) {
8294 a_aux = a_goal - a_aux;
8297 a_new = a_goal + a_goal;
8301 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8302 to force the additions and subtractions to be done in an order that avoids
8305 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8308 a_new = a_new + a_aux;
8311 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8312 |fraction_four|. To simplify the rest of the |arc_test| routine, we strengthen
8313 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8314 this bound. Note that recursive calls will maintain this invariant.
8316 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8317 dx01 = half(dx0 + dx1);
8318 dx12 = half(dx1 + dx2);
8319 dx02 = half(dx01 + dx12);
8320 dy01 = half(dy0 + dy1);
8321 dy12 = half(dy1 + dy2);
8322 dy02 = half(dy01 + dy12)
8324 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8325 |a_goal=el_gordo| is guaranteed to yield the arc length.
8327 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8328 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8329 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8331 arc1 = v002 + half(halfp(v0+tmp) - v002);
8332 arc = v022 + half(halfp(v2+tmp) - v022);
8333 if ( (arc < el_gordo-arc1) ) {
8336 mp->arith_error = true;
8337 if ( a_goal==el_gordo ) return (el_gordo);
8341 @ @<Other local variables in |arc_test|@>=
8342 scaled tmp, tmp2; /* all purpose temporary registers */
8343 scaled arc1; /* arc length estimate for the first half */
8345 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8346 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8347 ((dx0<=0) && (dx1<=0) && (dx2<=0));
8349 simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8350 ((dy0<=0) && (dy1<=0) && (dy2<=0));
8352 simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8353 ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8355 simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8356 ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8359 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8361 it is appropriate to use the same approximation to decide when the integral
8362 reaches the intermediate value |a_goal|. At this point
8364 {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8365 {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8366 {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8367 {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8368 {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8372 $$ {\vb\dot B(t)\vb\over 3} \approx
8373 \cases{B\left(\hbox{|v0|},
8374 \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8375 {1\over 2}\hbox{|v02|}; 2t \right)&
8376 if $t\le{1\over 2}$\cr
8377 B\left({1\over 2}\hbox{|v02|},
8378 \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8379 \hbox{|v2|}; 2t-1 \right)&
8380 if $t\ge{1\over 2}$.\cr}
8383 We can integrate $\vb\dot B(t)\vb$ by using
8384 $$\int 3B(a,b,c;\tau)\,dt =
8385 {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8388 This construction allows us to find the time when the arc length reaches
8389 |a_goal| by solving a cubic equation of the form
8390 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8391 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8392 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8393 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8394 $d\tau\over dt$. We shall define a function |solve_rising_cubic| that finds
8395 $\tau$ given $a$, $b$, $c$, and $x$.
8397 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8399 tmp = (v02 + 2) / 4;
8400 if ( a_goal<=arc1 ) {
8403 (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8406 return ((half_unit - two) +
8407 halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8411 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8412 $$ B(0, a, a+b, a+b+c; t) = x. $$
8413 This routine is based on |crossing_point| but is simplified by the
8414 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8415 If rounding error causes this condition to be violated slightly, we just ignore
8416 it and proceed with binary search. This finds a time when the function value
8417 reaches |x| and the slope is positive.
8419 @<Declare subroutines needed by |arc_test|@>=
8420 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b, scaled c, scaled x) {
8421 scaled ab, bc, ac; /* bisection results */
8422 integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8423 integer xx; /* temporary for updating |x| */
8424 if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8425 @:this can't happen rising?}{\quad rising?@>
8428 } else if ( x >= a+b+c ) {
8432 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8436 @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8437 xx = x - a - ab - ac;
8438 if ( xx < -x ) { x+=x; b=ab; c=ac; }
8439 else { x = x + xx; a=ac; b=mp->bc; t = t+1; };
8440 } while (t < unity);
8445 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8450 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8452 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8453 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) {
8460 @ It is convenient to have a simpler interface to |arc_test| that requires no
8461 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8462 length less than |fraction_four|.
8464 @d arc_tol 16 /* quit when change in arc length estimate reaches this */
8466 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1,
8467 scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8468 scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8469 scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8470 v0 = mp_pyth_add(mp, dx0,dy0);
8471 v1 = mp_pyth_add(mp, dx1,dy1);
8472 v2 = mp_pyth_add(mp, dx2,dy2);
8473 if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) {
8474 mp->arith_error = true;
8475 if ( a_goal==el_gordo ) return el_gordo;
8478 v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8479 return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8480 v0, v02, v2, a_goal, arc_tol));
8484 @ Now it is easy to find the arc length of an entire path.
8486 @c scaled mp_get_arc_length (MP mp,pointer h) {
8487 pointer p,q; /* for traversing the path */
8488 scaled a,a_tot; /* current and total arc lengths */
8491 while ( right_type(p)!=mp_endpoint ){
8493 a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8494 left_x(q)-right_x(p), left_y(q)-right_y(p),
8495 x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8496 a_tot = mp_slow_add(mp, a, a_tot);
8497 if ( q==h ) break; else p=q;
8503 @ The inverse operation of finding the time on a path~|h| when the arc length
8504 reaches some value |arc0| can also be accomplished via |do_arc_test|. Some care
8505 is required to handle very large times or negative times on cyclic paths. For
8506 non-cyclic paths, |arc0| values that are negative or too large cause
8507 |get_arc_time| to return 0 or the length of path~|h|.
8509 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8510 time value greater than the length of the path. Since it could be much greater,
8511 we must be prepared to compute the arc length of path~|h| and divide this into
8512 |arc0| to find how many multiples of the length of path~|h| to add.
8514 @c scaled mp_get_arc_time (MP mp,pointer h, scaled arc0) {
8515 pointer p,q; /* for traversing the path */
8516 scaled t_tot; /* accumulator for the result */
8517 scaled t; /* the result of |do_arc_test| */
8518 scaled arc; /* portion of |arc0| not used up so far */
8519 integer n; /* number of extra times to go around the cycle */
8521 @<Deal with a negative |arc0| value and |return|@>;
8523 if ( arc0==el_gordo ) decr(arc0);
8527 while ( (right_type(p)!=mp_endpoint) && (arc>0) ) {
8529 t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8530 left_x(q)-right_x(p), left_y(q)-right_y(p),
8531 x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8532 @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8534 @<Update |t_tot| and |arc| to avoid going around the cyclic
8535 path too many times but set |arith_error:=true| and |goto done| on
8544 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8545 if ( t<0 ) { t_tot = t_tot + t + two; arc = 0; }
8546 else { t_tot = t_tot + unity; arc = arc - t; }
8548 @ @<Deal with a negative |arc0| value and |return|@>=
8550 if ( left_type(h)==mp_endpoint ) {
8553 p = mp_htap_ypoc(mp, h);
8554 t_tot = -mp_get_arc_time(mp, p, -arc0);
8555 mp_toss_knot_list(mp, p);
8561 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8563 n = arc / (arc0 - arc);
8564 arc = arc - n*(arc0 - arc);
8565 if ( t_tot > el_gordo / (n+1) ) {
8566 mp->arith_error = true;
8570 t_tot = (n + 1)*t_tot;
8573 @* \[20] Data structures for pens.
8574 A Pen in \MP\ can be either elliptical or polygonal. Elliptical pens result
8575 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8576 @:stroke}{\&{stroke} command@>
8577 converted into an area fill as described in the next part of this program.
8578 The mathematics behind this process is based on simple aspects of the theory
8579 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8580 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8581 Foundations of Computer Science {\bf 24} (1983), 100--111].
8583 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8584 @:makepen_}{\&{makepen} primitive@>
8585 This path representation is almost sufficient for our purposes except that
8586 a pen path should always be a convex polygon with the vertices in
8587 counter-clockwise order.
8588 Since we will need to scan pen polygons both forward and backward, a pen
8589 should be represented as a doubly linked ring of knot nodes. There is
8590 room for the extra back pointer because we do not need the
8591 |left_type| or |right_type| fields. In fact, we don't need the |left_x|,
8592 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8593 so that certain procedures can operate on both pens and paths. In particular,
8594 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8597 /* this replaces the |left_type| and |right_type| fields in a pen knot */
8599 @ The |make_pen| procedure turns a path into a pen by initializing
8600 the |knil| pointers and making sure the knots form a convex polygon.
8601 Thus each cubic in the given path becomes a straight line and the control
8602 points are ignored. If the path is not cyclic, the ends are connected by a
8605 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8607 @c @<Declare a function called |convex_hull|@>;
8608 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8609 pointer p,q; /* two consecutive knots */
8616 h=mp_convex_hull(mp, h);
8617 @<Make sure |h| isn't confused with an elliptical pen@>;
8622 @ The only information required about an elliptical pen is the overall
8623 transformation that has been applied to the original \&{pencircle}.
8624 @:pencircle_}{\&{pencircle} primitive@>
8625 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8626 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8627 knot node and transformed as if it were a path.
8629 @d pen_is_elliptical(A) ((A)==link((A)))
8631 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8632 pointer h; /* the knot node to return */
8633 h=mp_get_node(mp, knot_node_size);
8634 link(h)=h; knil(h)=h;
8635 originator(h)=mp_program_code;
8636 x_coord(h)=0; y_coord(h)=0;
8637 left_x(h)=diam; left_y(h)=0;
8638 right_x(h)=0; right_y(h)=diam;
8642 @ If the polygon being returned by |make_pen| has only one vertex, it will
8643 be interpreted as an elliptical pen. This is no problem since a degenerate
8644 polygon can equally well be thought of as a degenerate ellipse. We need only
8645 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8647 @<Make sure |h| isn't confused with an elliptical pen@>=
8648 if ( pen_is_elliptical( h) ){
8649 left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8650 right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8653 @ We have to cheat a little here but most operations on pens only use
8654 the first three words in each knot node.
8655 @^data structure assumptions@>
8657 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8658 x_coord(test_pen)=-half_unit;
8659 y_coord(test_pen)=0;
8660 x_coord(test_pen+3)=half_unit;
8661 y_coord(test_pen+3)=0;
8662 x_coord(test_pen+6)=0;
8663 y_coord(test_pen+6)=unity;
8664 link(test_pen)=test_pen+3;
8665 link(test_pen+3)=test_pen+6;
8666 link(test_pen+6)=test_pen;
8667 knil(test_pen)=test_pen+6;
8668 knil(test_pen+3)=test_pen;
8669 knil(test_pen+6)=test_pen+3
8671 @ Printing a polygonal pen is very much like printing a path
8673 @<Declare subroutines for printing expressions@>=
8674 void mp_pr_pen (MP mp,pointer h) {
8675 pointer p,q; /* for list traversal */
8676 if ( pen_is_elliptical(h) ) {
8677 @<Print the elliptical pen |h|@>;
8681 mp_print_two(mp, x_coord(p),y_coord(p));
8682 mp_print_nl(mp, " .. ");
8683 @<Advance |p| making sure the links are OK and |return| if there is
8686 mp_print(mp, "cycle");
8690 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8692 if ( (q==null) || (knil(q)!=p) ) {
8693 mp_print_nl(mp, "???"); return; /* this won't happen */
8698 @ @<Print the elliptical pen |h|@>=
8700 mp_print(mp, "pencircle transformed (");
8701 mp_print_scaled(mp, x_coord(h));
8702 mp_print_char(mp, ',');
8703 mp_print_scaled(mp, y_coord(h));
8704 mp_print_char(mp, ',');
8705 mp_print_scaled(mp, left_x(h)-x_coord(h));
8706 mp_print_char(mp, ',');
8707 mp_print_scaled(mp, right_x(h)-x_coord(h));
8708 mp_print_char(mp, ',');
8709 mp_print_scaled(mp, left_y(h)-y_coord(h));
8710 mp_print_char(mp, ',');
8711 mp_print_scaled(mp, right_y(h)-y_coord(h));
8712 mp_print_char(mp, ')');
8715 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8718 @<Declare subroutines for printing expressions@>=
8719 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) {
8720 mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8723 mp_end_diagnostic(mp, true);
8726 @ Making a polygonal pen into a path involves restoring the |left_type| and
8727 |right_type| fields and setting the control points so as to make a polygonal
8731 void mp_make_path (MP mp,pointer h) {
8732 pointer p; /* for traversing the knot list */
8733 small_number k; /* a loop counter */
8734 @<Other local variables in |make_path|@>;
8735 if ( pen_is_elliptical(h) ) {
8736 @<Make the elliptical pen |h| into a path@>;
8740 left_type(p)=mp_explicit;
8741 right_type(p)=mp_explicit;
8742 @<copy the coordinates of knot |p| into its control points@>;
8748 @ @<copy the coordinates of knot |p| into its control points@>=
8749 left_x(p)=x_coord(p);
8750 left_y(p)=y_coord(p);
8751 right_x(p)=x_coord(p);
8752 right_y(p)=y_coord(p)
8754 @ We need an eight knot path to get a good approximation to an ellipse.
8756 @<Make the elliptical pen |h| into a path@>=
8758 @<Extract the transformation parameters from the elliptical pen~|h|@>;
8760 for (k=0;k<=7;k++ ) {
8761 @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8762 transforming it appropriately@>;
8763 if ( k==7 ) link(p)=h; else link(p)=mp_get_node(mp, knot_node_size);
8768 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8769 center_x=x_coord(h);
8770 center_y=y_coord(h);
8771 width_x=left_x(h)-center_x;
8772 width_y=left_y(h)-center_y;
8773 height_x=right_x(h)-center_x;
8774 height_y=right_y(h)-center_y
8776 @ @<Other local variables in |make_path|@>=
8777 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8778 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8779 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8780 scaled dx,dy; /* the vector from knot |p| to its right control point */
8782 /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8784 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8785 find the point $k/8$ of the way around the circle and the direction vector
8788 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8790 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8791 +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8792 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8793 +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8794 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8795 +mp_take_fraction(mp, mp->d_cos[k],height_x);
8796 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8797 +mp_take_fraction(mp, mp->d_cos[k],height_y);
8798 right_x(p)=x_coord(p)+dx;
8799 right_y(p)=y_coord(p)+dy;
8800 left_x(p)=x_coord(p)-dx;
8801 left_y(p)=y_coord(p)-dy;
8802 left_type(p)=mp_explicit;
8803 right_type(p)=mp_explicit;
8804 originator(p)=mp_program_code
8807 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8808 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8810 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8811 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8812 function for $\theta=\phi=22.5^\circ$. This comes out to be
8813 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8814 \approx 0.132608244919772.
8818 mp->half_cos[0]=fraction_half;
8819 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8821 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8822 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8824 for (k=3;k<= 4;k++ ) {
8825 mp->half_cos[k]=-mp->half_cos[4-k];
8826 mp->d_cos[k]=-mp->d_cos[4-k];
8828 for (k=5;k<= 7;k++ ) {
8829 mp->half_cos[k]=mp->half_cos[8-k];
8830 mp->d_cos[k]=mp->d_cos[8-k];
8833 @ The |convex_hull| function forces a pen polygon to be convex when it is
8834 returned by |make_pen| and after any subsequent transformation where rounding
8835 error might allow the convexity to be lost.
8836 The convex hull algorithm used here is described by F.~P. Preparata and
8837 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8839 @<Declare a function called |convex_hull|@>=
8840 @<Declare a procedure called |move_knot|@>;
8841 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8842 pointer l,r; /* the leftmost and rightmost knots */
8843 pointer p,q; /* knots being scanned */
8844 pointer s; /* the starting point for an upcoming scan */
8845 scaled dx,dy; /* a temporary pointer */
8846 if ( pen_is_elliptical(h) ) {
8849 @<Set |l| to the leftmost knot in polygon~|h|@>;
8850 @<Set |r| to the rightmost knot in polygon~|h|@>;
8853 @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8854 move them past~|r|@>;
8855 @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8856 move them past~|l|@>;
8857 @<Sort the path from |l| to |r| by increasing $x$@>;
8858 @<Sort the path from |r| to |l| by decreasing $x$@>;
8861 @<Do a Gramm scan and remove vertices where there is no left turn@>;
8867 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8869 @<Set |l| to the leftmost knot in polygon~|h|@>=
8873 if ( x_coord(p)<=x_coord(l) )
8874 if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8879 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8883 if ( x_coord(p)>=x_coord(r) )
8884 if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8889 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8890 dx=x_coord(r)-x_coord(l);
8891 dy=y_coord(r)-y_coord(l);
8895 if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8896 mp_move_knot(mp, p, r);
8900 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8903 @ @<Declare a procedure called |move_knot|@>=
8904 void mp_move_knot (MP mp,pointer p, pointer q) {
8905 link(knil(p))=link(p);
8906 knil(link(p))=knil(p);
8913 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8917 if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8918 mp_move_knot(mp, p,l);
8922 @ The list is likely to be in order already so we just do linear insertions.
8923 Secondary comparisons on $y$ ensure that the sort is consistent with the
8924 choice of |l| and |r|.
8926 @<Sort the path from |l| to |r| by increasing $x$@>=
8930 while ( x_coord(q)>x_coord(p) ) q=knil(q);
8931 while ( x_coord(q)==x_coord(p) ) {
8932 if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8934 if ( q==knil(p) ) p=link(p);
8935 else { p=link(p); mp_move_knot(mp, knil(p),q); };
8938 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8942 while ( x_coord(q)<x_coord(p) ) q=knil(q);
8943 while ( x_coord(q)==x_coord(p) ) {
8944 if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8946 if ( q==knil(p) ) p=link(p);
8947 else { p=link(p); mp_move_knot(mp, knil(p),q); };
8950 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8951 at knot |q|. There usually will be a left turn so we streamline the case
8952 where the |then| clause is not executed.
8954 @<Do a Gramm scan and remove vertices where there...@>=
8958 dx=x_coord(q)-x_coord(p);
8959 dy=y_coord(q)-y_coord(p);
8963 if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8964 @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8969 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8972 mp_free_node(mp, p,knot_node_size);
8973 link(s)=q; knil(q)=s;
8975 else { p=knil(s); q=s; };
8978 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8979 offset associated with the given direction |(x,y)|. If two different offsets
8980 apply, it chooses one of them.
8983 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8984 pointer p,q; /* consecutive knots */
8986 /* the transformation matrix for an elliptical pen */
8987 fraction xx,yy; /* untransformed offset for an elliptical pen */
8988 fraction d; /* a temporary register */
8989 if ( pen_is_elliptical(h) ) {
8990 @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8995 } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0));
8998 } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0));
8999 mp->cur_x=x_coord(p);
9000 mp->cur_y=y_coord(p);
9006 scaled cur_y; /* all-purpose return value registers */
9008 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
9009 if ( (x==0) && (y==0) ) {
9010 mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);
9012 @<Find the non-constant part of the transformation for |h|@>;
9013 while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){
9016 @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
9017 untransformed version of |(x,y)|@>;
9018 mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
9019 mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
9022 @ @<Find the non-constant part of the transformation for |h|@>=
9023 wx=left_x(h)-x_coord(h);
9024 wy=left_y(h)-y_coord(h);
9025 hx=right_x(h)-x_coord(h);
9026 hy=right_y(h)-y_coord(h)
9028 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
9029 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
9030 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
9031 d=mp_pyth_add(mp, xx,yy);
9033 xx=half(mp_make_fraction(mp, xx,d));
9034 yy=half(mp_make_fraction(mp, yy,d));
9037 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
9038 But we can handle that case by just calling |find_offset| twice. The answer
9039 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
9042 void mp_pen_bbox (MP mp,pointer h) {
9043 pointer p; /* for scanning the knot list */
9044 if ( pen_is_elliptical(h) ) {
9045 @<Find the bounding box of an elliptical pen@>;
9047 minx=x_coord(h); maxx=minx;
9048 miny=y_coord(h); maxy=miny;
9051 if ( x_coord(p)<minx ) minx=x_coord(p);
9052 if ( y_coord(p)<miny ) miny=y_coord(p);
9053 if ( x_coord(p)>maxx ) maxx=x_coord(p);
9054 if ( y_coord(p)>maxy ) maxy=y_coord(p);
9060 @ @<Find the bounding box of an elliptical pen@>=
9062 mp_find_offset(mp, 0,fraction_one,h);
9064 minx=2*x_coord(h)-mp->cur_x;
9065 mp_find_offset(mp, -fraction_one,0,h);
9067 miny=2*y_coord(h)-mp->cur_y;
9070 @* \[21] Edge structures.
9071 Now we come to \MP's internal scheme for representing pictures.
9072 The representation is very different from \MF's edge structures
9073 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9074 images. However, the basic idea is somewhat similar in that shapes
9075 are represented via their boundaries.
9077 The main purpose of edge structures is to keep track of graphical objects
9078 until it is time to translate them into \ps. Since \MP\ does not need to
9079 know anything about an edge structure other than how to translate it into
9080 \ps\ and how to find its bounding box, edge structures can be just linked
9081 lists of graphical objects. \MP\ has no easy way to determine whether
9082 two such objects overlap, but it suffices to draw the first one first and
9083 let the second one overwrite it if necessary.
9086 enum mp_graphical_object_code {
9087 @<Graphical object codes@>
9090 @ Let's consider the types of graphical objects one at a time.
9091 First of all, a filled contour is represented by a eight-word node. The first
9092 word contains |type| and |link| fields, and the next six words contain a
9093 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9094 parameter. If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9095 give the relevant information.
9097 @d path_p(A) link((A)+1)
9098 /* a pointer to the path that needs filling */
9099 @d pen_p(A) info((A)+1)
9100 /* a pointer to the pen to fill or stroke with */
9101 @d color_model(A) type((A)+2) /* the color model */
9102 @d obj_red_loc(A) ((A)+3) /* the first of three locations for the color */
9103 @d obj_cyan_loc obj_red_loc /* the first of four locations for the color */
9104 @d obj_grey_loc obj_red_loc /* the location for the color */
9105 @d red_val(A) mp->mem[(A)+3].sc
9106 /* the red component of the color in the range $0\ldots1$ */
9109 @d green_val(A) mp->mem[(A)+4].sc
9110 /* the green component of the color in the range $0\ldots1$ */
9111 @d magenta_val green_val
9112 @d blue_val(A) mp->mem[(A)+5].sc
9113 /* the blue component of the color in the range $0\ldots1$ */
9114 @d yellow_val blue_val
9115 @d black_val(A) mp->mem[(A)+6].sc
9116 /* the blue component of the color in the range $0\ldots1$ */
9117 @d ljoin_val(A) name_type((A)) /* the value of \&{linejoin} */
9118 @:mp_linejoin_}{\&{linejoin} primitive@>
9119 @d miterlim_val(A) mp->mem[(A)+7].sc /* the value of \&{miterlimit} */
9120 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9121 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9122 /* interpret an object pointer that has been offset by |red_part..blue_part| */
9123 @d pre_script(A) mp->mem[(A)+8].hh.lh
9124 @d post_script(A) mp->mem[(A)+8].hh.rh
9127 @ @<Graphical object codes@>=
9131 pointer mp_new_fill_node (MP mp,pointer p) {
9132 /* make a fill node for cyclic path |p| and color black */
9133 pointer t; /* the new node */
9134 t=mp_get_node(mp, fill_node_size);
9135 type(t)=mp_fill_code;
9137 pen_p(t)=null; /* |null| means don't use a pen */
9142 color_model(t)=mp_uninitialized_model;
9144 post_script(t)=null;
9145 @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9149 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9150 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9151 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9152 else ljoin_val(t)=0;
9153 if ( mp->internal[mp_miterlimit]<unity )
9154 miterlim_val(t)=unity;
9156 miterlim_val(t)=mp->internal[mp_miterlimit]
9158 @ A stroked path is represented by an eight-word node that is like a filled
9159 contour node except that it contains the current \&{linecap} value, a scale
9160 factor for the dash pattern, and a pointer that is non-null if the stroke
9161 is to be dashed. The purpose of the scale factor is to allow a picture to
9162 be transformed without touching the picture that |dash_p| points to.
9164 @d dash_p(A) link((A)+9)
9165 /* a pointer to the edge structure that gives the dash pattern */
9166 @d lcap_val(A) type((A)+9)
9167 /* the value of \&{linecap} */
9168 @:mp_linecap_}{\&{linecap} primitive@>
9169 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9170 @d stroked_node_size 11
9172 @ @<Graphical object codes@>=
9176 pointer mp_new_stroked_node (MP mp,pointer p) {
9177 /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9178 pointer t; /* the new node */
9179 t=mp_get_node(mp, stroked_node_size);
9180 type(t)=mp_stroked_code;
9181 path_p(t)=p; pen_p(t)=null;
9183 dash_scale(t)=unity;
9188 color_model(t)=mp_uninitialized_model;
9190 post_script(t)=null;
9191 @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9192 if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9193 else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9198 @ When a dashed line is computed in a transformed coordinate system, the dash
9199 lengths get scaled like the pen shape and we need to compensate for this. Since
9200 there is no unique scale factor for an arbitrary transformation, we use the
9201 the square root of the determinant. The properties of the determinant make it
9202 easier to maintain the |dash_scale|. The computation is fairly straight-forward
9203 except for the initialization of the scale factor |s|. The factor of 64 is
9204 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9205 to counteract the effect of |take_fraction|.
9207 @<Declare subroutines needed by |print_edges|@>=
9208 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9209 scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9210 integer s; /* amount by which the result of |square_rt| needs to be scaled */
9211 @<Initialize |maxabs|@>;
9213 while ( (maxabs<fraction_one) && (s>1) ){
9214 a+=a; b+=b; c+=c; d+=d;
9215 maxabs+=maxabs; s=halfp(s);
9217 return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9220 scaled mp_get_pen_scale (MP mp,pointer p) {
9221 return mp_sqrt_det(mp,
9222 left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9223 left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9226 @ @<Internal library ...@>=
9227 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9230 @ @<Initialize |maxabs|@>=
9232 if ( abs(b)>maxabs ) maxabs=abs(b);
9233 if ( abs(c)>maxabs ) maxabs=abs(c);
9234 if ( abs(d)>maxabs ) maxabs=abs(d)
9236 @ When a picture contains text, this is represented by a fourteen-word node
9237 where the color information and |type| and |link| fields are augmented by
9238 additional fields that describe the text and how it is transformed.
9239 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9240 the font and a string number that gives the text to be displayed.
9241 The |width|, |height|, and |depth| fields
9242 give the dimensions of the text at its design size, and the remaining six
9243 words give a transformation to be applied to the text. The |new_text_node|
9244 function initializes everything to default values so that the text comes out
9245 black with its reference point at the origin.
9247 @d text_p(A) link((A)+1) /* a string pointer for the text to display */
9248 @d font_n(A) info((A)+1) /* the font number */
9249 @d width_val(A) mp->mem[(A)+7].sc /* unscaled width of the text */
9250 @d height_val(A) mp->mem[(A)+9].sc /* unscaled height of the text */
9251 @d depth_val(A) mp->mem[(A)+10].sc /* unscaled depth of the text */
9252 @d text_tx_loc(A) ((A)+11)
9253 /* the first of six locations for transformation parameters */
9254 @d tx_val(A) mp->mem[(A)+11].sc /* $x$ shift amount */
9255 @d ty_val(A) mp->mem[(A)+12].sc /* $y$ shift amount */
9256 @d txx_val(A) mp->mem[(A)+13].sc /* |txx| transformation parameter */
9257 @d txy_val(A) mp->mem[(A)+14].sc /* |txy| transformation parameter */
9258 @d tyx_val(A) mp->mem[(A)+15].sc /* |tyx| transformation parameter */
9259 @d tyy_val(A) mp->mem[(A)+16].sc /* |tyy| transformation parameter */
9260 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9261 /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9262 @d text_node_size 17
9264 @ @<Graphical object codes@>=
9267 @ @c @<Declare text measuring subroutines@>;
9268 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9269 /* make a text node for font |f| and text string |s| */
9270 pointer t; /* the new node */
9271 t=mp_get_node(mp, text_node_size);
9272 type(t)=mp_text_code;
9274 font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9279 color_model(t)=mp_uninitialized_model;
9281 post_script(t)=null;
9282 tx_val(t)=0; ty_val(t)=0;
9283 txx_val(t)=unity; txy_val(t)=0;
9284 tyx_val(t)=0; tyy_val(t)=unity;
9285 mp_set_text_box(mp, t); /* this finds the bounding box */
9289 @ The last two types of graphical objects that can occur in an edge structure
9290 are clipping paths and \&{setbounds} paths. These are slightly more difficult
9291 @:set_bounds_}{\&{setbounds} primitive@>
9292 to implement because we must keep track of exactly what is being clipped or
9293 bounded when pictures get merged together. For this reason, each clipping or
9294 \&{setbounds} operation is represented by a pair of nodes: first comes a
9295 two-word node whose |path_p| gives the relevant path, then there is the list
9296 of objects to clip or bound followed by a two-word node whose second word is
9299 Using at least two words for each graphical object node allows them all to be
9300 allocated and deallocated similarly with a global array |gr_object_size| to
9301 give the size in words for each object type.
9303 @d start_clip_size 2
9304 @d start_bounds_size 2
9305 @d stop_clip_size 2 /* the second word is not used here */
9306 @d stop_bounds_size 2 /* the second word is not used here */
9308 @d stop_type(A) ((A)+2)
9309 /* matching |type| for |start_clip_code| or |start_bounds_code| */
9310 @d has_color(A) (type((A))<mp_start_clip_code)
9311 /* does a graphical object have color fields? */
9312 @d has_pen(A) (type((A))<mp_text_code)
9313 /* does a graphical object have a |pen_p| field? */
9314 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9315 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9317 @ @<Graphical object codes@>=
9318 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9319 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9320 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9321 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9324 pointer mp_new_bounds_node (MP mp,pointer p, small_number c) {
9325 /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9326 pointer t; /* the new node */
9327 t=mp_get_node(mp, mp->gr_object_size[c]);
9333 @ We need an array to keep track of the sizes of graphical objects.
9336 small_number gr_object_size[mp_stop_bounds_code+1];
9339 mp->gr_object_size[mp_fill_code]=fill_node_size;
9340 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9341 mp->gr_object_size[mp_text_code]=text_node_size;
9342 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9343 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9344 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9345 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9347 @ All the essential information in an edge structure is encoded as a linked list
9348 of graphical objects as we have just seen, but it is helpful to add some
9349 redundant information. A single edge structure might be used as a dash pattern
9350 many times, and it would be nice to avoid scanning the same structure
9351 repeatedly. Thus, an edge structure known to be a suitable dash pattern
9352 has a header that gives a list of dashes in a sorted order designed for rapid
9353 translation into \ps.
9355 Each dash is represented by a three-word node containing the initial and final
9356 $x$~coordinates as well as the usual |link| field. The |link| fields points to
9357 the dash node with the next higher $x$-coordinates and the final link points
9358 to a special location called |null_dash|. (There should be no overlap between
9359 dashes). Since the $y$~coordinate of the dash pattern is needed to determine
9360 the period of repetition, this needs to be stored in the edge header along
9361 with a pointer to the list of dash nodes.
9363 @d start_x(A) mp->mem[(A)+1].sc /* the starting $x$~coordinate in a dash node */
9364 @d stop_x(A) mp->mem[(A)+2].sc /* the ending $x$~coordinate in a dash node */
9367 /* in an edge header this points to the first dash node */
9368 @d dash_y(A) mp->mem[(A)+1].sc /* $y$ value for the dash list in an edge header */
9370 @ It is also convenient for an edge header to contain the bounding
9371 box information needed by the \&{llcorner} and \&{urcorner} operators
9372 so that this does not have to be recomputed unnecessarily. This is done by
9373 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9374 how far the bounding box computation has gotten. Thus if the user asks for
9375 the bounding box and then adds some more text to the picture before asking
9376 for more bounding box information, the second computation need only look at
9377 the additional text.
9379 When the bounding box has not been computed, the |bblast| pointer points
9380 to a dummy link at the head of the graphical object list while the |minx_val|
9381 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9382 fields contain |-el_gordo|.
9384 Since the bounding box of pictures containing objects of type
9385 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9386 @:mp_true_corners_}{\&{truecorners} primitive@>
9387 data might not be valid for all values of this parameter. Hence, the |bbtype|
9388 field is needed to keep track of this.
9390 @d minx_val(A) mp->mem[(A)+2].sc
9391 @d miny_val(A) mp->mem[(A)+3].sc
9392 @d maxx_val(A) mp->mem[(A)+4].sc
9393 @d maxy_val(A) mp->mem[(A)+5].sc
9394 @d bblast(A) link((A)+6) /* last item considered in bounding box computation */
9395 @d bbtype(A) info((A)+6) /* tells how bounding box data depends on \&{truecorners} */
9396 @d dummy_loc(A) ((A)+7) /* where the object list begins in an edge header */
9398 /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9400 /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9402 /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9405 void mp_init_bbox (MP mp,pointer h) {
9406 /* Initialize the bounding box information in edge structure |h| */
9407 bblast(h)=dummy_loc(h);
9408 bbtype(h)=no_bounds;
9409 minx_val(h)=el_gordo;
9410 miny_val(h)=el_gordo;
9411 maxx_val(h)=-el_gordo;
9412 maxy_val(h)=-el_gordo;
9415 @ The only other entries in an edge header are a reference count in the first
9416 word and a pointer to the tail of the object list in the last word.
9418 @d obj_tail(A) info((A)+7) /* points to the last entry in the object list */
9419 @d edge_header_size 8
9422 void mp_init_edges (MP mp,pointer h) {
9423 /* initialize an edge header to null values */
9424 dash_list(h)=null_dash;
9425 obj_tail(h)=dummy_loc(h);
9426 link(dummy_loc(h))=null;
9428 mp_init_bbox(mp, h);
9431 @ Here is how edge structures are deleted. The process can be recursive because
9432 of the need to dereference edge structures that are used as dash patterns.
9435 @d add_edge_ref(A) incr(ref_count(A))
9436 @d delete_edge_ref(A) {
9437 if ( ref_count((A))==null )
9438 mp_toss_edges(mp, A);
9443 @<Declare the recycling subroutines@>=
9444 void mp_flush_dash_list (MP mp,pointer h);
9445 pointer mp_toss_gr_object (MP mp,pointer p) ;
9446 void mp_toss_edges (MP mp,pointer h) ;
9448 @ @c void mp_toss_edges (MP mp,pointer h) {
9449 pointer p,q; /* pointers that scan the list being recycled */
9450 pointer r; /* an edge structure that object |p| refers to */
9451 mp_flush_dash_list(mp, h);
9452 q=link(dummy_loc(h));
9453 while ( (q!=null) ) {
9455 r=mp_toss_gr_object(mp, p);
9456 if ( r!=null ) delete_edge_ref(r);
9458 mp_free_node(mp, h,edge_header_size);
9460 void mp_flush_dash_list (MP mp,pointer h) {
9461 pointer p,q; /* pointers that scan the list being recycled */
9463 while ( q!=null_dash ) {
9465 mp_free_node(mp, p,dash_node_size);
9467 dash_list(h)=null_dash;
9469 pointer mp_toss_gr_object (MP mp,pointer p) {
9470 /* returns an edge structure that needs to be dereferenced */
9471 pointer e; /* the edge structure to return */
9473 @<Prepare to recycle graphical object |p|@>;
9474 mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9478 @ @<Prepare to recycle graphical object |p|@>=
9481 mp_toss_knot_list(mp, path_p(p));
9482 if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9483 if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9484 if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9486 case mp_stroked_code:
9487 mp_toss_knot_list(mp, path_p(p));
9488 if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9489 if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9490 if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9494 delete_str_ref(text_p(p));
9495 if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9496 if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9498 case mp_start_clip_code:
9499 case mp_start_bounds_code:
9500 mp_toss_knot_list(mp, path_p(p));
9502 case mp_stop_clip_code:
9503 case mp_stop_bounds_code:
9505 } /* there are no other cases */
9507 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9508 to be done before making a significant change to an edge structure. Much of
9509 the work is done in a separate routine |copy_objects| that copies a list of
9510 graphical objects into a new edge header.
9512 @c @<Declare a function called |copy_objects|@>;
9513 pointer mp_private_edges (MP mp,pointer h) {
9514 /* make a private copy of the edge structure headed by |h| */
9515 pointer hh; /* the edge header for the new copy */
9516 pointer p,pp; /* pointers for copying the dash list */
9517 if ( ref_count(h)==null ) {
9521 hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9522 @<Copy the dash list from |h| to |hh|@>;
9523 @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9524 point into the new object list@>;
9529 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9530 @^data structure assumptions@>
9532 @<Copy the dash list from |h| to |hh|@>=
9533 pp=hh; p=dash_list(h);
9534 while ( (p!=null_dash) ) {
9535 link(pp)=mp_get_node(mp, dash_node_size);
9537 start_x(pp)=start_x(p);
9538 stop_x(pp)=stop_x(p);
9542 dash_y(hh)=dash_y(h)
9545 @ |h| is an edge structure
9547 @d gr_start_x(A) (A)->start_x_field
9548 @d gr_stop_x(A) (A)->stop_x_field
9549 @d gr_dash_link(A) (A)->next_field
9551 @d gr_dash_list(A) (A)->list_field
9552 @d gr_dash_y(A) (A)->y_field
9555 struct mp_dash_list *mp_export_dashes (MP mp, pointer h) {
9556 struct mp_dash_list *dl;
9557 struct mp_dash_item *dh, *di;
9559 if (h==null || dash_list(h)==null_dash)
9562 dl = mp_xmalloc(mp,1,sizeof(struct mp_dash_list));
9563 gr_dash_list(dl) = NULL;
9564 gr_dash_y(dl) = dash_y(h);
9566 while (p != null_dash) {
9567 di=mp_xmalloc(mp,1,sizeof(struct mp_dash_item));
9568 gr_dash_link(di) = NULL;
9569 gr_start_x(di) = start_x(p);
9570 gr_stop_x(di) = stop_x(p);
9572 gr_dash_list(dl) = di;
9574 gr_dash_link(dh) = di;
9583 @ @<Copy the bounding box information from |h| to |hh|...@>=
9584 minx_val(hh)=minx_val(h);
9585 miny_val(hh)=miny_val(h);
9586 maxx_val(hh)=maxx_val(h);
9587 maxy_val(hh)=maxy_val(h);
9588 bbtype(hh)=bbtype(h);
9589 p=dummy_loc(h); pp=dummy_loc(hh);
9590 while ((p!=bblast(h)) ) {
9591 if ( p==null ) mp_confusion(mp, "bblast");
9592 @:this can't happen bblast}{\quad bblast@>
9593 p=link(p); pp=link(pp);
9597 @ Here is the promised routine for copying graphical objects into a new edge
9598 structure. It starts copying at object~|p| and stops just before object~|q|.
9599 If |q| is null, it copies the entire sublist headed at |p|. The resulting edge
9600 structure requires further initialization by |init_bbox|.
9602 @<Declare a function called |copy_objects|@>=
9603 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9604 pointer hh; /* the new edge header */
9605 pointer pp; /* the last newly copied object */
9606 small_number k; /* temporary register */
9607 hh=mp_get_node(mp, edge_header_size);
9608 dash_list(hh)=null_dash;
9612 @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9619 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9620 { k=mp->gr_object_size[type(p)];
9621 link(pp)=mp_get_node(mp, k);
9623 while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k]; };
9624 @<Fix anything in graphical object |pp| that should differ from the
9625 corresponding field in |p|@>;
9629 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9631 case mp_start_clip_code:
9632 case mp_start_bounds_code:
9633 path_p(pp)=mp_copy_path(mp, path_p(p));
9636 path_p(pp)=mp_copy_path(mp, path_p(p));
9637 if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9639 case mp_stroked_code:
9640 path_p(pp)=mp_copy_path(mp, path_p(p));
9641 pen_p(pp)=copy_pen(pen_p(p));
9642 if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9645 add_str_ref(text_p(pp));
9647 case mp_stop_clip_code:
9648 case mp_stop_bounds_code:
9650 } /* there are no other cases */
9652 @ Here is one way to find an acceptable value for the second argument to
9653 |copy_objects|. Given a non-null graphical object list, |skip_1component|
9654 skips past one picture component, where a ``picture component'' is a single
9655 graphical object, or a start bounds or start clip object and everything up
9656 through the matching stop bounds or stop clip object. The macro version avoids
9657 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9658 unless |p| points to a stop bounds or stop clip node, in which case it executes
9661 @d skip_component(A)
9662 if ( ! is_start_or_stop((A)) ) (A)=link((A));
9663 else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9667 pointer mp_skip_1component (MP mp,pointer p) {
9668 integer lev; /* current nesting level */
9671 if ( is_start_or_stop(p) ) {
9672 if ( is_stop(p) ) decr(lev); else incr(lev);
9679 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9681 @<Declare subroutines for printing expressions@>=
9682 @<Declare subroutines needed by |print_edges|@>;
9683 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9684 pointer p; /* a graphical object to be printed */
9685 pointer hh,pp; /* temporary pointers */
9686 scaled scf; /* a scale factor for the dash pattern */
9687 boolean ok_to_dash; /* |false| for polygonal pen strokes */
9688 mp_print_diagnostic(mp, "Edge structure",s,nuline);
9690 while ( link(p)!=null ) {
9694 @<Cases for printing graphical object node |p|@>;
9696 mp_print(mp, "[unknown object type!]");
9700 mp_print_nl(mp, "End edges");
9701 if ( p!=obj_tail(h) ) mp_print(mp, "?");
9703 mp_end_diagnostic(mp, true);
9706 @ @<Cases for printing graphical object node |p|@>=
9708 mp_print(mp, "Filled contour ");
9709 mp_print_obj_color(mp, p);
9710 mp_print_char(mp, ':'); mp_print_ln(mp);
9711 mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9712 if ( (pen_p(p)!=null) ) {
9713 @<Print join type for graphical object |p|@>;
9714 mp_print(mp, " with pen"); mp_print_ln(mp);
9715 mp_pr_pen(mp, pen_p(p));
9719 @ @<Print join type for graphical object |p|@>=
9720 switch (ljoin_val(p)) {
9722 mp_print(mp, "mitered joins limited ");
9723 mp_print_scaled(mp, miterlim_val(p));
9726 mp_print(mp, "round joins");
9729 mp_print(mp, "beveled joins");
9732 mp_print(mp, "?? joins");
9737 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9739 @<Print join and cap types for stroked node |p|@>=
9740 switch (lcap_val(p)) {
9741 case 0:mp_print(mp, "butt"); break;
9742 case 1:mp_print(mp, "round"); break;
9743 case 2:mp_print(mp, "square"); break;
9744 default: mp_print(mp, "??"); break;
9747 mp_print(mp, " ends, ");
9748 @<Print join type for graphical object |p|@>
9750 @ Here is a routine that prints the color of a graphical object if it isn't
9751 black (the default color).
9753 @<Declare subroutines needed by |print_edges|@>=
9754 @<Declare a procedure called |print_compact_node|@>;
9755 void mp_print_obj_color (MP mp,pointer p) {
9756 if ( color_model(p)==mp_grey_model ) {
9757 if ( grey_val(p)>0 ) {
9758 mp_print(mp, "greyed ");
9759 mp_print_compact_node(mp, obj_grey_loc(p),1);
9761 } else if ( color_model(p)==mp_cmyk_model ) {
9762 if ( (cyan_val(p)>0) || (magenta_val(p)>0) ||
9763 (yellow_val(p)>0) || (black_val(p)>0) ) {
9764 mp_print(mp, "processcolored ");
9765 mp_print_compact_node(mp, obj_cyan_loc(p),4);
9767 } else if ( color_model(p)==mp_rgb_model ) {
9768 if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) {
9769 mp_print(mp, "colored ");
9770 mp_print_compact_node(mp, obj_red_loc(p),3);
9775 @ We also need a procedure for printing consecutive scaled values as if they
9776 were a known big node.
9778 @<Declare a procedure called |print_compact_node|@>=
9779 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9780 pointer q; /* last location to print */
9782 mp_print_char(mp, '(');
9784 mp_print_scaled(mp, mp->mem[p].sc);
9785 if ( p<q ) mp_print_char(mp, ',');
9788 mp_print_char(mp, ')');
9791 @ @<Cases for printing graphical object node |p|@>=
9792 case mp_stroked_code:
9793 mp_print(mp, "Filled pen stroke ");
9794 mp_print_obj_color(mp, p);
9795 mp_print_char(mp, ':'); mp_print_ln(mp);
9796 mp_pr_path(mp, path_p(p));
9797 if ( dash_p(p)!=null ) {
9798 mp_print_nl(mp, "dashed (");
9799 @<Finish printing the dash pattern that |p| refers to@>;
9802 @<Print join and cap types for stroked node |p|@>;
9803 mp_print(mp, " with pen"); mp_print_ln(mp);
9804 if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9806 else mp_pr_pen(mp, pen_p(p));
9809 @ Normally, the |dash_list| field in an edge header is set to |null_dash|
9810 when it is not known to define a suitable dash pattern. This is disallowed
9811 here because the |dash_p| field should never point to such an edge header.
9812 Note that memory is allocated for |start_x(null_dash)| and we are free to
9813 give it any convenient value.
9815 @<Finish printing the dash pattern that |p| refers to@>=
9816 ok_to_dash=pen_is_elliptical(pen_p(p));
9817 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9820 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9821 mp_print(mp, " ??");
9822 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9823 while ( pp!=null_dash ) {
9824 mp_print(mp, "on ");
9825 mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9826 mp_print(mp, " off ");
9827 mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9829 if ( pp!=null_dash ) mp_print_char(mp, ' ');
9831 mp_print(mp, ") shifted ");
9832 mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9833 if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9836 @ @<Declare subroutines needed by |print_edges|@>=
9837 scaled mp_dash_offset (MP mp,pointer h) {
9838 scaled x; /* the answer */
9839 if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9840 @:this can't happen dash0}{\quad dash0@>
9841 if ( dash_y(h)==0 ) {
9844 x=-(start_x(dash_list(h)) % dash_y(h));
9845 if ( x<0 ) x=x+dash_y(h);
9850 @ @<Cases for printing graphical object node |p|@>=
9852 mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9853 mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9854 mp_print_char(mp, '"'); mp_print_ln(mp);
9855 mp_print_obj_color(mp, p);
9856 mp_print(mp, "transformed ");
9857 mp_print_compact_node(mp, text_tx_loc(p),6);
9860 @ @<Cases for printing graphical object node |p|@>=
9861 case mp_start_clip_code:
9862 mp_print(mp, "clipping path:");
9864 mp_pr_path(mp, path_p(p));
9866 case mp_stop_clip_code:
9867 mp_print(mp, "stop clipping");
9870 @ @<Cases for printing graphical object node |p|@>=
9871 case mp_start_bounds_code:
9872 mp_print(mp, "setbounds path:");
9874 mp_pr_path(mp, path_p(p));
9876 case mp_stop_bounds_code:
9877 mp_print(mp, "end of setbounds");
9880 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9881 subroutine that scans an edge structure and tries to interpret it as a dash
9882 pattern. This can only be done when there are no filled regions or clipping
9883 paths and all the pen strokes have the same color. The first step is to let
9884 $y_0$ be the initial $y$~coordinate of the first pen stroke. Then we implicitly
9885 project all the pen stroke paths onto the line $y=y_0$ and require that there
9886 be no retracing. If the resulting paths cover a range of $x$~coordinates of
9887 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9888 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9890 @c @<Declare a procedure called |x_retrace_error|@>;
9891 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9892 pointer p; /* this scans the stroked nodes in the object list */
9893 pointer p0; /* if not |null| this points to the first stroked node */
9894 pointer pp,qq,rr; /* pointers into |path_p(p)| */
9895 pointer d,dd; /* pointers used to create the dash list */
9896 @<Other local variables in |make_dashes|@>;
9897 scaled y0=0; /* the initial $y$ coordinate */
9898 if ( dash_list(h)!=null_dash )
9901 p=link(dummy_loc(h));
9903 if ( type(p)!=mp_stroked_code ) {
9904 @<Compain that the edge structure contains a node of the wrong type
9905 and |goto not_found|@>;
9908 if ( p0==null ){ p0=p; y0=y_coord(pp); };
9909 @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9910 or |goto not_found| if there is an error@>;
9911 @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9914 if ( dash_list(h)==null_dash )
9915 goto NOT_FOUND; /* No error message */
9916 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9917 @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9920 @<Flush the dash list, recycle |h| and return |null|@>;
9923 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9925 print_err("Picture is too complicated to use as a dash pattern");
9926 help3("When you say `dashed p', picture p should not contain any")
9927 ("text, filled regions, or clipping paths. This time it did")
9928 ("so I'll just make it a solid line instead.");
9929 mp_put_get_error(mp);
9933 @ A similar error occurs when monotonicity fails.
9935 @<Declare a procedure called |x_retrace_error|@>=
9936 void mp_x_retrace_error (MP mp) {
9937 print_err("Picture is too complicated to use as a dash pattern");
9938 help3("When you say `dashed p', every path in p should be monotone")
9939 ("in x and there must be no overlapping. This failed")
9940 ("so I'll just make it a solid line instead.");
9941 mp_put_get_error(mp);
9944 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9945 handle the case where the pen stroke |p| is itself dashed.
9947 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9948 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9951 if ( link(pp)!=pp ) {
9954 @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9955 if there is a problem@>;
9956 } while (right_type(rr)!=mp_endpoint);
9958 d=mp_get_node(mp, dash_node_size);
9959 if ( dash_p(p)==0 ) info(d)=0; else info(d)=p;
9960 if ( x_coord(pp)<x_coord(rr) ) {
9961 start_x(d)=x_coord(pp);
9962 stop_x(d)=x_coord(rr);
9964 start_x(d)=x_coord(rr);
9965 stop_x(d)=x_coord(pp);
9968 @ We also need to check for the case where the segment from |qq| to |rr| is
9969 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9971 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9976 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9977 if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9978 if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9979 mp_x_retrace_error(mp); goto NOT_FOUND;
9983 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9984 if ( (x_coord(pp)<x0) || (x0<x3) ) {
9985 mp_x_retrace_error(mp); goto NOT_FOUND;
9989 @ @<Other local variables in |make_dashes|@>=
9990 scaled x0,x1,x2,x3; /* $x$ coordinates of the segment from |qq| to |rr| */
9992 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9993 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9994 (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9995 print_err("Picture is too complicated to use as a dash pattern");
9996 help3("When you say `dashed p', everything in picture p should")
9997 ("be the same color. I can\'t handle your color changes")
9998 ("so I'll just make it a solid line instead.");
9999 mp_put_get_error(mp);
10003 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
10004 start_x(null_dash)=stop_x(d);
10005 dd=h; /* this makes |link(dd)=dash_list(h)| */
10006 while ( start_x(link(dd))<stop_x(d) )
10009 if ( (stop_x(dd)>start_x(d)) )
10010 { mp_x_retrace_error(mp); goto NOT_FOUND; };
10015 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
10017 while ( (link(d)!=null_dash) )
10020 dash_y(h)=stop_x(d)-start_x(dd);
10021 if ( abs(y0)>dash_y(h) ) {
10023 } else if ( d!=dd ) {
10024 dash_list(h)=link(dd);
10025 stop_x(d)=stop_x(dd)+dash_y(h);
10026 mp_free_node(mp, dd,dash_node_size);
10029 @ We get here when the argument is a null picture or when there is an error.
10030 Recovering from an error involves making |dash_list(h)| empty to indicate
10031 that |h| is not known to be a valid dash pattern. We also dereference |h|
10032 since it is not being used for the return value.
10034 @<Flush the dash list, recycle |h| and return |null|@>=
10035 mp_flush_dash_list(mp, h);
10036 delete_edge_ref(h);
10039 @ Having carefully saved the dashed stroked nodes in the
10040 corresponding dash nodes, we must be prepared to break up these dashes into
10043 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
10044 d=h; /* now |link(d)=dash_list(h)| */
10045 while ( link(d)!=null_dash ) {
10051 hsf=dash_scale(ds);
10052 if ( (hh==null) ) mp_confusion(mp, "dash1");
10053 @:this can't happen dash0}{\quad dash1@>
10054 if ( dash_y(hh)==0 ) {
10057 if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
10058 @:this can't happen dash0}{\quad dash1@>
10059 @<Replace |link(d)| by a dashed version as determined by edge header
10060 |hh| and scale factor |ds|@>;
10065 @ @<Other local variables in |make_dashes|@>=
10066 pointer dln; /* |link(d)| */
10067 pointer hh; /* an edge header that tells how to break up |dln| */
10068 scaled hsf; /* the dash pattern from |hh| gets scaled by this */
10069 pointer ds; /* the stroked node from which |hh| and |hsf| are derived */
10070 scaled xoff; /* added to $x$ values in |dash_list(hh)| to match |dln| */
10072 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
10075 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10076 mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10077 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10078 +mp_take_scaled(mp, hsf,dash_y(hh));
10079 stop_x(null_dash)=start_x(null_dash);
10080 @<Advance |dd| until finding the first dash that overlaps |dln| when
10081 offset by |xoff|@>;
10082 while ( start_x(dln)<=stop_x(dln) ) {
10083 @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10084 @<Insert a dash between |d| and |dln| for the overlap with the offset version
10087 start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10090 mp_free_node(mp, dln,dash_node_size)
10092 @ The name of this module is a bit of a lie because we actually just find the
10093 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10094 overlap possible. It could be that the unoffset version of dash |dln| falls
10095 in the gap between |dd| and its predecessor.
10097 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10098 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10102 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10103 if ( dd==null_dash ) {
10105 xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10108 @ At this point we already know that
10109 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10111 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10112 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10113 link(d)=mp_get_node(mp, dash_node_size);
10116 if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10117 start_x(d)=start_x(dln);
10119 start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10120 if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd))))
10121 stop_x(d)=stop_x(dln);
10123 stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10126 @ The next major task is to update the bounding box information in an edge
10127 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10128 header's bounding box to accommodate the box computed by |path_bbox| or
10129 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10132 @c void mp_adjust_bbox (MP mp,pointer h) {
10133 if ( minx<minx_val(h) ) minx_val(h)=minx;
10134 if ( miny<miny_val(h) ) miny_val(h)=miny;
10135 if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
10136 if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
10139 @ Here is a special routine for updating the bounding box information in
10140 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10141 that is to be stroked with the pen~|pp|.
10143 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10144 pointer q; /* a knot node adjacent to knot |p| */
10145 fraction dx,dy; /* a unit vector in the direction out of the path at~|p| */
10146 scaled d; /* a factor for adjusting the length of |(dx,dy)| */
10147 scaled z; /* a coordinate being tested against the bounding box */
10148 scaled xx,yy; /* the extreme pen vertex in the |(dx,dy)| direction */
10149 integer i; /* a loop counter */
10150 if ( right_type(p)!=mp_endpoint ) {
10153 @<Make |(dx,dy)| the final direction for the path segment from
10154 |q| to~|p|; set~|d|@>;
10155 d=mp_pyth_add(mp, dx,dy);
10157 @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10158 for (i=1;i<= 2;i++) {
10159 @<Use |(dx,dy)| to generate a vertex of the square end cap and
10160 update the bounding box to accommodate it@>;
10164 if ( right_type(p)==mp_endpoint ) {
10167 @<Advance |p| to the end of the path and make |q| the previous knot@>;
10173 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10174 if ( q==link(p) ) {
10175 dx=x_coord(p)-right_x(p);
10176 dy=y_coord(p)-right_y(p);
10177 if ( (dx==0)&&(dy==0) ) {
10178 dx=x_coord(p)-left_x(q);
10179 dy=y_coord(p)-left_y(q);
10182 dx=x_coord(p)-left_x(p);
10183 dy=y_coord(p)-left_y(p);
10184 if ( (dx==0)&&(dy==0) ) {
10185 dx=x_coord(p)-right_x(q);
10186 dy=y_coord(p)-right_y(q);
10189 dx=x_coord(p)-x_coord(q);
10190 dy=y_coord(p)-y_coord(q)
10192 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10193 dx=mp_make_fraction(mp, dx,d);
10194 dy=mp_make_fraction(mp, dy,d);
10195 mp_find_offset(mp, -dy,dx,pp);
10196 xx=mp->cur_x; yy=mp->cur_y
10198 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10199 mp_find_offset(mp, dx,dy,pp);
10200 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10201 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2)))
10202 mp_confusion(mp, "box_ends");
10203 @:this can't happen box ends}{\quad\\{box\_ends}@>
10204 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10205 if ( z<minx_val(h) ) minx_val(h)=z;
10206 if ( z>maxx_val(h) ) maxx_val(h)=z;
10207 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10208 if ( z<miny_val(h) ) miny_val(h)=z;
10209 if ( z>maxy_val(h) ) maxy_val(h)=z
10211 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10215 } while (right_type(p)!=mp_endpoint)
10217 @ The major difficulty in finding the bounding box of an edge structure is the
10218 effect of clipping paths. We treat them conservatively by only clipping to the
10219 clipping path's bounding box, but this still
10220 requires recursive calls to |set_bbox| in order to find the bounding box of
10222 the objects to be clipped. Such calls are distinguished by the fact that the
10223 boolean parameter |top_level| is false.
10225 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10226 pointer p; /* a graphical object being considered */
10227 scaled sminx,sminy,smaxx,smaxy;
10228 /* for saving the bounding box during recursive calls */
10229 scaled x0,x1,y0,y1; /* temporary registers */
10230 integer lev; /* nesting level for |mp_start_bounds_code| nodes */
10231 @<Wipe out any existing bounding box information if |bbtype(h)| is
10232 incompatible with |internal[mp_true_corners]|@>;
10233 while ( link(bblast(h))!=null ) {
10237 case mp_stop_clip_code:
10238 if ( top_level ) mp_confusion(mp, "bbox"); else return;
10239 @:this can't happen bbox}{\quad bbox@>
10241 @<Other cases for updating the bounding box based on the type of object |p|@>;
10242 } /* all cases are enumerated above */
10244 if ( ! top_level ) mp_confusion(mp, "bbox");
10247 @ @<Internal library declarations@>=
10248 void mp_set_bbox (MP mp,pointer h, boolean top_level);
10250 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10251 switch (bbtype(h)) {
10255 if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10258 if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10260 } /* there are no other cases */
10262 @ @<Other cases for updating the bounding box...@>=
10264 mp_path_bbox(mp, path_p(p));
10265 if ( pen_p(p)!=null ) {
10268 mp_pen_bbox(mp, pen_p(p));
10274 mp_adjust_bbox(mp, h);
10277 @ @<Other cases for updating the bounding box...@>=
10278 case mp_start_bounds_code:
10279 if ( mp->internal[mp_true_corners]>0 ) {
10280 bbtype(h)=bounds_unset;
10282 bbtype(h)=bounds_set;
10283 mp_path_bbox(mp, path_p(p));
10284 mp_adjust_bbox(mp, h);
10285 @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10289 case mp_stop_bounds_code:
10290 if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10291 @:this can't happen bbox2}{\quad bbox2@>
10294 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10297 if ( link(p)==null ) mp_confusion(mp, "bbox2");
10298 @:this can't happen bbox2}{\quad bbox2@>
10300 if ( type(p)==mp_start_bounds_code ) incr(lev);
10301 else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10305 @ It saves a lot of grief here to be slightly conservative and not account for
10306 omitted parts of dashed lines. We also don't worry about the material omitted
10307 when using butt end caps. The basic computation is for round end caps and
10308 |box_ends| augments it for square end caps.
10310 @<Other cases for updating the bounding box...@>=
10311 case mp_stroked_code:
10312 mp_path_bbox(mp, path_p(p));
10315 mp_pen_bbox(mp, pen_p(p));
10320 mp_adjust_bbox(mp, h);
10321 if ( (left_type(path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10322 mp_box_ends(mp, path_p(p), pen_p(p), h);
10325 @ The height width and depth information stored in a text node determines a
10326 rectangle that needs to be transformed according to the transformation
10327 parameters stored in the text node.
10329 @<Other cases for updating the bounding box...@>=
10331 x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10332 y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10333 y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10336 if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1; }
10337 else { minx=minx+y1; maxx=maxx+y0; }
10338 if ( x1<0 ) minx=minx+x1; else maxx=maxx+x1;
10339 x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10340 y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10341 y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10344 if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1; }
10345 else { miny=miny+y1; maxy=maxy+y0; }
10346 if ( x1<0 ) miny=miny+x1; else maxy=maxy+x1;
10347 mp_adjust_bbox(mp, h);
10350 @ This case involves a recursive call that advances |bblast(h)| to the node of
10351 type |mp_stop_clip_code| that matches |p|.
10353 @<Other cases for updating the bounding box...@>=
10354 case mp_start_clip_code:
10355 mp_path_bbox(mp, path_p(p));
10358 sminx=minx_val(h); sminy=miny_val(h);
10359 smaxx=maxx_val(h); smaxy=maxy_val(h);
10360 @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10361 starting at |link(p)|@>;
10362 @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10364 minx=sminx; miny=sminy;
10365 maxx=smaxx; maxy=smaxy;
10366 mp_adjust_bbox(mp, h);
10369 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10370 minx_val(h)=el_gordo;
10371 miny_val(h)=el_gordo;
10372 maxx_val(h)=-el_gordo;
10373 maxy_val(h)=-el_gordo;
10374 mp_set_bbox(mp, h,false)
10376 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10377 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10378 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10379 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10380 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10382 @* \[22] Finding an envelope.
10383 When \MP\ has a path and a polygonal pen, it needs to express the desired
10384 shape in terms of things \ps\ can understand. The present task is to compute
10385 a new path that describes the region to be filled. It is convenient to
10386 define this as a two step process where the first step is determining what
10387 offset to use for each segment of the path.
10389 @ Given a pointer |c| to a cyclic path,
10390 and a pointer~|h| to the first knot of a pen polygon,
10391 the |offset_prep| routine changes the path into cubics that are
10392 associated with particular pen offsets. Thus if the cubic between |p|
10393 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10394 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10395 to because |l-k| could be negative.)
10397 After overwriting the type information with offset differences, we no longer
10398 have a true path so we refer to the knot list returned by |offset_prep| as an
10401 Since an envelope spec only determines relative changes in pen offsets,
10402 |offset_prep| sets a global variable |spec_offset| to the relative change from
10403 |h| to the first offset.
10405 @d zero_off 16384 /* added to offset changes to make them positive */
10408 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10410 @ @c @<Declare subroutines needed by |offset_prep|@>;
10411 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10412 halfword n; /* the number of vertices in the pen polygon */
10413 pointer p,q,q0,r,w, ww; /* for list manipulation */
10414 integer k_needed; /* amount to be added to |info(p)| when it is computed */
10415 pointer w0; /* a pointer to pen offset to use just before |p| */
10416 scaled dxin,dyin; /* the direction into knot |p| */
10417 integer turn_amt; /* change in pen offsets for the current cubic */
10418 @<Other local variables for |offset_prep|@>;
10420 @<Initialize the pen size~|n|@>;
10421 @<Initialize the incoming direction and pen offset at |c|@>;
10425 @<Split the cubic between |p| and |q|, if necessary, into cubics
10426 associated with single offsets, after which |q| should
10427 point to the end of the final such cubic@>;
10429 @<Advance |p| to node |q|, removing any ``dead'' cubics that
10430 might have been introduced by the splitting process@>;
10432 @<Fix the offset change in |info(c)| and set |c| to the return value of
10437 @ We shall want to keep track of where certain knots on the cyclic path
10438 wind up in the envelope spec. It doesn't suffice just to keep pointers to
10439 knot nodes because some nodes are deleted while removing dead cubics. Thus
10440 |offset_prep| updates the following pointers
10444 pointer spec_p2; /* pointers to distinguished knots */
10447 mp->spec_p1=null; mp->spec_p2=null;
10449 @ @<Initialize the pen size~|n|@>=
10456 @ Since the true incoming direction isn't known yet, we just pick a direction
10457 consistent with the pen offset~|h|. If this is wrong, it can be corrected
10460 @<Initialize the incoming direction and pen offset at |c|@>=
10461 dxin=x_coord(link(h))-x_coord(knil(h));
10462 dyin=y_coord(link(h))-y_coord(knil(h));
10463 if ( (dxin==0)&&(dyin==0) ) {
10464 dxin=y_coord(knil(h))-y_coord(h);
10465 dyin=x_coord(h)-x_coord(knil(h));
10469 @ We must be careful not to remove the only cubic in a cycle.
10471 But we must also be careful for another reason. If the user-supplied
10472 path starts with a set of degenerate cubics, the target node |q| can
10473 be collapsed to the initial node |p| which might be the same as the
10474 initial node |c| of the curve. This would cause the |offset_prep| routine
10475 to bail out too early, causing distress later on. (See for example
10476 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10479 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10483 if ( x_coord(p)==right_x(p) && y_coord(p)==right_y(p) &&
10484 x_coord(p)==left_x(r) && y_coord(p)==left_y(r) &&
10485 x_coord(p)==x_coord(r) && y_coord(p)==y_coord(r) &&
10487 @<Remove the cubic following |p| and update the data structures
10488 to merge |r| into |p|@>;
10492 /* Check if we removed too much */
10496 @ @<Remove the cubic following |p| and update the data structures...@>=
10497 { k_needed=info(p)-zero_off;
10501 info(p)=k_needed+info(r);
10504 if ( r==c ) { info(p)=info(c); c=p; };
10505 if ( r==mp->spec_p1 ) mp->spec_p1=p;
10506 if ( r==mp->spec_p2 ) mp->spec_p2=p;
10507 r=p; mp_remove_cubic(mp, p);
10510 @ Not setting the |info| field of the newly created knot allows the splitting
10511 routine to work for paths.
10513 @<Declare subroutines needed by |offset_prep|@>=
10514 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10515 scaled v; /* an intermediate value */
10516 pointer q,r; /* for list manipulation */
10517 q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10518 originator(r)=mp_program_code;
10519 left_type(r)=mp_explicit; right_type(r)=mp_explicit;
10520 v=t_of_the_way(right_x(p),left_x(q));
10521 right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10522 left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10523 left_x(r)=t_of_the_way(right_x(p),v);
10524 right_x(r)=t_of_the_way(v,left_x(q));
10525 x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10526 v=t_of_the_way(right_y(p),left_y(q));
10527 right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10528 left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10529 left_y(r)=t_of_the_way(right_y(p),v);
10530 right_y(r)=t_of_the_way(v,left_y(q));
10531 y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10534 @ This does not set |info(p)| or |right_type(p)|.
10536 @<Declare subroutines needed by |offset_prep|@>=
10537 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10538 pointer q; /* the node that disappears */
10539 q=link(p); link(p)=link(q);
10540 right_x(p)=right_x(q); right_y(p)=right_y(q);
10541 mp_free_node(mp, q,knot_node_size);
10544 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10545 strictly between zero and $180^\circ$. Then we can define $d\preceq d'$ to
10546 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10547 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10548 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10549 When listed by increasing $k$, these directions occur in counter-clockwise
10550 order so that $d_k\preceq d\k$ for all~$k$.
10551 The goal of |offset_prep| is to find an offset index~|k| to associate with
10552 each cubic, such that the direction $d(t)$ of the cubic satisfies
10553 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10554 We may have to split a cubic into many pieces before each
10555 piece corresponds to a unique offset.
10557 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10558 info(p)=zero_off+k_needed;
10560 @<Prepare for derivative computations;
10561 |goto not_found| if the current cubic is dead@>;
10562 @<Find the initial direction |(dx,dy)|@>;
10563 @<Update |info(p)| and find the offset $w_k$ such that
10564 $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10565 the direction change at |p|@>;
10566 @<Find the final direction |(dxin,dyin)|@>;
10567 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10568 @<Complete the offset splitting process@>;
10569 w0=mp_pen_walk(mp, w0,turn_amt)
10571 @ @<Declare subroutines needed by |offset_prep|@>=
10572 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10573 /* walk |k| steps around a pen from |w| */
10574 while ( k>0 ) { w=link(w); decr(k); };
10575 while ( k<0 ) { w=knil(w); incr(k); };
10579 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10580 calculated from the quadratic polynomials
10581 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10582 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10583 Since we may be calculating directions from several cubics
10584 split from the current one, it is desirable to do these calculations
10585 without losing too much precision. ``Scaled up'' values of the
10586 derivatives, which will be less tainted by accumulated errors than
10587 derivatives found from the cubics themselves, are maintained in
10588 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10589 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10590 represent $Y_0=2^l(y_1-y_0)$, $Y_1=2^l(y_2-y_1)$, and $Y_2=2^l(y_3-y_2)$.
10592 @<Other local variables for |offset_prep|@>=
10593 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10594 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10595 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10596 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10597 integer max_coef; /* used while scaling */
10598 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10599 fraction t; /* where the derivative passes through zero */
10600 fraction s; /* a temporary value */
10602 @ @<Prepare for derivative computations...@>=
10603 x0=right_x(p)-x_coord(p);
10604 x2=x_coord(q)-left_x(q);
10605 x1=left_x(q)-right_x(p);
10606 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10607 y1=left_y(q)-right_y(p);
10609 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10610 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10611 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10612 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10613 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10614 if ( max_coef==0 ) goto NOT_FOUND;
10615 while ( max_coef<fraction_half ) {
10617 double(x0); double(x1); double(x2);
10618 double(y0); double(y1); double(y2);
10621 @ Let us first solve a special case of the problem: Suppose we
10622 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10623 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10624 $d(0)\succ d_{k-1}$.
10625 Then, in a sense, we're halfway done, since one of the two relations
10626 in $(*)$ is satisfied, and the other couldn't be satisfied for
10627 any other value of~|k|.
10629 Actually, the conditions can be relaxed somewhat since a relation such as
10630 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10631 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10632 the origin. The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10633 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10634 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10635 counterclockwise direction.
10637 The |fin_offset_prep| subroutine solves the stated subproblem.
10638 It has a parameter called |rise| that is |1| in
10639 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10640 the derivative of the cubic following |p|.
10641 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10642 be set properly. The |turn_amt| parameter gives the absolute value of the
10643 overall net change in pen offsets.
10645 @<Declare subroutines needed by |offset_prep|@>=
10646 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer
10647 x0,integer x1, integer x2, integer y0, integer y1, integer y2,
10648 integer rise, integer turn_amt) {
10649 pointer ww; /* for list manipulation */
10650 scaled du,dv; /* for slope calculation */
10651 integer t0,t1,t2; /* test coefficients */
10652 fraction t; /* place where the derivative passes a critical slope */
10653 fraction s; /* slope or reciprocal slope */
10654 integer v; /* intermediate value for updating |x0..y2| */
10655 pointer q; /* original |link(p)| */
10658 if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10659 else ww=knil(w); /* a pointer to $w_{k-1}$ */
10660 @<Compute test coefficients |(t0,t1,t2)|
10661 for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10662 t=mp_crossing_point(mp, t0,t1,t2);
10663 if ( t>=fraction_one ) {
10664 if ( turn_amt>0 ) t=fraction_one; else return;
10666 @<Split the cubic at $t$,
10667 and split off another cubic if the derivative crosses back@>;
10672 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10673 $-90^\circ$ rotation of the vector from |w| to |ww|. This makes the resulting
10674 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10677 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10678 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10679 if ( abs(du)>=abs(dv) ) {
10680 s=mp_make_fraction(mp, dv,du);
10681 t0=mp_take_fraction(mp, x0,s)-y0;
10682 t1=mp_take_fraction(mp, x1,s)-y1;
10683 t2=mp_take_fraction(mp, x2,s)-y2;
10684 if ( du<0 ) { negate(t0); negate(t1); negate(t2); }
10686 s=mp_make_fraction(mp, du,dv);
10687 t0=x0-mp_take_fraction(mp, y0,s);
10688 t1=x1-mp_take_fraction(mp, y1,s);
10689 t2=x2-mp_take_fraction(mp, y2,s);
10690 if ( dv<0 ) { negate(t0); negate(t1); negate(t2); }
10692 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10694 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10695 $(*)$, and it might cross again, yielding another solution of $(*)$.
10697 @<Split the cubic at $t$, and split off another...@>=
10699 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10701 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10702 x0=t_of_the_way(v,x1);
10703 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10704 y0=t_of_the_way(v,y1);
10705 if ( turn_amt<0 ) {
10706 t1=t_of_the_way(t1,t2);
10707 if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10708 t=mp_crossing_point(mp, 0,-t1,-t2);
10709 if ( t>fraction_one ) t=fraction_one;
10711 if ( (t==fraction_one)&&(link(p)!=q) ) {
10712 info(link(p))=info(link(p))-rise;
10714 mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10715 v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10716 x2=t_of_the_way(x1,v);
10717 v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10718 y2=t_of_the_way(y1,v);
10723 @ Now we must consider the general problem of |offset_prep|, when
10724 nothing is known about a given cubic. We start by finding its
10725 direction in the vicinity of |t=0|.
10727 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10728 has not yet introduced any more numerical errors. Thus we can compute
10729 the true initial direction for the given cubic, even if it is almost
10732 @<Find the initial direction |(dx,dy)|@>=
10734 if ( dx==0 && dy==0 ) {
10736 if ( dx==0 && dy==0 ) {
10740 if ( p==c ) { dx0=dx; dy0=dy; }
10742 @ @<Find the final direction |(dxin,dyin)|@>=
10744 if ( dxin==0 && dyin==0 ) {
10746 if ( dxin==0 && dyin==0 ) {
10751 @ The next step is to bracket the initial direction between consecutive
10752 edges of the pen polygon. We must be careful to turn clockwise only if
10753 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10754 counter-clockwise in order to make \&{doublepath} envelopes come out
10755 @:double_path_}{\&{doublepath} primitive@>
10756 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10758 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10759 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10760 w=mp_pen_walk(mp, w0, turn_amt);
10762 info(p)=info(p)+turn_amt
10764 @ Decide how many pen offsets to go away from |w| in order to find the offset
10765 for |(dx,dy)|, going counterclockwise if |ccw| is |true|. This assumes that
10766 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10767 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10769 If the pen polygon has only two edges, they could both be parallel
10770 to |(dx,dy)|. In this case, we must be careful to stop after crossing the first
10771 such edge in order to avoid an infinite loop.
10773 @<Declare subroutines needed by |offset_prep|@>=
10774 integer mp_get_turn_amt (MP mp,pointer w, scaled dx,
10775 scaled dy, boolean ccw) {
10776 pointer ww; /* a neighbor of knot~|w| */
10777 integer s; /* turn amount so far */
10778 integer t; /* |ab_vs_cd| result */
10783 t=mp_ab_vs_cd(mp, dy,(x_coord(ww)-x_coord(w)),
10784 dx,(y_coord(ww)-y_coord(w)));
10791 while ( mp_ab_vs_cd(mp, dy,(x_coord(w)-x_coord(ww)),
10792 dx,(y_coord(w)-y_coord(ww))) < 0) {
10800 @ When we're all done, the final offset is |w0| and the final curve direction
10801 is |(dxin,dyin)|. With this knowledge of the incoming direction at |c|, we
10802 can correct |info(c)| which was erroneously based on an incoming offset
10805 @d fix_by(A) info(c)=info(c)+(A)
10807 @<Fix the offset change in |info(c)| and set |c| to the return value of...@>=
10808 mp->spec_offset=info(c)-zero_off;
10809 if ( link(c)==c ) {
10810 info(c)=zero_off+n;
10813 while ( w0!=h ) { fix_by(1); w0=link(w0); };
10814 while ( info(c)<=zero_off-n ) fix_by(n);
10815 while ( info(c)>zero_off ) fix_by(-n);
10816 if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10820 @ Finally we want to reduce the general problem to situations that
10821 |fin_offset_prep| can handle. We split the cubic into at most three parts
10822 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10824 @<Complete the offset splitting process@>=
10826 @<Compute test coeff...@>;
10827 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10828 |t:=fraction_one+1|@>;
10829 if ( t>fraction_one ) {
10830 mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10832 mp_split_cubic(mp, p,t); r=link(p);
10833 x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10834 x2a=t_of_the_way(x1a,x1);
10835 y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10836 y2a=t_of_the_way(y1a,y1);
10837 mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10838 info(r)=zero_off-1;
10839 if ( turn_amt>=0 ) {
10840 t1=t_of_the_way(t1,t2);
10842 t=mp_crossing_point(mp, 0,-t1,-t2);
10843 if ( t>fraction_one ) t=fraction_one;
10844 @<Split off another rising cubic for |fin_offset_prep|@>;
10845 mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10847 mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10851 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10852 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10853 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10854 x0a=t_of_the_way(x1,x1a);
10855 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10856 y0a=t_of_the_way(y1,y1a);
10857 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10860 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10861 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10862 need to decide whether the directions are parallel or antiparallel. We
10863 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10864 should be avoided when the value of |turn_amt| already determines the
10865 answer. If |t2<0|, there is one crossing and it is antiparallel only if
10866 |turn_amt>=0|. If |turn_amt<0|, there should always be at least one
10867 crossing and the first crossing cannot be antiparallel.
10869 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10870 t=mp_crossing_point(mp, t0,t1,t2);
10871 if ( turn_amt>=0 ) {
10875 u0=t_of_the_way(x0,x1);
10876 u1=t_of_the_way(x1,x2);
10877 ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10878 v0=t_of_the_way(y0,y1);
10879 v1=t_of_the_way(y1,y2);
10880 ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10881 if ( ss<0 ) t=fraction_one+1;
10883 } else if ( t>fraction_one ) {
10887 @ @<Other local variables for |offset_prep|@>=
10888 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10889 integer ss = 0; /* the part of the dot product computed so far */
10890 int d_sign; /* sign of overall change in direction for this cubic */
10892 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10893 problem to decide which way it loops around but that's OK as long we're
10894 consistent. To make \&{doublepath} envelopes work properly, reversing
10895 the path should always change the sign of |turn_amt|.
10897 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10898 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10900 @<Check rotation direction based on node position@>
10904 if ( dy>0 ) d_sign=1; else d_sign=-1;
10906 if ( dx>0 ) d_sign=1; else d_sign=-1;
10909 @<Make |ss| negative if and only if the total change in direction is
10910 more than $180^\circ$@>;
10911 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
10912 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10914 @ We check rotation direction by looking at the vector connecting the current
10915 node with the next. If its angle with incoming and outgoing tangents has the
10916 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
10917 Otherwise we proceed to the cusp code.
10919 @<Check rotation direction based on node position@>=
10920 u0=x_coord(q)-x_coord(p);
10921 u1=y_coord(q)-y_coord(p);
10922 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
10923 mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
10925 @ In order to be invariant under path reversal, the result of this computation
10926 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10927 then swapped with |(x2,y2)|. We make use of the identities
10928 |take_fraction(-a,-b)=take_fraction(a,b)| and
10929 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10931 @<Make |ss| negative if and only if the total change in direction is...@>=
10932 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10933 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
10934 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10936 t=mp_crossing_point(mp, t0,t1,-t0);
10937 u0=t_of_the_way(x0,x1);
10938 u1=t_of_the_way(x1,x2);
10939 v0=t_of_the_way(y0,y1);
10940 v1=t_of_the_way(y1,y2);
10942 t=mp_crossing_point(mp, -t0,t1,t0);
10943 u0=t_of_the_way(x2,x1);
10944 u1=t_of_the_way(x1,x0);
10945 v0=t_of_the_way(y2,y1);
10946 v1=t_of_the_way(y1,y0);
10948 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
10949 mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
10951 @ Here's a routine that prints an envelope spec in symbolic form. It assumes
10952 that the |cur_pen| has not been walked around to the first offset.
10955 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
10956 pointer p,q; /* list traversal */
10957 pointer w; /* the current pen offset */
10958 mp_print_diagnostic(mp, "Envelope spec",s,true);
10959 p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10961 mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10962 mp_print(mp, " % beginning with offset ");
10963 mp_print_two(mp, x_coord(w),y_coord(w));
10967 @<Print the cubic between |p| and |q|@>;
10969 if ((p==cur_spec) || (info(p)!=zero_off))
10972 if ( info(p)!=zero_off ) {
10973 @<Update |w| as indicated by |info(p)| and print an explanation@>;
10975 } while (p!=cur_spec);
10976 mp_print_nl(mp, " & cycle");
10977 mp_end_diagnostic(mp, true);
10980 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10982 w=mp_pen_walk(mp, w, (info(p)-zero_off));
10983 mp_print(mp, " % ");
10984 if ( info(p)>zero_off ) mp_print(mp, "counter");
10985 mp_print(mp, "clockwise to offset ");
10986 mp_print_two(mp, x_coord(w),y_coord(w));
10989 @ @<Print the cubic between |p| and |q|@>=
10991 mp_print_nl(mp, " ..controls ");
10992 mp_print_two(mp, right_x(p),right_y(p));
10993 mp_print(mp, " and ");
10994 mp_print_two(mp, left_x(q),left_y(q));
10995 mp_print_nl(mp, " ..");
10996 mp_print_two(mp, x_coord(q),y_coord(q));
10999 @ Once we have an envelope spec, the remaining task to construct the actual
11000 envelope by offsetting each cubic as determined by the |info| fields in
11001 the knots. First we use |offset_prep| to convert the |c| into an envelope
11002 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
11005 The |ljoin| and |miterlim| parameters control the treatment of points where the
11006 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
11007 The endpoints are easily located because |c| is given in undoubled form
11008 and then doubled in this procedure. We use |spec_p1| and |spec_p2| to keep
11009 track of the endpoints and treat them like very sharp corners.
11010 Butt end caps are treated like beveled joins; round end caps are treated like
11011 round joins; and square end caps are achieved by setting |join_type:=3|.
11013 None of these parameters apply to inside joins where the convolution tracing
11014 has retrograde lines. In such cases we use a simple connect-the-endpoints
11015 approach that is achieved by setting |join_type:=2|.
11017 @c @<Declare a function called |insert_knot|@>;
11018 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
11019 small_number lcap, scaled miterlim) {
11020 pointer p,q,r,q0; /* for manipulating the path */
11021 int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
11022 pointer w,w0; /* the pen knot for the current offset */
11023 scaled qx,qy; /* unshifted coordinates of |q| */
11024 halfword k,k0; /* controls pen edge insertion */
11025 @<Other local variables for |make_envelope|@>;
11026 dxin=0; dyin=0; dxout=0; dyout=0;
11027 mp->spec_p1=null; mp->spec_p2=null;
11028 @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
11029 @<Use |offset_prep| to compute the envelope spec then walk |h| around to
11030 the initial offset@>;
11035 qx=x_coord(q); qy=y_coord(q);
11038 if ( k!=zero_off ) {
11039 @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
11041 @<Add offset |w| to the cubic from |p| to |q|@>;
11042 while ( k!=zero_off ) {
11043 @<Step |w| and move |k| one step closer to |zero_off|@>;
11044 if ( (join_type==1)||(k==zero_off) )
11045 q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
11047 if ( q!=link(p) ) {
11048 @<Set |p=link(p)| and add knots between |p| and |q| as
11049 required by |join_type|@>;
11056 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
11057 c=mp_offset_prep(mp, c,h);
11058 if ( mp->internal[mp_tracing_specs]>0 )
11059 mp_print_spec(mp, c,h,"");
11060 h=mp_pen_walk(mp, h,mp->spec_offset)
11062 @ Mitered and squared-off joins depend on path directions that are difficult to
11063 compute for degenerate cubics. The envelope spec computed by |offset_prep| can
11064 have degenerate cubics only if the entire cycle collapses to a single
11065 degenerate cubic. Setting |join_type:=2| in this case makes the computed
11066 envelope degenerate as well.
11068 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
11069 if ( k<zero_off ) {
11072 if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
11073 else if ( lcap==2 ) join_type=3;
11074 else join_type=2-lcap;
11075 if ( (join_type==0)||(join_type==3) ) {
11076 @<Set the incoming and outgoing directions at |q|; in case of
11077 degeneracy set |join_type:=2|@>;
11078 if ( join_type==0 ) {
11079 @<If |miterlim| is less than the secant of half the angle at |q|
11080 then set |join_type:=2|@>;
11085 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11087 tmp=mp_take_fraction(mp, miterlim,fraction_half+
11088 half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11090 if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11093 @ @<Other local variables for |make_envelope|@>=
11094 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11095 scaled tmp; /* a temporary value */
11097 @ The coordinates of |p| have already been shifted unless |p| is the first
11098 knot in which case they get shifted at the very end.
11100 @<Add offset |w| to the cubic from |p| to |q|@>=
11101 right_x(p)=right_x(p)+x_coord(w);
11102 right_y(p)=right_y(p)+y_coord(w);
11103 left_x(q)=left_x(q)+x_coord(w);
11104 left_y(q)=left_y(q)+y_coord(w);
11105 x_coord(q)=x_coord(q)+x_coord(w);
11106 y_coord(q)=y_coord(q)+y_coord(w);
11107 left_type(q)=mp_explicit;
11108 right_type(q)=mp_explicit
11110 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11111 if ( k>zero_off ){ w=link(w); decr(k); }
11112 else { w=knil(w); incr(k); }
11114 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11115 the |right_x| and |right_y| fields of |r| are set from |q|. This is done in
11116 case the cubic containing these control points is ``yet to be examined.''
11118 @<Declare a function called |insert_knot|@>=
11119 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11120 /* returns the inserted knot */
11121 pointer r; /* the new knot */
11122 r=mp_get_node(mp, knot_node_size);
11123 link(r)=link(q); link(q)=r;
11124 right_x(r)=right_x(q);
11125 right_y(r)=right_y(q);
11128 right_x(q)=x_coord(q);
11129 right_y(q)=y_coord(q);
11130 left_x(r)=x_coord(r);
11131 left_y(r)=y_coord(r);
11132 left_type(r)=mp_explicit;
11133 right_type(r)=mp_explicit;
11134 originator(r)=mp_program_code;
11138 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
11140 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
11143 if ( (join_type==0)||(join_type==3) ) {
11144 if ( join_type==0 ) {
11145 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11147 @<Make |r| the last of two knots inserted between |p| and |q| to form a
11151 right_x(r)=x_coord(r);
11152 right_y(r)=y_coord(r);
11157 @ For very small angles, adding a knot is unnecessary and would cause numerical
11158 problems, so we just set |r:=null| in that case.
11160 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11162 det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11163 if ( abs(det)<26844 ) {
11164 r=null; /* sine $<10^{-4}$ */
11166 tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
11167 mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
11168 tmp=mp_make_fraction(mp, tmp,det);
11169 r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11170 y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11174 @ @<Other local variables for |make_envelope|@>=
11175 fraction det; /* a determinant used for mitered join calculations */
11177 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11179 ht_x=y_coord(w)-y_coord(w0);
11180 ht_y=x_coord(w0)-x_coord(w);
11181 while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) {
11182 ht_x+=ht_x; ht_y+=ht_y;
11184 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11185 product with |(ht_x,ht_y)|@>;
11186 tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11187 mp_take_fraction(mp, dyin,ht_y));
11188 r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11189 y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11190 tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11191 mp_take_fraction(mp, dyout,ht_y));
11192 r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11193 y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11196 @ @<Other local variables for |make_envelope|@>=
11197 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11198 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11199 halfword kk; /* keeps track of the pen vertices being scanned */
11200 pointer ww; /* the pen vertex being tested */
11202 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11203 from zero to |max_ht|.
11205 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11210 @<Step |ww| and move |kk| one step closer to |k0|@>;
11211 if ( kk==k0 ) break;
11212 tmp=mp_take_fraction(mp, (x_coord(ww)-x_coord(w0)),ht_x)+
11213 mp_take_fraction(mp, (y_coord(ww)-y_coord(w0)),ht_y);
11214 if ( tmp>max_ht ) max_ht=tmp;
11218 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11219 if ( kk>k0 ) { ww=link(ww); decr(kk); }
11220 else { ww=knil(ww); incr(kk); }
11222 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11223 if ( left_type(c)==mp_endpoint ) {
11224 mp->spec_p1=mp_htap_ypoc(mp, c);
11225 mp->spec_p2=mp->path_tail;
11226 originator(mp->spec_p1)=mp_program_code;
11227 link(mp->spec_p2)=link(mp->spec_p1);
11228 link(mp->spec_p1)=c;
11229 mp_remove_cubic(mp, mp->spec_p1);
11231 if ( c!=link(c) ) {
11232 originator(mp->spec_p2)=mp_program_code;
11233 mp_remove_cubic(mp, mp->spec_p2);
11235 @<Make |c| look like a cycle of length one@>;
11239 @ @<Make |c| look like a cycle of length one@>=
11241 left_type(c)=mp_explicit; right_type(c)=mp_explicit;
11242 left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11243 right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11246 @ In degenerate situations we might have to look at the knot preceding~|q|.
11247 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11249 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11250 dxin=x_coord(q)-left_x(q);
11251 dyin=y_coord(q)-left_y(q);
11252 if ( (dxin==0)&&(dyin==0) ) {
11253 dxin=x_coord(q)-right_x(p);
11254 dyin=y_coord(q)-right_y(p);
11255 if ( (dxin==0)&&(dyin==0) ) {
11256 dxin=x_coord(q)-x_coord(p);
11257 dyin=y_coord(q)-y_coord(p);
11258 if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11259 dxin=dxin+x_coord(w);
11260 dyin=dyin+y_coord(w);
11264 tmp=mp_pyth_add(mp, dxin,dyin);
11268 dxin=mp_make_fraction(mp, dxin,tmp);
11269 dyin=mp_make_fraction(mp, dyin,tmp);
11270 @<Set the outgoing direction at |q|@>;
11273 @ If |q=c| then the coordinates of |r| and the control points between |q|
11274 and~|r| have already been offset by |h|.
11276 @<Set the outgoing direction at |q|@>=
11277 dxout=right_x(q)-x_coord(q);
11278 dyout=right_y(q)-y_coord(q);
11279 if ( (dxout==0)&&(dyout==0) ) {
11281 dxout=left_x(r)-x_coord(q);
11282 dyout=left_y(r)-y_coord(q);
11283 if ( (dxout==0)&&(dyout==0) ) {
11284 dxout=x_coord(r)-x_coord(q);
11285 dyout=y_coord(r)-y_coord(q);
11289 dxout=dxout-x_coord(h);
11290 dyout=dyout-y_coord(h);
11292 tmp=mp_pyth_add(mp, dxout,dyout);
11293 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11294 @:this can't happen degerate spec}{\quad degenerate spec@>
11295 dxout=mp_make_fraction(mp, dxout,tmp);
11296 dyout=mp_make_fraction(mp, dyout,tmp)
11298 @* \[23] Direction and intersection times.
11299 A path of length $n$ is defined parametrically by functions $x(t)$ and
11300 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11301 reaches the point $\bigl(x(t),y(t)\bigr)$. In this section of the program
11302 we shall consider operations that determine special times associated with
11303 given paths: the first time that a path travels in a given direction, and
11304 a pair of times at which two paths cross each other.
11306 @ Let's start with the easier task. The function |find_direction_time| is
11307 given a direction |(x,y)| and a path starting at~|h|. If the path never
11308 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11309 it will be nonnegative.
11311 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11312 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11313 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11314 assumed to match any given direction at time~|t|.
11316 The routine solves this problem in nondegenerate cases by rotating the path
11317 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11318 to find when a given path first travels ``due east.''
11321 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11322 scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11323 pointer p,q; /* for list traversal */
11324 scaled n; /* the direction time at knot |p| */
11325 scaled tt; /* the direction time within a cubic */
11326 @<Other local variables for |find_direction_time|@>;
11327 @<Normalize the given direction for better accuracy;
11328 but |return| with zero result if it's zero@>;
11331 if ( right_type(p)==mp_endpoint ) break;
11333 @<Rotate the cubic between |p| and |q|; then
11334 |goto found| if the rotated cubic travels due east at some time |tt|;
11335 but |break| if an entire cyclic path has been traversed@>;
11343 @ @<Normalize the given direction for better accuracy...@>=
11344 if ( abs(x)<abs(y) ) {
11345 x=mp_make_fraction(mp, x,abs(y));
11346 if ( y>0 ) y=fraction_one; else y=-fraction_one;
11347 } else if ( x==0 ) {
11350 y=mp_make_fraction(mp, y,abs(x));
11351 if ( x>0 ) x=fraction_one; else x=-fraction_one;
11354 @ Since we're interested in the tangent directions, we work with the
11355 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11356 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11357 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11358 in order to achieve better accuracy.
11360 The given path may turn abruptly at a knot, and it might pass the critical
11361 tangent direction at such a time. Therefore we remember the direction |phi|
11362 in which the previous rotated cubic was traveling. (The value of |phi| will be
11363 undefined on the first cubic, i.e., when |n=0|.)
11365 @<Rotate the cubic between |p| and |q|; then...@>=
11367 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11368 points of the rotated derivatives@>;
11369 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11371 @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11374 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11375 @<Exit to |found| if the curve whose derivatives are specified by
11376 |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11378 @ @<Other local variables for |find_direction_time|@>=
11379 scaled x1,x2,x3,y1,y2,y3; /* multiples of rotated derivatives */
11380 angle theta,phi; /* angles of exit and entry at a knot */
11381 fraction t; /* temp storage */
11383 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11384 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11385 x3=x_coord(q)-left_x(q);
11386 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11387 y3=y_coord(q)-left_y(q);
11389 if ( abs(x2)>max ) max=abs(x2);
11390 if ( abs(x3)>max ) max=abs(x3);
11391 if ( abs(y1)>max ) max=abs(y1);
11392 if ( abs(y2)>max ) max=abs(y2);
11393 if ( abs(y3)>max ) max=abs(y3);
11394 if ( max==0 ) goto FOUND;
11395 while ( max<fraction_half ){
11396 max+=max; x1+=x1; x2+=x2; x3+=x3;
11397 y1+=y1; y2+=y2; y3+=y3;
11399 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11400 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11401 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11402 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11403 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11404 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11406 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11407 theta=mp_n_arg(mp, x1,y1);
11408 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11409 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11411 @ In this step we want to use the |crossing_point| routine to find the
11412 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11413 Several complications arise: If the quadratic equation has a double root,
11414 the curve never crosses zero, and |crossing_point| will find nothing;
11415 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11416 equation has simple roots, or only one root, we may have to negate it
11417 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11418 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11421 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11422 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11423 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11424 @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11425 either |goto found| or |goto done|@>;
11428 if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11429 else if ( y2>0 ){ y2=-y2; y3=-y3; };
11431 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11432 $B(x_1,x_2,x_3;t)\ge0$@>;
11435 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11436 two roots, because we know that it isn't identically zero.
11438 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11439 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11440 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11441 subject to rounding errors. Yet this code optimistically tries to
11442 do the right thing.
11444 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11446 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11447 t=mp_crossing_point(mp, y1,y2,y3);
11448 if ( t>fraction_one ) goto DONE;
11449 y2=t_of_the_way(y2,y3);
11450 x1=t_of_the_way(x1,x2);
11451 x2=t_of_the_way(x2,x3);
11452 x1=t_of_the_way(x1,x2);
11453 if ( x1>=0 ) we_found_it;
11455 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11456 if ( t>fraction_one ) goto DONE;
11457 x1=t_of_the_way(x1,x2);
11458 x2=t_of_the_way(x2,x3);
11459 if ( t_of_the_way(x1,x2)>=0 ) {
11460 t=t_of_the_way(tt,fraction_one); we_found_it;
11463 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11464 either |goto found| or |goto done|@>=
11466 if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11467 t=mp_make_fraction(mp, y1,y1-y2);
11468 x1=t_of_the_way(x1,x2);
11469 x2=t_of_the_way(x2,x3);
11470 if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11471 } else if ( y3==0 ) {
11473 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11474 } else if ( x3>=0 ) {
11475 tt=unity; goto FOUND;
11481 @ At this point we know that the derivative of |y(t)| is identically zero,
11482 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11485 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11487 t=mp_crossing_point(mp, -x1,-x2,-x3);
11488 if ( t<=fraction_one ) we_found_it;
11489 if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) {
11490 t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11494 @ The intersection of two cubics can be found by an interesting variant
11495 of the general bisection scheme described in the introduction to
11497 Given $w(t)=B(w_0,w_1,w_2,w_3;t)$ and $z(t)=B(z_0,z_1,z_2,z_3;t)$,
11498 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11499 if an intersection exists. First we find the smallest rectangle that
11500 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11501 the smallest rectangle that encloses
11502 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11503 But if the rectangles do overlap, we bisect the intervals, getting
11504 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11505 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11506 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11507 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11508 levels of bisection we will have determined the intersection times $t_1$
11509 and~$t_2$ to $l$~bits of accuracy.
11511 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11512 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11513 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11514 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11515 to determine when the enclosing rectangles overlap. Here's why:
11516 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11517 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11518 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11519 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11520 overlap if and only if $u\submin\L x\submax$ and
11521 $x\submin\L u\submax$. Letting
11522 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11523 U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11524 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11526 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11527 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11528 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11529 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11530 because of the overlap condition; i.e., we know that $X\submin$,
11531 $X\submax$, and their relatives are bounded, hence $X\submax-
11532 U\submin$ and $X\submin-U\submax$ are bounded.
11534 @ Incidentally, if the given cubics intersect more than once, the process
11535 just sketched will not necessarily find the lexicographically smallest pair
11536 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11537 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11538 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11539 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11540 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11541 Shuffled order agrees with lexicographic order if all pairs of solutions
11542 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11543 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11544 and the bisection algorithm would be substantially less efficient if it were
11545 constrained by lexicographic order.
11547 For example, suppose that an overlap has been found for $l=3$ and
11548 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11549 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11550 Then there is probably an intersection in one of the subintervals
11551 $(.1011,.011x)$; but lexicographic order would require us to explore
11552 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11553 want to store all of the subdivision data for the second path, so the
11554 subdivisions would have to be regenerated many times. Such inefficiencies
11555 would be associated with every `1' in the binary representation of~$t_1$.
11557 @ The subdivision process introduces rounding errors, hence we need to
11558 make a more liberal test for overlap. It is not hard to show that the
11559 computed values of $U_i$ differ from the truth by at most~$l$, on
11560 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11561 If $\beta$ is an upper bound on the absolute error in the computed
11562 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11563 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11564 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11566 More accuracy is obtained if we try the algorithm first with |tol=0|;
11567 the more liberal tolerance is used only if an exact approach fails.
11568 It is convenient to do this double-take by letting `3' in the preceding
11569 paragraph be a parameter, which is first 0, then 3.
11572 unsigned int tol_step; /* either 0 or 3, usually */
11574 @ We shall use an explicit stack to implement the recursive bisection
11575 method described above. The |bisect_stack| array will contain numerous 5-word
11576 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11577 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11579 The following macros define the allocation of stack positions to
11580 the quantities needed for bisection-intersection.
11582 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11583 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11584 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11585 @d stack_min(A) mp->bisect_stack[(A)+3]
11586 /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11587 @d stack_max(A) mp->bisect_stack[(A)+4]
11588 /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11589 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11591 @d u_packet(A) ((A)-5)
11592 @d v_packet(A) ((A)-10)
11593 @d x_packet(A) ((A)-15)
11594 @d y_packet(A) ((A)-20)
11595 @d l_packets (mp->bisect_ptr-int_packets)
11596 @d r_packets mp->bisect_ptr
11597 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11598 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11599 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11600 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11601 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11602 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11603 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11604 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11606 @d u1l stack_1(ul_packet) /* $U'_1$ */
11607 @d u2l stack_2(ul_packet) /* $U'_2$ */
11608 @d u3l stack_3(ul_packet) /* $U'_3$ */
11609 @d v1l stack_1(vl_packet) /* $V'_1$ */
11610 @d v2l stack_2(vl_packet) /* $V'_2$ */
11611 @d v3l stack_3(vl_packet) /* $V'_3$ */
11612 @d x1l stack_1(xl_packet) /* $X'_1$ */
11613 @d x2l stack_2(xl_packet) /* $X'_2$ */
11614 @d x3l stack_3(xl_packet) /* $X'_3$ */
11615 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11616 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11617 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11618 @d u1r stack_1(ur_packet) /* $U''_1$ */
11619 @d u2r stack_2(ur_packet) /* $U''_2$ */
11620 @d u3r stack_3(ur_packet) /* $U''_3$ */
11621 @d v1r stack_1(vr_packet) /* $V''_1$ */
11622 @d v2r stack_2(vr_packet) /* $V''_2$ */
11623 @d v3r stack_3(vr_packet) /* $V''_3$ */
11624 @d x1r stack_1(xr_packet) /* $X''_1$ */
11625 @d x2r stack_2(xr_packet) /* $X''_2$ */
11626 @d x3r stack_3(xr_packet) /* $X''_3$ */
11627 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11628 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11629 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11631 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11632 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11633 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11634 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11635 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11636 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11639 integer *bisect_stack;
11640 unsigned int bisect_ptr;
11642 @ @<Allocate or initialize ...@>=
11643 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11645 @ @<Dealloc variables@>=
11646 xfree(mp->bisect_stack);
11648 @ @<Check the ``constant''...@>=
11649 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11651 @ Computation of the min and max is a tedious but fairly fast sequence of
11652 instructions; exactly four comparisons are made in each branch.
11655 if ( stack_1((A))<0 ) {
11656 if ( stack_3((A))>=0 ) {
11657 if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11658 else stack_min((A))=stack_1((A));
11659 stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11660 if ( stack_max((A))<0 ) stack_max((A))=0;
11662 stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11663 if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11664 stack_max((A))=stack_1((A))+stack_2((A));
11665 if ( stack_max((A))<0 ) stack_max((A))=0;
11667 } else if ( stack_3((A))<=0 ) {
11668 if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11669 else stack_max((A))=stack_1((A));
11670 stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11671 if ( stack_min((A))>0 ) stack_min((A))=0;
11673 stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11674 if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11675 stack_min((A))=stack_1((A))+stack_2((A));
11676 if ( stack_min((A))>0 ) stack_min((A))=0;
11679 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11680 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11681 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11682 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11683 plus the |scaled| values of $t_1$ and~$t_2$.
11685 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11686 finds no intersection. The routine gives up and gives an approximate answer
11687 if it has backtracked
11688 more than 5000 times (otherwise there are cases where several minutes
11689 of fruitless computation would be possible).
11691 @d max_patience 5000
11694 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11695 integer time_to_go; /* this many backtracks before giving up */
11696 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11698 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11699 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11700 and |(pp,link(pp))|, respectively.
11702 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11703 pointer q,qq; /* |link(p)|, |link(pp)| */
11704 mp->time_to_go=max_patience; mp->max_t=2;
11705 @<Initialize for intersections at level zero@>;
11708 if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11709 if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11710 if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11711 if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv)))
11713 if ( mp->cur_t>=mp->max_t ){
11714 if ( mp->max_t==two ) { /* we've done 17 bisections */
11715 mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11717 mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11719 @<Subdivide for a new level of intersection@>;
11722 if ( mp->time_to_go>0 ) {
11723 decr(mp->time_to_go);
11725 while ( mp->appr_t<unity ) {
11726 mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11728 mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11730 @<Advance to the next pair |(cur_t,cur_tt)|@>;
11734 @ The following variables are global, although they are used only by
11735 |cubic_intersection|, because it is necessary on some machines to
11736 split |cubic_intersection| up into two procedures.
11739 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11740 integer tol; /* bound on the uncertainly in the overlap test */
11742 unsigned int xy; /* pointers to the current packets of interest */
11743 integer three_l; /* |tol_step| times the bisection level */
11744 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11746 @ We shall assume that the coordinates are sufficiently non-extreme that
11747 integer overflow will not occur.
11749 @<Initialize for intersections at level zero@>=
11750 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11751 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11752 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11753 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11754 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11755 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11756 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11757 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11758 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11759 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11760 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets;
11761 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11763 @ @<Subdivide for a new level of intersection@>=
11764 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol;
11765 stack_uv=mp->uv; stack_xy=mp->xy;
11766 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11767 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11768 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11769 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11770 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11771 u3l=half(u2l+u2r); u1r=u3l;
11772 set_min_max(ul_packet); set_min_max(ur_packet);
11773 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11774 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11775 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11776 v3l=half(v2l+v2r); v1r=v3l;
11777 set_min_max(vl_packet); set_min_max(vr_packet);
11778 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11779 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11780 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11781 x3l=half(x2l+x2r); x1r=x3l;
11782 set_min_max(xl_packet); set_min_max(xr_packet);
11783 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11784 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11785 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11786 y3l=half(y2l+y2r); y1r=y3l;
11787 set_min_max(yl_packet); set_min_max(yr_packet);
11788 mp->uv=l_packets; mp->xy=l_packets;
11789 mp->delx+=mp->delx; mp->dely+=mp->dely;
11790 mp->tol=mp->tol-mp->three_l+mp->tol_step;
11791 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11793 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11795 if ( odd(mp->cur_tt) ) {
11796 if ( odd(mp->cur_t) ) {
11797 @<Descend to the previous level and |goto not_found|@>;
11800 mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11801 +stack_3(u_packet(mp->uv));
11802 mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11803 +stack_3(v_packet(mp->uv));
11804 mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11805 decr(mp->cur_tt); mp->xy=mp->xy-int_packets;
11806 /* switch from |r_packet| to |l_packet| */
11807 mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11808 +stack_3(x_packet(mp->xy));
11809 mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11810 +stack_3(y_packet(mp->xy));
11813 incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11814 mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11815 -stack_3(x_packet(mp->xy));
11816 mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11817 -stack_3(y_packet(mp->xy));
11818 mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11821 @ @<Descend to the previous level...@>=
11823 mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11824 if ( mp->cur_t==0 ) return;
11825 mp->bisect_ptr=mp->bisect_ptr-int_increment;
11826 mp->three_l=mp->three_l-mp->tol_step;
11827 mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol;
11828 mp->uv=stack_uv; mp->xy=stack_xy;
11832 @ The |path_intersection| procedure is much simpler.
11833 It invokes |cubic_intersection| in lexicographic order until finding a
11834 pair of cubics that intersect. The final intersection times are placed in
11835 |cur_t| and~|cur_tt|.
11837 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11838 pointer p,pp; /* link registers that traverse the given paths */
11839 integer n,nn; /* integer parts of intersection times, minus |unity| */
11840 @<Change one-point paths into dead cycles@>;
11845 if ( right_type(p)!=mp_endpoint ) {
11848 if ( right_type(pp)!=mp_endpoint ) {
11849 mp_cubic_intersection(mp, p,pp);
11850 if ( mp->cur_t>0 ) {
11851 mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn;
11855 nn=nn+unity; pp=link(pp);
11858 n=n+unity; p=link(p);
11860 mp->tol_step=mp->tol_step+3;
11861 } while (mp->tol_step<=3);
11862 mp->cur_t=-unity; mp->cur_tt=-unity;
11865 @ @<Change one-point paths...@>=
11866 if ( right_type(h)==mp_endpoint ) {
11867 right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11868 right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=mp_explicit;
11870 if ( right_type(hh)==mp_endpoint ) {
11871 right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11872 right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=mp_explicit;
11875 @* \[24] Dynamic linear equations.
11876 \MP\ users define variables implicitly by stating equations that should be
11877 satisfied; the computer is supposed to be smart enough to solve those equations.
11878 And indeed, the computer tries valiantly to do so, by distinguishing five
11879 different types of numeric values:
11882 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11883 of the variable whose address is~|p|.
11886 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11887 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11888 as a |scaled| number plus a sum of independent variables with |fraction|
11892 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11893 number'' reflecting the time this variable was first used in an equation;
11894 also |0<=m<64|, and each dependent variable
11895 that refers to this one is actually referring to the future value of
11896 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11897 scaling are sometimes needed to keep the coefficients in dependency lists
11898 from getting too large. The value of~|m| will always be even.)
11901 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11902 equation before, but it has been explicitly declared to be numeric.
11905 |type(p)=undefined| means that variable |p| hasn't appeared before.
11907 \smallskip\noindent
11908 We have actually discussed these five types in the reverse order of their
11909 history during a computation: Once |known|, a variable never again
11910 becomes |dependent|; once |dependent|, it almost never again becomes
11911 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11912 and once |mp_numeric_type|, it never again becomes |undefined| (except
11913 of course when the user specifically decides to scrap the old value
11914 and start again). A backward step may, however, take place: Sometimes
11915 a |dependent| variable becomes |mp_independent| again, when one of the
11916 independent variables it depends on is reverting to |undefined|.
11919 The next patch detects overflow of independent-variable serial
11920 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11922 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11923 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11924 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11925 @d new_indep(A) /* create a new independent variable */
11926 { if ( mp->serial_no==max_serial_no )
11927 mp_fatal_error(mp, "variable instance identifiers exhausted");
11928 type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11929 value((A))=mp->serial_no;
11933 integer serial_no; /* the most recent serial number, times |s_scale| */
11935 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11937 @ But how are dependency lists represented? It's simple: The linear combination
11938 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11939 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11940 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11941 of $\alpha_1$; and |link(p)| points to the dependency list
11942 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11943 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11944 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11945 they appear in decreasing order of their |value| fields (i.e., of
11946 their serial numbers). \ (It is convenient to use decreasing order,
11947 since |value(null)=0|. If the independent variables were not sorted by
11948 serial number but by some other criterion, such as their location in |mem|,
11949 the equation-solving mechanism would be too system-dependent, because
11950 the ordering can affect the computed results.)
11952 The |link| field in the node that contains the constant term $\beta$ is
11953 called the {\sl final link\/} of the dependency list. \MP\ maintains
11954 a doubly-linked master list of all dependency lists, in terms of a permanently
11956 in |mem| called |dep_head|. If there are no dependencies, we have
11957 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11958 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11959 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11960 points to its dependency list. If the final link of that dependency list
11961 occurs in location~|q|, then |link(q)| points to the next dependent
11962 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11964 @d dep_list(A) link(value_loc((A)))
11965 /* half of the |value| field in a |dependent| variable */
11966 @d prev_dep(A) info(value_loc((A)))
11967 /* the other half; makes a doubly linked list */
11968 @d dep_node_size 2 /* the number of words per dependency node */
11970 @<Initialize table entries...@>= mp->serial_no=0;
11971 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11972 info(dep_head)=null; dep_list(dep_head)=null;
11974 @ Actually the description above contains a little white lie. There's
11975 another kind of variable called |mp_proto_dependent|, which is
11976 just like a |dependent| one except that the $\alpha$ coefficients
11977 in its dependency list are |scaled| instead of being fractions.
11978 Proto-dependency lists are mixed with dependency lists in the
11979 nodes reachable from |dep_head|.
11981 @ Here is a procedure that prints a dependency list in symbolic form.
11982 The second parameter should be either |dependent| or |mp_proto_dependent|,
11983 to indicate the scaling of the coefficients.
11985 @<Declare subroutines for printing expressions@>=
11986 void mp_print_dependency (MP mp,pointer p, small_number t) {
11987 integer v; /* a coefficient */
11988 pointer pp,q; /* for list manipulation */
11991 v=abs(value(p)); q=info(p);
11992 if ( q==null ) { /* the constant term */
11993 if ( (v!=0)||(p==pp) ) {
11994 if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11995 mp_print_scaled(mp, value(p));
11999 @<Print the coefficient, unless it's $\pm1.0$@>;
12000 if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
12001 @:this can't happen dep}{\quad dep@>
12002 mp_print_variable_name(mp, q); v=value(q) % s_scale;
12003 while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
12008 @ @<Print the coefficient, unless it's $\pm1.0$@>=
12009 if ( value(p)<0 ) mp_print_char(mp, '-');
12010 else if ( p!=pp ) mp_print_char(mp, '+');
12011 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
12012 if ( v!=unity ) mp_print_scaled(mp, v)
12014 @ The maximum absolute value of a coefficient in a given dependency list
12015 is returned by the following simple function.
12017 @c fraction mp_max_coef (MP mp,pointer p) {
12018 fraction x; /* the maximum so far */
12020 while ( info(p)!=null ) {
12021 if ( abs(value(p))>x ) x=abs(value(p));
12027 @ One of the main operations needed on dependency lists is to add a multiple
12028 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
12029 to dependency lists and |f| is a fraction.
12031 If the coefficient of any independent variable becomes |coef_bound| or
12032 more, in absolute value, this procedure changes the type of that variable
12033 to `|independent_needing_fix|', and sets the global variable |fix_needed|
12034 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
12035 $\mu^2+\mu<8$; this means that the numbers we deal with won't
12036 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
12037 2.3723$, the safer value 7/3 is taken as the threshold.)
12039 The changes mentioned in the preceding paragraph are actually done only if
12040 the global variable |watch_coefs| is |true|. But it usually is; in fact,
12041 it is |false| only when \MP\ is making a dependency list that will soon
12042 be equated to zero.
12044 Several procedures that act on dependency lists, including |p_plus_fq|,
12045 set the global variable |dep_final| to the final (constant term) node of
12046 the dependency list that they produce.
12048 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
12049 @d independent_needing_fix 0
12052 boolean fix_needed; /* does at least one |independent| variable need scaling? */
12053 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
12054 pointer dep_final; /* location of the constant term and final link */
12057 mp->fix_needed=false; mp->watch_coefs=true;
12059 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
12060 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
12061 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
12062 should be |mp_proto_dependent| if |q| is a proto-dependency list.
12064 List |q| is unchanged by the operation; but list |p| is totally destroyed.
12066 The final link of the dependency list or proto-dependency list returned
12067 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
12068 constant term of the result will be located in the same |mem| location
12069 as the original constant term of~|p|.
12071 Coefficients of the result are assumed to be zero if they are less than
12072 a certain threshold. This compensates for inevitable rounding errors,
12073 and tends to make more variables `|known|'. The threshold is approximately
12074 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12075 proto-dependencies.
12077 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12078 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12079 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12080 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12082 @<Declare basic dependency-list subroutines@>=
12083 pointer mp_p_plus_fq ( MP mp, pointer p, integer f,
12084 pointer q, small_number t, small_number tt) ;
12087 pointer mp_p_plus_fq ( MP mp, pointer p, integer f,
12088 pointer q, small_number t, small_number tt) {
12089 pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12090 pointer r,s; /* for list manipulation */
12091 integer mp_threshold; /* defines a neighborhood of zero */
12092 integer v; /* temporary register */
12093 if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12094 else mp_threshold=scaled_threshold;
12095 r=temp_head; pp=info(p); qq=info(q);
12101 @<Contribute a term from |p|, plus |f| times the
12102 corresponding term from |q|@>
12104 } else if ( value(pp)<value(qq) ) {
12105 @<Contribute a term from |q|, multiplied by~|f|@>
12107 link(r)=p; r=p; p=link(p); pp=info(p);
12110 if ( t==mp_dependent )
12111 value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12113 value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12114 link(r)=p; mp->dep_final=p;
12115 return link(temp_head);
12118 @ @<Contribute a term from |p|, plus |f|...@>=
12120 if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12121 else v=value(p)+mp_take_scaled(mp, f,value(q));
12122 value(p)=v; s=p; p=link(p);
12123 if ( abs(v)<mp_threshold ) {
12124 mp_free_node(mp, s,dep_node_size);
12126 if ( (abs(v)>=coef_bound) && mp->watch_coefs ) {
12127 type(qq)=independent_needing_fix; mp->fix_needed=true;
12131 pp=info(p); q=link(q); qq=info(q);
12134 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12136 if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12137 else v=mp_take_scaled(mp, f,value(q));
12138 if ( abs(v)>halfp(mp_threshold) ) {
12139 s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
12140 if ( (abs(v)>=coef_bound) && mp->watch_coefs ) {
12141 type(qq)=independent_needing_fix; mp->fix_needed=true;
12145 q=link(q); qq=info(q);
12148 @ It is convenient to have another subroutine for the special case
12149 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12150 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12152 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
12153 pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12154 pointer r,s; /* for list manipulation */
12155 integer mp_threshold; /* defines a neighborhood of zero */
12156 integer v; /* temporary register */
12157 if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12158 else mp_threshold=scaled_threshold;
12159 r=temp_head; pp=info(p); qq=info(q);
12165 @<Contribute a term from |p|, plus the
12166 corresponding term from |q|@>
12168 } else if ( value(pp)<value(qq) ) {
12169 s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
12170 q=link(q); qq=info(q); link(r)=s; r=s;
12172 link(r)=p; r=p; p=link(p); pp=info(p);
12175 value(p)=mp_slow_add(mp, value(p),value(q));
12176 link(r)=p; mp->dep_final=p;
12177 return link(temp_head);
12180 @ @<Contribute a term from |p|, plus the...@>=
12182 v=value(p)+value(q);
12183 value(p)=v; s=p; p=link(p); pp=info(p);
12184 if ( abs(v)<mp_threshold ) {
12185 mp_free_node(mp, s,dep_node_size);
12187 if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12188 type(qq)=independent_needing_fix; mp->fix_needed=true;
12192 q=link(q); qq=info(q);
12195 @ A somewhat simpler routine will multiply a dependency list
12196 by a given constant~|v|. The constant is either a |fraction| less than
12197 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12198 convert a dependency list to a proto-dependency list.
12199 Parameters |t0| and |t1| are the list types before and after;
12200 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12201 and |v_is_scaled=true|.
12203 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
12204 small_number t1, boolean v_is_scaled) {
12205 pointer r,s; /* for list manipulation */
12206 integer w; /* tentative coefficient */
12207 integer mp_threshold;
12208 boolean scaling_down;
12209 if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
12210 if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12211 else mp_threshold=half_scaled_threshold;
12213 while ( info(p)!=null ) {
12214 if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12215 else w=mp_take_scaled(mp, v,value(p));
12216 if ( abs(w)<=mp_threshold ) {
12217 s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12219 if ( abs(w)>=coef_bound ) {
12220 mp->fix_needed=true; type(info(p))=independent_needing_fix;
12222 link(r)=p; r=p; value(p)=w; p=link(p);
12226 if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12227 else value(p)=mp_take_fraction(mp, value(p),v);
12228 return link(temp_head);
12231 @ Similarly, we sometimes need to divide a dependency list
12232 by a given |scaled| constant.
12234 @<Declare basic dependency-list subroutines@>=
12235 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number
12236 t0, small_number t1) ;
12239 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number
12240 t0, small_number t1) {
12241 pointer r,s; /* for list manipulation */
12242 integer w; /* tentative coefficient */
12243 integer mp_threshold;
12244 boolean scaling_down;
12245 if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12246 if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12247 else mp_threshold=half_scaled_threshold;
12249 while ( info( p)!=null ) {
12250 if ( scaling_down ) {
12251 if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12252 else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12254 w=mp_make_scaled(mp, value(p),v);
12256 if ( abs(w)<=mp_threshold ) {
12257 s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12259 if ( abs(w)>=coef_bound ) {
12260 mp->fix_needed=true; type(info(p))=independent_needing_fix;
12262 link(r)=p; r=p; value(p)=w; p=link(p);
12265 link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12266 return link(temp_head);
12269 @ Here's another utility routine for dependency lists. When an independent
12270 variable becomes dependent, we want to remove it from all existing
12271 dependencies. The |p_with_x_becoming_q| function computes the
12272 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12274 This procedure has basically the same calling conventions as |p_plus_fq|:
12275 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12276 final link are inherited from~|p|; and the fourth parameter tells whether
12277 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12278 is not altered if |x| does not occur in list~|p|.
12280 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12281 pointer x, pointer q, small_number t) {
12282 pointer r,s; /* for list manipulation */
12283 integer v; /* coefficient of |x| */
12284 integer sx; /* serial number of |x| */
12285 s=p; r=temp_head; sx=value(x);
12286 while ( value(info(s))>sx ) { r=s; s=link(s); };
12287 if ( info(s)!=x ) {
12290 link(temp_head)=p; link(r)=link(s); v=value(s);
12291 mp_free_node(mp, s,dep_node_size);
12292 return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12296 @ Here's a simple procedure that reports an error when a variable
12297 has just received a known value that's out of the required range.
12299 @<Declare basic dependency-list subroutines@>=
12300 void mp_val_too_big (MP mp,scaled x) ;
12302 @ @c void mp_val_too_big (MP mp,scaled x) {
12303 if ( mp->internal[mp_warning_check]>0 ) {
12304 print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12305 @.Value is too large@>
12306 help4("The equation I just processed has given some variable")
12307 ("a value of 4096 or more. Continue and I'll try to cope")
12308 ("with that big value; but it might be dangerous.")
12309 ("(Set warningcheck:=0 to suppress this message.)");
12314 @ When a dependent variable becomes known, the following routine
12315 removes its dependency list. Here |p| points to the variable, and
12316 |q| points to the dependency list (which is one node long).
12318 @<Declare basic dependency-list subroutines@>=
12319 void mp_make_known (MP mp,pointer p, pointer q) ;
12321 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12322 int t; /* the previous type */
12323 prev_dep(link(q))=prev_dep(p);
12324 link(prev_dep(p))=link(q); t=type(p);
12325 type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12326 if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12327 if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12328 mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12329 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12330 mp_print_variable_name(mp, p);
12331 mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12332 mp_end_diagnostic(mp, false);
12334 if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12335 mp->cur_type=mp_known; mp->cur_exp=value(p);
12336 mp_free_node(mp, p,value_node_size);
12340 @ The |fix_dependencies| routine is called into action when |fix_needed|
12341 has been triggered. The program keeps a list~|s| of independent variables
12342 whose coefficients must be divided by~4.
12344 In unusual cases, this fixup process might reduce one or more coefficients
12345 to zero, so that a variable will become known more or less by default.
12347 @<Declare basic dependency-list subroutines@>=
12348 void mp_fix_dependencies (MP mp);
12350 @ @c void mp_fix_dependencies (MP mp) {
12351 pointer p,q,r,s,t; /* list manipulation registers */
12352 pointer x; /* an independent variable */
12353 r=link(dep_head); s=null;
12354 while ( r!=dep_head ){
12356 @<Run through the dependency list for variable |t|, fixing
12357 all nodes, and ending with final link~|q|@>;
12359 if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12361 while ( s!=null ) {
12362 p=link(s); x=info(s); free_avail(s); s=p;
12363 type(x)=mp_independent; value(x)=value(x)+2;
12365 mp->fix_needed=false;
12368 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12370 @<Run through the dependency list for variable |t|...@>=
12371 r=value_loc(t); /* |link(r)=dep_list(t)| */
12373 q=link(r); x=info(q);
12374 if ( x==null ) break;
12375 if ( type(x)<=independent_being_fixed ) {
12376 if ( type(x)<independent_being_fixed ) {
12377 p=mp_get_avail(mp); link(p)=s; s=p;
12378 info(s)=x; type(x)=independent_being_fixed;
12380 value(q)=value(q) / 4;
12381 if ( value(q)==0 ) {
12382 link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12389 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12390 linking it into the list of all known dependencies. We assume that
12391 |dep_final| points to the final node of list~|p|.
12393 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12394 pointer r; /* what used to be the first dependency */
12395 dep_list(q)=p; prev_dep(q)=dep_head;
12396 r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12400 @ Here is one of the ways a dependency list gets started.
12401 The |const_dependency| routine produces a list that has nothing but
12404 @c pointer mp_const_dependency (MP mp, scaled v) {
12405 mp->dep_final=mp_get_node(mp, dep_node_size);
12406 value(mp->dep_final)=v; info(mp->dep_final)=null;
12407 return mp->dep_final;
12410 @ And here's a more interesting way to start a dependency list from scratch:
12411 The parameter to |single_dependency| is the location of an
12412 independent variable~|x|, and the result is the simple dependency list
12415 In the unlikely event that the given independent variable has been doubled so
12416 often that we can't refer to it with a nonzero coefficient,
12417 |single_dependency| returns the simple list `0'. This case can be
12418 recognized by testing that the returned list pointer is equal to
12421 @c pointer mp_single_dependency (MP mp,pointer p) {
12422 pointer q; /* the new dependency list */
12423 integer m; /* the number of doublings */
12424 m=value(p) % s_scale;
12426 return mp_const_dependency(mp, 0);
12428 q=mp_get_node(mp, dep_node_size);
12429 value(q)=two_to_the(28-m); info(q)=p;
12430 link(q)=mp_const_dependency(mp, 0);
12435 @ We sometimes need to make an exact copy of a dependency list.
12437 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12438 pointer q; /* the new dependency list */
12439 q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12441 info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12442 if ( info(mp->dep_final)==null ) break;
12443 link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12444 mp->dep_final=link(mp->dep_final); p=link(p);
12449 @ But how do variables normally become known? Ah, now we get to the heart of the
12450 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12451 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12452 appears. It equates this list to zero, by choosing an independent variable
12453 with the largest coefficient and making it dependent on the others. The
12454 newly dependent variable is eliminated from all current dependencies,
12455 thereby possibly making other dependent variables known.
12457 The given list |p| is, of course, totally destroyed by all this processing.
12459 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12460 pointer q,r,s; /* for link manipulation */
12461 pointer x; /* the variable that loses its independence */
12462 integer n; /* the number of times |x| had been halved */
12463 integer v; /* the coefficient of |x| in list |p| */
12464 pointer prev_r; /* lags one step behind |r| */
12465 pointer final_node; /* the constant term of the new dependency list */
12466 integer w; /* a tentative coefficient */
12467 @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12468 x=info(q); n=value(x) % s_scale;
12469 @<Divide list |p| by |-v|, removing node |q|@>;
12470 if ( mp->internal[mp_tracing_equations]>0 ) {
12471 @<Display the new dependency@>;
12473 @<Simplify all existing dependencies by substituting for |x|@>;
12474 @<Change variable |x| from |independent| to |dependent| or |known|@>;
12475 if ( mp->fix_needed ) mp_fix_dependencies(mp);
12478 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12479 q=p; r=link(p); v=value(q);
12480 while ( info(r)!=null ) {
12481 if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12485 @ Here we want to change the coefficients from |scaled| to |fraction|,
12486 except in the constant term. In the common case of a trivial equation
12487 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12489 @<Divide list |p| by |-v|, removing node |q|@>=
12490 s=temp_head; link(s)=p; r=p;
12493 link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12495 w=mp_make_fraction(mp, value(r),v);
12496 if ( abs(w)<=half_fraction_threshold ) {
12497 link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12503 } while (info(r)!=null);
12504 if ( t==mp_proto_dependent ) {
12505 value(r)=-mp_make_scaled(mp, value(r),v);
12506 } else if ( v!=-fraction_one ) {
12507 value(r)=-mp_make_fraction(mp, value(r),v);
12509 final_node=r; p=link(temp_head)
12511 @ @<Display the new dependency@>=
12512 if ( mp_interesting(mp, x) ) {
12513 mp_begin_diagnostic(mp); mp_print_nl(mp, "## ");
12514 mp_print_variable_name(mp, x);
12515 @:]]]\#\#_}{\.{\#\#}@>
12517 while ( w>0 ) { mp_print(mp, "*4"); w=w-2; };
12518 mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent);
12519 mp_end_diagnostic(mp, false);
12522 @ @<Simplify all existing dependencies by substituting for |x|@>=
12523 prev_r=dep_head; r=link(dep_head);
12524 while ( r!=dep_head ) {
12525 s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12526 if ( info(q)==null ) {
12527 mp_make_known(mp, r,q);
12530 do { q=link(q); } while (info(q)!=null);
12536 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12537 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12538 if ( info(p)==null ) {
12541 if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12542 mp_free_node(mp, p,dep_node_size);
12543 if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12544 mp->cur_exp=value(x); mp->cur_type=mp_known;
12545 mp_free_node(mp, x,value_node_size);
12548 type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12549 if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12552 @ @<Divide list |p| by $2^n$@>=
12554 s=temp_head; link(temp_head)=p; r=p;
12557 else w=value(r) / two_to_the(n);
12558 if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12560 mp_free_node(mp, r,dep_node_size);
12565 } while (info(s)!=null);
12569 @ The |check_mem| procedure, which is used only when \MP\ is being
12570 debugged, makes sure that the current dependency lists are well formed.
12572 @<Check the list of linear dependencies@>=
12573 q=dep_head; p=link(q);
12574 while ( p!=dep_head ) {
12575 if ( prev_dep(p)!=q ) {
12576 mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12581 r=info(p); q=p; p=link(q);
12582 if ( r==null ) break;
12583 if ( value(info(p))>=value(r) ) {
12584 mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12585 @.Out of order...@>
12590 @* \[25] Dynamic nonlinear equations.
12591 Variables of numeric type are maintained by the general scheme of
12592 independent, dependent, and known values that we have just studied;
12593 and the components of pair and transform variables are handled in the
12594 same way. But \MP\ also has five other types of values: \&{boolean},
12595 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12597 Equations are allowed between nonlinear quantities, but only in a
12598 simple form. Two variables that haven't yet been assigned values are
12599 either equal to each other, or they're not.
12601 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12602 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12603 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12604 |null| (which means that no other variables are equivalent to this one), or
12605 it points to another variable of the same undefined type. The pointers in the
12606 latter case form a cycle of nodes, which we shall call a ``ring.''
12607 Rings of undefined variables may include capsules, which arise as
12608 intermediate results within expressions or as \&{expr} parameters to macros.
12610 When one member of a ring receives a value, the same value is given to
12611 all the other members. In the case of paths and pictures, this implies
12612 making separate copies of a potentially large data structure; users should
12613 restrain their enthusiasm for such generality, unless they have lots and
12614 lots of memory space.
12616 @ The following procedure is called when a capsule node is being
12617 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12619 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12620 pointer q; /* the new capsule node */
12621 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12623 if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12628 @ Conversely, we might delete a capsule or a variable before it becomes known.
12629 The following procedure simply detaches a quantity from its ring,
12630 without recycling the storage.
12632 @<Declare the recycling subroutines@>=
12633 void mp_ring_delete (MP mp,pointer p) {
12636 if ( q!=null ) if ( q!=p ){
12637 while ( value(q)!=p ) q=value(q);
12642 @ Eventually there might be an equation that assigns values to all of the
12643 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12644 propagation of values.
12646 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12647 value, it will soon be recycled.
12649 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12650 small_number t; /* the type of ring |p| */
12651 pointer q,r; /* link manipulation registers */
12652 t=type(p)-unknown_tag; q=value(p);
12653 if ( flush_p ) type(p)=mp_vacuous; else p=q;
12655 r=value(q); type(q)=t;
12657 case mp_boolean_type: value(q)=v; break;
12658 case mp_string_type: value(q)=v; add_str_ref(v); break;
12659 case mp_pen_type: value(q)=copy_pen(v); break;
12660 case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12661 case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12662 } /* there ain't no more cases */
12667 @ If two members of rings are equated, and if they have the same type,
12668 the |ring_merge| procedure is called on to make them equivalent.
12670 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12671 pointer r; /* traverses one list */
12675 @<Exclaim about a redundant equation@>;
12680 r=value(p); value(p)=value(q); value(q)=r;
12683 @ @<Exclaim about a redundant equation@>=
12685 print_err("Redundant equation");
12686 @.Redundant equation@>
12687 help2("I already knew that this equation was true.")
12688 ("But perhaps no harm has been done; let's continue.");
12689 mp_put_get_error(mp);
12692 @* \[26] Introduction to the syntactic routines.
12693 Let's pause a moment now and try to look at the Big Picture.
12694 The \MP\ program consists of three main parts: syntactic routines,
12695 semantic routines, and output routines. The chief purpose of the
12696 syntactic routines is to deliver the user's input to the semantic routines,
12697 while parsing expressions and locating operators and operands. The
12698 semantic routines act as an interpreter responding to these operators,
12699 which may be regarded as commands. And the output routines are
12700 periodically called on to produce compact font descriptions that can be
12701 used for typesetting or for making interim proof drawings. We have
12702 discussed the basic data structures and many of the details of semantic
12703 operations, so we are good and ready to plunge into the part of \MP\ that
12704 actually controls the activities.
12706 Our current goal is to come to grips with the |get_next| procedure,
12707 which is the keystone of \MP's input mechanism. Each call of |get_next|
12708 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12709 representing the next input token.
12710 $$\vbox{\halign{#\hfil\cr
12711 \hbox{|cur_cmd| denotes a command code from the long list of codes
12713 \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12714 \hbox{|cur_sym| is the hash address of the symbolic token that was
12716 \hbox{\qquad or zero in the case of a numeric or string
12717 or capsule token.}\cr}}$$
12718 Underlying this external behavior of |get_next| is all the machinery
12719 necessary to convert from character files to tokens. At a given time we
12720 may be only partially finished with the reading of several files (for
12721 which \&{input} was specified), and partially finished with the expansion
12722 of some user-defined macros and/or some macro parameters, and partially
12723 finished reading some text that the user has inserted online,
12724 and so on. When reading a character file, the characters must be
12725 converted to tokens; comments and blank spaces must
12726 be removed, numeric and string tokens must be evaluated.
12728 To handle these situations, which might all be present simultaneously,
12729 \MP\ uses various stacks that hold information about the incomplete
12730 activities, and there is a finite state control for each level of the
12731 input mechanism. These stacks record the current state of an implicitly
12732 recursive process, but the |get_next| procedure is not recursive.
12735 eight_bits cur_cmd; /* current command set by |get_next| */
12736 integer cur_mod; /* operand of current command */
12737 halfword cur_sym; /* hash address of current symbol */
12739 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12740 command code and its modifier.
12741 It consists of a rather tedious sequence of print
12742 commands, and most of it is essentially an inverse to the |primitive|
12743 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12744 all of this procedure appears elsewhere in the program, together with the
12745 corresponding |primitive| calls.
12747 @<Declare the procedure called |print_cmd_mod|@>=
12748 void mp_print_cmd_mod (MP mp,integer c, integer m) {
12750 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12751 default: mp_print(mp, "[unknown command code!]"); break;
12755 @ Here is a procedure that displays a given command in braces, in the
12756 user's transcript file.
12758 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12761 void mp_show_cmd_mod (MP mp,integer c, integer m) {
12762 mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12763 mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12764 mp_end_diagnostic(mp, false);
12767 @* \[27] Input stacks and states.
12768 The state of \MP's input mechanism appears in the input stack, whose
12769 entries are records with five fields, called |index|, |start|, |loc|,
12770 |limit|, and |name|. The top element of this stack is maintained in a
12771 global variable for which no subscripting needs to be done; the other
12772 elements of the stack appear in an array. Hence the stack is declared thus:
12776 quarterword index_field;
12777 halfword start_field, loc_field, limit_field, name_field;
12781 in_state_record *input_stack;
12782 integer input_ptr; /* first unused location of |input_stack| */
12783 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12784 in_state_record cur_input; /* the ``top'' input state */
12785 int stack_size; /* maximum number of simultaneous input sources */
12787 @ @<Allocate or initialize ...@>=
12788 mp->stack_size = 300;
12789 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12791 @ @<Dealloc variables@>=
12792 xfree(mp->input_stack);
12794 @ We've already defined the special variable |loc==cur_input.loc_field|
12795 in our discussion of basic input-output routines. The other components of
12796 |cur_input| are defined in the same way:
12798 @d index mp->cur_input.index_field /* reference for buffer information */
12799 @d start mp->cur_input.start_field /* starting position in |buffer| */
12800 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12801 @d name mp->cur_input.name_field /* name of the current file */
12803 @ Let's look more closely now at the five control variables
12804 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12805 assuming that \MP\ is reading a line of characters that have been input
12806 from some file or from the user's terminal. There is an array called
12807 |buffer| that acts as a stack of all lines of characters that are
12808 currently being read from files, including all lines on subsidiary
12809 levels of the input stack that are not yet completed. \MP\ will return to
12810 the other lines when it is finished with the present input file.
12812 (Incidentally, on a machine with byte-oriented addressing, it would be
12813 appropriate to combine |buffer| with the |str_pool| array,
12814 letting the buffer entries grow downward from the top of the string pool
12815 and checking that these two tables don't bump into each other.)
12817 The line we are currently working on begins in position |start| of the
12818 buffer; the next character we are about to read is |buffer[loc]|; and
12819 |limit| is the location of the last character present. We always have
12820 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12821 that the end of a line is easily sensed.
12823 The |name| variable is a string number that designates the name of
12824 the current file, if we are reading an ordinary text file. Special codes
12825 |is_term..max_spec_src| indicate other sources of input text.
12827 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12828 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12829 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12830 @d max_spec_src is_scantok
12832 @ Additional information about the current line is available via the
12833 |index| variable, which counts how many lines of characters are present
12834 in the buffer below the current level. We have |index=0| when reading
12835 from the terminal and prompting the user for each line; then if the user types,
12836 e.g., `\.{input figs}', we will have |index=1| while reading
12837 the file \.{figs.mp}. However, it does not follow that |index| is the
12838 same as the input stack pointer, since many of the levels on the input
12839 stack may come from token lists and some |index| values may correspond
12840 to \.{MPX} files that are not currently on the stack.
12842 The global variable |in_open| is equal to the highest |index| value counting
12843 \.{MPX} files but excluding token-list input levels. Thus, the number of
12844 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12845 when we are not reading a token list.
12847 If we are not currently reading from the terminal,
12848 we are reading from the file variable |input_file[index]|. We use
12849 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12850 and |cur_file| as an abbreviation for |input_file[index]|.
12852 When \MP\ is not reading from the terminal, the global variable |line| contains
12853 the line number in the current file, for use in error messages. More precisely,
12854 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12855 the line number for each file in the |input_file| array.
12857 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12858 array so that the name doesn't get lost when the file is temporarily removed
12859 from the input stack.
12860 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12861 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12862 Since this is not an \.{MPX} file, we have
12863 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12864 This |name| field is set to |finished| when |input_file[k]| is completely
12867 If more information about the input state is needed, it can be
12868 included in small arrays like those shown here. For example,
12869 the current page or segment number in the input file might be put
12870 into a variable |page|, that is really a macro for the current entry
12871 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12872 by analogy with |line_stack|.
12873 @^system dependencies@>
12875 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12876 @d cur_file mp->input_file[index] /* the current |FILE *| variable */
12877 @d line mp->line_stack[index] /* current line number in the current source file */
12878 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12879 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12880 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12881 @d mpx_reading (mp->mpx_name[index]>absent)
12882 /* when reading a file, is it an \.{MPX} file? */
12884 /* |name_field| value when the corresponding \.{MPX} file is finished */
12887 integer in_open; /* the number of lines in the buffer, less one */
12888 unsigned int open_parens; /* the number of open text files */
12889 FILE * *input_file ;
12890 integer *line_stack ; /* the line number for each file */
12891 char * *iname_stack; /* used for naming \.{MPX} files */
12892 char * *iarea_stack; /* used for naming \.{MPX} files */
12893 halfword*mpx_name ;
12895 @ @<Allocate or ...@>=
12896 mp->input_file = xmalloc((mp->max_in_open+1),sizeof(FILE *));
12897 mp->line_stack = xmalloc((mp->max_in_open+1),sizeof(integer));
12898 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12899 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12900 mp->mpx_name = xmalloc((mp->max_in_open+1),sizeof(halfword));
12903 for (k=0;k<=mp->max_in_open;k++) {
12904 mp->iname_stack[k] =NULL;
12905 mp->iarea_stack[k] =NULL;
12909 @ @<Dealloc variables@>=
12912 for (l=0;l<=mp->max_in_open;l++) {
12913 xfree(mp->iname_stack[l]);
12914 xfree(mp->iarea_stack[l]);
12917 xfree(mp->input_file);
12918 xfree(mp->line_stack);
12919 xfree(mp->iname_stack);
12920 xfree(mp->iarea_stack);
12921 xfree(mp->mpx_name);
12924 @ However, all this discussion about input state really applies only to the
12925 case that we are inputting from a file. There is another important case,
12926 namely when we are currently getting input from a token list. In this case
12927 |index>max_in_open|, and the conventions about the other state variables
12930 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12931 the node that will be read next. If |loc=null|, the token list has been
12934 \yskip\hang|start| points to the first node of the token list; this node
12935 may or may not contain a reference count, depending on the type of token
12938 \yskip\hang|token_type|, which takes the place of |index| in the
12939 discussion above, is a code number that explains what kind of token list
12942 \yskip\hang|name| points to the |eqtb| address of the control sequence
12943 being expanded, if the current token list is a macro not defined by
12944 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12945 can be deduced by looking at their first two parameters.
12947 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12948 the parameters of the current macro or loop text begin in the |param_stack|.
12950 \yskip\noindent The |token_type| can take several values, depending on
12951 where the current token list came from:
12954 \indent|forever_text|, if the token list being scanned is the body of
12955 a \&{forever} loop;
12957 \indent|loop_text|, if the token list being scanned is the body of
12958 a \&{for} or \&{forsuffixes} loop;
12960 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12962 \indent|backed_up|, if the token list being scanned has been inserted as
12963 `to be read again'.
12965 \indent|inserted|, if the token list being scanned has been inserted as
12966 part of error recovery;
12968 \indent|macro|, if the expansion of a user-defined symbolic token is being
12972 The token list begins with a reference count if and only if |token_type=
12974 @^reference counts@>
12976 @d token_type index /* type of current token list */
12977 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12978 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12979 @d param_start limit /* base of macro parameters in |param_stack| */
12980 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12981 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12982 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12983 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12984 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12985 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12987 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12988 lists for parameters at the current level and subsidiary levels of input.
12989 This stack grows at a different rate from the others.
12992 pointer *param_stack; /* token list pointers for parameters */
12993 integer param_ptr; /* first unused entry in |param_stack| */
12994 integer max_param_stack; /* largest value of |param_ptr| */
12996 @ @<Allocate or initialize ...@>=
12997 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12999 @ @<Dealloc variables@>=
13000 xfree(mp->param_stack);
13002 @ Notice that the |line| isn't valid when |token_state| is true because it
13003 depends on |index|. If we really need to know the line number for the
13004 topmost file in the index stack we use the following function. If a page
13005 number or other information is needed, this routine should be modified to
13006 compute it as well.
13007 @^system dependencies@>
13009 @<Declare a function called |true_line|@>=
13010 integer mp_true_line (MP mp) {
13011 int k; /* an index into the input stack */
13012 if ( file_state && (name>max_spec_src) ) {
13017 ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
13018 (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
13021 return mp->line_stack[(k-1)];
13026 @ Thus, the ``current input state'' can be very complicated indeed; there
13027 can be many levels and each level can arise in a variety of ways. The
13028 |show_context| procedure, which is used by \MP's error-reporting routine to
13029 print out the current input state on all levels down to the most recent
13030 line of characters from an input file, illustrates most of these conventions.
13031 The global variable |file_ptr| contains the lowest level that was
13032 displayed by this procedure.
13035 integer file_ptr; /* shallowest level shown by |show_context| */
13037 @ The status at each level is indicated by printing two lines, where the first
13038 line indicates what was read so far and the second line shows what remains
13039 to be read. The context is cropped, if necessary, so that the first line
13040 contains at most |half_error_line| characters, and the second contains
13041 at most |error_line|. Non-current input levels whose |token_type| is
13042 `|backed_up|' are shown only if they have not been fully read.
13044 @c void mp_show_context (MP mp) { /* prints where the scanner is */
13045 int old_setting; /* saved |selector| setting */
13046 @<Local variables for formatting calculations@>
13047 mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
13048 /* store current state */
13050 mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
13051 @<Display the current context@>;
13053 if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
13054 decr(mp->file_ptr);
13056 mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
13059 @ @<Display the current context@>=
13060 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
13061 (token_type!=backed_up) || (loc!=null) ) {
13062 /* we omit backed-up token lists that have already been read */
13063 mp->tally=0; /* get ready to count characters */
13064 old_setting=mp->selector;
13065 if ( file_state ) {
13066 @<Print location of current line@>;
13067 @<Pseudoprint the line@>;
13069 @<Print type of token list@>;
13070 @<Pseudoprint the token list@>;
13072 mp->selector=old_setting; /* stop pseudoprinting */
13073 @<Print two lines using the tricky pseudoprinted information@>;
13076 @ This routine should be changed, if necessary, to give the best possible
13077 indication of where the current line resides in the input file.
13078 For example, on some systems it is best to print both a page and line number.
13079 @^system dependencies@>
13081 @<Print location of current line@>=
13082 if ( name>max_spec_src ) {
13083 mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13084 } else if ( terminal_input ) {
13085 if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13086 else mp_print_nl(mp, "<insert>");
13087 } else if ( name==is_scantok ) {
13088 mp_print_nl(mp, "<scantokens>");
13090 mp_print_nl(mp, "<read>");
13092 mp_print_char(mp, ' ')
13094 @ Can't use case statement here because the |token_type| is not
13095 a constant expression.
13097 @<Print type of token list@>=
13099 if(token_type==forever_text) {
13100 mp_print_nl(mp, "<forever> ");
13101 } else if (token_type==loop_text) {
13102 @<Print the current loop value@>;
13103 } else if (token_type==parameter) {
13104 mp_print_nl(mp, "<argument> ");
13105 } else if (token_type==backed_up) {
13106 if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13107 else mp_print_nl(mp, "<to be read again> ");
13108 } else if (token_type==inserted) {
13109 mp_print_nl(mp, "<inserted text> ");
13110 } else if (token_type==macro) {
13112 if ( name!=null ) mp_print_text(name);
13113 else @<Print the name of a \&{vardef}'d macro@>;
13114 mp_print(mp, "->");
13116 mp_print_nl(mp, "?");/* this should never happen */
13121 @ The parameter that corresponds to a loop text is either a token list
13122 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13123 We'll discuss capsules later; for now, all we need to know is that
13124 the |link| field in a capsule parameter is |void| and that
13125 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13127 @<Print the current loop value@>=
13128 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13130 if ( link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13131 else mp_show_token_list(mp, p,null,20,mp->tally);
13133 mp_print(mp, ")> ");
13136 @ The first two parameters of a macro defined by \&{vardef} will be token
13137 lists representing the macro's prefix and ``at point.'' By putting these
13138 together, we get the macro's full name.
13140 @<Print the name of a \&{vardef}'d macro@>=
13141 { p=mp->param_stack[param_start];
13143 mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13146 while ( link(q)!=null ) q=link(q);
13147 link(q)=mp->param_stack[param_start+1];
13148 mp_show_token_list(mp, p,null,20,mp->tally);
13153 @ Now it is necessary to explain a little trick. We don't want to store a long
13154 string that corresponds to a token list, because that string might take up
13155 lots of memory; and we are printing during a time when an error message is
13156 being given, so we dare not do anything that might overflow one of \MP's
13157 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13158 that stores characters into a buffer of length |error_line|, where character
13159 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13160 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13161 |tally:=0| and |trick_count:=1000000|; then when we reach the
13162 point where transition from line 1 to line 2 should occur, we
13163 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13164 tally+1+error_line-half_error_line)|. At the end of the
13165 pseudoprinting, the values of |first_count|, |tally|, and
13166 |trick_count| give us all the information we need to print the two lines,
13167 and all of the necessary text is in |trick_buf|.
13169 Namely, let |l| be the length of the descriptive information that appears
13170 on the first line. The length of the context information gathered for that
13171 line is |k=first_count|, and the length of the context information
13172 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13173 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13174 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13175 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13176 and print `\.{...}' followed by
13177 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13178 where subscripts of |trick_buf| are circular modulo |error_line|. The
13179 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13180 unless |n+m>error_line|; in the latter case, further cropping is done.
13181 This is easier to program than to explain.
13183 @<Local variables for formatting...@>=
13184 int i; /* index into |buffer| */
13185 integer l; /* length of descriptive information on line 1 */
13186 integer m; /* context information gathered for line 2 */
13187 int n; /* length of line 1 */
13188 integer p; /* starting or ending place in |trick_buf| */
13189 integer q; /* temporary index */
13191 @ The following code tells the print routines to gather
13192 the desired information.
13194 @d begin_pseudoprint {
13195 l=mp->tally; mp->tally=0; mp->selector=pseudo;
13196 mp->trick_count=1000000;
13198 @d set_trick_count {
13199 mp->first_count=mp->tally;
13200 mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13201 if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13204 @ And the following code uses the information after it has been gathered.
13206 @<Print two lines using the tricky pseudoprinted information@>=
13207 if ( mp->trick_count==1000000 ) set_trick_count;
13208 /* |set_trick_count| must be performed */
13209 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13210 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13211 if ( l+mp->first_count<=mp->half_error_line ) {
13212 p=0; n=l+mp->first_count;
13214 mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13215 n=mp->half_error_line;
13217 for (q=p;q<=mp->first_count-1;q++) {
13218 mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13221 for (q=1;q<=n;q++) {
13222 mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13224 if ( m+n<=mp->error_line ) p=mp->first_count+m;
13225 else p=mp->first_count+(mp->error_line-n-3);
13226 for (q=mp->first_count;q<=p-1;q++) {
13227 mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13229 if ( m+n>mp->error_line ) mp_print(mp, "...")
13231 @ But the trick is distracting us from our current goal, which is to
13232 understand the input state. So let's concentrate on the data structures that
13233 are being pseudoprinted as we finish up the |show_context| procedure.
13235 @<Pseudoprint the line@>=
13238 for (i=start;i<=limit-1;i++) {
13239 if ( i==loc ) set_trick_count;
13240 mp_print_str(mp, mp->buffer[i]);
13244 @ @<Pseudoprint the token list@>=
13246 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13247 else mp_show_macro(mp, start,loc,100000)
13249 @ Here is the missing piece of |show_token_list| that is activated when the
13250 token beginning line~2 is about to be shown:
13252 @<Do magic computation@>=set_trick_count
13254 @* \[28] Maintaining the input stacks.
13255 The following subroutines change the input status in commonly needed ways.
13257 First comes |push_input|, which stores the current state and creates a
13258 new level (having, initially, the same properties as the old).
13260 @d push_input { /* enter a new input level, save the old */
13261 if ( mp->input_ptr>mp->max_in_stack ) {
13262 mp->max_in_stack=mp->input_ptr;
13263 if ( mp->input_ptr==mp->stack_size ) {
13264 int l = (mp->stack_size+(mp->stack_size>>2));
13265 XREALLOC(mp->input_stack, l, in_state_record);
13266 mp->stack_size = l;
13269 mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13270 incr(mp->input_ptr);
13273 @ And of course what goes up must come down.
13275 @d pop_input { /* leave an input level, re-enter the old */
13276 decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13279 @ Here is a procedure that starts a new level of token-list input, given
13280 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13281 set |name|, reset~|loc|, and increase the macro's reference count.
13283 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13285 @c void mp_begin_token_list (MP mp,pointer p, quarterword t) {
13286 push_input; start=p; token_type=t;
13287 param_start=mp->param_ptr; loc=p;
13290 @ When a token list has been fully scanned, the following computations
13291 should be done as we leave that level of input.
13294 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13295 pointer p; /* temporary register */
13296 if ( token_type>=backed_up ) { /* token list to be deleted */
13297 if ( token_type<=inserted ) {
13298 mp_flush_token_list(mp, start); goto DONE;
13300 mp_delete_mac_ref(mp, start); /* update reference count */
13303 while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13304 decr(mp->param_ptr);
13305 p=mp->param_stack[mp->param_ptr];
13307 if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
13308 mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13310 mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13315 pop_input; check_interrupt;
13318 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13319 token by the |cur_tok| routine.
13322 @c @<Declare the procedure called |make_exp_copy|@>;
13323 pointer mp_cur_tok (MP mp) {
13324 pointer p; /* a new token node */
13325 small_number save_type; /* |cur_type| to be restored */
13326 integer save_exp; /* |cur_exp| to be restored */
13327 if ( mp->cur_sym==0 ) {
13328 if ( mp->cur_cmd==capsule_token ) {
13329 save_type=mp->cur_type; save_exp=mp->cur_exp;
13330 mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13331 mp->cur_type=save_type; mp->cur_exp=save_exp;
13333 p=mp_get_node(mp, token_node_size);
13334 value(p)=mp->cur_mod; name_type(p)=mp_token;
13335 if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13336 else type(p)=mp_string_type;
13339 fast_get_avail(p); info(p)=mp->cur_sym;
13344 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13345 seen. The |back_input| procedure takes care of this by putting the token
13346 just scanned back into the input stream, ready to be read again.
13347 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13350 void mp_back_input (MP mp);
13352 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13353 pointer p; /* a token list of length one */
13355 while ( token_state &&(loc==null) )
13356 mp_end_token_list(mp); /* conserve stack space */
13360 @ The |back_error| routine is used when we want to restore or replace an
13361 offending token just before issuing an error message. We disable interrupts
13362 during the call of |back_input| so that the help message won't be lost.
13365 void mp_error (MP mp);
13366 void mp_back_error (MP mp);
13368 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13369 mp->OK_to_interrupt=false;
13371 mp->OK_to_interrupt=true; mp_error(mp);
13373 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13374 mp->OK_to_interrupt=false;
13375 mp_back_input(mp); token_type=inserted;
13376 mp->OK_to_interrupt=true; mp_error(mp);
13379 @ The |begin_file_reading| procedure starts a new level of input for lines
13380 of characters to be read from a file, or as an insertion from the
13381 terminal. It does not take care of opening the file, nor does it set |loc|
13382 or |limit| or |line|.
13383 @^system dependencies@>
13385 @c void mp_begin_file_reading (MP mp) {
13386 if ( mp->in_open==mp->max_in_open )
13387 mp_overflow(mp, "text input levels",mp->max_in_open);
13388 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13389 if ( mp->first==mp->buf_size )
13390 mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13391 incr(mp->in_open); push_input; index=mp->in_open;
13392 mp->mpx_name[index]=absent;
13394 name=is_term; /* |terminal_input| is now |true| */
13397 @ Conversely, the variables must be downdated when such a level of input
13398 is finished. Any associated \.{MPX} file must also be closed and popped
13399 off the file stack.
13401 @c void mp_end_file_reading (MP mp) {
13402 if ( mp->in_open>index ) {
13403 if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13404 mp_confusion(mp, "endinput");
13405 @:this can't happen endinput}{\quad endinput@>
13407 fclose(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13408 delete_str_ref(mp->mpx_name[mp->in_open]);
13413 if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13414 if ( name>max_spec_src ) {
13416 delete_str_ref(name);
13420 pop_input; decr(mp->in_open);
13423 @ Here is a function that tries to resume input from an \.{MPX} file already
13424 associated with the current input file. It returns |false| if this doesn't
13427 @c boolean mp_begin_mpx_reading (MP mp) {
13428 if ( mp->in_open!=index+1 ) {
13431 if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13432 @:this can't happen mpx}{\quad mpx@>
13433 if ( mp->first==mp->buf_size )
13434 mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13435 push_input; index=mp->in_open;
13437 name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13438 @<Put an empty line in the input buffer@>;
13443 @ This procedure temporarily stops reading an \.{MPX} file.
13445 @c void mp_end_mpx_reading (MP mp) {
13446 if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13447 @:this can't happen mpx}{\quad mpx@>
13449 @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13455 @ Here we enforce a restriction that simplifies the input stacks considerably.
13456 This should not inconvenience the user because \.{MPX} files are generated
13457 by an auxiliary program called \.{DVItoMP}.
13459 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13461 print_err("`mpxbreak' must be at the end of a line");
13462 help4("This file contains picture expressions for btex...etex")
13463 ("blocks. Such files are normally generated automatically")
13464 ("but this one seems to be messed up. I'm going to ignore")
13465 ("the rest of this line.");
13469 @ In order to keep the stack from overflowing during a long sequence of
13470 inserted `\.{show}' commands, the following routine removes completed
13471 error-inserted lines from memory.
13473 @c void mp_clear_for_error_prompt (MP mp) {
13474 while ( file_state && terminal_input &&
13475 (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13476 mp_print_ln(mp); clear_terminal;
13479 @ To get \MP's whole input mechanism going, we perform the following
13482 @<Initialize the input routines@>=
13483 { mp->input_ptr=0; mp->max_in_stack=0;
13484 mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13485 mp->param_ptr=0; mp->max_param_stack=0;
13487 start=1; index=0; line=0; name=is_term;
13488 mp->mpx_name[0]=absent;
13489 mp->force_eof=false;
13490 if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13491 limit=mp->last; mp->first=mp->last+1;
13492 /* |init_terminal| has set |loc| and |last| */
13495 @* \[29] Getting the next token.
13496 The heart of \MP's input mechanism is the |get_next| procedure, which
13497 we shall develop in the next few sections of the program. Perhaps we
13498 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13499 eyes and mouth, reading the source files and gobbling them up. And it also
13500 helps \MP\ to regurgitate stored token lists that are to be processed again.
13502 The main duty of |get_next| is to input one token and to set |cur_cmd|
13503 and |cur_mod| to that token's command code and modifier. Furthermore, if
13504 the input token is a symbolic token, that token's |hash| address
13505 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13507 Underlying this simple description is a certain amount of complexity
13508 because of all the cases that need to be handled.
13509 However, the inner loop of |get_next| is reasonably short and fast.
13511 @ Before getting into |get_next|, we need to consider a mechanism by which
13512 \MP\ helps keep errors from propagating too far. Whenever the program goes
13513 into a mode where it keeps calling |get_next| repeatedly until a certain
13514 condition is met, it sets |scanner_status| to some value other than |normal|.
13515 Then if an input file ends, or if an `\&{outer}' symbol appears,
13516 an appropriate error recovery will be possible.
13518 The global variable |warning_info| helps in this error recovery by providing
13519 additional information. For example, |warning_info| might indicate the
13520 name of a macro whose replacement text is being scanned.
13522 @d normal 0 /* |scanner_status| at ``quiet times'' */
13523 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13524 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13525 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13526 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13527 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13528 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13529 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13532 integer scanner_status; /* are we scanning at high speed? */
13533 integer warning_info; /* if so, what else do we need to know,
13534 in case an error occurs? */
13536 @ @<Initialize the input routines@>=
13537 mp->scanner_status=normal;
13539 @ The following subroutine
13540 is called when an `\&{outer}' symbolic token has been scanned or
13541 when the end of a file has been reached. These two cases are distinguished
13542 by |cur_sym|, which is zero at the end of a file.
13544 @c boolean mp_check_outer_validity (MP mp) {
13545 pointer p; /* points to inserted token list */
13546 if ( mp->scanner_status==normal ) {
13548 } else if ( mp->scanner_status==tex_flushing ) {
13549 @<Check if the file has ended while flushing \TeX\ material and set the
13550 result value for |check_outer_validity|@>;
13552 mp->deletions_allowed=false;
13553 @<Back up an outer symbolic token so that it can be reread@>;
13554 if ( mp->scanner_status>skipping ) {
13555 @<Tell the user what has run away and try to recover@>;
13557 print_err("Incomplete if; all text was ignored after line ");
13558 @.Incomplete if...@>
13559 mp_print_int(mp, mp->warning_info);
13560 help3("A forbidden `outer' token occurred in skipped text.")
13561 ("This kind of error happens when you say `if...' and forget")
13562 ("the matching `fi'. I've inserted a `fi'; this might work.");
13563 if ( mp->cur_sym==0 )
13564 mp->help_line[2]="The file ended while I was skipping conditional text.";
13565 mp->cur_sym=frozen_fi; mp_ins_error(mp);
13567 mp->deletions_allowed=true;
13572 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13573 if ( mp->cur_sym!=0 ) {
13576 mp->deletions_allowed=false;
13577 print_err("TeX mode didn't end; all text was ignored after line ");
13578 mp_print_int(mp, mp->warning_info);
13579 help2("The file ended while I was looking for the `etex' to")
13580 ("finish this TeX material. I've inserted `etex' now.");
13581 mp->cur_sym = frozen_etex;
13583 mp->deletions_allowed=true;
13587 @ @<Back up an outer symbolic token so that it can be reread@>=
13588 if ( mp->cur_sym!=0 ) {
13589 p=mp_get_avail(mp); info(p)=mp->cur_sym;
13590 back_list(p); /* prepare to read the symbolic token again */
13593 @ @<Tell the user what has run away...@>=
13595 mp_runaway(mp); /* print the definition-so-far */
13596 if ( mp->cur_sym==0 ) {
13597 print_err("File ended");
13598 @.File ended while scanning...@>
13600 print_err("Forbidden token found");
13601 @.Forbidden token found...@>
13603 mp_print(mp, " while scanning ");
13604 help4("I suspect you have forgotten an `enddef',")
13605 ("causing me to read past where you wanted me to stop.")
13606 ("I'll try to recover; but if the error is serious,")
13607 ("you'd better type `E' or `X' now and fix your file.");
13608 switch (mp->scanner_status) {
13609 @<Complete the error message,
13610 and set |cur_sym| to a token that might help recover from the error@>
13611 } /* there are no other cases */
13615 @ As we consider various kinds of errors, it is also appropriate to
13616 change the first line of the help message just given; |help_line[3]|
13617 points to the string that might be changed.
13619 @<Complete the error message,...@>=
13621 mp_print(mp, "to the end of the statement");
13622 mp->help_line[3]="A previous error seems to have propagated,";
13623 mp->cur_sym=frozen_semicolon;
13626 mp_print(mp, "a text argument");
13627 mp->help_line[3]="It seems that a right delimiter was left out,";
13628 if ( mp->warning_info==0 ) {
13629 mp->cur_sym=frozen_end_group;
13631 mp->cur_sym=frozen_right_delimiter;
13632 equiv(frozen_right_delimiter)=mp->warning_info;
13637 mp_print(mp, "the definition of ");
13638 if ( mp->scanner_status==op_defining )
13639 mp_print_text(mp->warning_info);
13641 mp_print_variable_name(mp, mp->warning_info);
13642 mp->cur_sym=frozen_end_def;
13644 case loop_defining:
13645 mp_print(mp, "the text of a ");
13646 mp_print_text(mp->warning_info);
13647 mp_print(mp, " loop");
13648 mp->help_line[3]="I suspect you have forgotten an `endfor',";
13649 mp->cur_sym=frozen_end_for;
13652 @ The |runaway| procedure displays the first part of the text that occurred
13653 when \MP\ began its special |scanner_status|, if that text has been saved.
13655 @<Declare the procedure called |runaway|@>=
13656 void mp_runaway (MP mp) {
13657 if ( mp->scanner_status>flushing ) {
13658 mp_print_nl(mp, "Runaway ");
13659 switch (mp->scanner_status) {
13660 case absorbing: mp_print(mp, "text?"); break;
13662 case op_defining: mp_print(mp,"definition?"); break;
13663 case loop_defining: mp_print(mp, "loop?"); break;
13664 } /* there are no other cases */
13666 mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13670 @ We need to mention a procedure that may be called by |get_next|.
13673 void mp_firm_up_the_line (MP mp);
13675 @ And now we're ready to take the plunge into |get_next| itself.
13676 Note that the behavior depends on the |scanner_status| because percent signs
13677 and double quotes need to be passed over when skipping TeX material.
13680 void mp_get_next (MP mp) {
13681 /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13683 /*restart*/ /* go here to get the next input token */
13684 /*exit*/ /* go here when the next input token has been got */
13685 /*|common_ending|*/ /* go here to finish getting a symbolic token */
13686 /*found*/ /* go here when the end of a symbolic token has been found */
13687 /*switch*/ /* go here to branch on the class of an input character */
13688 /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13689 /* go here at crucial stages when scanning a number */
13690 int k; /* an index into |buffer| */
13691 ASCII_code c; /* the current character in the buffer */
13692 ASCII_code class; /* its class number */
13693 integer n,f; /* registers for decimal-to-binary conversion */
13696 if ( file_state ) {
13697 @<Input from external file; |goto restart| if no input found,
13698 or |return| if a non-symbolic token is found@>;
13700 @<Input from token list; |goto restart| if end of list or
13701 if a parameter needs to be expanded,
13702 or |return| if a non-symbolic token is found@>;
13705 @<Finish getting the symbolic token in |cur_sym|;
13706 |goto restart| if it is illegal@>;
13709 @ When a symbolic token is declared to be `\&{outer}', its command code
13710 is increased by |outer_tag|.
13713 @<Finish getting the symbolic token in |cur_sym|...@>=
13714 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13715 if ( mp->cur_cmd>=outer_tag ) {
13716 if ( mp_check_outer_validity(mp) )
13717 mp->cur_cmd=mp->cur_cmd-outer_tag;
13722 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13723 to have a special test for end-of-line.
13726 @<Input from external file;...@>=
13729 c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13731 case digit_class: goto START_NUMERIC_TOKEN; break;
13733 class=mp->char_class[mp->buffer[loc]];
13734 if ( class>period_class ) {
13736 } else if ( class<period_class ) { /* |class=digit_class| */
13737 n=0; goto START_DECIMAL_TOKEN;
13741 case space_class: goto SWITCH; break;
13742 case percent_class:
13743 if ( mp->scanner_status==tex_flushing ) {
13744 if ( loc<limit ) goto SWITCH;
13746 @<Move to next line of file, or |goto restart| if there is no next line@>;
13751 if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13752 else @<Get a string token and |return|@>;
13754 case isolated_classes:
13755 k=loc-1; goto FOUND; break;
13756 case invalid_class:
13757 if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13758 else @<Decry the invalid character and |goto restart|@>;
13760 default: break; /* letters, etc. */
13763 while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13765 START_NUMERIC_TOKEN:
13766 @<Get the integer part |n| of a numeric token;
13767 set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13768 START_DECIMAL_TOKEN:
13769 @<Get the fraction part |f| of a numeric token@>;
13771 @<Pack the numeric and fraction parts of a numeric token
13774 mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13777 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13778 |token_list| after the error has been dealt with
13779 (cf.\ |clear_for_error_prompt|).
13781 @<Decry the invalid...@>=
13783 print_err("Text line contains an invalid character");
13784 @.Text line contains...@>
13785 help2("A funny symbol that I can\'t read has just been input.")
13786 ("Continue, and I'll forget that it ever happened.");
13787 mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13791 @ @<Get a string token and |return|@>=
13793 if ( mp->buffer[loc]=='"' ) {
13794 mp->cur_mod=rts("");
13796 k=loc; mp->buffer[limit+1]='"';
13799 } while (mp->buffer[loc]!='"');
13801 @<Decry the missing string delimiter and |goto restart|@>;
13804 mp->cur_mod=mp->buffer[k];
13808 append_char(mp->buffer[k]); incr(k);
13810 mp->cur_mod=mp_make_string(mp);
13813 incr(loc); mp->cur_cmd=string_token;
13817 @ We go to |restart| after this error message, not to |SWITCH|,
13818 because the |clear_for_error_prompt| routine might have reinstated
13819 |token_state| after |error| has finished.
13821 @<Decry the missing string delimiter and |goto restart|@>=
13823 loc=limit; /* the next character to be read on this line will be |"%"| */
13824 print_err("Incomplete string token has been flushed");
13825 @.Incomplete string token...@>
13826 help3("Strings should finish on the same line as they began.")
13827 ("I've deleted the partial string; you might want to")
13828 ("insert another by typing, e.g., `I\"new string\"'.");
13829 mp->deletions_allowed=false; mp_error(mp);
13830 mp->deletions_allowed=true;
13834 @ @<Get the integer part |n| of a numeric token...@>=
13836 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13837 if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13840 if ( mp->buffer[loc]=='.' )
13841 if ( mp->char_class[mp->buffer[loc+1]]==digit_class )
13844 goto FIN_NUMERIC_TOKEN;
13847 @ @<Get the fraction part |f| of a numeric token@>=
13850 if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13851 mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13854 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13855 f=mp_round_decimals(mp, k);
13860 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13862 @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13863 } else if ( mp->scanner_status!=tex_flushing ) {
13864 print_err("Enormous number has been reduced");
13865 @.Enormous number...@>
13866 help2("I can\'t handle numbers bigger than 32767.99998;")
13867 ("so I've changed your constant to that maximum amount.");
13868 mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13869 mp->cur_mod=el_gordo;
13871 mp->cur_cmd=numeric_token; return
13873 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13875 mp->cur_mod=n*unity+f;
13876 if ( mp->cur_mod>=fraction_one ) {
13877 if ( (mp->internal[mp_warning_check]>0) &&
13878 (mp->scanner_status!=tex_flushing) ) {
13879 print_err("Number is too large (");
13880 mp_print_scaled(mp, mp->cur_mod);
13881 mp_print_char(mp, ')');
13882 help3("It is at least 4096. Continue and I'll try to cope")
13883 ("with that big value; but it might be dangerous.")
13884 ("(Set warningcheck:=0 to suppress this message.)");
13890 @ Let's consider now what happens when |get_next| is looking at a token list.
13893 @<Input from token list;...@>=
13894 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13895 mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13896 if ( mp->cur_sym>=expr_base ) {
13897 if ( mp->cur_sym>=suffix_base ) {
13898 @<Insert a suffix or text parameter and |goto restart|@>;
13900 mp->cur_cmd=capsule_token;
13901 mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13902 mp->cur_sym=0; return;
13905 } else if ( loc>null ) {
13906 @<Get a stored numeric or string or capsule token and |return|@>
13907 } else { /* we are done with this token list */
13908 mp_end_token_list(mp); goto RESTART; /* resume previous level */
13911 @ @<Insert a suffix or text parameter...@>=
13913 if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13914 /* |param_size=text_base-suffix_base| */
13915 mp_begin_token_list(mp,
13916 mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13921 @ @<Get a stored numeric or string or capsule token...@>=
13923 if ( name_type(loc)==mp_token ) {
13924 mp->cur_mod=value(loc);
13925 if ( type(loc)==mp_known ) {
13926 mp->cur_cmd=numeric_token;
13928 mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13931 mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13933 loc=link(loc); return;
13936 @ All of the easy branches of |get_next| have now been taken care of.
13937 There is one more branch.
13939 @<Move to next line of file, or |goto restart|...@>=
13940 if ( name>max_spec_src ) {
13941 @<Read next line of file into |buffer|, or
13942 |goto restart| if the file has ended@>;
13944 if ( mp->input_ptr>0 ) {
13945 /* text was inserted during error recovery or by \&{scantokens} */
13946 mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13948 if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13949 if ( mp->interaction>mp_nonstop_mode ) {
13950 if ( limit==start ) /* previous line was empty */
13951 mp_print_nl(mp, "(Please type a command or say `end')");
13953 mp_print_ln(mp); mp->first=start;
13954 prompt_input("*"); /* input on-line into |buffer| */
13956 limit=mp->last; mp->buffer[limit]='%';
13957 mp->first=limit+1; loc=start;
13959 mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13961 /* nonstop mode, which is intended for overnight batch processing,
13962 never waits for on-line input */
13966 @ The global variable |force_eof| is normally |false|; it is set |true|
13967 by an \&{endinput} command.
13970 boolean force_eof; /* should the next \&{input} be aborted early? */
13972 @ We must decrement |loc| in order to leave the buffer in a valid state
13973 when an error condition causes us to |goto restart| without calling
13974 |end_file_reading|.
13976 @<Read next line of file into |buffer|, or
13977 |goto restart| if the file has ended@>=
13979 incr(line); mp->first=start;
13980 if ( ! mp->force_eof ) {
13981 if ( mp_input_ln(mp, cur_file,true) ) /* not end of file */
13982 mp_firm_up_the_line(mp); /* this sets |limit| */
13984 mp->force_eof=true;
13986 if ( mp->force_eof ) {
13987 mp->force_eof=false;
13989 if ( mpx_reading ) {
13990 @<Complain that the \.{MPX} file ended unexpectly; then set
13991 |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13993 mp_print_char(mp, ')'); decr(mp->open_parens);
13994 update_terminal; /* show user that file has been read */
13995 mp_end_file_reading(mp); /* resume previous level */
13996 if ( mp_check_outer_validity(mp) ) goto RESTART;
14000 mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
14003 @ We should never actually come to the end of an \.{MPX} file because such
14004 files should have an \&{mpxbreak} after the translation of the last
14005 \&{btex}$\,\ldots\,$\&{etex} block.
14007 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
14009 mp->mpx_name[index]=finished;
14010 print_err("mpx file ended unexpectedly");
14011 help4("The file had too few picture expressions for btex...etex")
14012 ("blocks. Such files are normally generated automatically")
14013 ("but this one got messed up. You might want to insert a")
14014 ("picture expression now.");
14015 mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
14016 mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
14019 @ Sometimes we want to make it look as though we have just read a blank line
14020 without really doing so.
14022 @<Put an empty line in the input buffer@>=
14023 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
14024 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
14026 @ If the user has set the |mp_pausing| parameter to some positive value,
14027 and if nonstop mode has not been selected, each line of input is displayed
14028 on the terminal and the transcript file, followed by `\.{=>}'.
14029 \MP\ waits for a response. If the response is null (i.e., if nothing is
14030 typed except perhaps a few blank spaces), the original
14031 line is accepted as it stands; otherwise the line typed is
14032 used instead of the line in the file.
14034 @c void mp_firm_up_the_line (MP mp) {
14035 size_t k; /* an index into |buffer| */
14037 if ( mp->internal[mp_pausing]>0 ) if ( mp->interaction>mp_nonstop_mode ) {
14038 wake_up_terminal; mp_print_ln(mp);
14039 if ( start<limit ) {
14040 for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
14041 mp_print_str(mp, mp->buffer[k]);
14044 mp->first=limit; prompt_input("=>"); /* wait for user response */
14046 if ( mp->last>mp->first ) {
14047 for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
14048 mp->buffer[k+start-mp->first]=mp->buffer[k];
14050 limit=start+mp->last-mp->first;
14055 @* \[30] Dealing with \TeX\ material.
14056 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
14057 features need to be implemented at a low level in the scanning process
14058 so that \MP\ can stay in synch with the a preprocessor that treats
14059 blocks of \TeX\ material as they occur in the input file without trying
14060 to expand \MP\ macros. Thus we need a special version of |get_next|
14061 that does not expand macros and such but does handle \&{btex},
14062 \&{verbatimtex}, etc.
14064 The special version of |get_next| is called |get_t_next|. It works by flushing
14065 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
14066 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
14067 \&{btex}, and switching back when it sees \&{mpxbreak}.
14073 mp_primitive(mp, "btex",start_tex,btex_code);
14074 @:btex_}{\&{btex} primitive@>
14075 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14076 @:verbatimtex_}{\&{verbatimtex} primitive@>
14077 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14078 @:etex_}{\&{etex} primitive@>
14079 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14080 @:mpx_break_}{\&{mpxbreak} primitive@>
14082 @ @<Cases of |print_cmd...@>=
14083 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14084 else mp_print(mp, "verbatimtex"); break;
14085 case etex_marker: mp_print(mp, "etex"); break;
14086 case mpx_break: mp_print(mp, "mpxbreak"); break;
14088 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14089 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14092 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14095 void mp_start_mpx_input (MP mp);
14098 void mp_t_next (MP mp) {
14099 int old_status; /* saves the |scanner_status| */
14100 integer old_info; /* saves the |warning_info| */
14101 while ( mp->cur_cmd<=max_pre_command ) {
14102 if ( mp->cur_cmd==mpx_break ) {
14103 if ( ! file_state || (mp->mpx_name[index]==absent) ) {
14104 @<Complain about a misplaced \&{mpxbreak}@>;
14106 mp_end_mpx_reading(mp);
14109 } else if ( mp->cur_cmd==start_tex ) {
14110 if ( token_state || (name<=max_spec_src) ) {
14111 @<Complain that we are not reading a file@>;
14112 } else if ( mpx_reading ) {
14113 @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14114 } else if ( (mp->cur_mod!=verbatim_code)&&
14115 (mp->mpx_name[index]!=finished) ) {
14116 if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14121 @<Complain about a misplaced \&{etex}@>;
14123 goto COMMON_ENDING;
14125 @<Flush the \TeX\ material@>;
14131 @ We could be in the middle of an operation such as skipping false conditional
14132 text when \TeX\ material is encountered, so we must be careful to save the
14135 @<Flush the \TeX\ material@>=
14136 old_status=mp->scanner_status;
14137 old_info=mp->warning_info;
14138 mp->scanner_status=tex_flushing;
14139 mp->warning_info=line;
14140 do { mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14141 mp->scanner_status=old_status;
14142 mp->warning_info=old_info
14144 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14145 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14146 help4("This file contains picture expressions for btex...etex")
14147 ("blocks. Such files are normally generated automatically")
14148 ("but this one seems to be messed up. I'll just keep going")
14149 ("and hope for the best.");
14153 @ @<Complain that we are not reading a file@>=
14154 { print_err("You can only use `btex' or `verbatimtex' in a file");
14155 help3("I'll have to ignore this preprocessor command because it")
14156 ("only works when there is a file to preprocess. You might")
14157 ("want to delete everything up to the next `etex`.");
14161 @ @<Complain about a misplaced \&{mpxbreak}@>=
14162 { print_err("Misplaced mpxbreak");
14163 help2("I'll ignore this preprocessor command because it")
14164 ("doesn't belong here");
14168 @ @<Complain about a misplaced \&{etex}@>=
14169 { print_err("Extra etex will be ignored");
14170 help1("There is no btex or verbatimtex for this to match");
14174 @* \[31] Scanning macro definitions.
14175 \MP\ has a variety of ways to tuck tokens away into token lists for later
14176 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14177 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14178 All such operations are handled by the routines in this part of the program.
14180 The modifier part of each command code is zero for the ``ending delimiters''
14181 like \&{enddef} and \&{endfor}.
14183 @d start_def 1 /* command modifier for \&{def} */
14184 @d var_def 2 /* command modifier for \&{vardef} */
14185 @d end_def 0 /* command modifier for \&{enddef} */
14186 @d start_forever 1 /* command modifier for \&{forever} */
14187 @d end_for 0 /* command modifier for \&{endfor} */
14190 mp_primitive(mp, "def",macro_def,start_def);
14191 @:def_}{\&{def} primitive@>
14192 mp_primitive(mp, "vardef",macro_def,var_def);
14193 @:var_def_}{\&{vardef} primitive@>
14194 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14195 @:primary_def_}{\&{primarydef} primitive@>
14196 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14197 @:secondary_def_}{\&{secondarydef} primitive@>
14198 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14199 @:tertiary_def_}{\&{tertiarydef} primitive@>
14200 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14201 @:end_def_}{\&{enddef} primitive@>
14203 mp_primitive(mp, "for",iteration,expr_base);
14204 @:for_}{\&{for} primitive@>
14205 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14206 @:for_suffixes_}{\&{forsuffixes} primitive@>
14207 mp_primitive(mp, "forever",iteration,start_forever);
14208 @:forever_}{\&{forever} primitive@>
14209 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14210 @:end_for_}{\&{endfor} primitive@>
14212 @ @<Cases of |print_cmd...@>=
14214 if ( m<=var_def ) {
14215 if ( m==start_def ) mp_print(mp, "def");
14216 else if ( m<start_def ) mp_print(mp, "enddef");
14217 else mp_print(mp, "vardef");
14218 } else if ( m==secondary_primary_macro ) {
14219 mp_print(mp, "primarydef");
14220 } else if ( m==tertiary_secondary_macro ) {
14221 mp_print(mp, "secondarydef");
14223 mp_print(mp, "tertiarydef");
14227 if ( m<=start_forever ) {
14228 if ( m==start_forever ) mp_print(mp, "forever");
14229 else mp_print(mp, "endfor");
14230 } else if ( m==expr_base ) {
14231 mp_print(mp, "for");
14233 mp_print(mp, "forsuffixes");
14237 @ Different macro-absorbing operations have different syntaxes, but they
14238 also have a lot in common. There is a list of special symbols that are to
14239 be replaced by parameter tokens; there is a special command code that
14240 ends the definition; the quotation conventions are identical. Therefore
14241 it makes sense to have most of the work done by a single subroutine. That
14242 subroutine is called |scan_toks|.
14244 The first parameter to |scan_toks| is the command code that will
14245 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14247 The second parameter, |subst_list|, points to a (possibly empty) list
14248 of two-word nodes whose |info| and |value| fields specify symbol tokens
14249 before and after replacement. The list will be returned to free storage
14252 The third parameter is simply appended to the token list that is built.
14253 And the final parameter tells how many of the special operations
14254 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14255 When such parameters are present, they are called \.{(SUFFIX0)},
14256 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14258 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer
14259 subst_list, pointer tail_end, small_number suffix_count) {
14260 pointer p; /* tail of the token list being built */
14261 pointer q; /* temporary for link management */
14262 integer balance; /* left delimiters minus right delimiters */
14263 p=hold_head; balance=1; link(hold_head)=null;
14266 if ( mp->cur_sym>0 ) {
14267 @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14268 if ( mp->cur_cmd==terminator ) {
14269 @<Adjust the balance; |break| if it's zero@>;
14270 } else if ( mp->cur_cmd==macro_special ) {
14271 @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14274 link(p)=mp_cur_tok(mp); p=link(p);
14276 link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14277 return link(hold_head);
14280 @ @<Substitute for |cur_sym|...@>=
14283 while ( q!=null ) {
14284 if ( info(q)==mp->cur_sym ) {
14285 mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14291 @ @<Adjust the balance; |break| if it's zero@>=
14292 if ( mp->cur_mod>0 ) {
14300 @ Four commands are intended to be used only within macro texts: \&{quote},
14301 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14302 code called |macro_special|.
14304 @d quote 0 /* |macro_special| modifier for \&{quote} */
14305 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14306 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14307 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14310 mp_primitive(mp, "quote",macro_special,quote);
14311 @:quote_}{\&{quote} primitive@>
14312 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14313 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14314 mp_primitive(mp, "@@",macro_special,macro_at);
14315 @:]]]\AT!_}{\.{\AT!} primitive@>
14316 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14317 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14319 @ @<Cases of |print_cmd...@>=
14320 case macro_special:
14322 case macro_prefix: mp_print(mp, "#@@"); break;
14323 case macro_at: mp_print_char(mp, '@@'); break;
14324 case macro_suffix: mp_print(mp, "@@#"); break;
14325 default: mp_print(mp, "quote"); break;
14329 @ @<Handle quoted...@>=
14331 if ( mp->cur_mod==quote ) { get_t_next; }
14332 else if ( mp->cur_mod<=suffix_count )
14333 mp->cur_sym=suffix_base-1+mp->cur_mod;
14336 @ Here is a routine that's used whenever a token will be redefined. If
14337 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14338 substituted; the latter is redefinable but essentially impossible to use,
14339 hence \MP's tables won't get fouled up.
14341 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14344 if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14345 print_err("Missing symbolic token inserted");
14346 @.Missing symbolic token...@>
14347 help3("Sorry: You can\'t redefine a number, string, or expr.")
14348 ("I've inserted an inaccessible symbol so that your")
14349 ("definition will be completed without mixing me up too badly.");
14350 if ( mp->cur_sym>0 )
14351 mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14352 else if ( mp->cur_cmd==string_token )
14353 delete_str_ref(mp->cur_mod);
14354 mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14358 @ Before we actually redefine a symbolic token, we need to clear away its
14359 former value, if it was a variable. The following stronger version of
14360 |get_symbol| does that.
14362 @c void mp_get_clear_symbol (MP mp) {
14363 mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14366 @ Here's another little subroutine; it checks that an equals sign
14367 or assignment sign comes along at the proper place in a macro definition.
14369 @c void mp_check_equals (MP mp) {
14370 if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14371 mp_missing_err(mp, "=");
14373 help5("The next thing in this `def' should have been `=',")
14374 ("because I've already looked at the definition heading.")
14375 ("But don't worry; I'll pretend that an equals sign")
14376 ("was present. Everything from here to `enddef'")
14377 ("will be the replacement text of this macro.");
14382 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14383 handled now that we have |scan_toks|. In this case there are
14384 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14385 |expr_base| and |expr_base+1|).
14387 @c void mp_make_op_def (MP mp) {
14388 command_code m; /* the type of definition */
14389 pointer p,q,r; /* for list manipulation */
14391 mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14392 info(q)=mp->cur_sym; value(q)=expr_base;
14393 mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14394 mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14395 info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14396 get_t_next; mp_check_equals(mp);
14397 mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14398 r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14399 link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14400 mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14401 equiv(mp->warning_info)=q; mp_get_x_next(mp);
14404 @ Parameters to macros are introduced by the keywords \&{expr},
14405 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14408 mp_primitive(mp, "expr",param_type,expr_base);
14409 @:expr_}{\&{expr} primitive@>
14410 mp_primitive(mp, "suffix",param_type,suffix_base);
14411 @:suffix_}{\&{suffix} primitive@>
14412 mp_primitive(mp, "text",param_type,text_base);
14413 @:text_}{\&{text} primitive@>
14414 mp_primitive(mp, "primary",param_type,primary_macro);
14415 @:primary_}{\&{primary} primitive@>
14416 mp_primitive(mp, "secondary",param_type,secondary_macro);
14417 @:secondary_}{\&{secondary} primitive@>
14418 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14419 @:tertiary_}{\&{tertiary} primitive@>
14421 @ @<Cases of |print_cmd...@>=
14423 if ( m>=expr_base ) {
14424 if ( m==expr_base ) mp_print(mp, "expr");
14425 else if ( m==suffix_base ) mp_print(mp, "suffix");
14426 else mp_print(mp, "text");
14427 } else if ( m<secondary_macro ) {
14428 mp_print(mp, "primary");
14429 } else if ( m==secondary_macro ) {
14430 mp_print(mp, "secondary");
14432 mp_print(mp, "tertiary");
14436 @ Let's turn next to the more complex processing associated with \&{def}
14437 and \&{vardef}. When the following procedure is called, |cur_mod|
14438 should be either |start_def| or |var_def|.
14440 @c @<Declare the procedure called |check_delimiter|@>;
14441 @<Declare the function called |scan_declared_variable|@>;
14442 void mp_scan_def (MP mp) {
14443 int m; /* the type of definition */
14444 int n; /* the number of special suffix parameters */
14445 int k; /* the total number of parameters */
14446 int c; /* the kind of macro we're defining */
14447 pointer r; /* parameter-substitution list */
14448 pointer q; /* tail of the macro token list */
14449 pointer p; /* temporary storage */
14450 halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14451 pointer l_delim,r_delim; /* matching delimiters */
14452 m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14453 q=mp_get_avail(mp); ref_count(q)=null; r=null;
14454 @<Scan the token or variable to be defined;
14455 set |n|, |scanner_status|, and |warning_info|@>;
14457 if ( mp->cur_cmd==left_delimiter ) {
14458 @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14460 if ( mp->cur_cmd==param_type ) {
14461 @<Absorb undelimited parameters, putting them into list |r|@>;
14463 mp_check_equals(mp);
14464 p=mp_get_avail(mp); info(p)=c; link(q)=p;
14465 @<Attach the replacement text to the tail of node |p|@>;
14466 mp->scanner_status=normal; mp_get_x_next(mp);
14469 @ We don't put `|frozen_end_group|' into the replacement text of
14470 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14472 @<Attach the replacement text to the tail of node |p|@>=
14473 if ( m==start_def ) {
14474 link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14476 q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14477 p=mp_get_avail(mp); info(p)=mp->eg_loc;
14478 link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14480 if ( mp->warning_info==bad_vardef )
14481 mp_flush_token_list(mp, value(bad_vardef))
14485 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14487 @ @<Scan the token or variable to be defined;...@>=
14488 if ( m==start_def ) {
14489 mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14490 mp->scanner_status=op_defining; n=0;
14491 eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14493 p=mp_scan_declared_variable(mp);
14494 mp_flush_variable(mp, equiv(info(p)),link(p),true);
14495 mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14496 if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14497 mp->scanner_status=var_defining; n=2;
14498 if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14501 type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14502 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14504 @ @<Change to `\.{a bad variable}'@>=
14506 print_err("This variable already starts with a macro");
14507 @.This variable already...@>
14508 help2("After `vardef a' you can\'t say `vardef a.b'.")
14509 ("So I'll have to discard this definition.");
14510 mp_error(mp); mp->warning_info=bad_vardef;
14513 @ @<Initialize table entries...@>=
14514 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14515 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14517 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14519 l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14520 if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14523 print_err("Missing parameter type; `expr' will be assumed");
14524 @.Missing parameter type@>
14525 help1("You should've had `expr' or `suffix' or `text' here.");
14526 mp_back_error(mp); base=expr_base;
14528 @<Absorb parameter tokens for type |base|@>;
14529 mp_check_delimiter(mp, l_delim,r_delim);
14531 } while (mp->cur_cmd==left_delimiter)
14533 @ @<Absorb parameter tokens for type |base|@>=
14535 link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14536 mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14537 value(p)=base+k; info(p)=mp->cur_sym;
14538 if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14539 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14540 incr(k); link(p)=r; r=p; get_t_next;
14541 } while (mp->cur_cmd==comma)
14543 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14545 p=mp_get_node(mp, token_node_size);
14546 if ( mp->cur_mod<expr_base ) {
14547 c=mp->cur_mod; value(p)=expr_base+k;
14549 value(p)=mp->cur_mod+k;
14550 if ( mp->cur_mod==expr_base ) c=expr_macro;
14551 else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14554 if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14555 incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14556 if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14557 c=of_macro; p=mp_get_node(mp, token_node_size);
14558 if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14559 value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14560 link(p)=r; r=p; get_t_next;
14564 @* \[32] Expanding the next token.
14565 Only a few command codes |<min_command| can possibly be returned by
14566 |get_t_next|; in increasing order, they are
14567 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14568 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14570 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14571 like |get_t_next| except that it keeps getting more tokens until
14572 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14573 macros and removes conditionals or iterations or input instructions that
14576 It follows that |get_x_next| might invoke itself recursively. In fact,
14577 there is massive recursion, since macro expansion can involve the
14578 scanning of arbitrarily complex expressions, which in turn involve
14579 macro expansion and conditionals, etc.
14582 Therefore it's necessary to declare a whole bunch of |forward|
14583 procedures at this point, and to insert some other procedures
14584 that will be invoked by |get_x_next|.
14587 void mp_scan_primary (MP mp);
14588 void mp_scan_secondary (MP mp);
14589 void mp_scan_tertiary (MP mp);
14590 void mp_scan_expression (MP mp);
14591 void mp_scan_suffix (MP mp);
14592 @<Declare the procedure called |macro_call|@>;
14593 void mp_get_boolean (MP mp);
14594 void mp_pass_text (MP mp);
14595 void mp_conditional (MP mp);
14596 void mp_start_input (MP mp);
14597 void mp_begin_iteration (MP mp);
14598 void mp_resume_iteration (MP mp);
14599 void mp_stop_iteration (MP mp);
14601 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14602 when it has to do exotic expansion commands.
14604 @c void mp_expand (MP mp) {
14605 pointer p; /* for list manipulation */
14606 size_t k; /* something that we hope is |<=buf_size| */
14607 pool_pointer j; /* index into |str_pool| */
14608 if ( mp->internal[mp_tracing_commands]>unity )
14609 if ( mp->cur_cmd!=defined_macro )
14611 switch (mp->cur_cmd) {
14613 mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14616 @<Terminate the current conditional and skip to \&{fi}@>;
14619 @<Initiate or terminate input from a file@>;
14622 if ( mp->cur_mod==end_for ) {
14623 @<Scold the user for having an extra \&{endfor}@>;
14625 mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14632 @<Exit a loop if the proper time has come@>;
14637 @<Expand the token after the next token@>;
14640 @<Put a string into the input buffer@>;
14642 case defined_macro:
14643 mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14645 }; /* there are no other cases */
14648 @ @<Scold the user...@>=
14650 print_err("Extra `endfor'");
14652 help2("I'm not currently working on a for loop,")
14653 ("so I had better not try to end anything.");
14657 @ The processing of \&{input} involves the |start_input| subroutine,
14658 which will be declared later; the processing of \&{endinput} is trivial.
14661 mp_primitive(mp, "input",input,0);
14662 @:input_}{\&{input} primitive@>
14663 mp_primitive(mp, "endinput",input,1);
14664 @:end_input_}{\&{endinput} primitive@>
14666 @ @<Cases of |print_cmd_mod|...@>=
14668 if ( m==0 ) mp_print(mp, "input");
14669 else mp_print(mp, "endinput");
14672 @ @<Initiate or terminate input...@>=
14673 if ( mp->cur_mod>0 ) mp->force_eof=true;
14674 else mp_start_input(mp)
14676 @ We'll discuss the complicated parts of loop operations later. For now
14677 it suffices to know that there's a global variable called |loop_ptr|
14678 that will be |null| if no loop is in progress.
14681 { while ( token_state &&(loc==null) )
14682 mp_end_token_list(mp); /* conserve stack space */
14683 if ( mp->loop_ptr==null ) {
14684 print_err("Lost loop");
14686 help2("I'm confused; after exiting from a loop, I still seem")
14687 ("to want to repeat it. I'll try to forget the problem.");
14690 mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14694 @ @<Exit a loop if the proper time has come@>=
14695 { mp_get_boolean(mp);
14696 if ( mp->internal[mp_tracing_commands]>unity )
14697 mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14698 if ( mp->cur_exp==true_code ) {
14699 if ( mp->loop_ptr==null ) {
14700 print_err("No loop is in progress");
14701 @.No loop is in progress@>
14702 help1("Why say `exitif' when there's nothing to exit from?");
14703 if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14705 @<Exit prematurely from an iteration@>;
14707 } else if ( mp->cur_cmd!=semicolon ) {
14708 mp_missing_err(mp, ";");
14710 help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14711 ("I shall pretend that one was there."); mp_back_error(mp);
14715 @ Here we use the fact that |forever_text| is the only |token_type| that
14716 is less than |loop_text|.
14718 @<Exit prematurely...@>=
14721 if ( file_state ) {
14722 mp_end_file_reading(mp);
14724 if ( token_type<=loop_text ) p=start;
14725 mp_end_token_list(mp);
14728 if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14730 mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14733 @ @<Expand the token after the next token@>=
14735 p=mp_cur_tok(mp); get_t_next;
14736 if ( mp->cur_cmd<min_command ) mp_expand(mp);
14737 else mp_back_input(mp);
14741 @ @<Put a string into the input buffer@>=
14742 { mp_get_x_next(mp); mp_scan_primary(mp);
14743 if ( mp->cur_type!=mp_string_type ) {
14744 mp_disp_err(mp, null,"Not a string");
14746 help2("I'm going to flush this expression, since")
14747 ("scantokens should be followed by a known string.");
14748 mp_put_get_flush_error(mp, 0);
14751 if ( length(mp->cur_exp)>0 )
14752 @<Pretend we're reading a new one-line file@>;
14756 @ @<Pretend we're reading a new one-line file@>=
14757 { mp_begin_file_reading(mp); name=is_scantok;
14758 k=mp->first+length(mp->cur_exp);
14759 if ( k>=mp->max_buf_stack ) {
14760 while ( k>=mp->buf_size ) {
14761 mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14763 mp->max_buf_stack=k+1;
14765 j=mp->str_start[mp->cur_exp]; limit=k;
14766 while ( mp->first<(size_t)limit ) {
14767 mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14769 mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
14770 mp_flush_cur_exp(mp, 0);
14773 @ Here finally is |get_x_next|.
14775 The expression scanning routines to be considered later
14776 communicate via the global quantities |cur_type| and |cur_exp|;
14777 we must be very careful to save and restore these quantities while
14778 macros are being expanded.
14782 void mp_get_x_next (MP mp);
14784 @ @c void mp_get_x_next (MP mp) {
14785 pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14787 if ( mp->cur_cmd<min_command ) {
14788 save_exp=mp_stash_cur_exp(mp);
14790 if ( mp->cur_cmd==defined_macro )
14791 mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14795 } while (mp->cur_cmd<min_command);
14796 mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14800 @ Now let's consider the |macro_call| procedure, which is used to start up
14801 all user-defined macros. Since the arguments to a macro might be expressions,
14802 |macro_call| is recursive.
14805 The first parameter to |macro_call| points to the reference count of the
14806 token list that defines the macro. The second parameter contains any
14807 arguments that have already been parsed (see below). The third parameter
14808 points to the symbolic token that names the macro. If the third parameter
14809 is |null|, the macro was defined by \&{vardef}, so its name can be
14810 reconstructed from the prefix and ``at'' arguments found within the
14813 What is this second parameter? It's simply a linked list of one-word items,
14814 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14815 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14816 the first scanned argument, and |link(arg_list)| points to the list of
14817 further arguments (if any).
14819 Arguments of type \&{expr} are so-called capsules, which we will
14820 discuss later when we concentrate on expressions; they can be
14821 recognized easily because their |link| field is |void|. Arguments of type
14822 \&{suffix} and \&{text} are token lists without reference counts.
14824 @ After argument scanning is complete, the arguments are moved to the
14825 |param_stack|. (They can't be put on that stack any sooner, because
14826 the stack is growing and shrinking in unpredictable ways as more arguments
14827 are being acquired.) Then the macro body is fed to the scanner; i.e.,
14828 the replacement text of the macro is placed at the top of the \MP's
14829 input stack, so that |get_t_next| will proceed to read it next.
14831 @<Declare the procedure called |macro_call|@>=
14832 @<Declare the procedure called |print_macro_name|@>;
14833 @<Declare the procedure called |print_arg|@>;
14834 @<Declare the procedure called |scan_text_arg|@>;
14835 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list,
14836 pointer macro_name) ;
14839 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list,
14840 pointer macro_name) {
14841 /* invokes a user-defined control sequence */
14842 pointer r; /* current node in the macro's token list */
14843 pointer p,q; /* for list manipulation */
14844 integer n; /* the number of arguments */
14845 pointer tail = 0; /* tail of the argument list */
14846 pointer l_delim=0,r_delim=0; /* a delimiter pair */
14847 r=link(def_ref); add_mac_ref(def_ref);
14848 if ( arg_list==null ) {
14851 @<Determine the number |n| of arguments already supplied,
14852 and set |tail| to the tail of |arg_list|@>;
14854 if ( mp->internal[mp_tracing_macros]>0 ) {
14855 @<Show the text of the macro being expanded, and the existing arguments@>;
14857 @<Scan the remaining arguments, if any; set |r| to the first token
14858 of the replacement text@>;
14859 @<Feed the arguments and replacement text to the scanner@>;
14862 @ @<Show the text of the macro...@>=
14863 mp_begin_diagnostic(mp); mp_print_ln(mp);
14864 mp_print_macro_name(mp, arg_list,macro_name);
14865 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14866 mp_show_macro(mp, def_ref,null,100000);
14867 if ( arg_list!=null ) {
14871 mp_print_arg(mp, q,n,0);
14872 incr(n); p=link(p);
14875 mp_end_diagnostic(mp, false)
14878 @ @<Declare the procedure called |print_macro_name|@>=
14879 void mp_print_macro_name (MP mp,pointer a, pointer n);
14882 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14883 pointer p,q; /* they traverse the first part of |a| */
14889 mp_print_text(info(info(link(a))));
14892 while ( link(q)!=null ) q=link(q);
14893 link(q)=info(link(a));
14894 mp_show_token_list(mp, p,null,1000,0);
14900 @ @<Declare the procedure called |print_arg|@>=
14901 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14904 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14905 if ( link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
14906 else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14907 else mp_print_nl(mp, "(TEXT");
14908 mp_print_int(mp, n); mp_print(mp, ")<-");
14909 if ( link(q)==mp_void ) mp_print_exp(mp, q,1);
14910 else mp_show_token_list(mp, q,null,1000,0);
14913 @ @<Determine the number |n| of arguments already supplied...@>=
14915 n=1; tail=arg_list;
14916 while ( link(tail)!=null ) {
14917 incr(n); tail=link(tail);
14921 @ @<Scan the remaining arguments, if any; set |r|...@>=
14922 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14923 while ( info(r)>=expr_base ) {
14924 @<Scan the delimited argument represented by |info(r)|@>;
14927 if ( mp->cur_cmd==comma ) {
14928 print_err("Too many arguments to ");
14929 @.Too many arguments...@>
14930 mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14931 mp_print_nl(mp, " Missing `"); mp_print_text(r_delim);
14933 mp_print(mp, "' has been inserted");
14934 help3("I'm going to assume that the comma I just read was a")
14935 ("right delimiter, and then I'll begin expanding the macro.")
14936 ("You might want to delete some tokens before continuing.");
14939 if ( info(r)!=general_macro ) {
14940 @<Scan undelimited argument(s)@>;
14944 @ At this point, the reader will find it advisable to review the explanation
14945 of token list format that was presented earlier, paying special attention to
14946 the conventions that apply only at the beginning of a macro's token list.
14948 On the other hand, the reader will have to take the expression-parsing
14949 aspects of the following program on faith; we will explain |cur_type|
14950 and |cur_exp| later. (Several things in this program depend on each other,
14951 and it's necessary to jump into the circle somewhere.)
14953 @<Scan the delimited argument represented by |info(r)|@>=
14954 if ( mp->cur_cmd!=comma ) {
14956 if ( mp->cur_cmd!=left_delimiter ) {
14957 print_err("Missing argument to ");
14958 @.Missing argument...@>
14959 mp_print_macro_name(mp, arg_list,macro_name);
14960 help3("That macro has more parameters than you thought.")
14961 ("I'll continue by pretending that each missing argument")
14962 ("is either zero or null.");
14963 if ( info(r)>=suffix_base ) {
14964 mp->cur_exp=null; mp->cur_type=mp_token_list;
14966 mp->cur_exp=0; mp->cur_type=mp_known;
14968 mp_back_error(mp); mp->cur_cmd=right_delimiter;
14971 l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14973 @<Scan the argument represented by |info(r)|@>;
14974 if ( mp->cur_cmd!=comma )
14975 @<Check that the proper right delimiter was present@>;
14977 @<Append the current expression to |arg_list|@>
14979 @ @<Check that the proper right delim...@>=
14980 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14981 if ( info(link(r))>=expr_base ) {
14982 mp_missing_err(mp, ",");
14984 help3("I've finished reading a macro argument and am about to")
14985 ("read another; the arguments weren't delimited correctly.")
14986 ("You might want to delete some tokens before continuing.");
14987 mp_back_error(mp); mp->cur_cmd=comma;
14989 mp_missing_err(mp, str(text(r_delim)));
14991 help2("I've gotten to the end of the macro parameter list.")
14992 ("You might want to delete some tokens before continuing.");
14997 @ A \&{suffix} or \&{text} parameter will be have been scanned as
14998 a token list pointed to by |cur_exp|, in which case we will have
14999 |cur_type=token_list|.
15001 @<Append the current expression to |arg_list|@>=
15003 p=mp_get_avail(mp);
15004 if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
15005 else info(p)=mp_stash_cur_exp(mp);
15006 if ( mp->internal[mp_tracing_macros]>0 ) {
15007 mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r));
15008 mp_end_diagnostic(mp, false);
15010 if ( arg_list==null ) arg_list=p;
15015 @ @<Scan the argument represented by |info(r)|@>=
15016 if ( info(r)>=text_base ) {
15017 mp_scan_text_arg(mp, l_delim,r_delim);
15020 if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
15021 else mp_scan_expression(mp);
15024 @ The parameters to |scan_text_arg| are either a pair of delimiters
15025 or zero; the latter case is for undelimited text arguments, which
15026 end with the first semicolon or \&{endgroup} or \&{end} that is not
15027 contained in a group.
15029 @<Declare the procedure called |scan_text_arg|@>=
15030 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
15033 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
15034 integer balance; /* excess of |l_delim| over |r_delim| */
15035 pointer p; /* list tail */
15036 mp->warning_info=l_delim; mp->scanner_status=absorbing;
15037 p=hold_head; balance=1; link(hold_head)=null;
15040 if ( l_delim==0 ) {
15041 @<Adjust the balance for an undelimited argument; |break| if done@>;
15043 @<Adjust the balance for a delimited argument; |break| if done@>;
15045 link(p)=mp_cur_tok(mp); p=link(p);
15047 mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
15048 mp->scanner_status=normal;
15051 @ @<Adjust the balance for a delimited argument...@>=
15052 if ( mp->cur_cmd==right_delimiter ) {
15053 if ( mp->cur_mod==l_delim ) {
15055 if ( balance==0 ) break;
15057 } else if ( mp->cur_cmd==left_delimiter ) {
15058 if ( mp->cur_mod==r_delim ) incr(balance);
15061 @ @<Adjust the balance for an undelimited...@>=
15062 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
15063 if ( balance==1 ) { break; }
15064 else { if ( mp->cur_cmd==end_group ) decr(balance); }
15065 } else if ( mp->cur_cmd==begin_group ) {
15069 @ @<Scan undelimited argument(s)@>=
15071 if ( info(r)<text_macro ) {
15073 if ( info(r)!=suffix_macro ) {
15074 if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15078 case primary_macro:mp_scan_primary(mp); break;
15079 case secondary_macro:mp_scan_secondary(mp); break;
15080 case tertiary_macro:mp_scan_tertiary(mp); break;
15081 case expr_macro:mp_scan_expression(mp); break;
15083 @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15086 @<Scan a suffix with optional delimiters@>;
15088 case text_macro:mp_scan_text_arg(mp, 0,0); break;
15089 } /* there are no other cases */
15091 @<Append the current expression to |arg_list|@>;
15094 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15096 mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
15097 if ( mp->internal[mp_tracing_macros]>0 ) {
15098 mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0);
15099 mp_end_diagnostic(mp, false);
15101 if ( arg_list==null ) arg_list=p; else link(tail)=p;
15103 if ( mp->cur_cmd!=of_token ) {
15104 mp_missing_err(mp, "of"); mp_print(mp, " for ");
15106 mp_print_macro_name(mp, arg_list,macro_name);
15107 help1("I've got the first argument; will look now for the other.");
15110 mp_get_x_next(mp); mp_scan_primary(mp);
15113 @ @<Scan a suffix with optional delimiters@>=
15115 if ( mp->cur_cmd!=left_delimiter ) {
15118 l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15120 mp_scan_suffix(mp);
15121 if ( l_delim!=null ) {
15122 if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15123 mp_missing_err(mp, str(text(r_delim)));
15125 help2("I've gotten to the end of the macro parameter list.")
15126 ("You might want to delete some tokens before continuing.");
15133 @ Before we put a new token list on the input stack, it is wise to clean off
15134 all token lists that have recently been depleted. Then a user macro that ends
15135 with a call to itself will not require unbounded stack space.
15137 @<Feed the arguments and replacement text to the scanner@>=
15138 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15139 if ( mp->param_ptr+n>mp->max_param_stack ) {
15140 mp->max_param_stack=mp->param_ptr+n;
15141 if ( mp->max_param_stack>mp->param_size )
15142 mp_overflow(mp, "parameter stack size",mp->param_size);
15143 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15145 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15149 mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
15151 mp_flush_list(mp, arg_list);
15154 @ It's sometimes necessary to put a single argument onto |param_stack|.
15155 The |stack_argument| subroutine does this.
15157 @c void mp_stack_argument (MP mp,pointer p) {
15158 if ( mp->param_ptr==mp->max_param_stack ) {
15159 incr(mp->max_param_stack);
15160 if ( mp->max_param_stack>mp->param_size )
15161 mp_overflow(mp, "parameter stack size",mp->param_size);
15162 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15164 mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15167 @* \[33] Conditional processing.
15168 Let's consider now the way \&{if} commands are handled.
15170 Conditions can be inside conditions, and this nesting has a stack
15171 that is independent of other stacks.
15172 Four global variables represent the top of the condition stack:
15173 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15174 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15175 the largest code of a |fi_or_else| command that is syntactically legal;
15176 and |if_line| is the line number at which the current conditional began.
15178 If no conditions are currently in progress, the condition stack has the
15179 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15180 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15181 |link| fields of the first word contain |if_limit|, |cur_if|, and
15182 |cond_ptr| at the next level, and the second word contains the
15183 corresponding |if_line|.
15185 @d if_node_size 2 /* number of words in stack entry for conditionals */
15186 @d if_line_field(A) mp->mem[(A)+1].cint
15187 @d if_code 1 /* code for \&{if} being evaluated */
15188 @d fi_code 2 /* code for \&{fi} */
15189 @d else_code 3 /* code for \&{else} */
15190 @d else_if_code 4 /* code for \&{elseif} */
15193 pointer cond_ptr; /* top of the condition stack */
15194 integer if_limit; /* upper bound on |fi_or_else| codes */
15195 small_number cur_if; /* type of conditional being worked on */
15196 integer if_line; /* line where that conditional began */
15199 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15202 mp_primitive(mp, "if",if_test,if_code);
15203 @:if_}{\&{if} primitive@>
15204 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15205 @:fi_}{\&{fi} primitive@>
15206 mp_primitive(mp, "else",fi_or_else,else_code);
15207 @:else_}{\&{else} primitive@>
15208 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15209 @:else_if_}{\&{elseif} primitive@>
15211 @ @<Cases of |print_cmd_mod|...@>=
15215 case if_code:mp_print(mp, "if"); break;
15216 case fi_code:mp_print(mp, "fi"); break;
15217 case else_code:mp_print(mp, "else"); break;
15218 default: mp_print(mp, "elseif"); break;
15222 @ Here is a procedure that ignores text until coming to an \&{elseif},
15223 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15224 nesting. After it has acted, |cur_mod| will indicate the token that
15227 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15228 makes the skipping process a bit simpler.
15231 void mp_pass_text (MP mp) {
15233 mp->scanner_status=skipping;
15234 mp->warning_info=mp_true_line(mp);
15237 if ( mp->cur_cmd<=fi_or_else ) {
15238 if ( mp->cur_cmd<fi_or_else ) {
15242 if ( mp->cur_mod==fi_code ) decr(l);
15245 @<Decrease the string reference count,
15246 if the current token is a string@>;
15249 mp->scanner_status=normal;
15252 @ @<Decrease the string reference count...@>=
15253 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15255 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15256 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15257 condition has been evaluated, a colon will be inserted.
15258 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15260 @<Push the condition stack@>=
15261 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15262 name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15263 mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp);
15264 mp->cur_if=if_code;
15267 @ @<Pop the condition stack@>=
15268 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15269 mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15270 mp_free_node(mp, p,if_node_size);
15273 @ Here's a procedure that changes the |if_limit| code corresponding to
15274 a given value of |cond_ptr|.
15276 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15278 if ( p==mp->cond_ptr ) {
15279 mp->if_limit=l; /* that's the easy case */
15283 if ( q==null ) mp_confusion(mp, "if");
15284 @:this can't happen if}{\quad if@>
15285 if ( link(q)==p ) {
15293 @ The user is supposed to put colons into the proper parts of conditional
15294 statements. Therefore, \MP\ has to check for their presence.
15297 void mp_check_colon (MP mp) {
15298 if ( mp->cur_cmd!=colon ) {
15299 mp_missing_err(mp, ":");
15301 help2("There should've been a colon after the condition.")
15302 ("I shall pretend that one was there.");;
15307 @ A condition is started when the |get_x_next| procedure encounters
15308 an |if_test| command; in that case |get_x_next| calls |conditional|,
15309 which is a recursive procedure.
15312 @c void mp_conditional (MP mp) {
15313 pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15314 int new_if_limit; /* future value of |if_limit| */
15315 pointer p; /* temporary register */
15316 @<Push the condition stack@>;
15317 save_cond_ptr=mp->cond_ptr;
15319 mp_get_boolean(mp); new_if_limit=else_if_code;
15320 if ( mp->internal[mp_tracing_commands]>unity ) {
15321 @<Display the boolean value of |cur_exp|@>;
15324 mp_check_colon(mp);
15325 if ( mp->cur_exp==true_code ) {
15326 mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15327 return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15329 @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15331 mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15332 if ( mp->cur_mod==fi_code ) {
15333 @<Pop the condition stack@>
15334 } else if ( mp->cur_mod==else_if_code ) {
15337 mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp);
15342 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15343 \&{else}: \\{bar} \&{fi}', the first \&{else}
15344 that we come to after learning that the \&{if} is false is not the
15345 \&{else} we're looking for. Hence the following curious logic is needed.
15347 @<Skip to \&{elseif}...@>=
15350 if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15351 else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15355 @ @<Display the boolean value...@>=
15356 { mp_begin_diagnostic(mp);
15357 if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15358 else mp_print(mp, "{false}");
15359 mp_end_diagnostic(mp, false);
15362 @ The processing of conditionals is complete except for the following
15363 code, which is actually part of |get_x_next|. It comes into play when
15364 \&{elseif}, \&{else}, or \&{fi} is scanned.
15366 @<Terminate the current conditional and skip to \&{fi}@>=
15367 if ( mp->cur_mod>mp->if_limit ) {
15368 if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15369 mp_missing_err(mp, ":");
15371 mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15373 print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15377 help1("I'm ignoring this; it doesn't match any if.");
15381 while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15382 @<Pop the condition stack@>;
15385 @* \[34] Iterations.
15386 To bring our treatment of |get_x_next| to a close, we need to consider what
15387 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15389 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15390 that are currently active. If |loop_ptr=null|, no loops are in progress;
15391 otherwise |info(loop_ptr)| points to the iterative text of the current
15392 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15393 loops that enclose the current one.
15395 A loop-control node also has two other fields, called |loop_type| and
15396 |loop_list|, whose contents depend on the type of loop:
15398 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15399 points to a list of one-word nodes whose |info| fields point to the
15400 remaining argument values of a suffix list and expression list.
15402 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15405 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15406 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15407 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15410 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15411 header and |loop_list(loop_ptr)| points into the graphical object list for
15414 \yskip\noindent In the case of a progression node, the first word is not used
15415 because the link field of words in the dynamic memory area cannot be arbitrary.
15417 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15418 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15419 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15420 @d loop_node_size 2 /* the number of words in a loop control node */
15421 @d progression_node_size 4 /* the number of words in a progression node */
15422 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15423 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15424 @d progression_flag (null+2)
15425 /* |loop_type| value when |loop_list| points to a progression node */
15428 pointer loop_ptr; /* top of the loop-control-node stack */
15433 @ If the expressions that define an arithmetic progression in
15434 a \&{for} loop don't have known numeric values, the |bad_for|
15435 subroutine screams at the user.
15437 @c void mp_bad_for (MP mp, char * s) {
15438 mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15439 @.Improper...replaced by 0@>
15440 mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15441 help4("When you say `for x=a step b until c',")
15442 ("the initial value `a' and the step size `b'")
15443 ("and the final value `c' must have known numeric values.")
15444 ("I'm zeroing this one. Proceed, with fingers crossed.");
15445 mp_put_get_flush_error(mp, 0);
15448 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15449 has just been scanned. (This code requires slight familiarity with
15450 expression-parsing routines that we have not yet discussed; but it seems
15451 to belong in the present part of the program, even though the original author
15452 didn't write it until later. The reader may wish to come back to it.)
15454 @c void mp_begin_iteration (MP mp) {
15455 halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15456 halfword n; /* hash address of the current symbol */
15457 pointer s; /* the new loop-control node */
15458 pointer p; /* substitution list for |scan_toks| */
15459 pointer q; /* link manipulation register */
15460 pointer pp; /* a new progression node */
15461 m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15462 if ( m==start_forever ){
15463 loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15465 mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15466 info(p)=mp->cur_sym; value(p)=m;
15468 if ( mp->cur_cmd==within_token ) {
15469 @<Set up a picture iteration@>;
15471 @<Check for the |"="| or |":="| in a loop header@>;
15472 @<Scan the values to be used in the loop@>;
15475 @<Check for the presence of a colon@>;
15476 @<Scan the loop text and put it on the loop control stack@>;
15477 mp_resume_iteration(mp);
15480 @ @<Check for the |"="| or |":="| in a loop header@>=
15481 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) {
15482 mp_missing_err(mp, "=");
15484 help3("The next thing in this loop should have been `=' or `:='.")
15485 ("But don't worry; I'll pretend that an equals sign")
15486 ("was present, and I'll look for the values next.");
15490 @ @<Check for the presence of a colon@>=
15491 if ( mp->cur_cmd!=colon ) {
15492 mp_missing_err(mp, ":");
15494 help3("The next thing in this loop should have been a `:'.")
15495 ("So I'll pretend that a colon was present;")
15496 ("everything from here to `endfor' will be iterated.");
15500 @ We append a special |frozen_repeat_loop| token in place of the
15501 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15502 at the proper time to cause the loop to be repeated.
15504 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15505 he will be foiled by the |get_symbol| routine, which keeps frozen
15506 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15507 token, so it won't be lost accidentally.)
15509 @ @<Scan the loop text...@>=
15510 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15511 mp->scanner_status=loop_defining; mp->warning_info=n;
15512 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15513 link(s)=mp->loop_ptr; mp->loop_ptr=s
15515 @ @<Initialize table...@>=
15516 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15517 text(frozen_repeat_loop)=intern(" ENDFOR");
15519 @ The loop text is inserted into \MP's scanning apparatus by the
15520 |resume_iteration| routine.
15522 @c void mp_resume_iteration (MP mp) {
15523 pointer p,q; /* link registers */
15524 p=loop_type(mp->loop_ptr);
15525 if ( p==progression_flag ) {
15526 p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15527 mp->cur_exp=value(p);
15528 if ( @<The arithmetic progression has ended@> ) {
15529 mp_stop_iteration(mp);
15532 mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15533 value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15534 } else if ( p==null ) {
15535 p=loop_list(mp->loop_ptr);
15537 mp_stop_iteration(mp);
15540 loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15541 } else if ( p==mp_void ) {
15542 mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15544 @<Make |q| a capsule containing the next picture component from
15545 |loop_list(loop_ptr)| or |goto not_found|@>;
15547 mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15548 mp_stack_argument(mp, q);
15549 if ( mp->internal[mp_tracing_commands]>unity ) {
15550 @<Trace the start of a loop@>;
15554 mp_stop_iteration(mp);
15557 @ @<The arithmetic progression has ended@>=
15558 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15559 ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15561 @ @<Trace the start of a loop@>=
15563 mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15565 if ( (q!=null)&&(link(q)==mp_void) ) mp_print_exp(mp, q,1);
15566 else mp_show_token_list(mp, q,null,50,0);
15567 mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15570 @ @<Make |q| a capsule containing the next picture component from...@>=
15571 { q=loop_list(mp->loop_ptr);
15572 if ( q==null ) goto NOT_FOUND;
15573 skip_component(q) goto NOT_FOUND;
15574 mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15575 mp_init_bbox(mp, mp->cur_exp);
15576 mp->cur_type=mp_picture_type;
15577 loop_list(mp->loop_ptr)=q;
15578 q=mp_stash_cur_exp(mp);
15581 @ A level of loop control disappears when |resume_iteration| has decided
15582 not to resume, or when an \&{exitif} construction has removed the loop text
15583 from the input stack.
15585 @c void mp_stop_iteration (MP mp) {
15586 pointer p,q; /* the usual */
15587 p=loop_type(mp->loop_ptr);
15588 if ( p==progression_flag ) {
15589 mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15590 } else if ( p==null ){
15591 q=loop_list(mp->loop_ptr);
15592 while ( q!=null ) {
15595 if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
15596 mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15598 mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15601 p=q; q=link(q); free_avail(p);
15603 } else if ( p>progression_flag ) {
15604 delete_edge_ref(p);
15606 p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15607 mp_free_node(mp, p,loop_node_size);
15610 @ Now that we know all about loop control, we can finish up
15611 the missing portion of |begin_iteration| and we'll be done.
15613 The following code is performed after the `\.=' has been scanned in
15614 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15615 (if |m=suffix_base|).
15617 @<Scan the values to be used in the loop@>=
15618 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15621 if ( m!=expr_base ) {
15622 mp_scan_suffix(mp);
15624 if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma )
15626 mp_scan_expression(mp);
15627 if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15628 @<Prepare for step-until construction and |break|@>;
15630 mp->cur_exp=mp_stash_cur_exp(mp);
15632 link(q)=mp_get_avail(mp); q=link(q);
15633 info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15636 } while (mp->cur_cmd==comma)
15638 @ @<Prepare for step-until construction and |break|@>=
15640 if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15641 pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15642 mp_get_x_next(mp); mp_scan_expression(mp);
15643 if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15644 step_size(pp)=mp->cur_exp;
15645 if ( mp->cur_cmd!=until_token ) {
15646 mp_missing_err(mp, "until");
15647 @.Missing `until'@>
15648 help2("I assume you meant to say `until' after `step'.")
15649 ("So I'll look for the final value and colon next.");
15652 mp_get_x_next(mp); mp_scan_expression(mp);
15653 if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15654 final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15655 loop_type(s)=progression_flag;
15659 @ The last case is when we have just seen ``\&{within}'', and we need to
15660 parse a picture expression and prepare to iterate over it.
15662 @<Set up a picture iteration@>=
15663 { mp_get_x_next(mp);
15664 mp_scan_expression(mp);
15665 @<Make sure the current expression is a known picture@>;
15666 loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15667 q=link(dummy_loc(mp->cur_exp));
15669 if ( is_start_or_stop(q) )
15670 if ( mp_skip_1component(mp, q)==null ) q=link(q);
15674 @ @<Make sure the current expression is a known picture@>=
15675 if ( mp->cur_type!=mp_picture_type ) {
15676 mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15677 help1("When you say `for x in p', p must be a known picture.");
15678 mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15679 mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15682 @* \[35] File names.
15683 It's time now to fret about file names. Besides the fact that different
15684 operating systems treat files in different ways, we must cope with the
15685 fact that completely different naming conventions are used by different
15686 groups of people. The following programs show what is required for one
15687 particular operating system; similar routines for other systems are not
15688 difficult to devise.
15689 @^system dependencies@>
15691 \MP\ assumes that a file name has three parts: the name proper; its
15692 ``extension''; and a ``file area'' where it is found in an external file
15693 system. The extension of an input file is assumed to be
15694 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15695 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15696 metric files that describe characters in any fonts created by \MP; it is
15697 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15698 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15699 The file area can be arbitrary on input files, but files are usually
15700 output to the user's current area. If an input file cannot be
15701 found on the specified area, \MP\ will look for it on a special system
15702 area; this special area is intended for commonly used input files.
15704 Simple uses of \MP\ refer only to file names that have no explicit
15705 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15706 instead of `\.{input} \.{cmr10.new}'. Simple file
15707 names are best, because they make the \MP\ source files portable;
15708 whenever a file name consists entirely of letters and digits, it should be
15709 treated in the same way by all implementations of \MP. However, users
15710 need the ability to refer to other files in their environment, especially
15711 when responding to error messages concerning unopenable files; therefore
15712 we want to let them use the syntax that appears in their favorite
15715 @ \MP\ uses the same conventions that have proved to be satisfactory for
15716 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15717 @^system dependencies@>
15718 the system-independent parts of \MP\ are expressed in terms
15719 of three system-dependent
15720 procedures called |begin_name|, |more_name|, and |end_name|. In
15721 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15722 the system-independent driver program does the operations
15723 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15725 These three procedures communicate with each other via global variables.
15726 Afterwards the file name will appear in the string pool as three strings
15727 called |cur_name|\penalty10000\hskip-.05em,
15728 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15729 |""|), unless they were explicitly specified by the user.
15731 Actually the situation is slightly more complicated, because \MP\ needs
15732 to know when the file name ends. The |more_name| routine is a function
15733 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15734 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15735 returns |false|; or, it returns |true| and $c_n$ is the last character
15736 on the current input line. In other words,
15737 |more_name| is supposed to return |true| unless it is sure that the
15738 file name has been completely scanned; and |end_name| is supposed to be able
15739 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15740 whether $|more_name|(c_n)$ returned |true| or |false|.
15743 char * cur_name; /* name of file just scanned */
15744 char * cur_area; /* file area just scanned, or \.{""} */
15745 char * cur_ext; /* file extension just scanned, or \.{""} */
15747 @ It is easier to maintain reference counts if we assign initial values.
15750 mp->cur_name=xstrdup("");
15751 mp->cur_area=xstrdup("");
15752 mp->cur_ext=xstrdup("");
15754 @ @<Dealloc variables@>=
15755 xfree(mp->cur_area);
15756 xfree(mp->cur_name);
15757 xfree(mp->cur_ext);
15759 @ The file names we shall deal with for illustrative purposes have the
15760 following structure: If the name contains `\.>' or `\.:', the file area
15761 consists of all characters up to and including the final such character;
15762 otherwise the file area is null. If the remaining file name contains
15763 `\..', the file extension consists of all such characters from the first
15764 remaining `\..' to the end, otherwise the file extension is null.
15765 @^system dependencies@>
15767 We can scan such file names easily by using two global variables that keep track
15768 of the occurrences of area and extension delimiters. Note that these variables
15769 cannot be of type |pool_pointer| because a string pool compaction could occur
15770 while scanning a file name.
15773 integer area_delimiter;
15774 /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15775 integer ext_delimiter; /* the relevant `\..', if any */
15777 @ Input files that can't be found in the user's area may appear in standard
15778 system areas called |MP_area| and |MF_area|. (The latter is used when the file
15779 extension is |".mf"|.) The standard system area for font metric files
15780 to be read is |MP_font_area|.
15781 This system area name will, of course, vary from place to place.
15782 @^system dependencies@>
15784 @d MP_area "MPinputs:"
15786 @d MF_area "MFinputs:"
15791 @ Here now is the first of the system-dependent routines for file name scanning.
15792 @^system dependencies@>
15794 @<Declare subroutines for parsing file names@>=
15795 void mp_begin_name (MP mp) {
15796 xfree(mp->cur_name);
15797 xfree(mp->cur_area);
15798 xfree(mp->cur_ext);
15799 mp->area_delimiter=-1;
15800 mp->ext_delimiter=-1;
15803 @ And here's the second.
15804 @^system dependencies@>
15806 @<Declare subroutines for parsing file names@>=
15807 boolean mp_more_name (MP mp, ASCII_code c) {
15811 if ( (c=='>')||(c==':') ) {
15812 mp->area_delimiter=mp->pool_ptr;
15813 mp->ext_delimiter=-1;
15814 } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15815 mp->ext_delimiter=mp->pool_ptr;
15817 str_room(1); append_char(c); /* contribute |c| to the current string */
15823 @^system dependencies@>
15825 @d copy_pool_segment(A,B,C) {
15826 A = xmalloc(C+1,sizeof(char));
15827 strncpy(A,(char *)(mp->str_pool+B),C);
15830 @<Declare subroutines for parsing file names@>=
15831 void mp_end_name (MP mp) {
15832 pool_pointer s; /* length of area, name, and extension */
15835 s = mp->str_start[mp->str_ptr];
15836 if ( mp->area_delimiter<0 ) {
15837 mp->cur_area=xstrdup("");
15839 len = mp->area_delimiter-s;
15840 copy_pool_segment(mp->cur_area,s,len);
15843 if ( mp->ext_delimiter<0 ) {
15844 mp->cur_ext=xstrdup("");
15845 len = mp->pool_ptr-s;
15847 copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15848 len = mp->ext_delimiter-s;
15850 copy_pool_segment(mp->cur_name,s,len);
15851 mp->pool_ptr=s; /* don't need this partial string */
15854 @ Conversely, here is a routine that takes three strings and prints a file
15855 name that might have produced them. (The routine is system dependent, because
15856 some operating systems put the file area last instead of first.)
15857 @^system dependencies@>
15859 @<Basic printing...@>=
15860 void mp_print_file_name (MP mp, char * n, char * a, char * e) {
15861 mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15864 @ Another system-dependent routine is needed to convert three internal
15866 to the |name_of_file| value that is used to open files. The present code
15867 allows both lowercase and uppercase letters in the file name.
15868 @^system dependencies@>
15870 @d append_to_name(A) { c=(A);
15871 if ( k<file_name_size ) {
15872 mp->name_of_file[k]=xchr(c);
15877 @<Declare subroutines for parsing file names@>=
15878 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15879 integer k; /* number of positions filled in |name_of_file| */
15880 ASCII_code c; /* character being packed */
15881 char *j; /* a character index */
15885 for (j=a;*j;j++) { append_to_name(*j); }
15887 for (j=n;*j;j++) { append_to_name(*j); }
15889 for (j=e;*j;j++) { append_to_name(*j); }
15891 mp->name_of_file[k]=0;
15895 @ @<Internal library declarations@>=
15896 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15898 @ A messier routine is also needed, since mem file names must be scanned
15899 before \MP's string mechanism has been initialized. We shall use the
15900 global variable |MP_mem_default| to supply the text for default system areas
15901 and extensions related to mem files.
15902 @^system dependencies@>
15904 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15905 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15906 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15909 char *MP_mem_default;
15910 char *mem_name; /* for commandline */
15912 @ @<Option variables@>=
15913 char *mem_name; /* for commandline */
15915 @ @<Allocate or initialize ...@>=
15916 mp->MP_mem_default = xstrdup("plain.mem");
15917 mp->mem_name = xstrdup(opt->mem_name);
15919 @^system dependencies@>
15921 @ @<Dealloc variables@>=
15922 xfree(mp->MP_mem_default);
15923 xfree(mp->mem_name);
15925 @ @<Check the ``constant'' values for consistency@>=
15926 if ( mem_default_length>file_name_size ) mp->bad=20;
15928 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15929 from the first |n| characters of |MP_mem_default|, followed by
15930 |buffer[a..b-1]|, followed by the last |mem_ext_length| characters of
15933 We dare not give error messages here, since \MP\ calls this routine before
15934 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15935 since the error will be detected in another way when a strange file name
15937 @^system dependencies@>
15939 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15941 integer k; /* number of positions filled in |name_of_file| */
15942 ASCII_code c; /* character being packed */
15943 integer j; /* index into |buffer| or |MP_mem_default| */
15944 if ( n+b-a+1+mem_ext_length>file_name_size )
15945 b=a+file_name_size-n-1-mem_ext_length;
15947 for (j=0;j<n;j++) {
15948 append_to_name(xord((int)mp->MP_mem_default[j]));
15950 for (j=a;j<b;j++) {
15951 append_to_name(mp->buffer[j]);
15953 for (j=mem_default_length-mem_ext_length;
15954 j<mem_default_length;j++) {
15955 append_to_name(xord((int)mp->MP_mem_default[j]));
15957 mp->name_of_file[k]=0;
15961 @ Here is the only place we use |pack_buffered_name|. This part of the program
15962 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15963 the preliminary initialization, or when the user is substituting another
15964 mem file by typing `\.\&' after the initial `\.{**}' prompt. The buffer
15965 contains the first line of input in |buffer[loc..(last-1)]|, where
15966 |loc<last| and |buffer[loc]<>" "|.
15969 boolean mp_open_mem_file (MP mp) ;
15972 boolean mp_open_mem_file (MP mp) {
15973 int j; /* the first space after the file name */
15974 if (mp->mem_name!=NULL) {
15975 mp->mem_file = mp_open_file(mp, mp->mem_name, "rb", mp_filetype_memfile);
15976 if ( mp->mem_file ) return true;
15979 if ( mp->buffer[loc]=='&' ) {
15980 incr(loc); j=loc; mp->buffer[mp->last]=' ';
15981 while ( mp->buffer[j]!=' ' ) incr(j);
15982 mp_pack_buffered_name(mp, 0,loc,j); /* try first without the system file area */
15983 if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15985 wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15986 @.Sorry, I can't find...@>
15989 /* now pull out all the stops: try for the system \.{plain} file */
15990 mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15991 if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15993 wterm_ln("I can\'t find the PLAIN mem file!\n");
15994 @.I can't find PLAIN...@>
15999 loc=j; return true;
16002 @ Operating systems often make it possible to determine the exact name (and
16003 possible version number) of a file that has been opened. The following routine,
16004 which simply makes a \MP\ string from the value of |name_of_file|, should
16005 ideally be changed to deduce the full name of file~|f|, which is the file
16006 most recently opened, if it is possible to do this in a \PASCAL\ program.
16007 @^system dependencies@>
16010 #define mp_a_make_name_string(A,B) mp_make_name_string(A)
16011 #define mp_b_make_name_string(A,B) mp_make_name_string(A)
16012 #define mp_w_make_name_string(A,B) mp_make_name_string(A)
16015 str_number mp_make_name_string (MP mp) {
16016 int k; /* index into |name_of_file| */
16017 str_room(mp->name_length);
16018 for (k=0;k<mp->name_length;k++) {
16019 append_char(xord((int)mp->name_of_file[k]));
16021 return mp_make_string(mp);
16024 @ Now let's consider the ``driver''
16025 routines by which \MP\ deals with file names
16026 in a system-independent manner. First comes a procedure that looks for a
16027 file name in the input by taking the information from the input buffer.
16028 (We can't use |get_next|, because the conversion to tokens would
16029 destroy necessary information.)
16031 This procedure doesn't allow semicolons or percent signs to be part of
16032 file names, because of other conventions of \MP.
16033 {\sl The {\logos METAFONT\/}book} doesn't
16034 use semicolons or percents immediately after file names, but some users
16035 no doubt will find it natural to do so; therefore system-dependent
16036 changes to allow such characters in file names should probably
16037 be made with reluctance, and only when an entire file name that
16038 includes special characters is ``quoted'' somehow.
16039 @^system dependencies@>
16041 @c void mp_scan_file_name (MP mp) {
16043 while ( mp->buffer[loc]==' ' ) incr(loc);
16045 if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
16046 if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
16052 @ Here is another version that takes its input from a string.
16054 @<Declare subroutines for parsing file names@>=
16055 void mp_str_scan_file (MP mp, str_number s) {
16056 pool_pointer p,q; /* current position and stopping point */
16058 p=mp->str_start[s]; q=str_stop(s);
16060 if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
16066 @ And one that reads from a |char*|.
16068 @<Declare subroutines for parsing file names@>=
16069 void mp_ptr_scan_file (MP mp, char *s) {
16070 char *p, *q; /* current position and stopping point */
16072 p=s; q=p+strlen(s);
16074 if ( ! mp_more_name(mp, *p)) break;
16081 @ The global variable |job_name| contains the file name that was first
16082 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16083 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16086 char *job_name; /* principal file name */
16087 boolean log_opened; /* has the transcript file been opened? */
16088 char *log_name; /* full name of the log file */
16090 @ @<Option variables@>=
16091 char *job_name; /* principal file name */
16093 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16094 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16095 except of course for a short time just after |job_name| has become nonzero.
16097 @<Allocate or ...@>=
16098 mp->job_name=opt->job_name;
16099 mp->log_opened=false;
16101 @ @<Dealloc variables@>=
16102 xfree(mp->job_name);
16104 @ Here is a routine that manufactures the output file names, assuming that
16105 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16108 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16111 void mp_pack_job_name (MP mp, char *s) ;
16113 @ @c void mp_pack_job_name (MP mp, char *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16114 xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16115 xfree(mp->cur_area); mp->cur_area=xstrdup("");
16116 xfree(mp->cur_ext); mp->cur_ext=xstrdup(s);
16120 @ If some trouble arises when \MP\ tries to open a file, the following
16121 routine calls upon the user to supply another file name. Parameter~|s|
16122 is used in the error message to identify the type of file; parameter~|e|
16123 is the default extension if none is given. Upon exit from the routine,
16124 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16125 ready for another attempt at file opening.
16128 void mp_prompt_file_name (MP mp,char * s, char * e) ;
16130 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
16131 size_t k; /* index into |buffer| */
16132 char * saved_cur_name;
16133 if ( mp->interaction==mp_scroll_mode )
16135 if (strcmp(s,"input file name")==0) {
16136 print_err("I can\'t find file `");
16137 @.I can't find file x@>
16139 print_err("I can\'t write on file `");
16141 @.I can't write on file x@>
16142 mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext);
16143 mp_print(mp, "'.");
16144 if (strcmp(e,"")==0)
16145 mp_show_context(mp);
16146 mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16148 if ( mp->interaction<mp_scroll_mode )
16149 mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16150 @.job aborted, file error...@>
16151 saved_cur_name = xstrdup(mp->cur_name);
16152 clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16153 if (strcmp(mp->cur_ext,"")==0)
16155 if (strlen(mp->cur_name)==0) {
16156 mp->cur_name=saved_cur_name;
16158 xfree(saved_cur_name);
16163 @ @<Scan file name in the buffer@>=
16165 mp_begin_name(mp); k=mp->first;
16166 while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16168 if ( k==mp->last ) break;
16169 if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16175 @ The |open_log_file| routine is used to open the transcript file and to help
16176 it catch up to what has previously been printed on the terminal.
16178 @c void mp_open_log_file (MP mp) {
16179 int old_setting; /* previous |selector| setting */
16180 int k; /* index into |months| and |buffer| */
16181 int l; /* end of first input line */
16182 integer m; /* the current month */
16183 char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
16184 /* abbreviations of month names */
16185 old_setting=mp->selector;
16186 if ( mp->job_name==NULL ) {
16187 mp->job_name=xstrdup("mpout");
16189 mp_pack_job_name(mp,".log");
16190 while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16191 @<Try to get a different log file name@>;
16193 mp->log_name=xstrdup(mp->name_of_file);
16194 mp->selector=log_only; mp->log_opened=true;
16195 @<Print the banner line, including the date and time@>;
16196 mp->input_stack[mp->input_ptr]=mp->cur_input;
16197 /* make sure bottom level is in memory */
16198 mp_print_nl(mp, "**");
16200 l=mp->input_stack[0].limit_field-1; /* last position of first line */
16201 for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16202 mp_print_ln(mp); /* now the transcript file contains the first line of input */
16203 mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16206 @ @<Dealloc variables@>=
16207 xfree(mp->log_name);
16209 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16210 unable to print error messages or even to |show_context|.
16211 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16212 routine will not be invoked because |log_opened| will be false.
16214 The normal idea of |mp_batch_mode| is that nothing at all should be written
16215 on the terminal. However, in the unusual case that
16216 no log file could be opened, we make an exception and allow
16217 an explanatory message to be seen.
16219 Incidentally, the program always refers to the log file as a `\.{transcript
16220 file}', because some systems cannot use the extension `\.{.log}' for
16223 @<Try to get a different log file name@>=
16225 mp->selector=term_only;
16226 mp_prompt_file_name(mp, "transcript file name",".log");
16229 @ @<Print the banner...@>=
16232 mp_print(mp, mp->mem_ident); mp_print(mp, " ");
16233 mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day]));
16234 mp_print_char(mp, ' ');
16235 m=mp_round_unscaled(mp, mp->internal[mp_month]);
16236 for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16237 mp_print_char(mp, ' ');
16238 mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year]));
16239 mp_print_char(mp, ' ');
16240 m=mp_round_unscaled(mp, mp->internal[mp_time]);
16241 mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16244 @ The |try_extension| function tries to open an input file determined by
16245 |cur_name|, |cur_area|, and the argument |ext|. It returns |false| if it
16246 can't find the file in |cur_area| or the appropriate system area.
16248 @c boolean mp_try_extension (MP mp,char *ext) {
16249 mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16250 in_name=xstrdup(mp->cur_name);
16251 in_area=xstrdup(mp->cur_area);
16252 if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16255 if (strcmp(ext,".mf")==0 ) in_area=xstrdup(MF_area);
16256 else in_area=xstrdup(MP_area);
16257 mp_pack_file_name(mp, mp->cur_name,in_area,ext);
16258 return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16263 @ Let's turn now to the procedure that is used to initiate file reading
16264 when an `\.{input}' command is being processed.
16266 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16267 char *fname = NULL;
16268 @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16270 mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16271 if ( strlen(mp->cur_ext)==0 ) {
16272 if ( mp_try_extension(mp, ".mp") ) break;
16273 else if ( mp_try_extension(mp, "") ) break;
16274 else if ( mp_try_extension(mp, ".mf") ) break;
16275 /* |else do_nothing; | */
16276 } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16279 mp_end_file_reading(mp); /* remove the level that didn't work */
16280 mp_prompt_file_name(mp, "input file name","");
16282 name=mp_a_make_name_string(mp, cur_file);
16283 fname = xstrdup(mp->name_of_file);
16284 if ( mp->job_name==NULL ) {
16285 mp->job_name=xstrdup(mp->cur_name);
16286 mp_open_log_file(mp);
16287 } /* |open_log_file| doesn't |show_context|, so |limit|
16288 and |loc| needn't be set to meaningful values yet */
16289 if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16290 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16291 mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname);
16294 @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16295 @<Read the first line of the new file@>;
16298 @ This code should be omitted if |a_make_name_string| returns something other
16299 than just a copy of its argument and the full file name is needed for opening
16300 \.{MPX} files or implementing the switch-to-editor option.
16301 @^system dependencies@>
16303 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16304 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16306 @ Here we have to remember to tell the |input_ln| routine not to
16307 start with a |get|. If the file is empty, it is considered to
16308 contain a single blank line.
16309 @^system dependencies@>
16311 @<Read the first line...@>=
16314 (void)mp_input_ln(mp, cur_file,false);
16315 mp_firm_up_the_line(mp);
16316 mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16319 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16320 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16321 if ( token_state ) {
16322 print_err("File names can't appear within macros");
16323 @.File names can't...@>
16324 help3("Sorry...I've converted what follows to tokens,")
16325 ("possibly garbaging the name you gave.")
16326 ("Please delete the tokens and insert the name again.");
16329 if ( file_state ) {
16330 mp_scan_file_name(mp);
16332 xfree(mp->cur_name); mp->cur_name=xstrdup("");
16333 xfree(mp->cur_ext); mp->cur_ext =xstrdup("");
16334 xfree(mp->cur_area); mp->cur_area=xstrdup("");
16337 @ Sometimes we need to deal with two file names at once. This procedure
16338 copies the given string into a special array for an old file name.
16340 @c void mp_copy_old_name (MP mp,str_number s) {
16341 integer k; /* number of positions filled in |old_file_name| */
16342 pool_pointer j; /* index into |str_pool| */
16344 for (j=mp->str_start[s];j<=str_stop(s)-1;j++) {
16346 if ( k<=file_name_size )
16347 mp->old_file_name[k]=xchr(mp->str_pool[j]);
16349 mp->old_file_name[++k] = 0;
16353 char old_file_name[file_name_size+1]; /* analogous to |name_of_file| */
16355 @ The following simple routine starts reading the \.{MPX} file associated
16356 with the current input file.
16358 @c void mp_start_mpx_input (MP mp) {
16359 mp_pack_file_name(mp, in_name, in_area, ".mpx");
16360 @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16361 |goto not_found| if there is a problem@>;
16362 mp_begin_file_reading(mp);
16363 if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16364 mp_end_file_reading(mp);
16367 name=mp_a_make_name_string(mp, cur_file);
16368 mp->mpx_name[index]=name; add_str_ref(name);
16369 @<Read the first line of the new file@>;
16372 @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16375 @ This should ideally be changed to do whatever is necessary to create the
16376 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16377 of date. This requires invoking \.{MPtoTeX} on the |old_file_name| and passing
16378 the results through \TeX\ and \.{DVItoMP}. (It is possible to use a
16379 completely different typesetting program if suitable postprocessor is
16380 available to perform the function of \.{DVItoMP}.)
16381 @^system dependencies@>
16383 @ @<Exported types@>=
16384 typedef int (*mp_run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16387 mp_run_make_mpx_command run_make_mpx;
16389 @ @<Option variables@>=
16390 mp_run_make_mpx_command run_make_mpx;
16392 @ @<Allocate or initialize ...@>=
16393 set_callback_option(run_make_mpx);
16395 @ @<Internal library declarations@>=
16396 int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16398 @ The default does nothing.
16400 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16401 if (mp && origname && mtxname) /* for -W */
16408 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16409 |goto not_found| if there is a problem@>=
16410 mp_copy_old_name(mp, name);
16411 if (!(mp->run_make_mpx)(mp, mp->old_file_name, mp->name_of_file))
16414 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16415 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16416 mp_print_nl(mp, ">> ");
16417 mp_print(mp, mp->old_file_name);
16418 mp_print_nl(mp, ">> ");
16419 mp_print(mp, mp->name_of_file);
16420 mp_print_nl(mp, "! Unable to make mpx file");
16421 help4("The two files given above are one of your source files")
16422 ("and an auxiliary file I need to read to find out what your")
16423 ("btex..etex blocks mean. If you don't know why I had trouble,")
16424 ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16427 @ The last file-opening commands are for files accessed via the \&{readfrom}
16428 @:read_from_}{\&{readfrom} primitive@>
16429 operator and the \&{write} command. Such files are stored in separate arrays.
16430 @:write_}{\&{write} primitive@>
16432 @<Types in the outer block@>=
16433 typedef unsigned int readf_index; /* |0..max_read_files| */
16434 typedef unsigned int write_index; /* |0..max_write_files| */
16437 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16438 FILE ** rd_file; /* \&{readfrom} files */
16439 char ** rd_fname; /* corresponding file name or 0 if file not open */
16440 readf_index read_files; /* number of valid entries in the above arrays */
16441 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16442 FILE ** wr_file; /* \&{write} files */
16443 char ** wr_fname; /* corresponding file name or 0 if file not open */
16444 write_index write_files; /* number of valid entries in the above arrays */
16446 @ @<Allocate or initialize ...@>=
16447 mp->max_read_files=8;
16448 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(FILE *));
16449 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16450 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16452 mp->max_write_files=8;
16453 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(FILE *));
16454 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16455 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16459 @ This routine starts reading the file named by string~|s| without setting
16460 |loc|, |limit|, or |name|. It returns |false| if the file is empty or cannot
16461 be opened. Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16463 @c boolean mp_start_read_input (MP mp,char *s, readf_index n) {
16464 mp_ptr_scan_file(mp, s);
16466 mp_begin_file_reading(mp);
16467 if ( ! mp_a_open_in(mp, &mp->rd_file[n], mp_filetype_text) )
16469 if ( ! mp_input_ln(mp, mp->rd_file[n], false) ) {
16470 fclose(mp->rd_file[n]);
16473 mp->rd_fname[n]=xstrdup(mp->name_of_file);
16476 mp_end_file_reading(mp);
16480 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16483 void mp_open_write_file (MP mp, char *s, readf_index n) ;
16485 @ @c void mp_open_write_file (MP mp,char *s, readf_index n) {
16486 mp_ptr_scan_file(mp, s);
16488 while ( ! mp_a_open_out(mp, &mp->wr_file[n], mp_filetype_text) )
16489 mp_prompt_file_name(mp, "file name for write output","");
16490 mp->wr_fname[n]=xstrdup(mp->name_of_file);
16494 @* \[36] Introduction to the parsing routines.
16495 We come now to the central nervous system that sparks many of \MP's activities.
16496 By evaluating expressions, from their primary constituents to ever larger
16497 subexpressions, \MP\ builds the structures that ultimately define complete
16498 pictures or fonts of type.
16500 Four mutually recursive subroutines are involved in this process: We call them
16501 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16502 and |scan_expression|.}$$
16504 Each of them is parameterless and begins with the first token to be scanned
16505 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16506 the value of the primary or secondary or tertiary or expression that was
16507 found will appear in the global variables |cur_type| and |cur_exp|. The
16508 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16511 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16512 backup mechanisms have been added in order to provide reasonable error
16516 small_number cur_type; /* the type of the expression just found */
16517 integer cur_exp; /* the value of the expression just found */
16522 @ Many different kinds of expressions are possible, so it is wise to have
16523 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16526 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16527 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16528 construction in which there was no expression before the \&{endgroup}.
16529 In this case |cur_exp| has some irrelevant value.
16532 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16536 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16537 node that is in the ring of variables equivalent
16538 to at least one undefined boolean variable.
16541 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16542 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16543 includes this particular reference.
16546 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16547 node that is in the ring of variables equivalent
16548 to at least one undefined string variable.
16551 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen. Nobody
16552 else points to any of the nodes in this pen. The pen may be polygonal or
16556 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16557 node that is in the ring of variables equivalent
16558 to at least one undefined pen variable.
16561 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16562 a path; nobody else points to this particular path. The control points of
16563 the path will have been chosen.
16566 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16567 node that is in the ring of variables equivalent
16568 to at least one undefined path variable.
16571 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16572 There may be other pointers to this particular set of edges. The header node
16573 contains a reference count that includes this particular reference.
16576 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16577 node that is in the ring of variables equivalent
16578 to at least one undefined picture variable.
16581 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16582 capsule node. The |value| part of this capsule
16583 points to a transform node that contains six numeric values,
16584 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16587 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16588 capsule node. The |value| part of this capsule
16589 points to a color node that contains three numeric values,
16590 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16593 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16594 capsule node. The |value| part of this capsule
16595 points to a color node that contains four numeric values,
16596 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16599 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16600 node whose type is |mp_pair_type|. The |value| part of this capsule
16601 points to a pair node that contains two numeric values,
16602 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16605 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16608 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16609 is |dependent|. The |dep_list| field in this capsule points to the associated
16613 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16614 capsule node. The |dep_list| field in this capsule
16615 points to the associated dependency list.
16618 |cur_type=independent| means that |cur_exp| points to a capsule node
16619 whose type is |independent|. This somewhat unusual case can arise, for
16620 example, in the expression
16621 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16624 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16625 tokens. This case arises only on the left-hand side of an assignment
16626 (`\.{:=}') operation, under very special circumstances.
16628 \smallskip\noindent
16629 The possible settings of |cur_type| have been listed here in increasing
16630 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16631 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16632 are allowed. Conversely, \MP\ has no variables of type |mp_vacuous| or
16635 @ Capsules are two-word nodes that have a similar meaning
16636 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16637 and |link<=mp_void|; and their |type| field is one of the possibilities for
16638 |cur_type| listed above.
16640 The |value| field of a capsule is, in most cases, the value that
16641 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16642 However, when |cur_exp| would point to a capsule,
16643 no extra layer of indirection is present; the |value|
16644 field is what would have been called |value(cur_exp)| if it had not been
16645 encapsulated. Furthermore, if the type is |dependent| or
16646 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16647 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16648 always part of the general |dep_list| structure.
16650 The |get_x_next| routine is careful not to change the values of |cur_type|
16651 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16652 call a macro, which might parse an expression, which might execute lots of
16653 commands in a group; hence it's possible that |cur_type| might change
16654 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16655 |known| or |independent|, during the time |get_x_next| is called. The
16656 programs below are careful to stash sensitive intermediate results in
16657 capsules, so that \MP's generality doesn't cause trouble.
16659 Here's a procedure that illustrates these conventions. It takes
16660 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16661 and stashes them away in a
16662 capsule. It is not used when |cur_type=mp_token_list|.
16663 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16664 copy path lists or to update reference counts, etc.
16666 The special link |mp_void| is put on the capsule returned by
16667 |stash_cur_exp|, because this procedure is used to store macro parameters
16668 that must be easily distinguishable from token lists.
16670 @<Declare the stashing/unstashing routines@>=
16671 pointer mp_stash_cur_exp (MP mp) {
16672 pointer p; /* the capsule that will be returned */
16673 switch (mp->cur_type) {
16674 case unknown_types:
16675 case mp_transform_type:
16676 case mp_color_type:
16679 case mp_proto_dependent:
16680 case mp_independent:
16681 case mp_cmykcolor_type:
16685 p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16686 type(p)=mp->cur_type; value(p)=mp->cur_exp;
16689 mp->cur_type=mp_vacuous; link(p)=mp_void;
16693 @ The inverse of |stash_cur_exp| is the following procedure, which
16694 deletes an unnecessary capsule and puts its contents into |cur_type|
16697 The program steps of \MP\ can be divided into two categories: those in
16698 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16699 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16700 information or not. It's important not to ignore them when they're alive,
16701 and it's important not to pay attention to them when they're dead.
16703 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16704 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16705 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16706 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16707 only when they are alive or dormant.
16709 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16710 are alive or dormant. The \\{unstash} procedure assumes that they are
16711 dead or dormant; it resuscitates them.
16713 @<Declare the stashing/unstashing...@>=
16714 void mp_unstash_cur_exp (MP mp,pointer p) ;
16717 void mp_unstash_cur_exp (MP mp,pointer p) {
16718 mp->cur_type=type(p);
16719 switch (mp->cur_type) {
16720 case unknown_types:
16721 case mp_transform_type:
16722 case mp_color_type:
16725 case mp_proto_dependent:
16726 case mp_independent:
16727 case mp_cmykcolor_type:
16731 mp->cur_exp=value(p);
16732 mp_free_node(mp, p,value_node_size);
16737 @ The following procedure prints the values of expressions in an
16738 abbreviated format. If its first parameter |p| is null, the value of
16739 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16740 containing the desired value. The second parameter controls the amount of
16741 output. If it is~0, dependency lists will be abbreviated to
16742 `\.{linearform}' unless they consist of a single term. If it is greater
16743 than~1, complicated structures (pens, pictures, and paths) will be displayed
16746 @<Declare subroutines for printing expressions@>=
16747 @<Declare the procedure called |print_dp|@>;
16748 @<Declare the stashing/unstashing routines@>;
16749 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16750 boolean restore_cur_exp; /* should |cur_exp| be restored? */
16751 small_number t; /* the type of the expression */
16752 pointer q; /* a big node being displayed */
16753 integer v=0; /* the value of the expression */
16755 restore_cur_exp=false;
16757 p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16760 if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16761 @<Print an abbreviated value of |v| with format depending on |t|@>;
16762 if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16765 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16767 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16768 case mp_boolean_type:
16769 if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16771 case unknown_types: case mp_numeric_type:
16772 @<Display a variable that's been declared but not defined@>;
16774 case mp_string_type:
16775 mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16777 case mp_pen_type: case mp_path_type: case mp_picture_type:
16778 @<Display a complex type@>;
16780 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16781 if ( v==null ) mp_print_type(mp, t);
16782 else @<Display a big node@>;
16784 case mp_known:mp_print_scaled(mp, v); break;
16785 case mp_dependent: case mp_proto_dependent:
16786 mp_print_dp(mp, t,v,verbosity);
16788 case mp_independent:mp_print_variable_name(mp, p); break;
16789 default: mp_confusion(mp, "exp"); break;
16790 @:this can't happen exp}{\quad exp@>
16793 @ @<Display a big node@>=
16795 mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16797 if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16798 else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16799 else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16801 if ( v!=q ) mp_print_char(mp, ',');
16803 mp_print_char(mp, ')');
16806 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16807 in the log file only, unless the user has given a positive value to
16810 @<Display a complex type@>=
16811 if ( verbosity<=1 ) {
16812 mp_print_type(mp, t);
16814 if ( mp->selector==term_and_log )
16815 if ( mp->internal[mp_tracing_online]<=0 ) {
16816 mp->selector=term_only;
16817 mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16818 mp->selector=term_and_log;
16821 case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16822 case mp_path_type:mp_print_path(mp, v,"",false); break;
16823 case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16824 } /* there are no other cases */
16827 @ @<Declare the procedure called |print_dp|@>=
16828 void mp_print_dp (MP mp,small_number t, pointer p,
16829 small_number verbosity) {
16830 pointer q; /* the node following |p| */
16832 if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16833 else mp_print(mp, "linearform");
16836 @ The displayed name of a variable in a ring will not be a capsule unless
16837 the ring consists entirely of capsules.
16839 @<Display a variable that's been declared but not defined@>=
16840 { mp_print_type(mp, t);
16842 { mp_print_char(mp, ' ');
16843 while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16844 mp_print_variable_name(mp, v);
16848 @ When errors are detected during parsing, it is often helpful to
16849 display an expression just above the error message, using |exp_err|
16850 or |disp_err| instead of |print_err|.
16852 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16854 @<Declare subroutines for printing expressions@>=
16855 void mp_disp_err (MP mp,pointer p, char *s) {
16856 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16857 mp_print_nl(mp, ">> ");
16859 mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16861 mp_print_nl(mp, "! "); mp_print(mp, s);
16866 @ If |cur_type| and |cur_exp| contain relevant information that should
16867 be recycled, we will use the following procedure, which changes |cur_type|
16868 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16869 and |cur_exp| as either alive or dormant after this has been done,
16870 because |cur_exp| will not contain a pointer value.
16872 @ @c void mp_flush_cur_exp (MP mp,scaled v) {
16873 switch (mp->cur_type) {
16874 case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16875 case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16876 mp_recycle_value(mp, mp->cur_exp);
16877 mp_free_node(mp, mp->cur_exp,value_node_size);
16879 case mp_string_type:
16880 delete_str_ref(mp->cur_exp); break;
16881 case mp_pen_type: case mp_path_type:
16882 mp_toss_knot_list(mp, mp->cur_exp); break;
16883 case mp_picture_type:
16884 delete_edge_ref(mp->cur_exp); break;
16888 mp->cur_type=mp_known; mp->cur_exp=v;
16891 @ There's a much more general procedure that is capable of releasing
16892 the storage associated with any two-word value packet.
16894 @<Declare the recycling subroutines@>=
16895 void mp_recycle_value (MP mp,pointer p) ;
16897 @ @c void mp_recycle_value (MP mp,pointer p) {
16898 small_number t; /* a type code */
16899 integer vv; /* another value */
16900 pointer q,r,s,pp; /* link manipulation registers */
16901 integer v=0; /* a value */
16903 if ( t<mp_dependent ) v=value(p);
16905 case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16906 case mp_numeric_type:
16908 case unknown_types:
16909 mp_ring_delete(mp, p); break;
16910 case mp_string_type:
16911 delete_str_ref(v); break;
16912 case mp_path_type: case mp_pen_type:
16913 mp_toss_knot_list(mp, v); break;
16914 case mp_picture_type:
16915 delete_edge_ref(v); break;
16916 case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16917 case mp_transform_type:
16918 @<Recycle a big node@>; break;
16919 case mp_dependent: case mp_proto_dependent:
16920 @<Recycle a dependency list@>; break;
16921 case mp_independent:
16922 @<Recycle an independent variable@>; break;
16923 case mp_token_list: case mp_structured:
16924 mp_confusion(mp, "recycle"); break;
16925 @:this can't happen recycle}{\quad recycle@>
16926 case mp_unsuffixed_macro: case mp_suffixed_macro:
16927 mp_delete_mac_ref(mp, value(p)); break;
16928 } /* there are no other cases */
16932 @ @<Recycle a big node@>=
16934 q=v+mp->big_node_size[t];
16936 q=q-2; mp_recycle_value(mp, q);
16938 mp_free_node(mp, v,mp->big_node_size[t]);
16941 @ @<Recycle a dependency list@>=
16944 while ( info(q)!=null ) q=link(q);
16945 link(prev_dep(p))=link(q);
16946 prev_dep(link(q))=prev_dep(p);
16947 link(q)=null; mp_flush_node_list(mp, dep_list(p));
16950 @ When an independent variable disappears, it simply fades away, unless
16951 something depends on it. In the latter case, a dependent variable whose
16952 coefficient of dependence is maximal will take its place.
16953 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16954 as part of his Ph.D. thesis (Stanford University, December 1982).
16955 @^Zabala Salelles, Ignacio Andres@>
16957 For example, suppose that variable $x$ is being recycled, and that the
16958 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16959 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16960 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16961 we will print `\.{\#\#\# -2x=-y+a}'.
16963 There's a slight complication, however: An independent variable $x$
16964 can occur both in dependency lists and in proto-dependency lists.
16965 This makes it necessary to be careful when deciding which coefficient
16968 Furthermore, this complication is not so slight when
16969 a proto-dependent variable is chosen to become independent. For example,
16970 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16971 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16972 large coefficient `50'.
16974 In order to deal with these complications without wasting too much time,
16975 we shall link together the occurrences of~$x$ among all the linear
16976 dependencies, maintaining separate lists for the dependent and
16977 proto-dependent cases.
16979 @<Recycle an independent variable@>=
16981 mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16982 mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16984 while ( q!=dep_head ) {
16985 s=value_loc(q); /* now |link(s)=dep_list(q)| */
16988 if ( info(r)==null ) break;;
16989 if ( info(r)!=p ) {
16992 t=type(q); link(s)=link(r); info(r)=q;
16993 if ( abs(value(r))>mp->max_c[t] ) {
16994 @<Record a new maximum coefficient of type |t|@>;
16996 link(r)=mp->max_link[t]; mp->max_link[t]=r;
17002 if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
17003 @<Choose a dependent variable to take the place of the disappearing
17004 independent variable, and change all remaining dependencies
17009 @ The code for independency removal makes use of three two-word arrays.
17012 integer max_c[mp_proto_dependent+1]; /* max coefficient magnitude */
17013 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
17014 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
17016 @ @<Record a new maximum coefficient...@>=
17018 if ( mp->max_c[t]>0 ) {
17019 link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17021 mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
17024 @ @<Choose a dependent...@>=
17026 if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
17029 t=mp_proto_dependent;
17030 @<Determine the dependency list |s| to substitute for the independent
17032 t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
17033 if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */
17034 link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17036 if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
17037 else { @<Substitute new proto-dependencies in place of |p|@>;}
17038 mp_flush_node_list(mp, s);
17039 if ( mp->fix_needed ) mp_fix_dependencies(mp);
17043 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
17044 and |info(s)| points to the dependent variable~|pp| of type~|t| from
17045 whose dependency list we have removed node~|s|. We must reinsert
17046 node~|s| into the dependency list, with coefficient $-1.0$, and with
17047 |pp| as the new independent variable. Since |pp| will have a larger serial
17048 number than any other variable, we can put node |s| at the head of the
17051 @<Determine the dep...@>=
17052 s=mp->max_ptr[t]; pp=info(s); v=value(s);
17053 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
17054 r=dep_list(pp); link(s)=r;
17055 while ( info(r)!=null ) r=link(r);
17056 q=link(r); link(r)=null;
17057 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
17059 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
17060 if ( mp->internal[mp_tracing_equations]>0 ) {
17061 @<Show the transformed dependency@>;
17064 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
17065 by the dependency list~|s|.
17067 @<Show the transformed...@>=
17068 if ( mp_interesting(mp, p) ) {
17069 mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
17070 @:]]]\#\#\#_}{\.{\#\#\#}@>
17071 if ( v>0 ) mp_print_char(mp, '-');
17072 if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
17073 else vv=mp->max_c[mp_proto_dependent];
17074 if ( vv!=unity ) mp_print_scaled(mp, vv);
17075 mp_print_variable_name(mp, p);
17076 while ( value(p) % s_scale>0 ) {
17077 mp_print(mp, "*4"); value(p)=value(p)-2;
17079 if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
17080 mp_print_dependency(mp, s,t);
17081 mp_end_diagnostic(mp, false);
17084 @ Finally, there are dependent and proto-dependent variables whose
17085 dependency lists must be brought up to date.
17087 @<Substitute new dependencies...@>=
17088 for (t=mp_dependent;t<=mp_proto_dependent;t++){
17090 while ( r!=null ) {
17092 dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17093 mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
17094 if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17095 q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17099 @ @<Substitute new proto...@>=
17100 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17102 while ( r!=null ) {
17104 if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17105 if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17106 mp->cur_type=mp_proto_dependent;
17107 dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
17108 type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
17110 dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17111 mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
17112 if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17113 q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17117 @ Here are some routines that provide handy combinations of actions
17118 that are often needed during error recovery. For example,
17119 `|flush_error|' flushes the current expression, replaces it by
17120 a given value, and calls |error|.
17122 Errors often are detected after an extra token has already been scanned.
17123 The `\\{put\_get}' routines put that token back before calling |error|;
17124 then they get it back again. (Or perhaps they get another token, if
17125 the user has changed things.)
17128 void mp_flush_error (MP mp,scaled v);
17129 void mp_put_get_error (MP mp);
17130 void mp_put_get_flush_error (MP mp,scaled v) ;
17133 void mp_flush_error (MP mp,scaled v) {
17134 mp_error(mp); mp_flush_cur_exp(mp, v);
17136 void mp_put_get_error (MP mp) {
17137 mp_back_error(mp); mp_get_x_next(mp);
17139 void mp_put_get_flush_error (MP mp,scaled v) {
17140 mp_put_get_error(mp);
17141 mp_flush_cur_exp(mp, v);
17144 @ A global variable |var_flag| is set to a special command code
17145 just before \MP\ calls |scan_expression|, if the expression should be
17146 treated as a variable when this command code immediately follows. For
17147 example, |var_flag| is set to |assignment| at the beginning of a
17148 statement, because we want to know the {\sl location\/} of a variable at
17149 the left of `\.{:=}', not the {\sl value\/} of that variable.
17151 The |scan_expression| subroutine calls |scan_tertiary|,
17152 which calls |scan_secondary|, which calls |scan_primary|, which sets
17153 |var_flag:=0|. In this way each of the scanning routines ``knows''
17154 when it has been called with a special |var_flag|, but |var_flag| is
17157 A variable preceding a command that equals |var_flag| is converted to a
17158 token list rather than a value. Furthermore, an `\.{=}' sign following an
17159 expression with |var_flag=assignment| is not considered to be a relation
17160 that produces boolean expressions.
17164 int var_flag; /* command that wants a variable */
17169 @* \[37] Parsing primary expressions.
17170 The first parsing routine, |scan_primary|, is also the most complicated one,
17171 since it involves so many different cases. But each case---with one
17172 exception---is fairly simple by itself.
17174 When |scan_primary| begins, the first token of the primary to be scanned
17175 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17176 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17177 earlier. If |cur_cmd| is not between |min_primary_command| and
17178 |max_primary_command|, inclusive, a syntax error will be signaled.
17180 @<Declare the basic parsing subroutines@>=
17181 void mp_scan_primary (MP mp) {
17182 pointer p,q,r; /* for list manipulation */
17183 quarterword c; /* a primitive operation code */
17184 int my_var_flag; /* initial value of |my_var_flag| */
17185 pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17186 @<Other local variables for |scan_primary|@>;
17187 my_var_flag=mp->var_flag; mp->var_flag=0;
17190 @<Supply diagnostic information, if requested@>;
17191 switch (mp->cur_cmd) {
17192 case left_delimiter:
17193 @<Scan a delimited primary@>; break;
17195 @<Scan a grouped primary@>; break;
17197 @<Scan a string constant@>; break;
17198 case numeric_token:
17199 @<Scan a primary that starts with a numeric token@>; break;
17201 @<Scan a nullary operation@>; break;
17202 case unary: case type_name: case cycle: case plus_or_minus:
17203 @<Scan a unary operation@>; break;
17204 case primary_binary:
17205 @<Scan a binary operation with `\&{of}' between its operands@>; break;
17207 @<Convert a suffix to a string@>; break;
17208 case internal_quantity:
17209 @<Scan an internal numeric quantity@>; break;
17210 case capsule_token:
17211 mp_make_exp_copy(mp, mp->cur_mod); break;
17213 @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17215 mp_bad_exp(mp, "A primary"); goto RESTART; break;
17216 @.A primary expression...@>
17218 mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17220 if ( mp->cur_cmd==left_bracket ) {
17221 if ( mp->cur_type>=mp_known ) {
17222 @<Scan a mediation construction@>;
17229 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17231 @c void mp_bad_exp (MP mp,char * s) {
17233 print_err(s); mp_print(mp, " expression can't begin with `");
17234 mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
17235 mp_print_char(mp, '\'');
17236 help4("I'm afraid I need some sort of value in order to continue,")
17237 ("so I've tentatively inserted `0'. You may want to")
17238 ("delete this zero and insert something else;")
17239 ("see Chapter 27 of The METAFONTbook for an example.");
17240 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17241 mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token;
17242 mp->cur_mod=0; mp_ins_error(mp);
17243 save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17244 mp->var_flag=save_flag;
17247 @ @<Supply diagnostic information, if requested@>=
17249 if ( mp->panicking ) mp_check_mem(mp, false);
17251 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17252 mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17255 @ @<Scan a delimited primary@>=
17257 l_delim=mp->cur_sym; r_delim=mp->cur_mod;
17258 mp_get_x_next(mp); mp_scan_expression(mp);
17259 if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17260 @<Scan the rest of a delimited set of numerics@>;
17262 mp_check_delimiter(mp, l_delim,r_delim);
17266 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17267 within a ``big node.''
17269 @c void mp_stash_in (MP mp,pointer p) {
17270 pointer q; /* temporary register */
17271 type(p)=mp->cur_type;
17272 if ( mp->cur_type==mp_known ) {
17273 value(p)=mp->cur_exp;
17275 if ( mp->cur_type==mp_independent ) {
17276 @<Stash an independent |cur_exp| into a big node@>;
17278 mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17279 /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17280 link(prev_dep(p))=p;
17282 mp_free_node(mp, mp->cur_exp,value_node_size);
17284 mp->cur_type=mp_vacuous;
17287 @ In rare cases the current expression can become |independent|. There
17288 may be many dependency lists pointing to such an independent capsule,
17289 so we can't simply move it into place within a big node. Instead,
17290 we copy it, then recycle it.
17292 @ @<Stash an independent |cur_exp|...@>=
17294 q=mp_single_dependency(mp, mp->cur_exp);
17295 if ( q==mp->dep_final ){
17296 type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17298 type(p)=mp_dependent; mp_new_dep(mp, p,q);
17300 mp_recycle_value(mp, mp->cur_exp);
17303 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17304 are synonymous with |x_part_loc| and |y_part_loc|.
17306 @<Scan the rest of a delimited set of numerics@>=
17308 p=mp_stash_cur_exp(mp);
17309 mp_get_x_next(mp); mp_scan_expression(mp);
17310 @<Make sure the second part of a pair or color has a numeric type@>;
17311 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17312 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17313 else type(q)=mp_pair_type;
17314 mp_init_big_node(mp, q); r=value(q);
17315 mp_stash_in(mp, y_part_loc(r));
17316 mp_unstash_cur_exp(mp, p);
17317 mp_stash_in(mp, x_part_loc(r));
17318 if ( mp->cur_cmd==comma ) {
17319 @<Scan the last of a triplet of numerics@>;
17321 if ( mp->cur_cmd==comma ) {
17322 type(q)=mp_cmykcolor_type;
17323 mp_init_big_node(mp, q); t=value(q);
17324 mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17325 value(cyan_part_loc(t))=value(red_part_loc(r));
17326 mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17327 value(magenta_part_loc(t))=value(green_part_loc(r));
17328 mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17329 value(yellow_part_loc(t))=value(blue_part_loc(r));
17330 mp_recycle_value(mp, r);
17332 @<Scan the last of a quartet of numerics@>;
17334 mp_check_delimiter(mp, l_delim,r_delim);
17335 mp->cur_type=type(q);
17339 @ @<Make sure the second part of a pair or color has a numeric type@>=
17340 if ( mp->cur_type<mp_known ) {
17341 exp_err("Nonnumeric ypart has been replaced by 0");
17342 @.Nonnumeric...replaced by 0@>
17343 help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17344 ("but after finding a nice `a' I found a `b' that isn't")
17345 ("of numeric type. So I've changed that part to zero.")
17346 ("(The b that I didn't like appears above the error message.)");
17347 mp_put_get_flush_error(mp, 0);
17350 @ @<Scan the last of a triplet of numerics@>=
17352 mp_get_x_next(mp); mp_scan_expression(mp);
17353 if ( mp->cur_type<mp_known ) {
17354 exp_err("Nonnumeric third part has been replaced by 0");
17355 @.Nonnumeric...replaced by 0@>
17356 help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17357 ("isn't of numeric type. So I've changed that part to zero.")
17358 ("(The c that I didn't like appears above the error message.)");
17359 mp_put_get_flush_error(mp, 0);
17361 mp_stash_in(mp, blue_part_loc(r));
17364 @ @<Scan the last of a quartet of numerics@>=
17366 mp_get_x_next(mp); mp_scan_expression(mp);
17367 if ( mp->cur_type<mp_known ) {
17368 exp_err("Nonnumeric blackpart has been replaced by 0");
17369 @.Nonnumeric...replaced by 0@>
17370 help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17371 ("of numeric type. So I've changed that part to zero.")
17372 ("(The k that I didn't like appears above the error message.)");
17373 mp_put_get_flush_error(mp, 0);
17375 mp_stash_in(mp, black_part_loc(r));
17378 @ The local variable |group_line| keeps track of the line
17379 where a \&{begingroup} command occurred; this will be useful
17380 in an error message if the group doesn't actually end.
17382 @<Other local variables for |scan_primary|@>=
17383 integer group_line; /* where a group began */
17385 @ @<Scan a grouped primary@>=
17387 group_line=mp_true_line(mp);
17388 if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17389 save_boundary_item(p);
17391 mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17392 } while (! (mp->cur_cmd!=semicolon));
17393 if ( mp->cur_cmd!=end_group ) {
17394 print_err("A group begun on line ");
17395 @.A group...never ended@>
17396 mp_print_int(mp, group_line);
17397 mp_print(mp, " never ended");
17398 help2("I saw a `begingroup' back there that hasn't been matched")
17399 ("by `endgroup'. So I've inserted `endgroup' now.");
17400 mp_back_error(mp); mp->cur_cmd=end_group;
17403 /* this might change |cur_type|, if independent variables are recycled */
17404 if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17407 @ @<Scan a string constant@>=
17409 mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17412 @ Later we'll come to procedures that perform actual operations like
17413 addition, square root, and so on; our purpose now is to do the parsing.
17414 But we might as well mention those future procedures now, so that the
17415 suspense won't be too bad:
17418 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17419 `\&{true}' or `\&{pencircle}');
17422 |do_unary(c)| applies a primitive operation to the current expression;
17425 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17426 and the current expression.
17428 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17430 @ @<Scan a unary operation@>=
17432 c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp);
17433 mp_do_unary(mp, c); goto DONE;
17436 @ A numeric token might be a primary by itself, or it might be the
17437 numerator of a fraction composed solely of numeric tokens, or it might
17438 multiply the primary that follows (provided that the primary doesn't begin
17439 with a plus sign or a minus sign). The code here uses the facts that
17440 |max_primary_command=plus_or_minus| and
17441 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17442 than unity, we try to retain higher precision when we use it in scalar
17445 @<Other local variables for |scan_primary|@>=
17446 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17448 @ @<Scan a primary that starts with a numeric token@>=
17450 mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17451 if ( mp->cur_cmd!=slash ) {
17455 if ( mp->cur_cmd!=numeric_token ) {
17457 mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17460 num=mp->cur_exp; denom=mp->cur_mod;
17461 if ( denom==0 ) { @<Protest division by zero@>; }
17462 else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17463 check_arith; mp_get_x_next(mp);
17465 if ( mp->cur_cmd>=min_primary_command ) {
17466 if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17467 p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17468 if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17469 mp_do_binary(mp, p,times);
17471 mp_frac_mult(mp, num,denom);
17472 mp_free_node(mp, p,value_node_size);
17479 @ @<Protest division...@>=
17481 print_err("Division by zero");
17482 @.Division by zero@>
17483 help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17486 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17488 c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17489 if ( mp->cur_cmd!=of_token ) {
17490 mp_missing_err(mp, "of"); mp_print(mp, " for ");
17491 mp_print_cmd_mod(mp, primary_binary,c);
17493 help1("I've got the first argument; will look now for the other.");
17496 p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp);
17497 mp_do_binary(mp, p,c); goto DONE;
17500 @ @<Convert a suffix to a string@>=
17502 mp_get_x_next(mp); mp_scan_suffix(mp);
17503 mp->old_setting=mp->selector; mp->selector=new_string;
17504 mp_show_token_list(mp, mp->cur_exp,null,100000,0);
17505 mp_flush_token_list(mp, mp->cur_exp);
17506 mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting;
17507 mp->cur_type=mp_string_type;
17511 @ If an internal quantity appears all by itself on the left of an
17512 assignment, we return a token list of length one, containing the address
17513 of the internal quantity plus |hash_end|. (This accords with the conventions
17514 of the save stack, as described earlier.)
17516 @<Scan an internal...@>=
17519 if ( my_var_flag==assignment ) {
17521 if ( mp->cur_cmd==assignment ) {
17522 mp->cur_exp=mp_get_avail(mp);
17523 info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list;
17528 mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17531 @ The most difficult part of |scan_primary| has been saved for last, since
17532 it was necessary to build up some confidence first. We can now face the task
17533 of scanning a variable.
17535 As we scan a variable, we build a token list containing the relevant
17536 names and subscript values, simultaneously following along in the
17537 ``collective'' structure to see if we are actually dealing with a macro
17538 instead of a value.
17540 The local variables |pre_head| and |post_head| will point to the beginning
17541 of the prefix and suffix lists; |tail| will point to the end of the list
17542 that is currently growing.
17544 Another local variable, |tt|, contains partial information about the
17545 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17546 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17547 doesn't bother to update its information about type. And if
17548 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17550 @ @<Other local variables for |scan_primary|@>=
17551 pointer pre_head,post_head,tail;
17552 /* prefix and suffix list variables */
17553 small_number tt; /* approximation to the type of the variable-so-far */
17554 pointer t; /* a token */
17555 pointer macro_ref = 0; /* reference count for a suffixed macro */
17557 @ @<Scan a variable primary...@>=
17559 fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17561 t=mp_cur_tok(mp); link(tail)=t;
17562 if ( tt!=undefined ) {
17563 @<Find the approximate type |tt| and corresponding~|q|@>;
17564 if ( tt>=mp_unsuffixed_macro ) {
17565 @<Either begin an unsuffixed macro call or
17566 prepare for a suffixed one@>;
17569 mp_get_x_next(mp); tail=t;
17570 if ( mp->cur_cmd==left_bracket ) {
17571 @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17573 if ( mp->cur_cmd>max_suffix_token ) break;
17574 if ( mp->cur_cmd<min_suffix_token ) break;
17575 } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17576 @<Handle unusual cases that masquerade as variables, and |goto restart|
17577 or |goto done| if appropriate;
17578 otherwise make a copy of the variable and |goto done|@>;
17581 @ @<Either begin an unsuffixed macro call or...@>=
17584 if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17585 post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17586 tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17588 @<Set up unsuffixed macro call and |goto restart|@>;
17592 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17594 mp_get_x_next(mp); mp_scan_expression(mp);
17595 if ( mp->cur_cmd!=right_bracket ) {
17596 @<Put the left bracket and the expression back to be rescanned@>;
17598 if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17599 mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17603 @ The left bracket that we thought was introducing a subscript might have
17604 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17605 So we don't issue an error message at this point; but we do want to back up
17606 so as to avoid any embarrassment about our incorrect assumption.
17608 @<Put the left bracket and the expression back to be rescanned@>=
17610 mp_back_input(mp); /* that was the token following the current expression */
17611 mp_back_expr(mp); mp->cur_cmd=left_bracket;
17612 mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17615 @ Here's a routine that puts the current expression back to be read again.
17617 @c void mp_back_expr (MP mp) {
17618 pointer p; /* capsule token */
17619 p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17622 @ Unknown subscripts lead to the following error message.
17624 @c void mp_bad_subscript (MP mp) {
17625 exp_err("Improper subscript has been replaced by zero");
17626 @.Improper subscript...@>
17627 help3("A bracketed subscript must have a known numeric value;")
17628 ("unfortunately, what I found was the value that appears just")
17629 ("above this error message. So I'll try a zero subscript.");
17630 mp_flush_error(mp, 0);
17633 @ Every time we call |get_x_next|, there's a chance that the variable we've
17634 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17635 into the variable structure; we need to start searching from the root each time.
17637 @<Find the approximate type |tt| and corresponding~|q|@>=
17640 p=link(pre_head); q=info(p); tt=undefined;
17641 if ( eq_type(q) % outer_tag==tag_token ) {
17643 if ( q==null ) goto DONE2;
17647 tt=type(q); goto DONE2;
17649 if ( type(q)!=mp_structured ) goto DONE2;
17650 q=link(attr_head(q)); /* the |collective_subscript| attribute */
17651 if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17652 do { q=link(q); } while (! (attr_loc(q)>=info(p)));
17653 if ( attr_loc(q)>info(p) ) goto DONE2;
17661 @ How do things stand now? Well, we have scanned an entire variable name,
17662 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17663 |cur_sym| represent the token that follows. If |post_head=null|, a
17664 token list for this variable name starts at |link(pre_head)|, with all
17665 subscripts evaluated. But if |post_head<>null|, the variable turned out
17666 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17667 |post_head| is the head of a token list containing both `\.{\AT!}' and
17670 Our immediate problem is to see if this variable still exists. (Variable
17671 structures can change drastically whenever we call |get_x_next|; users
17672 aren't supposed to do this, but the fact that it is possible means that
17673 we must be cautious.)
17675 The following procedure prints an error message when a variable
17676 unexpectedly disappears. Its help message isn't quite right for
17677 our present purposes, but we'll be able to fix that up.
17680 void mp_obliterated (MP mp,pointer q) {
17681 print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17682 mp_print(mp, " has been obliterated");
17683 @.Variable...obliterated@>
17684 help5("It seems you did a nasty thing---probably by accident,")
17685 ("but nevertheless you nearly hornswoggled me...")
17686 ("While I was evaluating the right-hand side of this")
17687 ("command, something happened, and the left-hand side")
17688 ("is no longer a variable! So I won't change anything.");
17691 @ If the variable does exist, we also need to check
17692 for a few other special cases before deciding that a plain old ordinary
17693 variable has, indeed, been scanned.
17695 @<Handle unusual cases that masquerade as variables...@>=
17696 if ( post_head!=null ) {
17697 @<Set up suffixed macro call and |goto restart|@>;
17699 q=link(pre_head); free_avail(pre_head);
17700 if ( mp->cur_cmd==my_var_flag ) {
17701 mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17703 p=mp_find_variable(mp, q);
17705 mp_make_exp_copy(mp, p);
17707 mp_obliterated(mp, q);
17708 mp->help_line[2]="While I was evaluating the suffix of this variable,";
17709 mp->help_line[1]="something was redefined, and it's no longer a variable!";
17710 mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17711 mp_put_get_flush_error(mp, 0);
17713 mp_flush_node_list(mp, q);
17716 @ The only complication associated with macro calling is that the prefix
17717 and ``at'' parameters must be packaged in an appropriate list of lists.
17719 @<Set up unsuffixed macro call and |goto restart|@>=
17721 p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17722 info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17727 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17728 we don't care, because we have reserved a pointer (|macro_ref|) to its
17731 @<Set up suffixed macro call and |goto restart|@>=
17733 mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17734 info(pre_head)=link(pre_head); link(pre_head)=post_head;
17735 info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17736 mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17737 mp_get_x_next(mp); goto RESTART;
17740 @ Our remaining job is simply to make a copy of the value that has been
17741 found. Some cases are harder than others, but complexity arises solely
17742 because of the multiplicity of possible cases.
17744 @<Declare the procedure called |make_exp_copy|@>=
17745 @<Declare subroutines needed by |make_exp_copy|@>;
17746 void mp_make_exp_copy (MP mp,pointer p) {
17747 pointer q,r,t; /* registers for list manipulation */
17749 mp->cur_type=type(p);
17750 switch (mp->cur_type) {
17751 case mp_vacuous: case mp_boolean_type: case mp_known:
17752 mp->cur_exp=value(p); break;
17753 case unknown_types:
17754 mp->cur_exp=mp_new_ring_entry(mp, p);
17756 case mp_string_type:
17757 mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17759 case mp_picture_type:
17760 mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17763 mp->cur_exp=copy_pen(value(p));
17766 mp->cur_exp=mp_copy_path(mp, value(p));
17768 case mp_transform_type: case mp_color_type:
17769 case mp_cmykcolor_type: case mp_pair_type:
17770 @<Copy the big node |p|@>;
17772 case mp_dependent: case mp_proto_dependent:
17773 mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17775 case mp_numeric_type:
17776 new_indep(p); goto RESTART;
17778 case mp_independent:
17779 q=mp_single_dependency(mp, p);
17780 if ( q==mp->dep_final ){
17781 mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17783 mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17787 mp_confusion(mp, "copy");
17788 @:this can't happen copy}{\quad copy@>
17793 @ The |encapsulate| subroutine assumes that |dep_final| is the
17794 tail of dependency list~|p|.
17796 @<Declare subroutines needed by |make_exp_copy|@>=
17797 void mp_encapsulate (MP mp,pointer p) {
17798 mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17799 name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17802 @ The most tedious case arises when the user refers to a
17803 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17804 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17807 @<Copy the big node |p|@>=
17809 if ( value(p)==null )
17810 mp_init_big_node(mp, p);
17811 t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17812 mp_init_big_node(mp, t);
17813 q=value(p)+mp->big_node_size[mp->cur_type];
17814 r=value(t)+mp->big_node_size[mp->cur_type];
17816 q=q-2; r=r-2; mp_install(mp, r,q);
17817 } while (q!=value(p));
17821 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17822 a big node that will be part of a capsule.
17824 @<Declare subroutines needed by |make_exp_copy|@>=
17825 void mp_install (MP mp,pointer r, pointer q) {
17826 pointer p; /* temporary register */
17827 if ( type(q)==mp_known ){
17828 value(r)=value(q); type(r)=mp_known;
17829 } else if ( type(q)==mp_independent ) {
17830 p=mp_single_dependency(mp, q);
17831 if ( p==mp->dep_final ) {
17832 type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17834 type(r)=mp_dependent; mp_new_dep(mp, r,p);
17837 type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17841 @ Expressions of the form `\.{a[b,c]}' are converted into
17842 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17843 provided that \.a is numeric.
17845 @<Scan a mediation...@>=
17847 p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17848 if ( mp->cur_cmd!=comma ) {
17849 @<Put the left bracket and the expression back...@>;
17850 mp_unstash_cur_exp(mp, p);
17852 q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17853 if ( mp->cur_cmd!=right_bracket ) {
17854 mp_missing_err(mp, "]");
17856 help3("I've scanned an expression of the form `a[b,c',")
17857 ("so a right bracket should have come next.")
17858 ("I shall pretend that one was there.");
17861 r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17862 mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times);
17863 mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17867 @ Here is a comparatively simple routine that is used to scan the
17868 \&{suffix} parameters of a macro.
17870 @<Declare the basic parsing subroutines@>=
17871 void mp_scan_suffix (MP mp) {
17872 pointer h,t; /* head and tail of the list being built */
17873 pointer p; /* temporary register */
17874 h=mp_get_avail(mp); t=h;
17876 if ( mp->cur_cmd==left_bracket ) {
17877 @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17879 if ( mp->cur_cmd==numeric_token ) {
17880 p=mp_new_num_tok(mp, mp->cur_mod);
17881 } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17882 p=mp_get_avail(mp); info(p)=mp->cur_sym;
17886 link(t)=p; t=p; mp_get_x_next(mp);
17888 mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17891 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17893 mp_get_x_next(mp); mp_scan_expression(mp);
17894 if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17895 if ( mp->cur_cmd!=right_bracket ) {
17896 mp_missing_err(mp, "]");
17898 help3("I've seen a `[' and a subscript value, in a suffix,")
17899 ("so a right bracket should have come next.")
17900 ("I shall pretend that one was there.");
17903 mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17906 @* \[38] Parsing secondary and higher expressions.
17907 After the intricacies of |scan_primary|\kern-1pt,
17908 the |scan_secondary| routine is
17909 refreshingly simple. It's not trivial, but the operations are relatively
17910 straightforward; the main difficulty is, again, that expressions and data
17911 structures might change drastically every time we call |get_x_next|, so a
17912 cautious approach is mandatory. For example, a macro defined by
17913 \&{primarydef} might have disappeared by the time its second argument has
17914 been scanned; we solve this by increasing the reference count of its token
17915 list, so that the macro can be called even after it has been clobbered.
17917 @<Declare the basic parsing subroutines@>=
17918 void mp_scan_secondary (MP mp) {
17919 pointer p; /* for list manipulation */
17920 halfword c,d; /* operation codes or modifiers */
17921 pointer mac_name; /* token defined with \&{primarydef} */
17923 if ((mp->cur_cmd<min_primary_command)||
17924 (mp->cur_cmd>max_primary_command) )
17925 mp_bad_exp(mp, "A secondary");
17926 @.A secondary expression...@>
17927 mp_scan_primary(mp);
17929 if ( mp->cur_cmd<=max_secondary_command )
17930 if ( mp->cur_cmd>=min_secondary_command ) {
17931 p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17932 if ( d==secondary_primary_macro ) {
17933 mac_name=mp->cur_sym; add_mac_ref(c);
17935 mp_get_x_next(mp); mp_scan_primary(mp);
17936 if ( d!=secondary_primary_macro ) {
17937 mp_do_binary(mp, p,c);
17939 mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17940 decr(ref_count(c)); mp_get_x_next(mp);
17947 @ The following procedure calls a macro that has two parameters,
17950 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17951 pointer q,r; /* nodes in the parameter list */
17952 q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17953 info(q)=p; info(r)=mp_stash_cur_exp(mp);
17954 mp_macro_call(mp, c,q,n);
17957 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17959 @<Declare the basic parsing subroutines@>=
17960 void mp_scan_tertiary (MP mp) {
17961 pointer p; /* for list manipulation */
17962 halfword c,d; /* operation codes or modifiers */
17963 pointer mac_name; /* token defined with \&{secondarydef} */
17965 if ((mp->cur_cmd<min_primary_command)||
17966 (mp->cur_cmd>max_primary_command) )
17967 mp_bad_exp(mp, "A tertiary");
17968 @.A tertiary expression...@>
17969 mp_scan_secondary(mp);
17971 if ( mp->cur_cmd<=max_tertiary_command ) {
17972 if ( mp->cur_cmd>=min_tertiary_command ) {
17973 p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17974 if ( d==tertiary_secondary_macro ) {
17975 mac_name=mp->cur_sym; add_mac_ref(c);
17977 mp_get_x_next(mp); mp_scan_secondary(mp);
17978 if ( d!=tertiary_secondary_macro ) {
17979 mp_do_binary(mp, p,c);
17981 mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17982 decr(ref_count(c)); mp_get_x_next(mp);
17990 @ Finally we reach the deepest level in our quartet of parsing routines.
17991 This one is much like the others; but it has an extra complication from
17992 paths, which materialize here.
17994 @d continue_path 25 /* a label inside of |scan_expression| */
17995 @d finish_path 26 /* another */
17997 @<Declare the basic parsing subroutines@>=
17998 void mp_scan_expression (MP mp) {
17999 pointer p,q,r,pp,qq; /* for list manipulation */
18000 halfword c,d; /* operation codes or modifiers */
18001 int my_var_flag; /* initial value of |var_flag| */
18002 pointer mac_name; /* token defined with \&{tertiarydef} */
18003 boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
18004 scaled x,y; /* explicit coordinates or tension at a path join */
18005 int t; /* knot type following a path join */
18007 my_var_flag=mp->var_flag; mac_name=null;
18009 if ((mp->cur_cmd<min_primary_command)||
18010 (mp->cur_cmd>max_primary_command) )
18011 mp_bad_exp(mp, "An");
18012 @.An expression...@>
18013 mp_scan_tertiary(mp);
18015 if ( mp->cur_cmd<=max_expression_command )
18016 if ( mp->cur_cmd>=min_expression_command ) {
18017 if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
18018 p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
18019 if ( d==expression_tertiary_macro ) {
18020 mac_name=mp->cur_sym; add_mac_ref(c);
18022 if ( (d<ampersand)||((d==ampersand)&&
18023 ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
18024 @<Scan a path construction operation;
18025 but |return| if |p| has the wrong type@>;
18027 mp_get_x_next(mp); mp_scan_tertiary(mp);
18028 if ( d!=expression_tertiary_macro ) {
18029 mp_do_binary(mp, p,c);
18031 mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18032 decr(ref_count(c)); mp_get_x_next(mp);
18041 @ The reader should review the data structure conventions for paths before
18042 hoping to understand the next part of this code.
18044 @<Scan a path construction operation...@>=
18047 @<Convert the left operand, |p|, into a partial path ending at~|q|;
18048 but |return| if |p| doesn't have a suitable type@>;
18050 @<Determine the path join parameters;
18051 but |goto finish_path| if there's only a direction specifier@>;
18052 if ( mp->cur_cmd==cycle ) {
18053 @<Get ready to close a cycle@>;
18055 mp_scan_tertiary(mp);
18056 @<Convert the right operand, |cur_exp|,
18057 into a partial path from |pp| to~|qq|@>;
18059 @<Join the partial paths and reset |p| and |q| to the head and tail
18061 if ( mp->cur_cmd>=min_expression_command )
18062 if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
18064 @<Choose control points for the path and put the result into |cur_exp|@>;
18067 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
18069 mp_unstash_cur_exp(mp, p);
18070 if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
18071 else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
18074 while ( link(q)!=p ) q=link(q);
18075 if ( left_type(p)!=mp_endpoint ) { /* open up a cycle */
18076 r=mp_copy_knot(mp, p); link(q)=r; q=r;
18078 left_type(p)=mp_open; right_type(q)=mp_open;
18081 @ A pair of numeric values is changed into a knot node for a one-point path
18082 when \MP\ discovers that the pair is part of a path.
18084 @c@<Declare the procedure called |known_pair|@>;
18085 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
18086 pointer q; /* the new node */
18087 q=mp_get_node(mp, knot_node_size); left_type(q)=mp_endpoint;
18088 right_type(q)=mp_endpoint; originator(q)=mp_metapost_user; link(q)=q;
18089 mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
18093 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
18094 of the current expression, assuming that the current expression is a
18095 pair of known numerics. Unknown components are zeroed, and the
18096 current expression is flushed.
18098 @<Declare the procedure called |known_pair|@>=
18099 void mp_known_pair (MP mp) {
18100 pointer p; /* the pair node */
18101 if ( mp->cur_type!=mp_pair_type ) {
18102 exp_err("Undefined coordinates have been replaced by (0,0)");
18103 @.Undefined coordinates...@>
18104 help5("I need x and y numbers for this part of the path.")
18105 ("The value I found (see above) was no good;")
18106 ("so I'll try to keep going by using zero instead.")
18107 ("(Chapter 27 of The METAFONTbook explains that")
18108 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18109 ("you might want to type `I ??" "?' now.)");
18110 mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18112 p=value(mp->cur_exp);
18113 @<Make sure that both |x| and |y| parts of |p| are known;
18114 copy them into |cur_x| and |cur_y|@>;
18115 mp_flush_cur_exp(mp, 0);
18119 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18120 if ( type(x_part_loc(p))==mp_known ) {
18121 mp->cur_x=value(x_part_loc(p));
18123 mp_disp_err(mp, x_part_loc(p),
18124 "Undefined x coordinate has been replaced by 0");
18125 @.Undefined coordinates...@>
18126 help5("I need a `known' x value for this part of the path.")
18127 ("The value I found (see above) was no good;")
18128 ("so I'll try to keep going by using zero instead.")
18129 ("(Chapter 27 of The METAFONTbook explains that")
18130 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18131 ("you might want to type `I ??" "?' now.)");
18132 mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18134 if ( type(y_part_loc(p))==mp_known ) {
18135 mp->cur_y=value(y_part_loc(p));
18137 mp_disp_err(mp, y_part_loc(p),
18138 "Undefined y coordinate has been replaced by 0");
18139 help5("I need a `known' y value for this part of the path.")
18140 ("The value I found (see above) was no good;")
18141 ("so I'll try to keep going by using zero instead.")
18142 ("(Chapter 27 of The METAFONTbook explains that")
18143 ("you might want to type `I ??" "?' now.)");
18144 mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18147 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18149 @<Determine the path join parameters...@>=
18150 if ( mp->cur_cmd==left_brace ) {
18151 @<Put the pre-join direction information into node |q|@>;
18154 if ( d==path_join ) {
18155 @<Determine the tension and/or control points@>;
18156 } else if ( d!=ampersand ) {
18160 if ( mp->cur_cmd==left_brace ) {
18161 @<Put the post-join direction information into |x| and |t|@>;
18162 } else if ( right_type(q)!=mp_explicit ) {
18166 @ The |scan_direction| subroutine looks at the directional information
18167 that is enclosed in braces, and also scans ahead to the following character.
18168 A type code is returned, either |open| (if the direction was $(0,0)$),
18169 or |curl| (if the direction was a curl of known value |cur_exp|), or
18170 |given| (if the direction is given by the |angle| value that now
18171 appears in |cur_exp|).
18173 There's nothing difficult about this subroutine, but the program is rather
18174 lengthy because a variety of potential errors need to be nipped in the bud.
18176 @c small_number mp_scan_direction (MP mp) {
18177 int t; /* the type of information found */
18178 scaled x; /* an |x| coordinate */
18180 if ( mp->cur_cmd==curl_command ) {
18181 @<Scan a curl specification@>;
18183 @<Scan a given direction@>;
18185 if ( mp->cur_cmd!=right_brace ) {
18186 mp_missing_err(mp, "}");
18187 @.Missing `\char`\}'@>
18188 help3("I've scanned a direction spec for part of a path,")
18189 ("so a right brace should have come next.")
18190 ("I shall pretend that one was there.");
18197 @ @<Scan a curl specification@>=
18198 { mp_get_x_next(mp); mp_scan_expression(mp);
18199 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){
18200 exp_err("Improper curl has been replaced by 1");
18202 help1("A curl must be a known, nonnegative number.");
18203 mp_put_get_flush_error(mp, unity);
18208 @ @<Scan a given direction@>=
18209 { mp_scan_expression(mp);
18210 if ( mp->cur_type>mp_pair_type ) {
18211 @<Get given directions separated by commas@>;
18215 if ( (mp->cur_x==0)&&(mp->cur_y==0) ) t=mp_open;
18216 else { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18219 @ @<Get given directions separated by commas@>=
18221 if ( mp->cur_type!=mp_known ) {
18222 exp_err("Undefined x coordinate has been replaced by 0");
18223 @.Undefined coordinates...@>
18224 help5("I need a `known' x value for this part of the path.")
18225 ("The value I found (see above) was no good;")
18226 ("so I'll try to keep going by using zero instead.")
18227 ("(Chapter 27 of The METAFONTbook explains that")
18228 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18229 ("you might want to type `I ??" "?' now.)");
18230 mp_put_get_flush_error(mp, 0);
18233 if ( mp->cur_cmd!=comma ) {
18234 mp_missing_err(mp, ",");
18236 help2("I've got the x coordinate of a path direction;")
18237 ("will look for the y coordinate next.");
18240 mp_get_x_next(mp); mp_scan_expression(mp);
18241 if ( mp->cur_type!=mp_known ) {
18242 exp_err("Undefined y coordinate has been replaced by 0");
18243 help5("I need a `known' y value for this part of the path.")
18244 ("The value I found (see above) was no good;")
18245 ("so I'll try to keep going by using zero instead.")
18246 ("(Chapter 27 of The METAFONTbook explains that")
18247 ("you might want to type `I ??" "?' now.)");
18248 mp_put_get_flush_error(mp, 0);
18250 mp->cur_y=mp->cur_exp; mp->cur_x=x;
18253 @ At this point |right_type(q)| is usually |open|, but it may have been
18254 set to some other value by a previous splicing operation. We must maintain
18255 the value of |right_type(q)| in unusual cases such as
18256 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18258 @<Put the pre-join...@>=
18260 t=mp_scan_direction(mp);
18261 if ( t!=mp_open ) {
18262 right_type(q)=t; right_given(q)=mp->cur_exp;
18263 if ( left_type(q)==mp_open ) {
18264 left_type(q)=t; left_given(q)=mp->cur_exp;
18265 } /* note that |left_given(q)=left_curl(q)| */
18269 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18270 and since |left_given| is similarly equivalent to |left_x|, we use
18271 |x| and |y| to hold the given direction and tension information when
18272 there are no explicit control points.
18274 @<Put the post-join...@>=
18276 t=mp_scan_direction(mp);
18277 if ( right_type(q)!=mp_explicit ) x=mp->cur_exp;
18278 else t=mp_explicit; /* the direction information is superfluous */
18281 @ @<Determine the tension and/or...@>=
18284 if ( mp->cur_cmd==tension ) {
18285 @<Set explicit tensions@>;
18286 } else if ( mp->cur_cmd==controls ) {
18287 @<Set explicit control points@>;
18289 right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18292 if ( mp->cur_cmd!=path_join ) {
18293 mp_missing_err(mp, "..");
18295 help1("A path join command should end with two dots.");
18302 @ @<Set explicit tensions@>=
18304 mp_get_x_next(mp); y=mp->cur_cmd;
18305 if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18306 mp_scan_primary(mp);
18307 @<Make sure that the current expression is a valid tension setting@>;
18308 if ( y==at_least ) negate(mp->cur_exp);
18309 right_tension(q)=mp->cur_exp;
18310 if ( mp->cur_cmd==and_command ) {
18311 mp_get_x_next(mp); y=mp->cur_cmd;
18312 if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18313 mp_scan_primary(mp);
18314 @<Make sure that the current expression is a valid tension setting@>;
18315 if ( y==at_least ) negate(mp->cur_exp);
18320 @ @d min_tension three_quarter_unit
18322 @<Make sure that the current expression is a valid tension setting@>=
18323 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18324 exp_err("Improper tension has been set to 1");
18325 @.Improper tension@>
18326 help1("The expression above should have been a number >=3/4.");
18327 mp_put_get_flush_error(mp, unity);
18330 @ @<Set explicit control points@>=
18332 right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18333 mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18334 if ( mp->cur_cmd!=and_command ) {
18335 x=right_x(q); y=right_y(q);
18337 mp_get_x_next(mp); mp_scan_primary(mp);
18338 mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18342 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18344 if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18345 else pp=mp->cur_exp;
18347 while ( link(qq)!=pp ) qq=link(qq);
18348 if ( left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18349 r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18351 left_type(pp)=mp_open; right_type(qq)=mp_open;
18354 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18355 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18356 shouldn't have length zero.
18358 @<Get ready to close a cycle@>=
18360 cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18361 if ( d==ampersand ) if ( p==q ) {
18362 d=path_join; right_tension(q)=unity; y=unity;
18366 @ @<Join the partial paths and reset |p| and |q|...@>=
18368 if ( d==ampersand ) {
18369 if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18370 print_err("Paths don't touch; `&' will be changed to `..'");
18371 @.Paths don't touch@>
18372 help3("When you join paths `p&q', the ending point of p")
18373 ("must be exactly equal to the starting point of q.")
18374 ("So I'm going to pretend that you said `p..q' instead.");
18375 mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18378 @<Plug an opening in |right_type(pp)|, if possible@>;
18379 if ( d==ampersand ) {
18380 @<Splice independent paths together@>;
18382 @<Plug an opening in |right_type(q)|, if possible@>;
18383 link(q)=pp; left_y(pp)=y;
18384 if ( t!=mp_open ) { left_x(pp)=x; left_type(pp)=t; };
18389 @ @<Plug an opening in |right_type(q)|...@>=
18390 if ( right_type(q)==mp_open ) {
18391 if ( (left_type(q)==mp_curl)||(left_type(q)==mp_given) ) {
18392 right_type(q)=left_type(q); right_given(q)=left_given(q);
18396 @ @<Plug an opening in |right_type(pp)|...@>=
18397 if ( right_type(pp)==mp_open ) {
18398 if ( (t==mp_curl)||(t==mp_given) ) {
18399 right_type(pp)=t; right_given(pp)=x;
18403 @ @<Splice independent paths together@>=
18405 if ( left_type(q)==mp_open ) if ( right_type(q)==mp_open ) {
18406 left_type(q)=mp_curl; left_curl(q)=unity;
18408 if ( right_type(pp)==mp_open ) if ( t==mp_open ) {
18409 right_type(pp)=mp_curl; right_curl(pp)=unity;
18411 right_type(q)=right_type(pp); link(q)=link(pp);
18412 right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18413 mp_free_node(mp, pp,knot_node_size);
18414 if ( qq==pp ) qq=q;
18417 @ @<Choose control points for the path...@>=
18419 if ( d==ampersand ) p=q;
18421 left_type(p)=mp_endpoint;
18422 if ( right_type(p)==mp_open ) {
18423 right_type(p)=mp_curl; right_curl(p)=unity;
18425 right_type(q)=mp_endpoint;
18426 if ( left_type(q)==mp_open ) {
18427 left_type(q)=mp_curl; left_curl(q)=unity;
18431 mp_make_choices(mp, p);
18432 mp->cur_type=mp_path_type; mp->cur_exp=p
18434 @ Finally, we sometimes need to scan an expression whose value is
18435 supposed to be either |true_code| or |false_code|.
18437 @<Declare the basic parsing subroutines@>=
18438 void mp_get_boolean (MP mp) {
18439 mp_get_x_next(mp); mp_scan_expression(mp);
18440 if ( mp->cur_type!=mp_boolean_type ) {
18441 exp_err("Undefined condition will be treated as `false'");
18442 @.Undefined condition...@>
18443 help2("The expression shown above should have had a definite")
18444 ("true-or-false value. I'm changing it to `false'.");
18445 mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18449 @* \[39] Doing the operations.
18450 The purpose of parsing is primarily to permit people to avoid piles of
18451 parentheses. But the real work is done after the structure of an expression
18452 has been recognized; that's when new expressions are generated. We
18453 turn now to the guts of \MP, which handles individual operators that
18454 have come through the parsing mechanism.
18456 We'll start with the easy ones that take no operands, then work our way
18457 up to operators with one and ultimately two arguments. In other words,
18458 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18459 that are invoked periodically by the expression scanners.
18461 First let's make sure that all of the primitive operators are in the
18462 hash table. Although |scan_primary| and its relatives made use of the
18463 \\{cmd} code for these operators, the \\{do} routines base everything
18464 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18465 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18468 mp_primitive(mp, "true",nullary,true_code);
18469 @:true_}{\&{true} primitive@>
18470 mp_primitive(mp, "false",nullary,false_code);
18471 @:false_}{\&{false} primitive@>
18472 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18473 @:null_picture_}{\&{nullpicture} primitive@>
18474 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18475 @:null_pen_}{\&{nullpen} primitive@>
18476 mp_primitive(mp, "jobname",nullary,job_name_op);
18477 @:job_name_}{\&{jobname} primitive@>
18478 mp_primitive(mp, "readstring",nullary,read_string_op);
18479 @:read_string_}{\&{readstring} primitive@>
18480 mp_primitive(mp, "pencircle",nullary,pen_circle);
18481 @:pen_circle_}{\&{pencircle} primitive@>
18482 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18483 @:normal_deviate_}{\&{normaldeviate} primitive@>
18484 mp_primitive(mp, "readfrom",unary,read_from_op);
18485 @:read_from_}{\&{readfrom} primitive@>
18486 mp_primitive(mp, "closefrom",unary,close_from_op);
18487 @:close_from_}{\&{closefrom} primitive@>
18488 mp_primitive(mp, "odd",unary,odd_op);
18489 @:odd_}{\&{odd} primitive@>
18490 mp_primitive(mp, "known",unary,known_op);
18491 @:known_}{\&{known} primitive@>
18492 mp_primitive(mp, "unknown",unary,unknown_op);
18493 @:unknown_}{\&{unknown} primitive@>
18494 mp_primitive(mp, "not",unary,not_op);
18495 @:not_}{\&{not} primitive@>
18496 mp_primitive(mp, "decimal",unary,decimal);
18497 @:decimal_}{\&{decimal} primitive@>
18498 mp_primitive(mp, "reverse",unary,reverse);
18499 @:reverse_}{\&{reverse} primitive@>
18500 mp_primitive(mp, "makepath",unary,make_path_op);
18501 @:make_path_}{\&{makepath} primitive@>
18502 mp_primitive(mp, "makepen",unary,make_pen_op);
18503 @:make_pen_}{\&{makepen} primitive@>
18504 mp_primitive(mp, "oct",unary,oct_op);
18505 @:oct_}{\&{oct} primitive@>
18506 mp_primitive(mp, "hex",unary,hex_op);
18507 @:hex_}{\&{hex} primitive@>
18508 mp_primitive(mp, "ASCII",unary,ASCII_op);
18509 @:ASCII_}{\&{ASCII} primitive@>
18510 mp_primitive(mp, "char",unary,char_op);
18511 @:char_}{\&{char} primitive@>
18512 mp_primitive(mp, "length",unary,length_op);
18513 @:length_}{\&{length} primitive@>
18514 mp_primitive(mp, "turningnumber",unary,turning_op);
18515 @:turning_number_}{\&{turningnumber} primitive@>
18516 mp_primitive(mp, "xpart",unary,x_part);
18517 @:x_part_}{\&{xpart} primitive@>
18518 mp_primitive(mp, "ypart",unary,y_part);
18519 @:y_part_}{\&{ypart} primitive@>
18520 mp_primitive(mp, "xxpart",unary,xx_part);
18521 @:xx_part_}{\&{xxpart} primitive@>
18522 mp_primitive(mp, "xypart",unary,xy_part);
18523 @:xy_part_}{\&{xypart} primitive@>
18524 mp_primitive(mp, "yxpart",unary,yx_part);
18525 @:yx_part_}{\&{yxpart} primitive@>
18526 mp_primitive(mp, "yypart",unary,yy_part);
18527 @:yy_part_}{\&{yypart} primitive@>
18528 mp_primitive(mp, "redpart",unary,red_part);
18529 @:red_part_}{\&{redpart} primitive@>
18530 mp_primitive(mp, "greenpart",unary,green_part);
18531 @:green_part_}{\&{greenpart} primitive@>
18532 mp_primitive(mp, "bluepart",unary,blue_part);
18533 @:blue_part_}{\&{bluepart} primitive@>
18534 mp_primitive(mp, "cyanpart",unary,cyan_part);
18535 @:cyan_part_}{\&{cyanpart} primitive@>
18536 mp_primitive(mp, "magentapart",unary,magenta_part);
18537 @:magenta_part_}{\&{magentapart} primitive@>
18538 mp_primitive(mp, "yellowpart",unary,yellow_part);
18539 @:yellow_part_}{\&{yellowpart} primitive@>
18540 mp_primitive(mp, "blackpart",unary,black_part);
18541 @:black_part_}{\&{blackpart} primitive@>
18542 mp_primitive(mp, "greypart",unary,grey_part);
18543 @:grey_part_}{\&{greypart} primitive@>
18544 mp_primitive(mp, "colormodel",unary,color_model_part);
18545 @:color_model_part_}{\&{colormodel} primitive@>
18546 mp_primitive(mp, "fontpart",unary,font_part);
18547 @:font_part_}{\&{fontpart} primitive@>
18548 mp_primitive(mp, "textpart",unary,text_part);
18549 @:text_part_}{\&{textpart} primitive@>
18550 mp_primitive(mp, "pathpart",unary,path_part);
18551 @:path_part_}{\&{pathpart} primitive@>
18552 mp_primitive(mp, "penpart",unary,pen_part);
18553 @:pen_part_}{\&{penpart} primitive@>
18554 mp_primitive(mp, "dashpart",unary,dash_part);
18555 @:dash_part_}{\&{dashpart} primitive@>
18556 mp_primitive(mp, "sqrt",unary,sqrt_op);
18557 @:sqrt_}{\&{sqrt} primitive@>
18558 mp_primitive(mp, "mexp",unary,m_exp_op);
18559 @:m_exp_}{\&{mexp} primitive@>
18560 mp_primitive(mp, "mlog",unary,m_log_op);
18561 @:m_log_}{\&{mlog} primitive@>
18562 mp_primitive(mp, "sind",unary,sin_d_op);
18563 @:sin_d_}{\&{sind} primitive@>
18564 mp_primitive(mp, "cosd",unary,cos_d_op);
18565 @:cos_d_}{\&{cosd} primitive@>
18566 mp_primitive(mp, "floor",unary,floor_op);
18567 @:floor_}{\&{floor} primitive@>
18568 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18569 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18570 mp_primitive(mp, "charexists",unary,char_exists_op);
18571 @:char_exists_}{\&{charexists} primitive@>
18572 mp_primitive(mp, "fontsize",unary,font_size);
18573 @:font_size_}{\&{fontsize} primitive@>
18574 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18575 @:ll_corner_}{\&{llcorner} primitive@>
18576 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18577 @:lr_corner_}{\&{lrcorner} primitive@>
18578 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18579 @:ul_corner_}{\&{ulcorner} primitive@>
18580 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18581 @:ur_corner_}{\&{urcorner} primitive@>
18582 mp_primitive(mp, "arclength",unary,arc_length);
18583 @:arc_length_}{\&{arclength} primitive@>
18584 mp_primitive(mp, "angle",unary,angle_op);
18585 @:angle_}{\&{angle} primitive@>
18586 mp_primitive(mp, "cycle",cycle,cycle_op);
18587 @:cycle_}{\&{cycle} primitive@>
18588 mp_primitive(mp, "stroked",unary,stroked_op);
18589 @:stroked_}{\&{stroked} primitive@>
18590 mp_primitive(mp, "filled",unary,filled_op);
18591 @:filled_}{\&{filled} primitive@>
18592 mp_primitive(mp, "textual",unary,textual_op);
18593 @:textual_}{\&{textual} primitive@>
18594 mp_primitive(mp, "clipped",unary,clipped_op);
18595 @:clipped_}{\&{clipped} primitive@>
18596 mp_primitive(mp, "bounded",unary,bounded_op);
18597 @:bounded_}{\&{bounded} primitive@>
18598 mp_primitive(mp, "+",plus_or_minus,plus);
18599 @:+ }{\.{+} primitive@>
18600 mp_primitive(mp, "-",plus_or_minus,minus);
18601 @:- }{\.{-} primitive@>
18602 mp_primitive(mp, "*",secondary_binary,times);
18603 @:* }{\.{*} primitive@>
18604 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18605 @:/ }{\.{/} primitive@>
18606 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18607 @:++_}{\.{++} primitive@>
18608 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18609 @:+-+_}{\.{+-+} primitive@>
18610 mp_primitive(mp, "or",tertiary_binary,or_op);
18611 @:or_}{\&{or} primitive@>
18612 mp_primitive(mp, "and",and_command,and_op);
18613 @:and_}{\&{and} primitive@>
18614 mp_primitive(mp, "<",expression_binary,less_than);
18615 @:< }{\.{<} primitive@>
18616 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18617 @:<=_}{\.{<=} primitive@>
18618 mp_primitive(mp, ">",expression_binary,greater_than);
18619 @:> }{\.{>} primitive@>
18620 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18621 @:>=_}{\.{>=} primitive@>
18622 mp_primitive(mp, "=",equals,equal_to);
18623 @:= }{\.{=} primitive@>
18624 mp_primitive(mp, "<>",expression_binary,unequal_to);
18625 @:<>_}{\.{<>} primitive@>
18626 mp_primitive(mp, "substring",primary_binary,substring_of);
18627 @:substring_}{\&{substring} primitive@>
18628 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18629 @:subpath_}{\&{subpath} primitive@>
18630 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18631 @:direction_time_}{\&{directiontime} primitive@>
18632 mp_primitive(mp, "point",primary_binary,point_of);
18633 @:point_}{\&{point} primitive@>
18634 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18635 @:precontrol_}{\&{precontrol} primitive@>
18636 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18637 @:postcontrol_}{\&{postcontrol} primitive@>
18638 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18639 @:pen_offset_}{\&{penoffset} primitive@>
18640 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18641 @:arc_time_of_}{\&{arctime} primitive@>
18642 mp_primitive(mp, "mpversion",nullary,mp_version);
18643 @:mp_verison_}{\&{mpversion} primitive@>
18644 mp_primitive(mp, "&",ampersand,concatenate);
18645 @:!!!}{\.{\&} primitive@>
18646 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18647 @:rotated_}{\&{rotated} primitive@>
18648 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18649 @:slanted_}{\&{slanted} primitive@>
18650 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18651 @:scaled_}{\&{scaled} primitive@>
18652 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18653 @:shifted_}{\&{shifted} primitive@>
18654 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18655 @:transformed_}{\&{transformed} primitive@>
18656 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18657 @:x_scaled_}{\&{xscaled} primitive@>
18658 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18659 @:y_scaled_}{\&{yscaled} primitive@>
18660 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18661 @:z_scaled_}{\&{zscaled} primitive@>
18662 mp_primitive(mp, "infont",secondary_binary,in_font);
18663 @:in_font_}{\&{infont} primitive@>
18664 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18665 @:intersection_times_}{\&{intersectiontimes} primitive@>
18666 mp_primitive(mp, "envelope",primary_binary,envelope_of);
18667 @:envelope_}{\&{envelope} primitive@>
18669 @ @<Cases of |print_cmd...@>=
18672 case primary_binary:
18673 case secondary_binary:
18674 case tertiary_binary:
18675 case expression_binary:
18677 case plus_or_minus:
18682 mp_print_op(mp, m);
18685 @ OK, let's look at the simplest \\{do} procedure first.
18687 @c @<Declare nullary action procedure@>;
18688 void mp_do_nullary (MP mp,quarterword c) {
18690 if ( mp->internal[mp_tracing_commands]>two )
18691 mp_show_cmd_mod(mp, nullary,c);
18693 case true_code: case false_code:
18694 mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18696 case null_picture_code:
18697 mp->cur_type=mp_picture_type;
18698 mp->cur_exp=mp_get_node(mp, edge_header_size);
18699 mp_init_edges(mp, mp->cur_exp);
18701 case null_pen_code:
18702 mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18704 case normal_deviate:
18705 mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18708 mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18711 if ( mp->job_name==NULL ) mp_open_log_file(mp);
18712 mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18715 mp->cur_type=mp_string_type;
18716 mp->cur_exp=intern(metapost_version) ;
18718 case read_string_op:
18719 @<Read a string from the terminal@>;
18721 } /* there are no other cases */
18725 @ @<Read a string...@>=
18727 if ( mp->interaction<=mp_nonstop_mode )
18728 mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18729 mp_begin_file_reading(mp); name=is_read;
18730 limit=start; prompt_input("");
18731 mp_finish_read(mp);
18734 @ @<Declare nullary action procedure@>=
18735 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18737 str_room((int)mp->last-start);
18738 for (k=start;k<=mp->last-1;k++) {
18739 append_char(mp->buffer[k]);
18741 mp_end_file_reading(mp); mp->cur_type=mp_string_type;
18742 mp->cur_exp=mp_make_string(mp);
18745 @ Things get a bit more interesting when there's an operand. The
18746 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18748 @c @<Declare unary action procedures@>;
18749 void mp_do_unary (MP mp,quarterword c) {
18750 pointer p,q,r; /* for list manipulation */
18751 integer x; /* a temporary register */
18753 if ( mp->internal[mp_tracing_commands]>two )
18754 @<Trace the current unary operation@>;
18757 if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18760 @<Negate the current expression@>;
18762 @<Additional cases of unary operators@>;
18763 } /* there are no other cases */
18767 @ The |nice_pair| function returns |true| if both components of a pair
18770 @<Declare unary action procedures@>=
18771 boolean mp_nice_pair (MP mp,integer p, quarterword t) {
18772 if ( t==mp_pair_type ) {
18774 if ( type(x_part_loc(p))==mp_known )
18775 if ( type(y_part_loc(p))==mp_known )
18781 @ The |nice_color_or_pair| function is analogous except that it also accepts
18782 fully known colors.
18784 @<Declare unary action procedures@>=
18785 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18786 pointer q,r; /* for scanning the big node */
18787 if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18791 r=q+mp->big_node_size[type(p)];
18794 if ( type(r)!=mp_known )
18801 @ @<Declare unary action...@>=
18802 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) {
18803 mp_print_char(mp, '(');
18804 if ( t>mp_known ) mp_print(mp, "unknown numeric");
18805 else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18806 if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18807 mp_print_type(mp, t);
18809 mp_print_char(mp, ')');
18812 @ @<Declare unary action...@>=
18813 void mp_bad_unary (MP mp,quarterword c) {
18814 exp_err("Not implemented: "); mp_print_op(mp, c);
18815 @.Not implemented...@>
18816 mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18817 help3("I'm afraid I don't know how to apply that operation to that")
18818 ("particular type. Continue, and I'll simply return the")
18819 ("argument (shown above) as the result of the operation.");
18820 mp_put_get_error(mp);
18823 @ @<Trace the current unary operation@>=
18825 mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
18826 mp_print_op(mp, c); mp_print_char(mp, '(');
18827 mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18828 mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18831 @ Negation is easy except when the current expression
18832 is of type |independent|, or when it is a pair with one or more
18833 |independent| components.
18835 It is tempting to argue that the negative of an independent variable
18836 is an independent variable, hence we don't have to do anything when
18837 negating it. The fallacy is that other dependent variables pointing
18838 to the current expression must change the sign of their
18839 coefficients if we make no change to the current expression.
18841 Instead, we work around the problem by copying the current expression
18842 and recycling it afterwards (cf.~the |stash_in| routine).
18844 @<Negate the current expression@>=
18845 switch (mp->cur_type) {
18846 case mp_color_type:
18847 case mp_cmykcolor_type:
18849 case mp_independent:
18850 q=mp->cur_exp; mp_make_exp_copy(mp, q);
18851 if ( mp->cur_type==mp_dependent ) {
18852 mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18853 } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18854 p=value(mp->cur_exp);
18855 r=p+mp->big_node_size[mp->cur_type];
18858 if ( type(r)==mp_known ) negate(value(r));
18859 else mp_negate_dep_list(mp, dep_list(r));
18861 } /* if |cur_type=mp_known| then |cur_exp=0| */
18862 mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18865 case mp_proto_dependent:
18866 mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18869 negate(mp->cur_exp);
18872 mp_bad_unary(mp, minus);
18876 @ @<Declare unary action...@>=
18877 void mp_negate_dep_list (MP mp,pointer p) {
18880 if ( info(p)==null ) return;
18885 @ @<Additional cases of unary operators@>=
18887 if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18888 else mp->cur_exp=true_code+false_code-mp->cur_exp;
18891 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18892 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18894 @<Additional cases of unary operators@>=
18901 case uniform_deviate:
18903 case char_exists_op:
18904 if ( mp->cur_type!=mp_known ) {
18905 mp_bad_unary(mp, c);
18908 case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18909 case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18910 case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18913 mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18914 if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18915 else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18917 case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18918 case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18920 boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18921 mp->cur_type=mp_boolean_type;
18923 case char_exists_op:
18924 @<Determine if a character has been shipped out@>;
18926 } /* there are no other cases */
18930 @ @<Additional cases of unary operators@>=
18932 if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18933 p=value(mp->cur_exp);
18934 x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18935 if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18936 else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18938 mp_bad_unary(mp, angle_op);
18942 @ If the current expression is a pair, but the context wants it to
18943 be a path, we call |pair_to_path|.
18945 @<Declare unary action...@>=
18946 void mp_pair_to_path (MP mp) {
18947 mp->cur_exp=mp_new_knot(mp);
18948 mp->cur_type=mp_path_type;
18951 @ @<Additional cases of unary operators@>=
18954 if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18955 mp_take_part(mp, c);
18956 else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18957 else mp_bad_unary(mp, c);
18963 if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18964 else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18965 else mp_bad_unary(mp, c);
18970 if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18971 else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18972 else mp_bad_unary(mp, c);
18978 if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c);
18979 else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18980 else mp_bad_unary(mp, c);
18983 if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18984 else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18985 else mp_bad_unary(mp, c);
18987 case color_model_part:
18988 if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18989 else mp_bad_unary(mp, c);
18992 @ In the following procedure, |cur_exp| points to a capsule, which points to
18993 a big node. We want to delete all but one part of the big node.
18995 @<Declare unary action...@>=
18996 void mp_take_part (MP mp,quarterword c) {
18997 pointer p; /* the big node */
18998 p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18999 link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
19000 mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
19001 mp_recycle_value(mp, temp_val);
19004 @ @<Initialize table entries...@>=
19005 name_type(temp_val)=mp_capsule;
19007 @ @<Additional cases of unary operators@>=
19013 if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19014 else mp_bad_unary(mp, c);
19017 @ @<Declarations@>=
19018 void mp_scale_edges (MP mp);
19020 @ @<Declare unary action...@>=
19021 void mp_take_pict_part (MP mp,quarterword c) {
19022 pointer p; /* first graphical object in |cur_exp| */
19023 p=link(dummy_loc(mp->cur_exp));
19026 case x_part: case y_part: case xx_part:
19027 case xy_part: case yx_part: case yy_part:
19028 if ( type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
19029 else goto NOT_FOUND;
19031 case red_part: case green_part: case blue_part:
19032 if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
19033 else goto NOT_FOUND;
19035 case cyan_part: case magenta_part: case yellow_part:
19037 if ( has_color(p) ) {
19038 if ( color_model(p)==mp_uninitialized_model )
19039 mp_flush_cur_exp(mp, unity);
19041 mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
19042 } else goto NOT_FOUND;
19045 if ( has_color(p) )
19046 mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
19047 else goto NOT_FOUND;
19049 case color_model_part:
19050 if ( has_color(p) ) {
19051 if ( color_model(p)==mp_uninitialized_model )
19052 mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
19054 mp_flush_cur_exp(mp, color_model(p)*unity);
19055 } else goto NOT_FOUND;
19057 @<Handle other cases in |take_pict_part| or |goto not_found|@>;
19058 } /* all cases have been enumerated */
19062 @<Convert the current expression to a null value appropriate
19066 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
19068 if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19070 mp_flush_cur_exp(mp, text_p(p));
19071 add_str_ref(mp->cur_exp);
19072 mp->cur_type=mp_string_type;
19076 if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19078 mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)]));
19079 add_str_ref(mp->cur_exp);
19080 mp->cur_type=mp_string_type;
19084 if ( type(p)==mp_text_code ) goto NOT_FOUND;
19085 else if ( is_stop(p) ) mp_confusion(mp, "pict");
19086 @:this can't happen pict}{\quad pict@>
19088 mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
19089 mp->cur_type=mp_path_type;
19093 if ( ! has_pen(p) ) goto NOT_FOUND;
19095 if ( pen_p(p)==null ) goto NOT_FOUND;
19096 else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
19097 mp->cur_type=mp_pen_type;
19102 if ( type(p)!=mp_stroked_code ) goto NOT_FOUND;
19103 else { if ( dash_p(p)==null ) goto NOT_FOUND;
19104 else { add_edge_ref(dash_p(p));
19105 mp->se_sf=dash_scale(p);
19106 mp->se_pic=dash_p(p);
19107 mp_scale_edges(mp);
19108 mp_flush_cur_exp(mp, mp->se_pic);
19109 mp->cur_type=mp_picture_type;
19114 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19115 parameterless procedure even though it really takes two arguments and updates
19116 one of them. Hence the following globals are needed.
19119 pointer se_pic; /* edge header used and updated by |scale_edges| */
19120 scaled se_sf; /* the scale factor argument to |scale_edges| */
19122 @ @<Convert the current expression to a null value appropriate...@>=
19124 case text_part: case font_part:
19125 mp_flush_cur_exp(mp, rts(""));
19126 mp->cur_type=mp_string_type;
19129 mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19130 left_type(mp->cur_exp)=mp_endpoint;
19131 right_type(mp->cur_exp)=mp_endpoint;
19132 link(mp->cur_exp)=mp->cur_exp;
19133 x_coord(mp->cur_exp)=0;
19134 y_coord(mp->cur_exp)=0;
19135 originator(mp->cur_exp)=mp_metapost_user;
19136 mp->cur_type=mp_path_type;
19139 mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19140 mp->cur_type=mp_pen_type;
19143 mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19144 mp_init_edges(mp, mp->cur_exp);
19145 mp->cur_type=mp_picture_type;
19148 mp_flush_cur_exp(mp, 0);
19152 @ @<Additional cases of unary...@>=
19154 if ( mp->cur_type!=mp_known ) {
19155 mp_bad_unary(mp, char_op);
19157 mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
19158 mp->cur_type=mp_string_type;
19159 if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19163 if ( mp->cur_type!=mp_known ) {
19164 mp_bad_unary(mp, decimal);
19166 mp->old_setting=mp->selector; mp->selector=new_string;
19167 mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19168 mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19174 if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19175 else mp_str_to_num(mp, c);
19178 if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19179 else @<Find the design size of the font whose name is |cur_exp|@>;
19182 @ @<Declare unary action...@>=
19183 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19184 integer n; /* accumulator */
19185 ASCII_code m; /* current character */
19186 pool_pointer k; /* index into |str_pool| */
19187 int b; /* radix of conversion */
19188 boolean bad_char; /* did the string contain an invalid digit? */
19189 if ( c==ASCII_op ) {
19190 if ( length(mp->cur_exp)==0 ) n=-1;
19191 else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19193 if ( c==oct_op ) b=8; else b=16;
19194 n=0; bad_char=false;
19195 for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19197 if ( (m>='0')&&(m<='9') ) m=m-'0';
19198 else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19199 else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19200 else { bad_char=true; m=0; };
19201 if ( m>=b ) { bad_char=true; m=0; };
19202 if ( n<32768 / b ) n=n*b+m; else n=32767;
19204 @<Give error messages if |bad_char| or |n>=4096|@>;
19206 mp_flush_cur_exp(mp, n*unity);
19209 @ @<Give error messages if |bad_char|...@>=
19211 exp_err("String contains illegal digits");
19212 @.String contains illegal digits@>
19214 help1("I zeroed out characters that weren't in the range 0..7.");
19216 help1("I zeroed out characters that weren't hex digits.");
19218 mp_put_get_error(mp);
19221 if ( mp->internal[mp_warning_check]>0 ) {
19222 print_err("Number too large (");
19223 mp_print_int(mp, n); mp_print_char(mp, ')');
19224 @.Number too large@>
19225 help2("I have trouble with numbers greater than 4095; watch out.")
19226 ("(Set warningcheck:=0 to suppress this message.)");
19227 mp_put_get_error(mp);
19231 @ The length operation is somewhat unusual in that it applies to a variety
19232 of different types of operands.
19234 @<Additional cases of unary...@>=
19236 switch (mp->cur_type) {
19237 case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19238 case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19239 case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19240 case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19242 if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19243 mp_flush_cur_exp(mp, mp_pyth_add(mp,
19244 value(x_part_loc(value(mp->cur_exp))),
19245 value(y_part_loc(value(mp->cur_exp)))));
19246 else mp_bad_unary(mp, c);
19251 @ @<Declare unary action...@>=
19252 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19253 scaled n; /* the path length so far */
19254 pointer p; /* traverser */
19256 if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
19257 do { p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19261 @ @<Declare unary action...@>=
19262 scaled mp_pict_length (MP mp) {
19263 /* counts interior components in picture |cur_exp| */
19264 scaled n; /* the count so far */
19265 pointer p; /* traverser */
19267 p=link(dummy_loc(mp->cur_exp));
19269 if ( is_start_or_stop(p) )
19270 if ( mp_skip_1component(mp, p)==null ) p=link(p);
19271 while ( p!=null ) {
19272 skip_component(p) return n;
19279 @ Implement |turningnumber|
19281 @<Additional cases of unary...@>=
19283 if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19284 else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19285 else if ( left_type(mp->cur_exp)==mp_endpoint )
19286 mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19288 mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19291 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19292 argument is |origin|.
19294 @<Declare unary action...@>=
19295 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19296 if ( (! ((xpar==0) && (ypar==0))) )
19297 return mp_n_arg(mp, xpar,ypar);
19302 @ The actual turning number is (for the moment) computed in a C function
19303 that receives eight integers corresponding to the four controlling points,
19304 and returns a single angle. Besides those, we have to account for discrete
19305 moves at the actual points.
19307 @d floor(a) (a>=0 ? a : -(int)(-a))
19308 @d bezier_error (720<<20)+1
19309 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19310 @d print_roots(a) { if (debuglevel>(65536*2))
19311 fprintf(stdout,"bezier_slope(): %s, i=%f, o=%f, angle=%f\n", (a),in,out,res); }
19312 @d out ((double)(xo>>20))
19313 @d mid ((double)(xm>>20))
19314 @d in ((double)(xi>>20))
19315 @d divisor (256*256)
19316 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19318 @<Declare unary action...@>=
19319 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19320 integer CX,integer CY,integer DX,integer DY, int debuglevel);
19323 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19324 integer CX,integer CY,integer DX,integer DY, int debuglevel) {
19326 integer deltax,deltay;
19327 double ax,ay,bx,by,cx,cy,dx,dy;
19328 angle xi = 0, xo = 0, xm = 0;
19330 ax=AX/divisor; ay=AY/divisor;
19331 bx=BX/divisor; by=BY/divisor;
19332 cx=CX/divisor; cy=CY/divisor;
19333 dx=DX/divisor; dy=DY/divisor;
19335 deltax = (BX-AX); deltay = (BY-AY);
19336 if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19337 if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19338 xi = mp_an_angle(mp,deltax,deltay);
19340 deltax = (CX-BX); deltay = (CY-BY);
19341 xm = mp_an_angle(mp,deltax,deltay);
19343 deltax = (DX-CX); deltay = (DY-CY);
19344 if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19345 if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19346 xo = mp_an_angle(mp,deltax,deltay);
19348 a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19349 b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19350 c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19352 if (debuglevel>(65536*2)) {
19354 "bezier_slope(): (%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f)\n",
19355 ax,ay,bx,by,cx,cy,dx,dy);
19357 "bezier_slope(): a,b,c,b^2,4ac: (%.2f,%.2f,%.2f,%.2f,%.2f)\n",a,b,c,b*b,4*a*c);
19360 if ((a==0)&&(c==0)) {
19361 res = (b==0 ? 0 : (out-in));
19362 print_roots("no roots (a)");
19363 } else if ((a==0)||(c==0)) {
19364 if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19365 res = out-in; /* ? */
19368 else if (res>180.0)
19370 print_roots("no roots (b)");
19372 res = out-in; /* ? */
19373 print_roots("one root (a)");
19375 } else if ((sign(a)*sign(c))<0) {
19376 res = out-in; /* ? */
19379 else if (res>180.0)
19381 print_roots("one root (b)");
19383 if (sign(a) == sign(b)) {
19384 res = out-in; /* ? */
19387 else if (res>180.0)
19389 print_roots("no roots (d)");
19391 if ((b*b) == (4*a*c)) {
19392 res = bezier_error;
19393 print_roots("double root"); /* cusp */
19394 } else if ((b*b) < (4*a*c)) {
19395 res = out-in; /* ? */
19396 if (res<=0.0 &&res>-180.0)
19398 else if (res>=0.0 && res<180.0)
19400 print_roots("no roots (e)");
19405 else if (res>180.0)
19407 print_roots("two roots"); /* two inflections */
19411 return double2angle(res);
19415 @d p_nextnext link(link(p))
19417 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19419 @<Declare unary action...@>=
19420 scaled mp_new_turn_cycles (MP mp,pointer c) {
19421 angle res,ang; /* the angles of intermediate results */
19422 scaled turns; /* the turn counter */
19423 pointer p; /* for running around the path */
19424 integer xp,yp; /* coordinates of next point */
19425 integer x,y; /* helper coordinates */
19426 angle in_angle,out_angle; /* helper angles */
19427 int old_setting; /* saved |selector| setting */
19431 old_setting = mp->selector; mp->selector=term_only;
19432 if ( mp->internal[mp_tracing_commands]>unity ) {
19433 mp_begin_diagnostic(mp);
19434 mp_print_nl(mp, "");
19435 mp_end_diagnostic(mp, false);
19438 xp = x_coord(p_next); yp = y_coord(p_next);
19439 ang = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19440 left_x(p_next), left_y(p_next), xp, yp,
19441 mp->internal[mp_tracing_commands]);
19442 if ( ang>seven_twenty_deg ) {
19443 print_err("Strange path");
19445 mp->selector=old_setting;
19449 if ( res > one_eighty_deg ) {
19450 res = res - three_sixty_deg;
19451 turns = turns + unity;
19453 if ( res <= -one_eighty_deg ) {
19454 res = res + three_sixty_deg;
19455 turns = turns - unity;
19457 /* incoming angle at next point */
19458 x = left_x(p_next); y = left_y(p_next);
19459 if ( (xp==x)&&(yp==y) ) { x = right_x(p); y = right_y(p); };
19460 if ( (xp==x)&&(yp==y) ) { x = x_coord(p); y = y_coord(p); };
19461 in_angle = mp_an_angle(mp, xp - x, yp - y);
19462 /* outgoing angle at next point */
19463 x = right_x(p_next); y = right_y(p_next);
19464 if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext); y = left_y(p_nextnext); };
19465 if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19466 out_angle = mp_an_angle(mp, x - xp, y- yp);
19467 ang = (out_angle - in_angle);
19471 if ( res >= one_eighty_deg ) {
19472 res = res - three_sixty_deg;
19473 turns = turns + unity;
19475 if ( res <= -one_eighty_deg ) {
19476 res = res + three_sixty_deg;
19477 turns = turns - unity;
19482 mp->selector=old_setting;
19487 @ This code is based on Bogus\l{}av Jackowski's
19488 |emergency_turningnumber| macro, with some minor changes by Taco
19489 Hoekwater. The macro code looked more like this:
19491 vardef turning\_number primary p =
19492 ~~save res, ang, turns;
19494 ~~if length p <= 2:
19495 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0: 1 else: -1 fi
19497 ~~~~for t = 0 upto length p-1 :
19498 ~~~~~~angc := Angle ((point t+1 of p) - (point t of p))
19499 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19500 ~~~~~~if angc > 180: angc := angc - 360; fi;
19501 ~~~~~~if angc < -180: angc := angc + 360; fi;
19502 ~~~~~~res := res + angc;
19507 The general idea is to calculate only the sum of the angles of
19508 straight lines between the points, of a path, not worrying about cusps
19509 or self-intersections in the segments at all. If the segment is not
19510 well-behaved, the result is not necesarily correct. But the old code
19511 was not always correct either, and worse, it sometimes failed for
19512 well-behaved paths as well. All known bugs that were triggered by the
19513 original code no longer occur with this code, and it runs roughly 3
19514 times as fast because the algorithm is much simpler.
19516 @ It is possible to overflow the return value of the |turn_cycles|
19517 function when the path is sufficiently long and winding, but I am not
19518 going to bother testing for that. In any case, it would only return
19519 the looped result value, which is not a big problem.
19521 The macro code for the repeat loop was a bit nicer to look
19522 at than the pascal code, because it could use |point -1 of p|. In
19523 pascal, the fastest way to loop around the path is not to look
19524 backward once, but forward twice. These defines help hide the trick.
19526 @d p_to link(link(p))
19530 @<Declare unary action...@>=
19531 scaled mp_turn_cycles (MP mp,pointer c) {
19532 angle res,ang; /* the angles of intermediate results */
19533 scaled turns; /* the turn counter */
19534 pointer p; /* for running around the path */
19535 res=0; turns= 0; p=c;
19537 ang = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here),
19538 y_coord(p_to) - y_coord(p_here))
19539 - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from),
19540 y_coord(p_here) - y_coord(p_from));
19543 if ( res >= three_sixty_deg ) {
19544 res = res - three_sixty_deg;
19545 turns = turns + unity;
19547 if ( res <= -three_sixty_deg ) {
19548 res = res + three_sixty_deg;
19549 turns = turns - unity;
19556 @ @<Declare unary action...@>=
19557 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19559 scaled saved_t_o; /* tracing\_online saved */
19560 if ( (link(c)==c)||(link(link(c))==c) ) {
19561 if ( mp_an_angle (mp, x_coord(c) - right_x(c), y_coord(c) - right_y(c)) > 0 )
19566 nval = mp_new_turn_cycles(mp, c);
19567 oval = mp_turn_cycles(mp, c);
19568 if ( nval!=oval ) {
19569 saved_t_o=mp->internal[mp_tracing_online];
19570 mp->internal[mp_tracing_online]=unity;
19571 mp_begin_diagnostic(mp);
19572 mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19573 " The current computed value is ");
19574 mp_print_scaled(mp, nval);
19575 mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19576 mp_print_scaled(mp, oval);
19577 mp_end_diagnostic(mp, false);
19578 mp->internal[mp_tracing_online]=saved_t_o;
19584 @ @<Declare unary action...@>=
19585 scaled mp_count_turns (MP mp,pointer c) {
19586 pointer p; /* a knot in envelope spec |c| */
19587 integer t; /* total pen offset changes counted */
19590 t=t+info(p)-zero_off;
19593 return ((t / 3)*unity);
19596 @ @d type_range(A,B) {
19597 if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) )
19598 mp_flush_cur_exp(mp, true_code);
19599 else mp_flush_cur_exp(mp, false_code);
19600 mp->cur_type=mp_boolean_type;
19603 if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19604 else mp_flush_cur_exp(mp, false_code);
19605 mp->cur_type=mp_boolean_type;
19608 @<Additional cases of unary operators@>=
19609 case mp_boolean_type:
19610 type_range(mp_boolean_type,mp_unknown_boolean); break;
19611 case mp_string_type:
19612 type_range(mp_string_type,mp_unknown_string); break;
19614 type_range(mp_pen_type,mp_unknown_pen); break;
19616 type_range(mp_path_type,mp_unknown_path); break;
19617 case mp_picture_type:
19618 type_range(mp_picture_type,mp_unknown_picture); break;
19619 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19621 type_test(c); break;
19622 case mp_numeric_type:
19623 type_range(mp_known,mp_independent); break;
19624 case known_op: case unknown_op:
19625 mp_test_known(mp, c); break;
19627 @ @<Declare unary action procedures@>=
19628 void mp_test_known (MP mp,quarterword c) {
19629 int b; /* is the current expression known? */
19630 pointer p,q; /* locations in a big node */
19632 switch (mp->cur_type) {
19633 case mp_vacuous: case mp_boolean_type: case mp_string_type:
19634 case mp_pen_type: case mp_path_type: case mp_picture_type:
19638 case mp_transform_type:
19639 case mp_color_type: case mp_cmykcolor_type: case mp_pair_type:
19640 p=value(mp->cur_exp);
19641 q=p+mp->big_node_size[mp->cur_type];
19644 if ( type(q)!=mp_known )
19653 if ( c==known_op ) mp_flush_cur_exp(mp, b);
19654 else mp_flush_cur_exp(mp, true_code+false_code-b);
19655 mp->cur_type=mp_boolean_type;
19658 @ @<Additional cases of unary operators@>=
19660 if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19661 else if ( left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19662 else mp_flush_cur_exp(mp, false_code);
19663 mp->cur_type=mp_boolean_type;
19666 @ @<Additional cases of unary operators@>=
19668 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19669 if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19670 else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19673 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19675 @^data structure assumptions@>
19677 @<Additional cases of unary operators@>=
19683 if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19684 else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19685 else if ( type(link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19686 mp_flush_cur_exp(mp, true_code);
19687 else mp_flush_cur_exp(mp, false_code);
19688 mp->cur_type=mp_boolean_type;
19691 @ @<Additional cases of unary operators@>=
19693 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19694 if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19696 mp->cur_type=mp_pen_type;
19697 mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19701 if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19703 mp->cur_type=mp_path_type;
19704 mp_make_path(mp, mp->cur_exp);
19708 if ( mp->cur_type==mp_path_type ) {
19709 p=mp_htap_ypoc(mp, mp->cur_exp);
19710 if ( right_type(p)==mp_endpoint ) p=link(p);
19711 mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19712 } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19713 else mp_bad_unary(mp, reverse);
19716 @ The |pair_value| routine changes the current expression to a
19717 given ordered pair of values.
19719 @<Declare unary action procedures@>=
19720 void mp_pair_value (MP mp,scaled x, scaled y) {
19721 pointer p; /* a pair node */
19722 p=mp_get_node(mp, value_node_size);
19723 mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19724 type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19726 type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19727 type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19730 @ @<Additional cases of unary operators@>=
19732 if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19733 else mp_pair_value(mp, minx,miny);
19736 if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19737 else mp_pair_value(mp, maxx,miny);
19740 if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19741 else mp_pair_value(mp, minx,maxy);
19744 if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19745 else mp_pair_value(mp, maxx,maxy);
19748 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19749 box of the current expression. The boolean result is |false| if the expression
19750 has the wrong type.
19752 @<Declare unary action procedures@>=
19753 boolean mp_get_cur_bbox (MP mp) {
19754 switch (mp->cur_type) {
19755 case mp_picture_type:
19756 mp_set_bbox(mp, mp->cur_exp,true);
19757 if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19758 minx=0; maxx=0; miny=0; maxy=0;
19760 minx=minx_val(mp->cur_exp);
19761 maxx=maxx_val(mp->cur_exp);
19762 miny=miny_val(mp->cur_exp);
19763 maxy=maxy_val(mp->cur_exp);
19767 mp_path_bbox(mp, mp->cur_exp);
19770 mp_pen_bbox(mp, mp->cur_exp);
19778 @ @<Additional cases of unary operators@>=
19780 case close_from_op:
19781 if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19782 else mp_do_read_or_close(mp,c);
19785 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19786 a line from the file or to close the file.
19788 @d close_file 46 /* go here when closing the file */
19790 @<Declare unary action procedures@>=
19791 void mp_do_read_or_close (MP mp,quarterword c) {
19792 readf_index n,n0; /* indices for searching |rd_fname| */
19793 @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19794 call |start_read_input| and |goto found| or |not_found|@>;
19795 mp_begin_file_reading(mp);
19797 if ( mp_input_ln(mp, mp->rd_file[n],true) )
19799 mp_end_file_reading(mp);
19801 @<Record the end of file and set |cur_exp| to a dummy value@>;
19804 mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
19807 mp_flush_cur_exp(mp, 0);
19808 mp_finish_read(mp);
19811 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19814 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19819 fn = str(mp->cur_exp);
19820 while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) {
19823 } else if ( c==close_from_op ) {
19826 if ( n0==mp->read_files ) {
19827 if ( mp->read_files<mp->max_read_files ) {
19828 incr(mp->read_files);
19833 l = mp->max_read_files + (mp->max_read_files>>2);
19834 rd_file = xmalloc((l+1), sizeof(FILE *));
19835 rd_fname = xmalloc((l+1), sizeof(char *));
19836 for (k=0;k<=l;k++) {
19837 if (k<=mp->max_read_files) {
19838 rd_file[k]=mp->rd_file[k];
19839 rd_fname[k]=mp->rd_fname[k];
19845 xfree(mp->rd_file); xfree(mp->rd_fname);
19846 mp->max_read_files = l;
19847 mp->rd_file = rd_file;
19848 mp->rd_fname = rd_fname;
19852 if ( mp_start_read_input(mp,fn,n) )
19857 if ( mp->rd_fname[n]==NULL ) { n0=n; }
19859 if ( c==close_from_op ) {
19860 fclose(mp->rd_file[n]);
19865 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19866 xfree(mp->rd_fname[n]);
19867 mp->rd_fname[n]=NULL;
19868 if ( n==mp->read_files-1 ) mp->read_files=n;
19869 if ( c==close_from_op )
19871 mp_flush_cur_exp(mp, mp->eof_line);
19872 mp->cur_type=mp_string_type
19874 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19877 str_number eof_line;
19882 @ Finally, we have the operations that combine a capsule~|p|
19883 with the current expression.
19885 @c @<Declare binary action procedures@>;
19886 void mp_do_binary (MP mp,pointer p, quarterword c) {
19887 pointer q,r,rr; /* for list manipulation */
19888 pointer old_p,old_exp; /* capsules to recycle */
19889 integer v; /* for numeric manipulation */
19891 if ( mp->internal[mp_tracing_commands]>two ) {
19892 @<Trace the current binary operation@>;
19894 @<Sidestep |independent| cases in capsule |p|@>;
19895 @<Sidestep |independent| cases in the current expression@>;
19897 case plus: case minus:
19898 @<Add or subtract the current expression from |p|@>;
19900 @<Additional cases of binary operators@>;
19901 }; /* there are no other cases */
19902 mp_recycle_value(mp, p);
19903 mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19905 @<Recycle any sidestepped |independent| capsules@>;
19908 @ @<Declare binary action...@>=
19909 void mp_bad_binary (MP mp,pointer p, quarterword c) {
19910 mp_disp_err(mp, p,"");
19911 exp_err("Not implemented: ");
19912 @.Not implemented...@>
19913 if ( c>=min_of ) mp_print_op(mp, c);
19914 mp_print_known_or_unknown_type(mp, type(p),p);
19915 if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19916 mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19917 help3("I'm afraid I don't know how to apply that operation to that")
19918 ("combination of types. Continue, and I'll return the second")
19919 ("argument (see above) as the result of the operation.");
19920 mp_put_get_error(mp);
19922 void mp_bad_envelope_pen (MP mp) {
19923 mp_disp_err(mp, null,"");
19924 exp_err("Not implemented: envelope(elliptical pen)of(path)");
19925 @.Not implemented...@>
19926 help3("I'm afraid I don't know how to apply that operation to that")
19927 ("combination of types. Continue, and I'll return the second")
19928 ("argument (see above) as the result of the operation.");
19929 mp_put_get_error(mp);
19932 @ @<Trace the current binary operation@>=
19934 mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19935 mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19936 mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19937 mp_print_exp(mp,null,0); mp_print(mp,")}");
19938 mp_end_diagnostic(mp, false);
19941 @ Several of the binary operations are potentially complicated by the
19942 fact that |independent| values can sneak into capsules. For example,
19943 we've seen an instance of this difficulty in the unary operation
19944 of negation. In order to reduce the number of cases that need to be
19945 handled, we first change the two operands (if necessary)
19946 to rid them of |independent| components. The original operands are
19947 put into capsules called |old_p| and |old_exp|, which will be
19948 recycled after the binary operation has been safely carried out.
19950 @<Recycle any sidestepped |independent| capsules@>=
19951 if ( old_p!=null ) {
19952 mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19954 if ( old_exp!=null ) {
19955 mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19958 @ A big node is considered to be ``tarnished'' if it contains at least one
19959 independent component. We will define a simple function called `|tarnished|'
19960 that returns |null| if and only if its argument is not tarnished.
19962 @<Sidestep |independent| cases in capsule |p|@>=
19964 case mp_transform_type:
19965 case mp_color_type:
19966 case mp_cmykcolor_type:
19968 old_p=mp_tarnished(mp, p);
19970 case mp_independent: old_p=mp_void; break;
19971 default: old_p=null; break;
19973 if ( old_p!=null ) {
19974 q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19975 p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19978 @ @<Sidestep |independent| cases in the current expression@>=
19979 switch (mp->cur_type) {
19980 case mp_transform_type:
19981 case mp_color_type:
19982 case mp_cmykcolor_type:
19984 old_exp=mp_tarnished(mp, mp->cur_exp);
19986 case mp_independent:old_exp=mp_void; break;
19987 default: old_exp=null; break;
19989 if ( old_exp!=null ) {
19990 old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19993 @ @<Declare binary action...@>=
19994 pointer mp_tarnished (MP mp,pointer p) {
19995 pointer q; /* beginning of the big node */
19996 pointer r; /* current position in the big node */
19997 q=value(p); r=q+mp->big_node_size[type(p)];
20000 if ( type(r)==mp_independent ) return mp_void;
20005 @ @<Add or subtract the current expression from |p|@>=
20006 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20007 mp_bad_binary(mp, p,c);
20009 if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20010 mp_add_or_subtract(mp, p,null,c);
20012 if ( mp->cur_type!=type(p) ) {
20013 mp_bad_binary(mp, p,c);
20015 q=value(p); r=value(mp->cur_exp);
20016 rr=r+mp->big_node_size[mp->cur_type];
20018 mp_add_or_subtract(mp, q,r,c);
20025 @ The first argument to |add_or_subtract| is the location of a value node
20026 in a capsule or pair node that will soon be recycled. The second argument
20027 is either a location within a pair or transform node of |cur_exp|,
20028 or it is null (which means that |cur_exp| itself should be the second
20029 argument). The third argument is either |plus| or |minus|.
20031 The sum or difference of the numeric quantities will replace the second
20032 operand. Arithmetic overflow may go undetected; users aren't supposed to
20033 be monkeying around with really big values.
20035 @<Declare binary action...@>=
20036 @<Declare the procedure called |dep_finish|@>;
20037 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
20038 small_number s,t; /* operand types */
20039 pointer r; /* list traverser */
20040 integer v; /* second operand value */
20043 if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
20046 if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
20048 if ( t==mp_known ) {
20049 if ( c==minus ) negate(v);
20050 if ( type(p)==mp_known ) {
20051 v=mp_slow_add(mp, value(p),v);
20052 if ( q==null ) mp->cur_exp=v; else value(q)=v;
20055 @<Add a known value to the constant term of |dep_list(p)|@>;
20057 if ( c==minus ) mp_negate_dep_list(mp, v);
20058 @<Add operand |p| to the dependency list |v|@>;
20062 @ @<Add a known value to the constant term of |dep_list(p)|@>=
20064 while ( info(r)!=null ) r=link(r);
20065 value(r)=mp_slow_add(mp, value(r),v);
20067 q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
20068 name_type(q)=mp_capsule;
20070 dep_list(q)=dep_list(p); type(q)=type(p);
20071 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
20072 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
20074 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
20075 nice to retain the extra accuracy of |fraction| coefficients.
20076 But we have to handle both kinds, and mixtures too.
20078 @<Add operand |p| to the dependency list |v|@>=
20079 if ( type(p)==mp_known ) {
20080 @<Add the known |value(p)| to the constant term of |v|@>;
20082 s=type(p); r=dep_list(p);
20083 if ( t==mp_dependent ) {
20084 if ( s==mp_dependent ) {
20085 if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
20086 v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
20087 } /* |fix_needed| will necessarily be false */
20088 t=mp_proto_dependent;
20089 v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
20091 if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
20092 else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
20094 @<Output the answer, |v| (which might have become |known|)@>;
20097 @ @<Add the known |value(p)| to the constant term of |v|@>=
20099 while ( info(v)!=null ) v=link(v);
20100 value(v)=mp_slow_add(mp, value(p),value(v));
20103 @ @<Output the answer, |v| (which might have become |known|)@>=
20104 if ( q!=null ) mp_dep_finish(mp, v,q,t);
20105 else { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
20107 @ Here's the current situation: The dependency list |v| of type |t|
20108 should either be put into the current expression (if |q=null|) or
20109 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20110 or |q|) formerly held a dependency list with the same
20111 final pointer as the list |v|.
20113 @<Declare the procedure called |dep_finish|@>=
20114 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
20115 pointer p; /* the destination */
20116 scaled vv; /* the value, if it is |known| */
20117 if ( q==null ) p=mp->cur_exp; else p=q;
20118 dep_list(p)=v; type(p)=t;
20119 if ( info(v)==null ) {
20122 mp_flush_cur_exp(mp, vv);
20124 mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv;
20126 } else if ( q==null ) {
20129 if ( mp->fix_needed ) mp_fix_dependencies(mp);
20132 @ Let's turn now to the six basic relations of comparison.
20134 @<Additional cases of binary operators@>=
20135 case less_than: case less_or_equal: case greater_than:
20136 case greater_or_equal: case equal_to: case unequal_to:
20137 check_arith; /* at this point |arith_error| should be |false|? */
20138 if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20139 mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20140 } else if ( mp->cur_type!=type(p) ) {
20141 mp_bad_binary(mp, p,c); goto DONE;
20142 } else if ( mp->cur_type==mp_string_type ) {
20143 mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20144 } else if ((mp->cur_type==mp_unknown_string)||
20145 (mp->cur_type==mp_unknown_boolean) ) {
20146 @<Check if unknowns have been equated@>;
20147 } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20148 @<Reduce comparison of big nodes to comparison of scalars@>;
20149 } else if ( mp->cur_type==mp_boolean_type ) {
20150 mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20152 mp_bad_binary(mp, p,c); goto DONE;
20154 @<Compare the current expression with zero@>;
20156 mp->arith_error=false; /* ignore overflow in comparisons */
20159 @ @<Compare the current expression with zero@>=
20160 if ( mp->cur_type!=mp_known ) {
20161 if ( mp->cur_type<mp_known ) {
20162 mp_disp_err(mp, p,"");
20163 help1("The quantities shown above have not been equated.")
20165 help2("Oh dear. I can\'t decide if the expression above is positive,")
20166 ("negative, or zero. So this comparison test won't be `true'.");
20168 exp_err("Unknown relation will be considered false");
20169 @.Unknown relation...@>
20170 mp_put_get_flush_error(mp, false_code);
20173 case less_than: boolean_reset(mp->cur_exp<0); break;
20174 case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20175 case greater_than: boolean_reset(mp->cur_exp>0); break;
20176 case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20177 case equal_to: boolean_reset(mp->cur_exp==0); break;
20178 case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20179 }; /* there are no other cases */
20181 mp->cur_type=mp_boolean_type
20183 @ When two unknown strings are in the same ring, we know that they are
20184 equal. Otherwise, we don't know whether they are equal or not, so we
20187 @<Check if unknowns have been equated@>=
20189 q=value(mp->cur_exp);
20190 while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20191 if ( q==p ) mp_flush_cur_exp(mp, 0);
20194 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20196 q=value(p); r=value(mp->cur_exp);
20197 rr=r+mp->big_node_size[mp->cur_type]-2;
20198 while (1) { mp_add_or_subtract(mp, q,r,minus);
20199 if ( type(r)!=mp_known ) break;
20200 if ( value(r)!=0 ) break;
20201 if ( r==rr ) break;
20204 mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
20207 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20209 @<Additional cases of binary operators@>=
20212 if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20213 mp_bad_binary(mp, p,c);
20214 else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20217 @ @<Additional cases of binary operators@>=
20219 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20220 mp_bad_binary(mp, p,times);
20221 } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
20222 @<Multiply when at least one operand is known@>;
20223 } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
20224 ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20225 (type(p)>mp_pair_type)) ) {
20226 mp_hard_times(mp, p); return;
20228 mp_bad_binary(mp, p,times);
20232 @ @<Multiply when at least one operand is known@>=
20234 if ( type(p)==mp_known ) {
20235 v=value(p); mp_free_node(mp, p,value_node_size);
20237 v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20239 if ( mp->cur_type==mp_known ) {
20240 mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20241 } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20242 (mp->cur_type==mp_cmykcolor_type) ) {
20243 p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20245 p=p-2; mp_dep_mult(mp, p,v,true);
20246 } while (p!=value(mp->cur_exp));
20248 mp_dep_mult(mp, null,v,true);
20253 @ @<Declare binary action...@>=
20254 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20255 pointer q; /* the dependency list being multiplied by |v| */
20256 small_number s,t; /* its type, before and after */
20259 } else if ( type(p)!=mp_known ) {
20262 if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20263 else value(p)=mp_take_fraction(mp, value(p),v);
20266 t=type(q); q=dep_list(q); s=t;
20267 if ( t==mp_dependent ) if ( v_is_scaled )
20268 if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 )
20269 t=mp_proto_dependent;
20270 q=mp_p_times_v(mp, q,v,s,t,v_is_scaled);
20271 mp_dep_finish(mp, q,p,t);
20274 @ Here is a routine that is similar to |times|; but it is invoked only
20275 internally, when |v| is a |fraction| whose magnitude is at most~1,
20276 and when |cur_type>=mp_color_type|.
20278 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20279 /* multiplies |cur_exp| by |n/d| */
20280 pointer p; /* a pair node */
20281 pointer old_exp; /* a capsule to recycle */
20282 fraction v; /* |n/d| */
20283 if ( mp->internal[mp_tracing_commands]>two ) {
20284 @<Trace the fraction multiplication@>;
20286 switch (mp->cur_type) {
20287 case mp_transform_type:
20288 case mp_color_type:
20289 case mp_cmykcolor_type:
20291 old_exp=mp_tarnished(mp, mp->cur_exp);
20293 case mp_independent: old_exp=mp_void; break;
20294 default: old_exp=null; break;
20296 if ( old_exp!=null ) {
20297 old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20299 v=mp_make_fraction(mp, n,d);
20300 if ( mp->cur_type==mp_known ) {
20301 mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20302 } else if ( mp->cur_type<=mp_pair_type ) {
20303 p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20306 mp_dep_mult(mp, p,v,false);
20307 } while (p!=value(mp->cur_exp));
20309 mp_dep_mult(mp, null,v,false);
20311 if ( old_exp!=null ) {
20312 mp_recycle_value(mp, old_exp);
20313 mp_free_node(mp, old_exp,value_node_size);
20317 @ @<Trace the fraction multiplication@>=
20319 mp_begin_diagnostic(mp);
20320 mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20321 mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0);
20323 mp_end_diagnostic(mp, false);
20326 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20328 @<Declare binary action procedures@>=
20329 void mp_hard_times (MP mp,pointer p) {
20330 pointer q; /* a copy of the dependent variable |p| */
20331 pointer r; /* a component of the big node for the nice color or pair */
20332 scaled v; /* the known value for |r| */
20333 if ( type(p)<=mp_pair_type ) {
20334 q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20335 }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20336 r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20341 if ( r==value(mp->cur_exp) )
20343 mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20344 mp_dep_mult(mp, r,v,true);
20346 mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20347 link(prev_dep(p))=r;
20348 mp_free_node(mp, p,value_node_size);
20349 mp_dep_mult(mp, r,v,true);
20352 @ @<Additional cases of binary operators@>=
20354 if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20355 mp_bad_binary(mp, p,over);
20357 v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20359 @<Squeal about division by zero@>;
20361 if ( mp->cur_type==mp_known ) {
20362 mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20363 } else if ( mp->cur_type<=mp_pair_type ) {
20364 p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20366 p=p-2; mp_dep_div(mp, p,v);
20367 } while (p!=value(mp->cur_exp));
20369 mp_dep_div(mp, null,v);
20376 @ @<Declare binary action...@>=
20377 void mp_dep_div (MP mp,pointer p, scaled v) {
20378 pointer q; /* the dependency list being divided by |v| */
20379 small_number s,t; /* its type, before and after */
20380 if ( p==null ) q=mp->cur_exp;
20381 else if ( type(p)!=mp_known ) q=p;
20382 else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20383 t=type(q); q=dep_list(q); s=t;
20384 if ( t==mp_dependent )
20385 if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 )
20386 t=mp_proto_dependent;
20387 q=mp_p_over_v(mp, q,v,s,t);
20388 mp_dep_finish(mp, q,p,t);
20391 @ @<Squeal about division by zero@>=
20393 exp_err("Division by zero");
20394 @.Division by zero@>
20395 help2("You're trying to divide the quantity shown above the error")
20396 ("message by zero. I'm going to divide it by one instead.");
20397 mp_put_get_error(mp);
20400 @ @<Additional cases of binary operators@>=
20403 if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20404 if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20405 else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20406 } else mp_bad_binary(mp, p,c);
20409 @ The next few sections of the program deal with affine transformations
20410 of coordinate data.
20412 @<Additional cases of binary operators@>=
20413 case rotated_by: case slanted_by:
20414 case scaled_by: case shifted_by: case transformed_by:
20415 case x_scaled: case y_scaled: case z_scaled:
20416 if ( type(p)==mp_path_type ) {
20417 path_trans(c,p); return;
20418 } else if ( type(p)==mp_pen_type ) {
20420 mp->cur_exp=mp_convex_hull(mp, mp->cur_exp);
20421 /* rounding error could destroy convexity */
20423 } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20424 mp_big_trans(mp, p,c);
20425 } else if ( type(p)==mp_picture_type ) {
20426 mp_do_edges_trans(mp, p,c); return;
20428 mp_bad_binary(mp, p,c);
20432 @ Let |c| be one of the eight transform operators. The procedure call
20433 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20434 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20435 change at all if |c=transformed_by|.)
20437 Then, if all components of the resulting transform are |known|, they are
20438 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20439 and |cur_exp| is changed to the known value zero.
20441 @<Declare binary action...@>=
20442 void mp_set_up_trans (MP mp,quarterword c) {
20443 pointer p,q,r; /* list manipulation registers */
20444 if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20445 @<Put the current transform into |cur_exp|@>;
20447 @<If the current transform is entirely known, stash it in global variables;
20448 otherwise |return|@>;
20457 scaled ty; /* current transform coefficients */
20459 @ @<Put the current transform...@>=
20461 p=mp_stash_cur_exp(mp);
20462 mp->cur_exp=mp_id_transform(mp);
20463 mp->cur_type=mp_transform_type;
20464 q=value(mp->cur_exp);
20466 @<For each of the eight cases, change the relevant fields of |cur_exp|
20468 but do nothing if capsule |p| doesn't have the appropriate type@>;
20469 }; /* there are no other cases */
20470 mp_disp_err(mp, p,"Improper transformation argument");
20471 @.Improper transformation argument@>
20472 help3("The expression shown above has the wrong type,")
20473 ("so I can\'t transform anything using it.")
20474 ("Proceed, and I'll omit the transformation.");
20475 mp_put_get_error(mp);
20477 mp_recycle_value(mp, p);
20478 mp_free_node(mp, p,value_node_size);
20481 @ @<If the current transform is entirely known, ...@>=
20482 q=value(mp->cur_exp); r=q+transform_node_size;
20485 if ( type(r)!=mp_known ) return;
20487 mp->txx=value(xx_part_loc(q));
20488 mp->txy=value(xy_part_loc(q));
20489 mp->tyx=value(yx_part_loc(q));
20490 mp->tyy=value(yy_part_loc(q));
20491 mp->tx=value(x_part_loc(q));
20492 mp->ty=value(y_part_loc(q));
20493 mp_flush_cur_exp(mp, 0)
20495 @ @<For each of the eight cases...@>=
20497 if ( type(p)==mp_known )
20498 @<Install sines and cosines, then |goto done|@>;
20501 if ( type(p)>mp_pair_type ) {
20502 mp_install(mp, xy_part_loc(q),p); goto DONE;
20506 if ( type(p)>mp_pair_type ) {
20507 mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p);
20512 if ( type(p)==mp_pair_type ) {
20513 r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20514 mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20518 if ( type(p)>mp_pair_type ) {
20519 mp_install(mp, xx_part_loc(q),p); goto DONE;
20523 if ( type(p)>mp_pair_type ) {
20524 mp_install(mp, yy_part_loc(q),p); goto DONE;
20528 if ( type(p)==mp_pair_type )
20529 @<Install a complex multiplier, then |goto done|@>;
20531 case transformed_by:
20535 @ @<Install sines and cosines, then |goto done|@>=
20536 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20537 value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20538 value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20539 value(xy_part_loc(q))=-value(yx_part_loc(q));
20540 value(yy_part_loc(q))=value(xx_part_loc(q));
20544 @ @<Install a complex multiplier, then |goto done|@>=
20547 mp_install(mp, xx_part_loc(q),x_part_loc(r));
20548 mp_install(mp, yy_part_loc(q),x_part_loc(r));
20549 mp_install(mp, yx_part_loc(q),y_part_loc(r));
20550 if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20551 else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20552 mp_install(mp, xy_part_loc(q),y_part_loc(r));
20556 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20557 insists that the transformation be entirely known.
20559 @<Declare binary action...@>=
20560 void mp_set_up_known_trans (MP mp,quarterword c) {
20561 mp_set_up_trans(mp, c);
20562 if ( mp->cur_type!=mp_known ) {
20563 exp_err("Transform components aren't all known");
20564 @.Transform components...@>
20565 help3("I'm unable to apply a partially specified transformation")
20566 ("except to a fully known pair or transform.")
20567 ("Proceed, and I'll omit the transformation.");
20568 mp_put_get_flush_error(mp, 0);
20569 mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity;
20570 mp->tx=0; mp->ty=0;
20574 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20575 coordinates in locations |p| and~|q|.
20577 @<Declare binary action...@>=
20578 void mp_trans (MP mp,pointer p, pointer q) {
20579 scaled v; /* the new |x| value */
20580 v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20581 mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20582 mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20583 mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20587 @ The simplest transformation procedure applies a transform to all
20588 coordinates of a path. The |path_trans(c)(p)| macro applies
20589 a transformation defined by |cur_exp| and the transform operator |c|
20592 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A));
20593 mp_unstash_cur_exp(mp, (B));
20594 mp_do_path_trans(mp, mp->cur_exp); }
20596 @<Declare binary action...@>=
20597 void mp_do_path_trans (MP mp,pointer p) {
20598 pointer q; /* list traverser */
20601 if ( left_type(q)!=mp_endpoint )
20602 mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20603 mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20604 if ( right_type(q)!=mp_endpoint )
20605 mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20606 @^data structure assumptions@>
20611 @ Transforming a pen is very similar, except that there are no |left_type|
20612 and |right_type| fields.
20614 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A));
20615 mp_unstash_cur_exp(mp, (B));
20616 mp_do_pen_trans(mp, mp->cur_exp); }
20618 @<Declare binary action...@>=
20619 void mp_do_pen_trans (MP mp,pointer p) {
20620 pointer q; /* list traverser */
20621 if ( pen_is_elliptical(p) ) {
20622 mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20623 mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20627 mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20628 @^data structure assumptions@>
20633 @ The next transformation procedure applies to edge structures. It will do
20634 any transformation, but the results may be substandard if the picture contains
20635 text that uses downloaded bitmap fonts. The binary action procedure is
20636 |do_edges_trans|, but we also need a function that just scales a picture.
20637 That routine is |scale_edges|. Both it and the underlying routine |edges_trans|
20638 should be thought of as procedures that update an edge structure |h|, except
20639 that they have to return a (possibly new) structure because of the need to call
20642 @<Declare binary action...@>=
20643 pointer mp_edges_trans (MP mp, pointer h) {
20644 pointer q; /* the object being transformed */
20645 pointer r,s; /* for list manipulation */
20646 scaled sx,sy; /* saved transformation parameters */
20647 scaled sqdet; /* square root of determinant for |dash_scale| */
20648 integer sgndet; /* sign of the determinant */
20649 scaled v; /* a temporary value */
20650 h=mp_private_edges(mp, h);
20651 sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20652 sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20653 if ( dash_list(h)!=null_dash ) {
20654 @<Try to transform the dash list of |h|@>;
20656 @<Make the bounding box of |h| unknown if it can't be updated properly
20657 without scanning the whole structure@>;
20658 q=link(dummy_loc(h));
20659 while ( q!=null ) {
20660 @<Transform graphical object |q|@>;
20665 void mp_do_edges_trans (MP mp,pointer p, quarterword c) {
20666 mp_set_up_known_trans(mp, c);
20667 value(p)=mp_edges_trans(mp, value(p));
20668 mp_unstash_cur_exp(mp, p);
20670 void mp_scale_edges (MP mp) {
20671 mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20672 mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20673 mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20676 @ @<Try to transform the dash list of |h|@>=
20677 if ( (mp->txy!=0)||(mp->tyx!=0)||
20678 (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20679 mp_flush_dash_list(mp, h);
20681 if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; }
20682 @<Scale the dash list by |txx| and shift it by |tx|@>;
20683 dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20686 @ @<Reverse the dash list of |h|@>=
20689 dash_list(h)=null_dash;
20690 while ( r!=null_dash ) {
20692 v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20693 link(s)=dash_list(h);
20698 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20700 while ( r!=null_dash ) {
20701 start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20702 stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20706 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20707 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20708 @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20709 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20710 mp_init_bbox(mp, h);
20713 if ( minx_val(h)<=maxx_val(h) ) {
20714 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20721 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20723 v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20724 v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20727 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero. The other
20730 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20732 minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20733 maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20734 miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20735 maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20736 if ( mp->txx+mp->txy<0 ) {
20737 v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20739 if ( mp->tyx+mp->tyy<0 ) {
20740 v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20744 @ Now we ready for the main task of transforming the graphical objects in edge
20747 @<Transform graphical object |q|@>=
20749 case mp_fill_code: case mp_stroked_code:
20750 mp_do_path_trans(mp, path_p(q));
20751 @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20753 case mp_start_clip_code: case mp_start_bounds_code:
20754 mp_do_path_trans(mp, path_p(q));
20758 @<Transform the compact transformation starting at |r|@>;
20760 case mp_stop_clip_code: case mp_stop_bounds_code:
20762 } /* there are no other cases */
20764 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20765 The |dash_scale| has to be adjusted to scale the dash lengths in |dash_p(q)|
20766 since the \ps\ output procedures will try to compensate for the transformation
20767 we are applying to |pen_p(q)|. Since this compensation is based on the square
20768 root of the determinant, |sqdet| is the appropriate factor.
20770 @<Transform |pen_p(q)|, making sure...@>=
20771 if ( pen_p(q)!=null ) {
20772 sx=mp->tx; sy=mp->ty;
20773 mp->tx=0; mp->ty=0;
20774 mp_do_pen_trans(mp, pen_p(q));
20775 if ( ((type(q)==mp_stroked_code)&&(dash_p(q)!=null)) )
20776 dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20777 if ( ! pen_is_elliptical(pen_p(q)) )
20779 pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true);
20780 /* this unreverses the pen */
20781 mp->tx=sx; mp->ty=sy;
20784 @ This uses the fact that transformations are stored in the order
20785 |(tx,ty,txx,txy,tyx,tyy)|.
20786 @^data structure assumptions@>
20788 @<Transform the compact transformation starting at |r|@>=
20789 mp_trans(mp, r,r+1);
20790 sx=mp->tx; sy=mp->ty;
20791 mp->tx=0; mp->ty=0;
20792 mp_trans(mp, r+2,r+4);
20793 mp_trans(mp, r+3,r+5);
20794 mp->tx=sx; mp->ty=sy
20796 @ The hard cases of transformation occur when big nodes are involved,
20797 and when some of their components are unknown.
20799 @<Declare binary action...@>=
20800 @<Declare subroutines needed by |big_trans|@>;
20801 void mp_big_trans (MP mp,pointer p, quarterword c) {
20802 pointer q,r,pp,qq; /* list manipulation registers */
20803 small_number s; /* size of a big node */
20804 s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20807 if ( type(r)!=mp_known ) {
20808 @<Transform an unknown big node and |return|@>;
20811 @<Transform a known big node@>;
20812 }; /* node |p| will now be recycled by |do_binary| */
20814 @ @<Transform an unknown big node and |return|@>=
20816 mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p);
20817 r=value(mp->cur_exp);
20818 if ( mp->cur_type==mp_transform_type ) {
20819 mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20820 mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20821 mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20822 mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20824 mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20825 mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20829 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20830 and let |q| point to a another value field. The |bilin1| procedure
20831 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20833 @<Declare subroutines needed by |big_trans|@>=
20834 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q,
20835 scaled u, scaled delta) {
20836 pointer r; /* list traverser */
20837 if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20839 if ( type(q)==mp_known ) {
20840 delta+=mp_take_scaled(mp, value(q),u);
20842 @<Ensure that |type(p)=mp_proto_dependent|@>;
20843 dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20844 mp_proto_dependent,type(q));
20847 if ( type(p)==mp_known ) {
20851 while ( info(r)!=null ) r=link(r);
20853 if ( r!=dep_list(p) ) value(r)=delta;
20854 else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20856 if ( mp->fix_needed ) mp_fix_dependencies(mp);
20859 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20860 if ( type(p)!=mp_proto_dependent ) {
20861 if ( type(p)==mp_known )
20862 mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20864 dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20865 mp_proto_dependent,true);
20866 type(p)=mp_proto_dependent;
20869 @ @<Transform a known big node@>=
20870 mp_set_up_trans(mp, c);
20871 if ( mp->cur_type==mp_known ) {
20872 @<Transform known by known@>;
20874 pp=mp_stash_cur_exp(mp); qq=value(pp);
20875 mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20876 if ( mp->cur_type==mp_transform_type ) {
20877 mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20878 value(xy_part_loc(q)),yx_part_loc(qq),null);
20879 mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20880 value(xx_part_loc(q)),yx_part_loc(qq),null);
20881 mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20882 value(yy_part_loc(q)),xy_part_loc(qq),null);
20883 mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20884 value(yx_part_loc(q)),xy_part_loc(qq),null);
20886 mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20887 value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20888 mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20889 value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20890 mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20893 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20894 at |dep_final|. The following procedure adds |v| times another
20895 numeric quantity to~|p|.
20897 @<Declare subroutines needed by |big_trans|@>=
20898 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) {
20899 if ( type(r)==mp_known ) {
20900 value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20902 dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20903 mp_proto_dependent,type(r));
20904 if ( mp->fix_needed ) mp_fix_dependencies(mp);
20908 @ The |bilin2| procedure is something like |bilin1|, but with known
20909 and unknown quantities reversed. Parameter |p| points to a value field
20910 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20911 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20912 unless it is |null| (which stands for zero). Location~|p| will be
20913 replaced by $p\cdot t+v\cdot u+q$.
20915 @<Declare subroutines needed by |big_trans|@>=
20916 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v,
20917 pointer u, pointer q) {
20918 scaled vv; /* temporary storage for |value(p)| */
20919 vv=value(p); type(p)=mp_proto_dependent;
20920 mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20922 mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20923 if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20924 if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20925 if ( dep_list(p)==mp->dep_final ) {
20926 vv=value(mp->dep_final); mp_recycle_value(mp, p);
20927 type(p)=mp_known; value(p)=vv;
20931 @ @<Transform known by known@>=
20933 mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20934 if ( mp->cur_type==mp_transform_type ) {
20935 mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20936 mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20937 mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20938 mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20940 mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20941 mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20944 @ Finally, in |bilin3| everything is |known|.
20946 @<Declare subroutines needed by |big_trans|@>=
20947 void mp_bilin3 (MP mp,pointer p, scaled t,
20948 scaled v, scaled u, scaled delta) {
20950 delta+=mp_take_scaled(mp, value(p),t);
20953 if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20954 else value(p)=delta;
20957 @ @<Additional cases of binary operators@>=
20959 if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20960 else mp_bad_binary(mp, p,concatenate);
20963 if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20964 mp_chop_string(mp, value(p));
20965 else mp_bad_binary(mp, p,substring_of);
20968 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20969 if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20970 mp_chop_path(mp, value(p));
20971 else mp_bad_binary(mp, p,subpath_of);
20974 @ @<Declare binary action...@>=
20975 void mp_cat (MP mp,pointer p) {
20976 str_number a,b; /* the strings being concatenated */
20977 pool_pointer k; /* index into |str_pool| */
20978 a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20979 for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20980 append_char(mp->str_pool[k]);
20982 for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20983 append_char(mp->str_pool[k]);
20985 mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20988 @ @<Declare binary action...@>=
20989 void mp_chop_string (MP mp,pointer p) {
20990 integer a, b; /* start and stop points */
20991 integer l; /* length of the original string */
20992 integer k; /* runs from |a| to |b| */
20993 str_number s; /* the original string */
20994 boolean reversed; /* was |a>b|? */
20995 a=mp_round_unscaled(mp, value(x_part_loc(p)));
20996 b=mp_round_unscaled(mp, value(y_part_loc(p)));
20997 if ( a<=b ) reversed=false;
20998 else { reversed=true; k=a; a=b; b=k; };
20999 s=mp->cur_exp; l=length(s);
21010 for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--) {
21011 append_char(mp->str_pool[k]);
21014 for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++) {
21015 append_char(mp->str_pool[k]);
21018 mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
21021 @ @<Declare binary action...@>=
21022 void mp_chop_path (MP mp,pointer p) {
21023 pointer q; /* a knot in the original path */
21024 pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
21025 scaled a,b,k,l; /* indices for chopping */
21026 boolean reversed; /* was |a>b|? */
21027 l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
21028 if ( a<=b ) reversed=false;
21029 else { reversed=true; k=a; a=b; b=k; };
21030 @<Dispense with the cases |a<0| and/or |b>l|@>;
21032 while ( a>=unity ) {
21033 q=link(q); a=a-unity; b=b-unity;
21036 @<Construct a path from |pp| to |qq| of length zero@>;
21038 @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>;
21040 left_type(pp)=mp_endpoint; right_type(qq)=mp_endpoint; link(qq)=pp;
21041 mp_toss_knot_list(mp, mp->cur_exp);
21043 mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
21049 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
21051 if ( left_type(mp->cur_exp)==mp_endpoint ) {
21052 a=0; if ( b<0 ) b=0;
21054 do { a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
21058 if ( left_type(mp->cur_exp)==mp_endpoint ) {
21059 b=l; if ( a>l ) a=l;
21067 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
21069 pp=mp_copy_knot(mp, q); qq=pp;
21071 q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
21074 ss=pp; pp=link(pp);
21075 mp_split_cubic(mp, ss,a*010000); pp=link(ss);
21076 mp_free_node(mp, ss,knot_node_size);
21078 b=mp_make_scaled(mp, b,unity-a); rr=pp;
21082 mp_split_cubic(mp, rr,(b+unity)*010000);
21083 mp_free_node(mp, qq,knot_node_size);
21088 @ @<Construct a path from |pp| to |qq| of length zero@>=
21090 if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
21091 pp=mp_copy_knot(mp, q); qq=pp;
21094 @ @<Additional cases of binary operators@>=
21095 case point_of: case precontrol_of: case postcontrol_of:
21096 if ( mp->cur_type==mp_pair_type )
21097 mp_pair_to_path(mp);
21098 if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21099 mp_find_point(mp, value(p),c);
21101 mp_bad_binary(mp, p,c);
21103 case pen_offset_of:
21104 if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
21105 mp_set_up_offset(mp, value(p));
21107 mp_bad_binary(mp, p,pen_offset_of);
21109 case direction_time_of:
21110 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21111 if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
21112 mp_set_up_direction_time(mp, value(p));
21114 mp_bad_binary(mp, p,direction_time_of);
21117 if ( (type(p) != mp_pen_type) || (mp->cur_type != mp_path_type) )
21118 mp_bad_binary(mp, p,envelope_of);
21120 mp_set_up_envelope(mp, p);
21123 @ @<Declare binary action...@>=
21124 void mp_set_up_offset (MP mp,pointer p) {
21125 mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21126 mp_pair_value(mp, mp->cur_x,mp->cur_y);
21128 void mp_set_up_direction_time (MP mp,pointer p) {
21129 mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21130 value(y_part_loc(p)),mp->cur_exp));
21132 void mp_set_up_envelope (MP mp,pointer p) {
21133 pointer q = mp_copy_path(mp, mp->cur_exp); /* the original path */
21134 /* TODO: accept elliptical pens for straight paths */
21135 if (pen_is_elliptical(value(p))) {
21136 mp_bad_envelope_pen(mp);
21138 mp->cur_type = mp_path_type;
21141 small_number ljoin, lcap;
21143 if ( mp->internal[mp_linejoin]>unity ) ljoin=2;
21144 else if ( mp->internal[mp_linejoin]>0 ) ljoin=1;
21146 if ( mp->internal[mp_linecap]>unity ) lcap=2;
21147 else if ( mp->internal[mp_linecap]>0 ) lcap=1;
21149 if ( mp->internal[mp_miterlimit]<unity )
21152 miterlim=mp->internal[mp_miterlimit];
21153 mp->cur_exp = mp_make_envelope(mp, q, value(p), ljoin,lcap,miterlim);
21154 mp->cur_type = mp_path_type;
21157 @ @<Declare binary action...@>=
21158 void mp_find_point (MP mp,scaled v, quarterword c) {
21159 pointer p; /* the path */
21160 scaled n; /* its length */
21162 if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
21163 do { p=link(p); n=n+unity; } while (p!=mp->cur_exp);
21166 } else if ( v<0 ) {
21167 if ( left_type(p)==mp_endpoint ) v=0;
21168 else v=n-1-((-v-1) % n);
21169 } else if ( v>n ) {
21170 if ( left_type(p)==mp_endpoint ) v=n;
21174 while ( v>=unity ) { p=link(p); v=v-unity; };
21176 @<Insert a fractional node by splitting the cubic@>;
21178 @<Set the current expression to the desired path coordinates@>;
21181 @ @<Insert a fractional node...@>=
21182 { mp_split_cubic(mp, p,v*010000); p=link(p); }
21184 @ @<Set the current expression to the desired path coordinates...@>=
21187 mp_pair_value(mp, x_coord(p),y_coord(p));
21189 case precontrol_of:
21190 if ( left_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21191 else mp_pair_value(mp, left_x(p),left_y(p));
21193 case postcontrol_of:
21194 if ( right_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21195 else mp_pair_value(mp, right_x(p),right_y(p));
21197 } /* there are no other cases */
21199 @ @<Additional cases of binary operators@>=
21201 if ( mp->cur_type==mp_pair_type )
21202 mp_pair_to_path(mp);
21203 if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21204 mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21206 mp_bad_binary(mp, p,c);
21209 @ @<Additional cases of bin...@>=
21211 if ( type(p)==mp_pair_type ) {
21212 q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21213 mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21215 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21216 if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
21217 mp_path_intersection(mp, value(p),mp->cur_exp);
21218 mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21220 mp_bad_binary(mp, p,intersect);
21224 @ @<Additional cases of bin...@>=
21226 if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type))
21227 mp_bad_binary(mp, p,in_font);
21228 else { mp_do_infont(mp, p); return; }
21231 @ Function |new_text_node| owns the reference count for its second argument
21232 (the text string) but not its first (the font name).
21234 @<Declare binary action...@>=
21235 void mp_do_infont (MP mp,pointer p) {
21237 q=mp_get_node(mp, edge_header_size);
21238 mp_init_edges(mp, q);
21239 link(obj_tail(q))=mp_new_text_node(mp, str(mp->cur_exp),value(p));
21240 obj_tail(q)=link(obj_tail(q));
21241 mp_free_node(mp, p,value_node_size);
21242 mp_flush_cur_exp(mp, q);
21243 mp->cur_type=mp_picture_type;
21246 @* \[40] Statements and commands.
21247 The chief executive of \MP\ is the |do_statement| routine, which
21248 contains the master switch that causes all the various pieces of \MP\
21249 to do their things, in the right order.
21251 In a sense, this is the grand climax of the program: It applies all the
21252 tools that we have worked so hard to construct. In another sense, this is
21253 the messiest part of the program: It necessarily refers to other pieces
21254 of code all over the place, so that a person can't fully understand what is
21255 going on without paging back and forth to be reminded of conventions that
21256 are defined elsewhere. We are now at the hub of the web.
21258 The structure of |do_statement| itself is quite simple. The first token
21259 of the statement is fetched using |get_x_next|. If it can be the first
21260 token of an expression, we look for an equation, an assignment, or a
21261 title. Otherwise we use a \&{case} construction to branch at high speed to
21262 the appropriate routine for various and sundry other types of commands,
21263 each of which has an ``action procedure'' that does the necessary work.
21265 The program uses the fact that
21266 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21267 to interpret a statement that starts with, e.g., `\&{string}',
21268 as a type declaration rather than a boolean expression.
21270 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21271 mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21272 if ( mp->cur_cmd>max_primary_command ) {
21273 @<Worry about bad statement@>;
21274 } else if ( mp->cur_cmd>max_statement_command ) {
21275 @<Do an equation, assignment, title, or
21276 `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21278 @<Do a statement that doesn't begin with an expression@>;
21280 if ( mp->cur_cmd<semicolon )
21281 @<Flush unparsable junk that was found after the statement@>;
21285 @ @<Declarations@>=
21286 @<Declare action procedures for use by |do_statement|@>;
21288 @ The only command codes |>max_primary_command| that can be present
21289 at the beginning of a statement are |semicolon| and higher; these
21290 occur when the statement is null.
21292 @<Worry about bad statement@>=
21294 if ( mp->cur_cmd<semicolon ) {
21295 print_err("A statement can't begin with `");
21296 @.A statement can't begin with x@>
21297 mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21298 help5("I was looking for the beginning of a new statement.")
21299 ("If you just proceed without changing anything, I'll ignore")
21300 ("everything up to the next `;'. Please insert a semicolon")
21301 ("now in front of anything that you don't want me to delete.")
21302 ("(See Chapter 27 of The METAFONTbook for an example.)");
21303 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21304 mp_back_error(mp); mp_get_x_next(mp);
21308 @ The help message printed here says that everything is flushed up to
21309 a semicolon, but actually the commands |end_group| and |stop| will
21310 also terminate a statement.
21312 @<Flush unparsable junk that was found after the statement@>=
21314 print_err("Extra tokens will be flushed");
21315 @.Extra tokens will be flushed@>
21316 help6("I've just read as much of that statement as I could fathom,")
21317 ("so a semicolon should have been next. It's very puzzling...")
21318 ("but I'll try to get myself back together, by ignoring")
21319 ("everything up to the next `;'. Please insert a semicolon")
21320 ("now in front of anything that you don't want me to delete.")
21321 ("(See Chapter 27 of The METAFONTbook for an example.)");
21322 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21323 mp_back_error(mp); mp->scanner_status=flushing;
21326 @<Decrease the string reference count...@>;
21327 } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21328 mp->scanner_status=normal;
21331 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21332 |cur_type=mp_vacuous| unless the statement was simply an expression;
21333 in the latter case, |cur_type| and |cur_exp| should represent that
21336 @<Do a statement that doesn't...@>=
21338 if ( mp->internal[mp_tracing_commands]>0 )
21340 switch (mp->cur_cmd ) {
21341 case type_name:mp_do_type_declaration(mp); break;
21343 if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21344 else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21346 @<Cases of |do_statement| that invoke particular commands@>;
21347 } /* there are no other cases */
21348 mp->cur_type=mp_vacuous;
21351 @ The most important statements begin with expressions.
21353 @<Do an equation, assignment, title, or...@>=
21355 mp->var_flag=assignment; mp_scan_expression(mp);
21356 if ( mp->cur_cmd<end_group ) {
21357 if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21358 else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21359 else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21360 else if ( mp->cur_type!=mp_vacuous ){
21361 exp_err("Isolated expression");
21362 @.Isolated expression@>
21363 help3("I couldn't find an `=' or `:=' after the")
21364 ("expression that is shown above this error message,")
21365 ("so I guess I'll just ignore it and carry on.");
21366 mp_put_get_error(mp);
21368 mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21374 if ( mp->internal[mp_tracing_titles]>0 ) {
21375 mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp); update_terminal;
21379 @ Equations and assignments are performed by the pair of mutually recursive
21381 routines |do_equation| and |do_assignment|. These routines are called when
21382 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21383 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21384 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21385 will be equal to the right-hand side (which will normally be equal
21386 to the left-hand side).
21388 @<Declare action procedures for use by |do_statement|@>=
21389 @<Declare the procedure called |try_eq|@>;
21390 @<Declare the procedure called |make_eq|@>;
21391 void mp_do_equation (MP mp) ;
21394 void mp_do_equation (MP mp) {
21395 pointer lhs; /* capsule for the left-hand side */
21396 pointer p; /* temporary register */
21397 lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp);
21398 mp->var_flag=assignment; mp_scan_expression(mp);
21399 if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21400 else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21401 if ( mp->internal[mp_tracing_commands]>two )
21402 @<Trace the current equation@>;
21403 if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21404 p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21405 }; /* in this case |make_eq| will change the pair to a path */
21406 mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21409 @ And |do_assignment| is similar to |do_expression|:
21412 void mp_do_assignment (MP mp);
21414 @ @<Declare action procedures for use by |do_statement|@>=
21415 void mp_do_assignment (MP mp) ;
21418 void mp_do_assignment (MP mp) {
21419 pointer lhs; /* token list for the left-hand side */
21420 pointer p; /* where the left-hand value is stored */
21421 pointer q; /* temporary capsule for the right-hand value */
21422 if ( mp->cur_type!=mp_token_list ) {
21423 exp_err("Improper `:=' will be changed to `='");
21425 help2("I didn't find a variable name at the left of the `:=',")
21426 ("so I'm going to pretend that you said `=' instead.");
21427 mp_error(mp); mp_do_equation(mp);
21429 lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21430 mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21431 if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21432 else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21433 if ( mp->internal[mp_tracing_commands]>two )
21434 @<Trace the current assignment@>;
21435 if ( info(lhs)>hash_end ) {
21436 @<Assign the current expression to an internal variable@>;
21438 @<Assign the current expression to the variable |lhs|@>;
21440 mp_flush_node_list(mp, lhs);
21444 @ @<Trace the current equation@>=
21446 mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21447 mp_print(mp,")=("); mp_print_exp(mp,null,0);
21448 mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21451 @ @<Trace the current assignment@>=
21453 mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21454 if ( info(lhs)>hash_end )
21455 mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21457 mp_show_token_list(mp, lhs,null,1000,0);
21458 mp_print(mp, ":="); mp_print_exp(mp, null,0);
21459 mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21462 @ @<Assign the current expression to an internal variable@>=
21463 if ( mp->cur_type==mp_known ) {
21464 mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21466 exp_err("Internal quantity `");
21467 @.Internal quantity...@>
21468 mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21469 mp_print(mp, "' must receive a known value");
21470 help2("I can\'t set an internal quantity to anything but a known")
21471 ("numeric value, so I'll have to ignore this assignment.");
21472 mp_put_get_error(mp);
21475 @ @<Assign the current expression to the variable |lhs|@>=
21477 p=mp_find_variable(mp, lhs);
21479 q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p);
21480 mp_recycle_value(mp, p);
21481 type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21482 p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21484 mp_obliterated(mp, lhs); mp_put_get_error(mp);
21489 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21490 a pointer to a capsule that is to be equated to the current expression.
21492 @<Declare the procedure called |make_eq|@>=
21493 void mp_make_eq (MP mp,pointer lhs) ;
21497 @c void mp_make_eq (MP mp,pointer lhs) {
21498 small_number t; /* type of the left-hand side */
21499 pointer p,q; /* pointers inside of big nodes */
21500 integer v=0; /* value of the left-hand side */
21503 if ( t<=mp_pair_type ) v=value(lhs);
21505 @<For each type |t|, make an equation and |goto done| unless |cur_type|
21506 is incompatible with~|t|@>;
21507 } /* all cases have been listed */
21508 @<Announce that the equation cannot be performed@>;
21510 check_arith; mp_recycle_value(mp, lhs);
21511 mp_free_node(mp, lhs,value_node_size);
21514 @ @<Announce that the equation cannot be performed@>=
21515 mp_disp_err(mp, lhs,"");
21516 exp_err("Equation cannot be performed (");
21517 @.Equation cannot be performed@>
21518 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21519 else mp_print(mp, "numeric");
21520 mp_print_char(mp, '=');
21521 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21522 else mp_print(mp, "numeric");
21523 mp_print_char(mp, ')');
21524 help2("I'm sorry, but I don't know how to make such things equal.")
21525 ("(See the two expressions just above the error message.)");
21526 mp_put_get_error(mp)
21528 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21529 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21530 case mp_path_type: case mp_picture_type:
21531 if ( mp->cur_type==t+unknown_tag ) {
21532 mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21533 } else if ( mp->cur_type==t ) {
21534 @<Report redundant or inconsistent equation and |goto done|@>;
21537 case unknown_types:
21538 if ( mp->cur_type==t-unknown_tag ) {
21539 mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21540 } else if ( mp->cur_type==t ) {
21541 mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21542 } else if ( mp->cur_type==mp_pair_type ) {
21543 if ( t==mp_unknown_path ) {
21544 mp_pair_to_path(mp); goto RESTART;
21548 case mp_transform_type: case mp_color_type:
21549 case mp_cmykcolor_type: case mp_pair_type:
21550 if ( mp->cur_type==t ) {
21551 @<Do multiple equations and |goto done|@>;
21554 case mp_known: case mp_dependent:
21555 case mp_proto_dependent: case mp_independent:
21556 if ( mp->cur_type>=mp_known ) {
21557 mp_try_eq(mp, lhs,null); goto DONE;
21563 @ @<Report redundant or inconsistent equation and |goto done|@>=
21565 if ( mp->cur_type<=mp_string_type ) {
21566 if ( mp->cur_type==mp_string_type ) {
21567 if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21570 } else if ( v!=mp->cur_exp ) {
21573 @<Exclaim about a redundant equation@>; goto DONE;
21575 print_err("Redundant or inconsistent equation");
21576 @.Redundant or inconsistent equation@>
21577 help2("An equation between already-known quantities can't help.")
21578 ("But don't worry; continue and I'll just ignore it.");
21579 mp_put_get_error(mp); goto DONE;
21581 print_err("Inconsistent equation");
21582 @.Inconsistent equation@>
21583 help2("The equation I just read contradicts what was said before.")
21584 ("But don't worry; continue and I'll just ignore it.");
21585 mp_put_get_error(mp); goto DONE;
21588 @ @<Do multiple equations and |goto done|@>=
21590 p=v+mp->big_node_size[t];
21591 q=value(mp->cur_exp)+mp->big_node_size[t];
21593 p=p-2; q=q-2; mp_try_eq(mp, p,q);
21598 @ The first argument to |try_eq| is the location of a value node
21599 in a capsule that will soon be recycled. The second argument is
21600 either a location within a pair or transform node pointed to by
21601 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21602 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21603 but to equate the two operands.
21605 @<Declare the procedure called |try_eq|@>=
21606 void mp_try_eq (MP mp,pointer l, pointer r) ;
21609 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21610 pointer p; /* dependency list for right operand minus left operand */
21611 int t; /* the type of list |p| */
21612 pointer q; /* the constant term of |p| is here */
21613 pointer pp; /* dependency list for right operand */
21614 int tt; /* the type of list |pp| */
21615 boolean copied; /* have we copied a list that ought to be recycled? */
21616 @<Remove the left operand from its container, negate it, and
21617 put it into dependency list~|p| with constant term~|q|@>;
21618 @<Add the right operand to list |p|@>;
21619 if ( info(p)==null ) {
21620 @<Deal with redundant or inconsistent equation@>;
21622 mp_linear_eq(mp, p,t);
21623 if ( r==null ) if ( mp->cur_type!=mp_known ) {
21624 if ( type(mp->cur_exp)==mp_known ) {
21625 pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21626 mp_free_node(mp, pp,value_node_size);
21632 @ @<Remove the left operand from its container, negate it, and...@>=
21634 if ( t==mp_known ) {
21635 t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21636 } else if ( t==mp_independent ) {
21637 t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21640 p=dep_list(l); q=p;
21643 if ( info(q)==null ) break;
21646 link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21650 @ @<Deal with redundant or inconsistent equation@>=
21652 if ( abs(value(p))>64 ) { /* off by .001 or more */
21653 print_err("Inconsistent equation");
21654 @.Inconsistent equation@>
21655 mp_print(mp, " (off by "); mp_print_scaled(mp, value(p));
21656 mp_print_char(mp, ')');
21657 help2("The equation I just read contradicts what was said before.")
21658 ("But don't worry; continue and I'll just ignore it.");
21659 mp_put_get_error(mp);
21660 } else if ( r==null ) {
21661 @<Exclaim about a redundant equation@>;
21663 mp_free_node(mp, p,dep_node_size);
21666 @ @<Add the right operand to list |p|@>=
21668 if ( mp->cur_type==mp_known ) {
21669 value(q)=value(q)+mp->cur_exp; goto DONE1;
21672 if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21673 else pp=dep_list(mp->cur_exp);
21676 if ( type(r)==mp_known ) {
21677 value(q)=value(q)+value(r); goto DONE1;
21680 if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21681 else pp=dep_list(r);
21684 if ( tt!=mp_independent ) copied=false;
21685 else { copied=true; tt=mp_dependent; };
21686 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21687 if ( copied ) mp_flush_node_list(mp, pp);
21690 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21691 mp->watch_coefs=false;
21693 p=mp_p_plus_q(mp, p,pp,t);
21694 } else if ( t==mp_proto_dependent ) {
21695 p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21698 while ( info(q)!=null ) {
21699 value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21701 t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21703 mp->watch_coefs=true;
21705 @ Our next goal is to process type declarations. For this purpose it's
21706 convenient to have a procedure that scans a $\langle\,$declared
21707 variable$\,\rangle$ and returns the corresponding token list. After the
21708 following procedure has acted, the token after the declared variable
21709 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21712 @<Declare the function called |scan_declared_variable|@>=
21713 pointer mp_scan_declared_variable (MP mp) {
21714 pointer x; /* hash address of the variable's root */
21715 pointer h,t; /* head and tail of the token list to be returned */
21716 pointer l; /* hash address of left bracket */
21717 mp_get_symbol(mp); x=mp->cur_sym;
21718 if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21719 h=mp_get_avail(mp); info(h)=x; t=h;
21722 if ( mp->cur_sym==0 ) break;
21723 if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity) {
21724 if ( mp->cur_cmd==left_bracket ) {
21725 @<Descend past a collective subscript@>;
21730 link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21732 if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21733 if ( equiv(x)==null ) mp_new_root(mp, x);
21737 @ If the subscript isn't collective, we don't accept it as part of the
21740 @<Descend past a collective subscript@>=
21742 l=mp->cur_sym; mp_get_x_next(mp);
21743 if ( mp->cur_cmd!=right_bracket ) {
21744 mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21746 mp->cur_sym=collective_subscript;
21750 @ Type declarations are introduced by the following primitive operations.
21753 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21754 @:numeric_}{\&{numeric} primitive@>
21755 mp_primitive(mp, "string",type_name,mp_string_type);
21756 @:string_}{\&{string} primitive@>
21757 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21758 @:boolean_}{\&{boolean} primitive@>
21759 mp_primitive(mp, "path",type_name,mp_path_type);
21760 @:path_}{\&{path} primitive@>
21761 mp_primitive(mp, "pen",type_name,mp_pen_type);
21762 @:pen_}{\&{pen} primitive@>
21763 mp_primitive(mp, "picture",type_name,mp_picture_type);
21764 @:picture_}{\&{picture} primitive@>
21765 mp_primitive(mp, "transform",type_name,mp_transform_type);
21766 @:transform_}{\&{transform} primitive@>
21767 mp_primitive(mp, "color",type_name,mp_color_type);
21768 @:color_}{\&{color} primitive@>
21769 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21770 @:color_}{\&{rgbcolor} primitive@>
21771 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21772 @:color_}{\&{cmykcolor} primitive@>
21773 mp_primitive(mp, "pair",type_name,mp_pair_type);
21774 @:pair_}{\&{pair} primitive@>
21776 @ @<Cases of |print_cmd...@>=
21777 case type_name: mp_print_type(mp, m); break;
21779 @ Now we are ready to handle type declarations, assuming that a
21780 |type_name| has just been scanned.
21782 @<Declare action procedures for use by |do_statement|@>=
21783 void mp_do_type_declaration (MP mp) ;
21786 void mp_do_type_declaration (MP mp) {
21787 small_number t; /* the type being declared */
21788 pointer p; /* token list for a declared variable */
21789 pointer q; /* value node for the variable */
21790 if ( mp->cur_mod>=mp_transform_type )
21793 t=mp->cur_mod+unknown_tag;
21795 p=mp_scan_declared_variable(mp);
21796 mp_flush_variable(mp, equiv(info(p)),link(p),false);
21797 q=mp_find_variable(mp, p);
21799 type(q)=t; value(q)=null;
21801 print_err("Declared variable conflicts with previous vardef");
21802 @.Declared variable conflicts...@>
21803 help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21804 ("Proceed, and I'll ignore the illegal redeclaration.");
21805 mp_put_get_error(mp);
21807 mp_flush_list(mp, p);
21808 if ( mp->cur_cmd<comma ) {
21809 @<Flush spurious symbols after the declared variable@>;
21811 } while (! end_of_statement);
21814 @ @<Flush spurious symbols after the declared variable@>=
21816 print_err("Illegal suffix of declared variable will be flushed");
21817 @.Illegal suffix...flushed@>
21818 help5("Variables in declarations must consist entirely of")
21819 ("names and collective subscripts, e.g., `x[]a'.")
21820 ("Are you trying to use a reserved word in a variable name?")
21821 ("I'm going to discard the junk I found here,")
21822 ("up to the next comma or the end of the declaration.");
21823 if ( mp->cur_cmd==numeric_token )
21824 mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21825 mp_put_get_error(mp); mp->scanner_status=flushing;
21828 @<Decrease the string reference count...@>;
21829 } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21830 mp->scanner_status=normal;
21833 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21834 until coming to the end of the user's program.
21835 Each execution of |do_statement| concludes with
21836 |cur_cmd=semicolon|, |end_group|, or |stop|.
21838 @c void mp_main_control (MP mp) {
21840 mp_do_statement(mp);
21841 if ( mp->cur_cmd==end_group ) {
21842 print_err("Extra `endgroup'");
21843 @.Extra `endgroup'@>
21844 help2("I'm not currently working on a `begingroup',")
21845 ("so I had better not try to end anything.");
21846 mp_flush_error(mp, 0);
21848 } while (mp->cur_cmd!=stop);
21850 int mp_run (MP mp) {
21851 @<Install and test the non-local jump buffer@>;
21852 mp_main_control(mp); /* come to life */
21853 mp_final_cleanup(mp); /* prepare for death */
21854 mp_close_files_and_terminate(mp);
21855 return mp->history;
21857 char * mp_mplib_version (MP mp) {
21859 return mplib_version;
21861 char * mp_metapost_version (MP mp) {
21863 return metapost_version;
21866 @ @<Exported function headers@>=
21867 int mp_run (MP mp);
21868 char * mp_mplib_version (MP mp);
21869 char * mp_metapost_version (MP mp);
21872 mp_primitive(mp, "end",stop,0);
21873 @:end_}{\&{end} primitive@>
21874 mp_primitive(mp, "dump",stop,1);
21875 @:dump_}{\&{dump} primitive@>
21877 @ @<Cases of |print_cmd...@>=
21879 if ( m==0 ) mp_print(mp, "end");
21880 else mp_print(mp, "dump");
21884 Let's turn now to statements that are classified as ``commands'' because
21885 of their imperative nature. We'll begin with simple ones, so that it
21886 will be clear how to hook command processing into the |do_statement| routine;
21887 then we'll tackle the tougher commands.
21889 Here's one of the simplest:
21891 @<Cases of |do_statement|...@>=
21892 case random_seed: mp_do_random_seed(mp); break;
21894 @ @<Declare action procedures for use by |do_statement|@>=
21895 void mp_do_random_seed (MP mp) ;
21897 @ @c void mp_do_random_seed (MP mp) {
21899 if ( mp->cur_cmd!=assignment ) {
21900 mp_missing_err(mp, ":=");
21902 help1("Always say `randomseed:=<numeric expression>'.");
21905 mp_get_x_next(mp); mp_scan_expression(mp);
21906 if ( mp->cur_type!=mp_known ) {
21907 exp_err("Unknown value will be ignored");
21908 @.Unknown value...ignored@>
21909 help2("Your expression was too random for me to handle,")
21910 ("so I won't change the random seed just now.");
21911 mp_put_get_flush_error(mp, 0);
21913 @<Initialize the random seed to |cur_exp|@>;
21917 @ @<Initialize the random seed to |cur_exp|@>=
21919 mp_init_randoms(mp, mp->cur_exp);
21920 if ( mp->selector>=log_only && mp->selector<write_file) {
21921 mp->old_setting=mp->selector; mp->selector=log_only;
21922 mp_print_nl(mp, "{randomseed:=");
21923 mp_print_scaled(mp, mp->cur_exp);
21924 mp_print_char(mp, '}');
21925 mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21929 @ And here's another simple one (somewhat different in flavor):
21931 @<Cases of |do_statement|...@>=
21933 mp_print_ln(mp); mp->interaction=mp->cur_mod;
21934 @<Initialize the print |selector| based on |interaction|@>;
21935 if ( mp->log_opened ) mp->selector=mp->selector+2;
21940 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21941 @:mp_batch_mode_}{\&{batchmode} primitive@>
21942 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21943 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21944 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21945 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21946 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21947 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21949 @ @<Cases of |print_cmd_mod|...@>=
21952 case mp_batch_mode: mp_print(mp, "batchmode"); break;
21953 case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21954 case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21955 default: mp_print(mp, "errorstopmode"); break;
21959 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21961 @<Cases of |do_statement|...@>=
21962 case protection_command: mp_do_protection(mp); break;
21965 mp_primitive(mp, "inner",protection_command,0);
21966 @:inner_}{\&{inner} primitive@>
21967 mp_primitive(mp, "outer",protection_command,1);
21968 @:outer_}{\&{outer} primitive@>
21970 @ @<Cases of |print_cmd...@>=
21971 case protection_command:
21972 if ( m==0 ) mp_print(mp, "inner");
21973 else mp_print(mp, "outer");
21976 @ @<Declare action procedures for use by |do_statement|@>=
21977 void mp_do_protection (MP mp) ;
21979 @ @c void mp_do_protection (MP mp) {
21980 int m; /* 0 to unprotect, 1 to protect */
21981 halfword t; /* the |eq_type| before we change it */
21984 mp_get_symbol(mp); t=eq_type(mp->cur_sym);
21986 if ( t>=outer_tag )
21987 eq_type(mp->cur_sym)=t-outer_tag;
21988 } else if ( t<outer_tag ) {
21989 eq_type(mp->cur_sym)=t+outer_tag;
21992 } while (mp->cur_cmd==comma);
21995 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
21996 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
21997 declaration assigns the command code |left_delimiter| to `\.{(}' and
21998 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
21999 hash address of its mate.
22001 @<Cases of |do_statement|...@>=
22002 case delimiters: mp_def_delims(mp); break;
22004 @ @<Declare action procedures for use by |do_statement|@>=
22005 void mp_def_delims (MP mp) ;
22007 @ @c void mp_def_delims (MP mp) {
22008 pointer l_delim,r_delim; /* the new delimiter pair */
22009 mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
22010 mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
22011 eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
22012 eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
22016 @ Here is a procedure that is called when \MP\ has reached a point
22017 where some right delimiter is mandatory.
22019 @<Declare the procedure called |check_delimiter|@>=
22020 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
22021 if ( mp->cur_cmd==right_delimiter )
22022 if ( mp->cur_mod==l_delim )
22024 if ( mp->cur_sym!=r_delim ) {
22025 mp_missing_err(mp, str(text(r_delim)));
22027 help2("I found no right delimiter to match a left one. So I've")
22028 ("put one in, behind the scenes; this may fix the problem.");
22031 print_err("The token `"); mp_print_text(r_delim);
22032 @.The token...delimiter@>
22033 mp_print(mp, "' is no longer a right delimiter");
22034 help3("Strange: This token has lost its former meaning!")
22035 ("I'll read it as a right delimiter this time;")
22036 ("but watch out, I'll probably miss it later.");
22041 @ The next four commands save or change the values associated with tokens.
22043 @<Cases of |do_statement|...@>=
22046 mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
22047 } while (mp->cur_cmd==comma);
22049 case interim_command: mp_do_interim(mp); break;
22050 case let_command: mp_do_let(mp); break;
22051 case new_internal: mp_do_new_internal(mp); break;
22053 @ @<Declare action procedures for use by |do_statement|@>=
22054 void mp_do_statement (MP mp);
22055 void mp_do_interim (MP mp);
22057 @ @c void mp_do_interim (MP mp) {
22059 if ( mp->cur_cmd!=internal_quantity ) {
22060 print_err("The token `");
22061 @.The token...quantity@>
22062 if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
22063 else mp_print_text(mp->cur_sym);
22064 mp_print(mp, "' isn't an internal quantity");
22065 help1("Something like `tracingonline' should follow `interim'.");
22068 mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
22070 mp_do_statement(mp);
22073 @ The following procedure is careful not to undefine the left-hand symbol
22074 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
22076 @<Declare action procedures for use by |do_statement|@>=
22077 void mp_do_let (MP mp) ;
22079 @ @c void mp_do_let (MP mp) {
22080 pointer l; /* hash location of the left-hand symbol */
22081 mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
22082 if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
22083 mp_missing_err(mp, "=");
22085 help3("You should have said `let symbol = something'.")
22086 ("But don't worry; I'll pretend that an equals sign")
22087 ("was present. The next token I read will be `something'.");
22091 switch (mp->cur_cmd) {
22092 case defined_macro: case secondary_primary_macro:
22093 case tertiary_secondary_macro: case expression_tertiary_macro:
22094 add_mac_ref(mp->cur_mod);
22099 mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
22100 if ( mp->cur_cmd==tag_token ) equiv(l)=null;
22101 else equiv(l)=mp->cur_mod;
22105 @ @<Declarations@>=
22106 void mp_grow_internals (MP mp, int l);
22107 void mp_do_new_internal (MP mp) ;
22110 void mp_grow_internals (MP mp, int l) {
22114 if ( hash_end+l>max_halfword ) {
22115 mp_confusion(mp, "out of memory space"); /* can't be reached */
22117 int_name = xmalloc ((l+1),sizeof(char *));
22118 internal = xmalloc ((l+1),sizeof(scaled));
22119 for (k=0;k<=l; k++ ) {
22120 if (k<=mp->max_internal) {
22121 internal[k]=mp->internal[k];
22122 int_name[k]=mp->int_name[k];
22128 xfree(mp->internal); xfree(mp->int_name);
22129 mp->int_name = int_name;
22130 mp->internal = internal;
22131 mp->max_internal = l;
22135 void mp_do_new_internal (MP mp) {
22137 if ( mp->int_ptr==mp->max_internal ) {
22138 mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
22140 mp_get_clear_symbol(mp); incr(mp->int_ptr);
22141 eq_type(mp->cur_sym)=internal_quantity;
22142 equiv(mp->cur_sym)=mp->int_ptr;
22143 if(mp->int_name[mp->int_ptr]!=NULL)
22144 xfree(mp->int_name[mp->int_ptr]);
22145 mp->int_name[mp->int_ptr]=str(text(mp->cur_sym));
22146 mp->internal[mp->int_ptr]=0;
22148 } while (mp->cur_cmd==comma);
22151 @ @<Dealloc variables@>=
22152 for (k=0;k<=mp->max_internal;k++) {
22153 xfree(mp->int_name[k]);
22155 xfree(mp->internal);
22156 xfree(mp->int_name);
22159 @ The various `\&{show}' commands are distinguished by modifier fields
22162 @d show_token_code 0 /* show the meaning of a single token */
22163 @d show_stats_code 1 /* show current memory and string usage */
22164 @d show_code 2 /* show a list of expressions */
22165 @d show_var_code 3 /* show a variable and its descendents */
22166 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22169 mp_primitive(mp, "showtoken",show_command,show_token_code);
22170 @:show_token_}{\&{showtoken} primitive@>
22171 mp_primitive(mp, "showstats",show_command,show_stats_code);
22172 @:show_stats_}{\&{showstats} primitive@>
22173 mp_primitive(mp, "show",show_command,show_code);
22174 @:show_}{\&{show} primitive@>
22175 mp_primitive(mp, "showvariable",show_command,show_var_code);
22176 @:show_var_}{\&{showvariable} primitive@>
22177 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22178 @:show_dependencies_}{\&{showdependencies} primitive@>
22180 @ @<Cases of |print_cmd...@>=
22183 case show_token_code:mp_print(mp, "showtoken"); break;
22184 case show_stats_code:mp_print(mp, "showstats"); break;
22185 case show_code:mp_print(mp, "show"); break;
22186 case show_var_code:mp_print(mp, "showvariable"); break;
22187 default: mp_print(mp, "showdependencies"); break;
22191 @ @<Cases of |do_statement|...@>=
22192 case show_command:mp_do_show_whatever(mp); break;
22194 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22195 if it's |show_code|, complicated structures are abbreviated, otherwise
22198 @<Declare action procedures for use by |do_statement|@>=
22199 void mp_do_show (MP mp) ;
22201 @ @c void mp_do_show (MP mp) {
22203 mp_get_x_next(mp); mp_scan_expression(mp);
22204 mp_print_nl(mp, ">> ");
22206 mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22207 } while (mp->cur_cmd==comma);
22210 @ @<Declare action procedures for use by |do_statement|@>=
22211 void mp_disp_token (MP mp) ;
22213 @ @c void mp_disp_token (MP mp) {
22214 mp_print_nl(mp, "> ");
22216 if ( mp->cur_sym==0 ) {
22217 @<Show a numeric or string or capsule token@>;
22219 mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
22220 if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22221 mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22222 if ( mp->cur_cmd==defined_macro ) {
22223 mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22224 } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22229 @ @<Show a numeric or string or capsule token@>=
22231 if ( mp->cur_cmd==numeric_token ) {
22232 mp_print_scaled(mp, mp->cur_mod);
22233 } else if ( mp->cur_cmd==capsule_token ) {
22234 mp->g_pointer=mp->cur_mod; mp_print_capsule(mp);
22236 mp_print_char(mp, '"');
22237 mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
22238 delete_str_ref(mp->cur_mod);
22242 @ The following cases of |print_cmd_mod| might arise in connection
22243 with |disp_token|, although they don't correspond to any
22246 @<Cases of |print_cmd_...@>=
22247 case left_delimiter:
22248 case right_delimiter:
22249 if ( c==left_delimiter ) mp_print(mp, "left");
22250 else mp_print(mp, "right");
22251 mp_print(mp, " delimiter that matches ");
22255 if ( m==null ) mp_print(mp, "tag");
22256 else mp_print(mp, "variable");
22258 case defined_macro:
22259 mp_print(mp, "macro:");
22261 case secondary_primary_macro:
22262 case tertiary_secondary_macro:
22263 case expression_tertiary_macro:
22264 mp_print_cmd_mod(mp, macro_def,c);
22265 mp_print(mp, "'d macro:");
22266 mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22269 mp_print(mp, "[repeat the loop]");
22271 case internal_quantity:
22272 mp_print(mp, mp->int_name[m]);
22275 @ @<Declare action procedures for use by |do_statement|@>=
22276 void mp_do_show_token (MP mp) ;
22278 @ @c void mp_do_show_token (MP mp) {
22280 get_t_next; mp_disp_token(mp);
22282 } while (mp->cur_cmd==comma);
22285 @ @<Declare action procedures for use by |do_statement|@>=
22286 void mp_do_show_stats (MP mp) ;
22288 @ @c void mp_do_show_stats (MP mp) {
22289 mp_print_nl(mp, "Memory usage ");
22290 @.Memory usage...@>
22291 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22293 mp_print(mp, "unknown");
22294 mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22295 mp_print(mp, " still untouched)"); mp_print_ln(mp);
22296 mp_print_nl(mp, "String usage ");
22297 mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22298 mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22300 mp_print(mp, "unknown");
22301 mp_print(mp, " (");
22302 mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22303 mp_print_int(mp, mp->pool_size-mp->pool_ptr);
22304 mp_print(mp, " now untouched)"); mp_print_ln(mp);
22308 @ Here's a recursive procedure that gives an abbreviated account
22309 of a variable, for use by |do_show_var|.
22311 @<Declare action procedures for use by |do_statement|@>=
22312 void mp_disp_var (MP mp,pointer p) ;
22314 @ @c void mp_disp_var (MP mp,pointer p) {
22315 pointer q; /* traverses attributes and subscripts */
22316 int n; /* amount of macro text to show */
22317 if ( type(p)==mp_structured ) {
22318 @<Descend the structure@>;
22319 } else if ( type(p)>=mp_unsuffixed_macro ) {
22320 @<Display a variable macro@>;
22321 } else if ( type(p)!=undefined ){
22322 mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22323 mp_print_char(mp, '=');
22324 mp_print_exp(mp, p,0);
22328 @ @<Descend the structure@>=
22331 do { mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22333 while ( name_type(q)==mp_subscr ) {
22334 mp_disp_var(mp, q); q=link(q);
22338 @ @<Display a variable macro@>=
22340 mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22341 if ( type(p)>mp_unsuffixed_macro )
22342 mp_print(mp, "@@#"); /* |suffixed_macro| */
22343 mp_print(mp, "=macro:");
22344 if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22345 else n=mp->max_print_line-mp->file_offset-15;
22346 mp_show_macro(mp, value(p),null,n);
22349 @ @<Declare action procedures for use by |do_statement|@>=
22350 void mp_do_show_var (MP mp) ;
22352 @ @c void mp_do_show_var (MP mp) {
22355 if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22356 if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22357 mp_disp_var(mp, mp->cur_mod); goto DONE;
22362 } while (mp->cur_cmd==comma);
22365 @ @<Declare action procedures for use by |do_statement|@>=
22366 void mp_do_show_dependencies (MP mp) ;
22368 @ @c void mp_do_show_dependencies (MP mp) {
22369 pointer p; /* link that runs through all dependencies */
22371 while ( p!=dep_head ) {
22372 if ( mp_interesting(mp, p) ) {
22373 mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22374 if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22375 else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22376 mp_print_dependency(mp, dep_list(p),type(p));
22379 while ( info(p)!=null ) p=link(p);
22385 @ Finally we are ready for the procedure that governs all of the
22388 @<Declare action procedures for use by |do_statement|@>=
22389 void mp_do_show_whatever (MP mp) ;
22391 @ @c void mp_do_show_whatever (MP mp) {
22392 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22393 switch (mp->cur_mod) {
22394 case show_token_code:mp_do_show_token(mp); break;
22395 case show_stats_code:mp_do_show_stats(mp); break;
22396 case show_code:mp_do_show(mp); break;
22397 case show_var_code:mp_do_show_var(mp); break;
22398 case show_dependencies_code:mp_do_show_dependencies(mp); break;
22399 } /* there are no other cases */
22400 if ( mp->internal[mp_showstopping]>0 ){
22403 if ( mp->interaction<mp_error_stop_mode ) {
22404 help0; decr(mp->error_count);
22406 help1("This isn't an error message; I'm just showing something.");
22408 if ( mp->cur_cmd==semicolon ) mp_error(mp);
22409 else mp_put_get_error(mp);
22413 @ The `\&{addto}' command needs the following additional primitives:
22415 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22416 @d contour_code 1 /* command modifier for `\&{contour}' */
22417 @d also_code 2 /* command modifier for `\&{also}' */
22419 @ Pre and postscripts need two new identifiers:
22421 @d with_pre_script 11
22422 @d with_post_script 13
22425 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22426 @:double_path_}{\&{doublepath} primitive@>
22427 mp_primitive(mp, "contour",thing_to_add,contour_code);
22428 @:contour_}{\&{contour} primitive@>
22429 mp_primitive(mp, "also",thing_to_add,also_code);
22430 @:also_}{\&{also} primitive@>
22431 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22432 @:with_pen_}{\&{withpen} primitive@>
22433 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22434 @:dashed_}{\&{dashed} primitive@>
22435 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22436 @:with_pre_script_}{\&{withprescript} primitive@>
22437 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22438 @:with_post_script_}{\&{withpostscript} primitive@>
22439 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
22440 @:with_color_}{\&{withoutcolor} primitive@>
22441 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
22442 @:with_color_}{\&{withgreyscale} primitive@>
22443 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
22444 @:with_color_}{\&{withcolor} primitive@>
22445 /* \&{withrgbcolor} is an alias for \&{withcolor} */
22446 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
22447 @:with_color_}{\&{withrgbcolor} primitive@>
22448 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
22449 @:with_color_}{\&{withcmykcolor} primitive@>
22451 @ @<Cases of |print_cmd...@>=
22453 if ( m==contour_code ) mp_print(mp, "contour");
22454 else if ( m==double_path_code ) mp_print(mp, "doublepath");
22455 else mp_print(mp, "also");
22458 if ( m==mp_pen_type ) mp_print(mp, "withpen");
22459 else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22460 else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22461 else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
22462 else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
22463 else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
22464 else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
22465 else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
22466 else mp_print(mp, "dashed");
22469 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22470 updates the list of graphical objects starting at |p|. Each $\langle$with
22471 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22472 Other objects are ignored.
22474 @<Declare action procedures for use by |do_statement|@>=
22475 void mp_scan_with_list (MP mp,pointer p) ;
22477 @ @c void mp_scan_with_list (MP mp,pointer p) {
22478 small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22479 pointer q; /* for list manipulation */
22480 int old_setting; /* saved |selector| setting */
22481 pointer k; /* for finding the near-last item in a list */
22482 str_number s; /* for string cleanup after combining */
22483 pointer cp,pp,dp,ap,bp;
22484 /* objects being updated; |void| initially; |null| to suppress update */
22485 cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
22487 while ( mp->cur_cmd==with_option ){
22490 if ( t!=mp_no_model ) mp_scan_expression(mp);
22491 if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22492 ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22493 ((t==mp_uninitialized_model)&&
22494 ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22495 &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22496 ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22497 ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
22498 ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
22499 ((t==mp_pen_type)&&(mp->cur_type!=t))||
22500 ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22501 @<Complain about improper type@>;
22502 } else if ( t==mp_uninitialized_model ) {
22503 if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22505 @<Transfer a color from the current expression to object~|cp|@>;
22506 mp_flush_cur_exp(mp, 0);
22507 } else if ( t==mp_rgb_model ) {
22508 if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22510 @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22511 mp_flush_cur_exp(mp, 0);
22512 } else if ( t==mp_cmyk_model ) {
22513 if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22515 @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22516 mp_flush_cur_exp(mp, 0);
22517 } else if ( t==mp_grey_model ) {
22518 if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22520 @<Transfer a greyscale from the current expression to object~|cp|@>;
22521 mp_flush_cur_exp(mp, 0);
22522 } else if ( t==mp_no_model ) {
22523 if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22525 @<Transfer a noncolor from the current expression to object~|cp|@>;
22526 } else if ( t==mp_pen_type ) {
22527 if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
22529 if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22530 pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22532 } else if ( t==with_pre_script ) {
22535 while ( (ap!=null)&&(! has_color(ap)) )
22538 if ( pre_script(ap)!=null ) { /* build a new,combined string */
22540 old_setting=mp->selector;
22541 mp->selector=new_string;
22542 str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22543 mp_print_str(mp, mp->cur_exp);
22544 append_char(13); /* a forced \ps\ newline */
22545 mp_print_str(mp, pre_script(ap));
22546 pre_script(ap)=mp_make_string(mp);
22548 mp->selector=old_setting;
22550 pre_script(ap)=mp->cur_exp;
22552 mp->cur_type=mp_vacuous;
22554 } else if ( t==with_post_script ) {
22558 while ( link(k)!=null ) {
22560 if ( has_color(k) ) bp=k;
22563 if ( post_script(bp)!=null ) {
22565 old_setting=mp->selector;
22566 mp->selector=new_string;
22567 str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22568 mp_print_str(mp, post_script(bp));
22569 append_char(13); /* a forced \ps\ newline */
22570 mp_print_str(mp, mp->cur_exp);
22571 post_script(bp)=mp_make_string(mp);
22573 mp->selector=old_setting;
22575 post_script(bp)=mp->cur_exp;
22577 mp->cur_type=mp_vacuous;
22580 if ( dp==mp_void ) {
22581 @<Make |dp| a stroked node in list~|p|@>;
22584 if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22585 dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22586 dash_scale(dp)=unity;
22587 mp->cur_type=mp_vacuous;
22591 @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22595 @ @<Complain about improper type@>=
22596 { exp_err("Improper type");
22598 help2("Next time say `withpen <known pen expression>';")
22599 ("I'll ignore the bad `with' clause and look for another.");
22600 if ( t==with_pre_script )
22601 mp->help_line[1]="Next time say `withprescript <known string expression>';";
22602 else if ( t==with_post_script )
22603 mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22604 else if ( t==mp_picture_type )
22605 mp->help_line[1]="Next time say `dashed <known picture expression>';";
22606 else if ( t==mp_uninitialized_model )
22607 mp->help_line[1]="Next time say `withcolor <known color expression>';";
22608 else if ( t==mp_rgb_model )
22609 mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22610 else if ( t==mp_cmyk_model )
22611 mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22612 else if ( t==mp_grey_model )
22613 mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22614 mp_put_get_flush_error(mp, 0);
22617 @ Forcing the color to be between |0| and |unity| here guarantees that no
22618 picture will ever contain a color outside the legal range for \ps\ graphics.
22620 @<Transfer a color from the current expression to object~|cp|@>=
22621 { if ( mp->cur_type==mp_color_type )
22622 @<Transfer a rgbcolor from the current expression to object~|cp|@>
22623 else if ( mp->cur_type==mp_cmykcolor_type )
22624 @<Transfer a cmykcolor from the current expression to object~|cp|@>
22625 else if ( mp->cur_type==mp_known )
22626 @<Transfer a greyscale from the current expression to object~|cp|@>
22627 else if ( mp->cur_exp==false_code )
22628 @<Transfer a noncolor from the current expression to object~|cp|@>;
22631 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22632 { q=value(mp->cur_exp);
22637 red_val(cp)=value(red_part_loc(q));
22638 green_val(cp)=value(green_part_loc(q));
22639 blue_val(cp)=value(blue_part_loc(q));
22640 color_model(cp)=mp_rgb_model;
22641 if ( red_val(cp)<0 ) red_val(cp)=0;
22642 if ( green_val(cp)<0 ) green_val(cp)=0;
22643 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22644 if ( red_val(cp)>unity ) red_val(cp)=unity;
22645 if ( green_val(cp)>unity ) green_val(cp)=unity;
22646 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22649 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22650 { q=value(mp->cur_exp);
22651 cyan_val(cp)=value(cyan_part_loc(q));
22652 magenta_val(cp)=value(magenta_part_loc(q));
22653 yellow_val(cp)=value(yellow_part_loc(q));
22654 black_val(cp)=value(black_part_loc(q));
22655 color_model(cp)=mp_cmyk_model;
22656 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22657 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22658 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22659 if ( black_val(cp)<0 ) black_val(cp)=0;
22660 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22661 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22662 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22663 if ( black_val(cp)>unity ) black_val(cp)=unity;
22666 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22673 color_model(cp)=mp_grey_model;
22674 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22675 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22678 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22685 color_model(cp)=mp_no_model;
22688 @ @<Make |cp| a colored object in object list~|p|@>=
22690 while ( cp!=null ){
22691 if ( has_color(cp) ) break;
22696 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22698 while ( pp!=null ) {
22699 if ( has_pen(pp) ) break;
22704 @ @<Make |dp| a stroked node in list~|p|@>=
22706 while ( dp!=null ) {
22707 if ( type(dp)==mp_stroked_code ) break;
22712 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22713 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22714 if ( pp>mp_void ) {
22715 @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22717 if ( dp>mp_void ) {
22718 @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>;
22722 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22724 while ( q!=null ) {
22725 if ( has_color(q) ) {
22726 red_val(q)=red_val(cp);
22727 green_val(q)=green_val(cp);
22728 blue_val(q)=blue_val(cp);
22729 black_val(q)=black_val(cp);
22730 color_model(q)=color_model(cp);
22736 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22738 while ( q!=null ) {
22739 if ( has_pen(q) ) {
22740 if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22741 pen_p(q)=copy_pen(pen_p(pp));
22747 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22749 while ( q!=null ) {
22750 if ( type(q)==mp_stroked_code ) {
22751 if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22752 dash_p(q)=dash_p(dp);
22753 dash_scale(q)=unity;
22754 if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22760 @ One of the things we need to do when we've parsed an \&{addto} or
22761 similar command is find the header of a supposed \&{picture} variable, given
22762 a token list for that variable. Since the edge structure is about to be
22763 updated, we use |private_edges| to make sure that this is possible.
22765 @<Declare action procedures for use by |do_statement|@>=
22766 pointer mp_find_edges_var (MP mp, pointer t) ;
22768 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22770 pointer cur_edges; /* the return value */
22771 p=mp_find_variable(mp, t); cur_edges=null;
22773 mp_obliterated(mp, t); mp_put_get_error(mp);
22774 } else if ( type(p)!=mp_picture_type ) {
22775 print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22776 @.Variable x is the wrong type@>
22777 mp_print(mp, " is the wrong type (");
22778 mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22779 help2("I was looking for a \"known\" picture variable.")
22780 ("So I'll not change anything just now.");
22781 mp_put_get_error(mp);
22783 value(p)=mp_private_edges(mp, value(p));
22784 cur_edges=value(p);
22786 mp_flush_node_list(mp, t);
22790 @ @<Cases of |do_statement|...@>=
22791 case add_to_command: mp_do_add_to(mp); break;
22792 case bounds_command:mp_do_bounds(mp); break;
22795 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22796 @:clip_}{\&{clip} primitive@>
22797 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22798 @:set_bounds_}{\&{setbounds} primitive@>
22800 @ @<Cases of |print_cmd...@>=
22801 case bounds_command:
22802 if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22803 else mp_print(mp, "setbounds");
22806 @ The following function parses the beginning of an \&{addto} or \&{clip}
22807 command: it expects a variable name followed by a token with |cur_cmd=sep|
22808 and then an expression. The function returns the token list for the variable
22809 and stores the command modifier for the separator token in the global variable
22810 |last_add_type|. We must be careful because this variable might get overwritten
22811 any time we call |get_x_next|.
22814 quarterword last_add_type;
22815 /* command modifier that identifies the last \&{addto} command */
22817 @ @<Declare action procedures for use by |do_statement|@>=
22818 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22820 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22821 pointer lhv; /* variable to add to left */
22822 quarterword add_type=0; /* value to be returned in |last_add_type| */
22824 mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22825 if ( mp->cur_type!=mp_token_list ) {
22826 @<Abandon edges command because there's no variable@>;
22828 lhv=mp->cur_exp; add_type=mp->cur_mod;
22829 mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22831 mp->last_add_type=add_type;
22835 @ @<Abandon edges command because there's no variable@>=
22836 { exp_err("Not a suitable variable");
22837 @.Not a suitable variable@>
22838 help4("At this point I needed to see the name of a picture variable.")
22839 ("(Or perhaps you have indeed presented me with one; I might")
22840 ("have missed it, if it wasn't followed by the proper token.)")
22841 ("So I'll not change anything just now.");
22842 mp_put_get_flush_error(mp, 0);
22845 @ Here is an example of how to use |start_draw_cmd|.
22847 @<Declare action procedures for use by |do_statement|@>=
22848 void mp_do_bounds (MP mp) ;
22850 @ @c void mp_do_bounds (MP mp) {
22851 pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22852 pointer p; /* for list manipulation */
22853 integer m; /* initial value of |cur_mod| */
22855 lhv=mp_start_draw_cmd(mp, to_token);
22857 lhe=mp_find_edges_var(mp, lhv);
22859 mp_flush_cur_exp(mp, 0);
22860 } else if ( mp->cur_type!=mp_path_type ) {
22861 exp_err("Improper `clip'");
22862 @.Improper `addto'@>
22863 help2("This expression should have specified a known path.")
22864 ("So I'll not change anything just now.");
22865 mp_put_get_flush_error(mp, 0);
22866 } else if ( left_type(mp->cur_exp)==mp_endpoint ) {
22867 @<Complain about a non-cycle@>;
22869 @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22874 @ @<Complain about a non-cycle@>=
22875 { print_err("Not a cycle");
22877 help2("That contour should have ended with `..cycle' or `&cycle'.")
22878 ("So I'll not change anything just now."); mp_put_get_error(mp);
22881 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22882 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22883 link(p)=link(dummy_loc(lhe));
22884 link(dummy_loc(lhe))=p;
22885 if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22886 p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22887 type(p)=stop_type(m);
22888 link(obj_tail(lhe))=p;
22890 mp_init_bbox(mp, lhe);
22893 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22894 cases to deal with.
22896 @<Declare action procedures for use by |do_statement|@>=
22897 void mp_do_add_to (MP mp) ;
22899 @ @c void mp_do_add_to (MP mp) {
22900 pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22901 pointer p; /* the graphical object or list for |scan_with_list| to update */
22902 pointer e; /* an edge structure to be merged */
22903 quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22904 lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22906 if ( add_type==also_code ) {
22907 @<Make sure the current expression is a suitable picture and set |e| and |p|
22910 @<Create a graphical object |p| based on |add_type| and the current
22913 mp_scan_with_list(mp, p);
22914 @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22918 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22919 setting |e:=null| prevents anything from being added to |lhe|.
22921 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22924 if ( mp->cur_type!=mp_picture_type ) {
22925 exp_err("Improper `addto'");
22926 @.Improper `addto'@>
22927 help2("This expression should have specified a known picture.")
22928 ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22930 e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22931 p=link(dummy_loc(e));
22935 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22936 attempts to add to the edge structure.
22938 @<Create a graphical object |p| based on |add_type| and the current...@>=
22940 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22941 if ( mp->cur_type!=mp_path_type ) {
22942 exp_err("Improper `addto'");
22943 @.Improper `addto'@>
22944 help2("This expression should have specified a known path.")
22945 ("So I'll not change anything just now.");
22946 mp_put_get_flush_error(mp, 0);
22947 } else if ( add_type==contour_code ) {
22948 if ( left_type(mp->cur_exp)==mp_endpoint ) {
22949 @<Complain about a non-cycle@>;
22951 p=mp_new_fill_node(mp, mp->cur_exp);
22952 mp->cur_type=mp_vacuous;
22955 p=mp_new_stroked_node(mp, mp->cur_exp);
22956 mp->cur_type=mp_vacuous;
22960 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22961 lhe=mp_find_edges_var(mp, lhv);
22963 if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22964 if ( e!=null ) delete_edge_ref(e);
22965 } else if ( add_type==also_code ) {
22967 @<Merge |e| into |lhe| and delete |e|@>;
22971 } else if ( p!=null ) {
22972 link(obj_tail(lhe))=p;
22974 if ( add_type==double_path_code )
22975 if ( pen_p(p)==null )
22976 pen_p(p)=mp_get_pen_circle(mp, 0);
22979 @ @<Merge |e| into |lhe| and delete |e|@>=
22980 { if ( link(dummy_loc(e))!=null ) {
22981 link(obj_tail(lhe))=link(dummy_loc(e));
22982 obj_tail(lhe)=obj_tail(e);
22983 obj_tail(e)=dummy_loc(e);
22984 link(dummy_loc(e))=null;
22985 mp_flush_dash_list(mp, lhe);
22987 mp_toss_edges(mp, e);
22990 @ @<Cases of |do_statement|...@>=
22991 case ship_out_command: mp_do_ship_out(mp); break;
22993 @ @<Declare action procedures for use by |do_statement|@>=
22994 @<Declare the function called |tfm_check|@>;
22995 @<Declare the \ps\ output procedures@>;
22996 void mp_do_ship_out (MP mp) ;
22998 @ @c void mp_do_ship_out (MP mp) {
22999 integer c; /* the character code */
23000 mp_get_x_next(mp); mp_scan_expression(mp);
23001 if ( mp->cur_type!=mp_picture_type ) {
23002 @<Complain that it's not a known picture@>;
23004 c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
23005 if ( c<0 ) c=c+256;
23006 @<Store the width information for character code~|c|@>;
23007 mp_ship_out(mp, mp->cur_exp);
23008 mp_flush_cur_exp(mp, 0);
23012 @ @<Complain that it's not a known picture@>=
23014 exp_err("Not a known picture");
23015 help1("I can only output known pictures.");
23016 mp_put_get_flush_error(mp, 0);
23019 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
23022 @<Cases of |do_statement|...@>=
23023 case every_job_command:
23024 mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
23028 halfword start_sym; /* a symbolic token to insert at beginning of job */
23033 @ Finally, we have only the ``message'' commands remaining.
23036 @d err_message_code 1
23038 @d filename_template_code 3
23039 @d print_with_leading_zeroes(A) g = mp->pool_ptr;
23040 mp_print_int(mp, (A)); g = mp->pool_ptr-g;
23042 mp->pool_ptr = mp->pool_ptr - g;
23044 mp_print_char(mp, '0');
23047 mp_print_int(mp, (A));
23052 mp_primitive(mp, "message",message_command,message_code);
23053 @:message_}{\&{message} primitive@>
23054 mp_primitive(mp, "errmessage",message_command,err_message_code);
23055 @:err_message_}{\&{errmessage} primitive@>
23056 mp_primitive(mp, "errhelp",message_command,err_help_code);
23057 @:err_help_}{\&{errhelp} primitive@>
23058 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
23059 @:filename_template_}{\&{filenametemplate} primitive@>
23061 @ @<Cases of |print_cmd...@>=
23062 case message_command:
23063 if ( m<err_message_code ) mp_print(mp, "message");
23064 else if ( m==err_message_code ) mp_print(mp, "errmessage");
23065 else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
23066 else mp_print(mp, "errhelp");
23069 @ @<Cases of |do_statement|...@>=
23070 case message_command: mp_do_message(mp); break;
23072 @ @<Declare action procedures for use by |do_statement|@>=
23073 @<Declare a procedure called |no_string_err|@>;
23074 void mp_do_message (MP mp) ;
23077 @c void mp_do_message (MP mp) {
23078 int m; /* the type of message */
23079 m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
23080 if ( mp->cur_type!=mp_string_type )
23081 mp_no_string_err(mp, "A message should be a known string expression.");
23085 mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
23087 case err_message_code:
23088 @<Print string |cur_exp| as an error message@>;
23090 case err_help_code:
23091 @<Save string |cur_exp| as the |err_help|@>;
23093 case filename_template_code:
23094 @<Save the filename template@>;
23096 } /* there are no other cases */
23098 mp_flush_cur_exp(mp, 0);
23101 @ @<Declare a procedure called |no_string_err|@>=
23102 void mp_no_string_err (MP mp,char *s) {
23103 exp_err("Not a string");
23106 mp_put_get_error(mp);
23109 @ The global variable |err_help| is zero when the user has most recently
23110 given an empty help string, or if none has ever been given.
23112 @<Save string |cur_exp| as the |err_help|@>=
23114 if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23115 if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23116 else { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23119 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23120 \&{errhelp}, we don't want to give a long help message each time. So we
23121 give a verbose explanation only once.
23124 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23126 @ @<Set init...@>=mp->long_help_seen=false;
23128 @ @<Print string |cur_exp| as an error message@>=
23130 print_err(""); mp_print_str(mp, mp->cur_exp);
23131 if ( mp->err_help!=0 ) {
23132 mp->use_err_help=true;
23133 } else if ( mp->long_help_seen ) {
23134 help1("(That was another `errmessage'.)") ;
23136 if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23137 help4("This error message was generated by an `errmessage'")
23138 ("command, so I can\'t give any explicit help.")
23139 ("Pretend that you're Miss Marple: Examine all clues,")
23141 ("and deduce the truth by inspired guesses.");
23143 mp_put_get_error(mp); mp->use_err_help=false;
23146 @ @<Cases of |do_statement|...@>=
23147 case write_command: mp_do_write(mp); break;
23149 @ @<Declare action procedures for use by |do_statement|@>=
23150 void mp_do_write (MP mp) ;
23152 @ @c void mp_do_write (MP mp) {
23153 str_number t; /* the line of text to be written */
23154 write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23155 int old_setting; /* for saving |selector| during output */
23157 mp_scan_expression(mp);
23158 if ( mp->cur_type!=mp_string_type ) {
23159 mp_no_string_err(mp, "The text to be written should be a known string expression");
23160 } else if ( mp->cur_cmd!=to_token ) {
23161 print_err("Missing `to' clause");
23162 help1("A write command should end with `to <filename>'");
23163 mp_put_get_error(mp);
23165 t=mp->cur_exp; mp->cur_type=mp_vacuous;
23167 mp_scan_expression(mp);
23168 if ( mp->cur_type!=mp_string_type )
23169 mp_no_string_err(mp, "I can\'t write to that file name. It isn't a known string");
23171 @<Write |t| to the file named by |cur_exp|@>;
23175 mp_flush_cur_exp(mp, 0);
23178 @ @<Write |t| to the file named by |cur_exp|@>=
23180 @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23181 |cur_exp| must be inserted@>;
23182 if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23183 @<Record the end of file on |wr_file[n]|@>;
23185 old_setting=mp->selector;
23186 mp->selector=n+write_file;
23187 mp_print_str(mp, t); mp_print_ln(mp);
23188 mp->selector = old_setting;
23192 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23194 char *fn = str(mp->cur_exp);
23196 n0=mp->write_files;
23197 while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) {
23198 if ( n==0 ) { /* bottom reached */
23199 if ( n0==mp->write_files ) {
23200 if ( mp->write_files<mp->max_write_files ) {
23201 incr(mp->write_files);
23206 l = mp->max_write_files + (mp->max_write_files>>2);
23207 wr_file = xmalloc((l+1),sizeof(FILE *));
23208 wr_fname = xmalloc((l+1),sizeof(char *));
23209 for (k=0;k<=l;k++) {
23210 if (k<=mp->max_write_files) {
23211 wr_file[k]=mp->wr_file[k];
23212 wr_fname[k]=mp->wr_fname[k];
23218 xfree(mp->wr_file); xfree(mp->wr_fname);
23219 mp->max_write_files = l;
23220 mp->wr_file = wr_file;
23221 mp->wr_fname = wr_fname;
23225 mp_open_write_file(mp, fn ,n);
23228 if ( mp->wr_fname[n]==NULL ) n0=n;
23233 @ @<Record the end of file on |wr_file[n]|@>=
23234 { fclose(mp->wr_file[n]);
23235 xfree(mp->wr_fname[n]);
23236 mp->wr_fname[n]=NULL;
23237 if ( n==mp->write_files-1 ) mp->write_files=n;
23241 @* \[42] Writing font metric data.
23242 \TeX\ gets its knowledge about fonts from font metric files, also called
23243 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23244 but other programs know about them too. One of \MP's duties is to
23245 write \.{TFM} files so that the user's fonts can readily be
23246 applied to typesetting.
23247 @:TFM files}{\.{TFM} files@>
23248 @^font metric files@>
23250 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23251 Since the number of bytes is always a multiple of~4, we could
23252 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23253 byte interpretation. The format of \.{TFM} files was designed by
23254 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23255 @^Ramshaw, Lyle Harold@>
23256 of information in a compact but useful form.
23259 FILE * tfm_file; /* the font metric output goes here */
23260 char * metric_file_name; /* full name of the font metric file */
23262 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23263 integers that give the lengths of the various subsequent portions
23264 of the file. These twelve integers are, in order:
23265 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23266 |lf|&length of the entire file, in words;\cr
23267 |lh|&length of the header data, in words;\cr
23268 |bc|&smallest character code in the font;\cr
23269 |ec|&largest character code in the font;\cr
23270 |nw|&number of words in the width table;\cr
23271 |nh|&number of words in the height table;\cr
23272 |nd|&number of words in the depth table;\cr
23273 |ni|&number of words in the italic correction table;\cr
23274 |nl|&number of words in the lig/kern table;\cr
23275 |nk|&number of words in the kern table;\cr
23276 |ne|&number of words in the extensible character table;\cr
23277 |np|&number of font parameter words.\cr}}$$
23278 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23280 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23281 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23282 and as few as 0 characters (if |bc=ec+1|).
23284 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23285 16 or more bits, the most significant bytes appear first in the file.
23286 This is called BigEndian order.
23287 @^BigEndian order@>
23289 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23292 The most important data type used here is a |fix_word|, which is
23293 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23294 quantity, with the two's complement of the entire word used to represent
23295 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23296 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23297 the smallest is $-2048$. We will see below, however, that all but two of
23298 the |fix_word| values must lie between $-16$ and $+16$.
23300 @ The first data array is a block of header information, which contains
23301 general facts about the font. The header must contain at least two words,
23302 |header[0]| and |header[1]|, whose meaning is explained below. Additional
23303 header information of use to other software routines might also be
23304 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23305 For example, 16 more words of header information are in use at the Xerox
23306 Palo Alto Research Center; the first ten specify the character coding
23307 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23308 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23309 last gives the ``face byte.''
23311 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23312 the \.{GF} output file. This helps ensure consistency between files,
23313 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23314 should match the check sums on actual fonts that are used. The actual
23315 relation between this check sum and the rest of the \.{TFM} file is not
23316 important; the check sum is simply an identification number with the
23317 property that incompatible fonts almost always have distinct check sums.
23320 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23321 font, in units of \TeX\ points. This number must be at least 1.0; it is
23322 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23323 font, i.e., a font that was designed to look best at a 10-point size,
23324 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23325 $\delta$ \.{pt}', the effect is to override the design size and replace it
23326 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23327 the font image by a factor of $\delta$ divided by the design size. {\sl
23328 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23329 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23330 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23331 since many fonts have a design size equal to one em. The other dimensions
23332 must be less than 16 design-size units in absolute value; thus,
23333 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23334 \.{TFM} file whose first byte might be something besides 0 or 255.
23336 @ Next comes the |char_info| array, which contains one |char_info_word|
23337 per character. Each word in this part of the file contains six fields
23338 packed into four bytes as follows.
23340 \yskip\hang first byte: |width_index| (8 bits)\par
23341 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23343 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23345 \hang fourth byte: |remainder| (8 bits)\par
23347 The actual width of a character is \\{width}|[width_index]|, in design-size
23348 units; this is a device for compressing information, since many characters
23349 have the same width. Since it is quite common for many characters
23350 to have the same height, depth, or italic correction, the \.{TFM} format
23351 imposes a limit of 16 different heights, 16 different depths, and
23352 64 different italic corrections.
23354 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23355 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23356 value of zero. The |width_index| should never be zero unless the
23357 character does not exist in the font, since a character is valid if and
23358 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23360 @ The |tag| field in a |char_info_word| has four values that explain how to
23361 interpret the |remainder| field.
23363 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23364 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23365 program starting at location |remainder| in the |lig_kern| array.\par
23366 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23367 characters of ascending sizes, and not the largest in the chain. The
23368 |remainder| field gives the character code of the next larger character.\par
23369 \hang|tag=3| (|ext_tag|) means that this character code represents an
23370 extensible character, i.e., a character that is built up of smaller pieces
23371 so that it can be made arbitrarily large. The pieces are specified in
23372 |exten[remainder]|.\par
23374 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23375 unless they are used in special circumstances in math formulas. For example,
23376 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23377 operation looks for both |list_tag| and |ext_tag|.
23379 @d no_tag 0 /* vanilla character */
23380 @d lig_tag 1 /* character has a ligature/kerning program */
23381 @d list_tag 2 /* character has a successor in a charlist */
23382 @d ext_tag 3 /* character is extensible */
23384 @ The |lig_kern| array contains instructions in a simple programming language
23385 that explains what to do for special letter pairs. Each word in this array is a
23386 |lig_kern_command| of four bytes.
23388 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23389 step if the byte is 128 or more, otherwise the next step is obtained by
23390 skipping this number of intervening steps.\par
23391 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23392 then perform the operation and stop, otherwise continue.''\par
23393 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23394 a kern step otherwise.\par
23395 \hang fourth byte: |remainder|.\par
23398 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23399 between the current character and |next_char|. This amount is
23400 often negative, so that the characters are brought closer together
23401 by kerning; but it might be positive.
23403 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23404 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23405 |remainder| is inserted between the current character and |next_char|;
23406 then the current character is deleted if $b=0$, and |next_char| is
23407 deleted if $c=0$; then we pass over $a$~characters to reach the next
23408 current character (which may have a ligature/kerning program of its own).
23410 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23411 the |next_char| byte is the so-called right boundary character of this font;
23412 the value of |next_char| need not lie between |bc| and~|ec|.
23413 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23414 there is a special ligature/kerning program for a left boundary character,
23415 beginning at location |256*op_byte+remainder|.
23416 The interpretation is that \TeX\ puts implicit boundary characters
23417 before and after each consecutive string of characters from the same font.
23418 These implicit characters do not appear in the output, but they can affect
23419 ligatures and kerning.
23421 If the very first instruction of a character's |lig_kern| program has
23422 |skip_byte>128|, the program actually begins in location
23423 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23424 arrays, because the first instruction must otherwise
23425 appear in a location |<=255|.
23427 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23429 $$\hbox{|256*op_byte+remainder<nl|.}$$
23430 If such an instruction is encountered during
23431 normal program execution, it denotes an unconditional halt; no ligature
23432 command is performed.
23435 /* value indicating `\.{STOP}' in a lig/kern program */
23436 @d kern_flag (128) /* op code for a kern step */
23437 @d skip_byte(A) mp->lig_kern[(A)].b0
23438 @d next_char(A) mp->lig_kern[(A)].b1
23439 @d op_byte(A) mp->lig_kern[(A)].b2
23440 @d rem_byte(A) mp->lig_kern[(A)].b3
23442 @ Extensible characters are specified by an |extensible_recipe|, which
23443 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23444 order). These bytes are the character codes of individual pieces used to
23445 build up a large symbol. If |top|, |mid|, or |bot| are zero, they are not
23446 present in the built-up result. For example, an extensible vertical line is
23447 like an extensible bracket, except that the top and bottom pieces are missing.
23449 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23450 if the piece isn't present. Then the extensible characters have the form
23451 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23452 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23453 The width of the extensible character is the width of $R$; and the
23454 height-plus-depth is the sum of the individual height-plus-depths of the
23455 components used, since the pieces are butted together in a vertical list.
23457 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23458 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23459 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23460 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23462 @ The final portion of a \.{TFM} file is the |param| array, which is another
23463 sequence of |fix_word| values.
23465 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23466 to help position accents. For example, |slant=.25| means that when you go
23467 up one unit, you also go .25 units to the right. The |slant| is a pure
23468 number; it is the only |fix_word| other than the design size itself that is
23469 not scaled by the design size.
23471 \hang|param[2]=space| is the normal spacing between words in text.
23472 Note that character 040 in the font need not have anything to do with
23475 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23477 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23479 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23480 the height of letters for which accents don't have to be raised or lowered.
23482 \hang|param[6]=quad| is the size of one em in the font.
23484 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23488 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23493 @d space_stretch_code 3
23494 @d space_shrink_code 4
23497 @d extra_space_code 7
23499 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23500 information, and it does this all at once at the end of a job.
23501 In order to prepare for such frenetic activity, it squirrels away the
23502 necessary facts in various arrays as information becomes available.
23504 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23505 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23506 |tfm_ital_corr|. Other information about a character (e.g., about
23507 its ligatures or successors) is accessible via the |char_tag| and
23508 |char_remainder| arrays. Other information about the font as a whole
23509 is kept in additional arrays called |header_byte|, |lig_kern|,
23510 |kern|, |exten|, and |param|.
23512 @d max_tfm_int 32510
23513 @d undefined_label max_tfm_int /* an undefined local label */
23516 #define TFM_ITEMS 257
23518 eight_bits ec; /* smallest and largest character codes shipped out */
23519 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23520 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23521 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23522 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23523 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23524 int char_tag[TFM_ITEMS]; /* |remainder| category */
23525 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23526 char *header_byte; /* bytes of the \.{TFM} header */
23527 int header_last; /* last initialized \.{TFM} header byte */
23528 int header_size; /* size of the \.{TFM} header */
23529 four_quarters *lig_kern; /* the ligature/kern table */
23530 short nl; /* the number of ligature/kern steps so far */
23531 scaled *kern; /* distinct kerning amounts */
23532 short nk; /* the number of distinct kerns so far */
23533 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23534 short ne; /* the number of extensible characters so far */
23535 scaled *param; /* \&{fontinfo} parameters */
23536 short np; /* the largest \&{fontinfo} parameter specified so far */
23537 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23538 short skip_table[TFM_ITEMS]; /* local label status */
23539 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23540 integer bchar; /* right boundary character */
23541 short bch_label; /* left boundary starting location */
23542 short ll;short lll; /* registers used for lig/kern processing */
23543 short label_loc[257]; /* lig/kern starting addresses */
23544 eight_bits label_char[257]; /* characters for |label_loc| */
23545 short label_ptr; /* highest position occupied in |label_loc| */
23547 @ @<Allocate or initialize ...@>=
23548 mp->header_last = 0; mp->header_size = 128; /* just for init */
23549 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23550 mp->lig_kern = NULL; /* allocated when needed */
23551 mp->kern = NULL; /* allocated when needed */
23552 mp->param = NULL; /* allocated when needed */
23554 @ @<Dealloc variables@>=
23555 xfree(mp->header_byte);
23556 xfree(mp->lig_kern);
23561 for (k=0;k<= 255;k++ ) {
23562 mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23563 mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23564 mp->skip_table[k]=undefined_label;
23566 memset(mp->header_byte,0,mp->header_size);
23567 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23568 mp->internal[mp_boundary_char]=-unity;
23569 mp->bch_label=undefined_label;
23570 mp->label_loc[0]=-1; mp->label_ptr=0;
23572 @ @<Declarations@>=
23573 scaled mp_tfm_check (MP mp,small_number m) ;
23575 @ @<Declare the function called |tfm_check|@>=
23576 scaled mp_tfm_check (MP mp,small_number m) {
23577 if ( abs(mp->internal[m])>=fraction_half ) {
23578 print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23579 @.Enormous charwd...@>
23580 @.Enormous chardp...@>
23581 @.Enormous charht...@>
23582 @.Enormous charic...@>
23583 @.Enormous designsize...@>
23584 mp_print(mp, " has been reduced");
23585 help1("Font metric dimensions must be less than 2048pt.");
23586 mp_put_get_error(mp);
23587 if ( mp->internal[m]>0 ) return (fraction_half-1);
23588 else return (1-fraction_half);
23590 return mp->internal[m];
23594 @ @<Store the width information for character code~|c|@>=
23595 if ( c<mp->bc ) mp->bc=c;
23596 if ( c>mp->ec ) mp->ec=c;
23597 mp->char_exists[c]=true;
23598 mp->tfm_width[c]=mp_tfm_check(mp, mp_char_wd);
23599 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
23600 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
23601 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
23603 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23605 @<Cases of |do_statement|...@>=
23606 case tfm_command: mp_do_tfm_command(mp); break;
23608 @ @d char_list_code 0
23609 @d lig_table_code 1
23610 @d extensible_code 2
23611 @d header_byte_code 3
23612 @d font_dimen_code 4
23615 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23616 @:char_list_}{\&{charlist} primitive@>
23617 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23618 @:lig_table_}{\&{ligtable} primitive@>
23619 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23620 @:extensible_}{\&{extensible} primitive@>
23621 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23622 @:header_byte_}{\&{headerbyte} primitive@>
23623 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23624 @:font_dimen_}{\&{fontdimen} primitive@>
23626 @ @<Cases of |print_cmd...@>=
23629 case char_list_code:mp_print(mp, "charlist"); break;
23630 case lig_table_code:mp_print(mp, "ligtable"); break;
23631 case extensible_code:mp_print(mp, "extensible"); break;
23632 case header_byte_code:mp_print(mp, "headerbyte"); break;
23633 default: mp_print(mp, "fontdimen"); break;
23637 @ @<Declare action procedures for use by |do_statement|@>=
23638 eight_bits mp_get_code (MP mp) ;
23640 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23641 integer c; /* the code value found */
23642 mp_get_x_next(mp); mp_scan_expression(mp);
23643 if ( mp->cur_type==mp_known ) {
23644 c=mp_round_unscaled(mp, mp->cur_exp);
23645 if ( c>=0 ) if ( c<256 ) return c;
23646 } else if ( mp->cur_type==mp_string_type ) {
23647 if ( length(mp->cur_exp)==1 ) {
23648 c=mp->str_pool[mp->str_start[mp->cur_exp]];
23652 exp_err("Invalid code has been replaced by 0");
23653 @.Invalid code...@>
23654 help2("I was looking for a number between 0 and 255, or for a")
23655 ("string of length 1. Didn't find it; will use 0 instead.");
23656 mp_put_get_flush_error(mp, 0); c=0;
23660 @ @<Declare action procedures for use by |do_statement|@>=
23661 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23663 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) {
23664 if ( mp->char_tag[c]==no_tag ) {
23665 mp->char_tag[c]=t; mp->char_remainder[c]=r;
23667 incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r;
23668 mp->label_char[mp->label_ptr]=c;
23671 @<Complain about a character tag conflict@>;
23675 @ @<Complain about a character tag conflict@>=
23677 print_err("Character ");
23678 if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23679 else if ( c==256 ) mp_print(mp, "||");
23680 else { mp_print(mp, "code "); mp_print_int(mp, c); };
23681 mp_print(mp, " is already ");
23682 @.Character c is already...@>
23683 switch (mp->char_tag[c]) {
23684 case lig_tag: mp_print(mp, "in a ligtable"); break;
23685 case list_tag: mp_print(mp, "in a charlist"); break;
23686 case ext_tag: mp_print(mp, "extensible"); break;
23687 } /* there are no other cases */
23688 help2("It's not legal to label a character more than once.")
23689 ("So I'll not change anything just now.");
23690 mp_put_get_error(mp);
23693 @ @<Declare action procedures for use by |do_statement|@>=
23694 void mp_do_tfm_command (MP mp) ;
23696 @ @c void mp_do_tfm_command (MP mp) {
23697 int c,cc; /* character codes */
23698 int k; /* index into the |kern| array */
23699 int j; /* index into |header_byte| or |param| */
23700 switch (mp->cur_mod) {
23701 case char_list_code:
23703 /* we will store a list of character successors */
23704 while ( mp->cur_cmd==colon ) {
23705 cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23708 case lig_table_code:
23709 if (mp->lig_kern==NULL)
23710 mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23711 if (mp->kern==NULL)
23712 mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23713 @<Store a list of ligature/kern steps@>;
23715 case extensible_code:
23716 @<Define an extensible recipe@>;
23718 case header_byte_code:
23719 case font_dimen_code:
23720 c=mp->cur_mod; mp_get_x_next(mp);
23721 mp_scan_expression(mp);
23722 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23723 exp_err("Improper location");
23724 @.Improper location@>
23725 help2("I was looking for a known, positive number.")
23726 ("For safety's sake I'll ignore the present command.");
23727 mp_put_get_error(mp);
23729 j=mp_round_unscaled(mp, mp->cur_exp);
23730 if ( mp->cur_cmd!=colon ) {
23731 mp_missing_err(mp, ":");
23733 help1("A colon should follow a headerbyte or fontinfo location.");
23736 if ( c==header_byte_code ) {
23737 @<Store a list of header bytes@>;
23739 if (mp->param==NULL)
23740 mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23741 @<Store a list of font dimensions@>;
23745 } /* there are no other cases */
23748 @ @<Store a list of ligature/kern steps@>=
23750 mp->lk_started=false;
23753 if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23754 @<Process a |skip_to| command and |goto done|@>;
23755 if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23756 else { mp_back_input(mp); c=mp_get_code(mp); };
23757 if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23758 @<Record a label in a lig/kern subprogram and |goto continue|@>;
23760 if ( mp->cur_cmd==lig_kern_token ) {
23761 @<Compile a ligature/kern command@>;
23763 print_err("Illegal ligtable step");
23764 @.Illegal ligtable step@>
23765 help1("I was looking for `=:' or `kern' here.");
23766 mp_back_error(mp); next_char(mp->nl)=qi(0);
23767 op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23768 skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23770 if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23772 if ( mp->cur_cmd==comma ) goto CONTINUE;
23773 if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23778 mp_primitive(mp, "=:",lig_kern_token,0);
23779 @:=:_}{\.{=:} primitive@>
23780 mp_primitive(mp, "=:|",lig_kern_token,1);
23781 @:=:/_}{\.{=:\char'174} primitive@>
23782 mp_primitive(mp, "=:|>",lig_kern_token,5);
23783 @:=:/>_}{\.{=:\char'174>} primitive@>
23784 mp_primitive(mp, "|=:",lig_kern_token,2);
23785 @:=:/_}{\.{\char'174=:} primitive@>
23786 mp_primitive(mp, "|=:>",lig_kern_token,6);
23787 @:=:/>_}{\.{\char'174=:>} primitive@>
23788 mp_primitive(mp, "|=:|",lig_kern_token,3);
23789 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23790 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23791 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23792 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23793 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23794 mp_primitive(mp, "kern",lig_kern_token,128);
23795 @:kern_}{\&{kern} primitive@>
23797 @ @<Cases of |print_cmd...@>=
23798 case lig_kern_token:
23800 case 0:mp_print(mp, "=:"); break;
23801 case 1:mp_print(mp, "=:|"); break;
23802 case 2:mp_print(mp, "|=:"); break;
23803 case 3:mp_print(mp, "|=:|"); break;
23804 case 5:mp_print(mp, "=:|>"); break;
23805 case 6:mp_print(mp, "|=:>"); break;
23806 case 7:mp_print(mp, "|=:|>"); break;
23807 case 11:mp_print(mp, "|=:|>>"); break;
23808 default: mp_print(mp, "kern"); break;
23812 @ Local labels are implemented by maintaining the |skip_table| array,
23813 where |skip_table[c]| is either |undefined_label| or the address of the
23814 most recent lig/kern instruction that skips to local label~|c|. In the
23815 latter case, the |skip_byte| in that instruction will (temporarily)
23816 be zero if there were no prior skips to this label, or it will be the
23817 distance to the prior skip.
23819 We may need to cancel skips that span more than 127 lig/kern steps.
23821 @d cancel_skips(A) mp->ll=(A);
23823 mp->lll=qo(skip_byte(mp->ll));
23824 skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23825 } while (mp->lll!=0)
23826 @d skip_error(A) { print_err("Too far to skip");
23827 @.Too far to skip@>
23828 help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23829 mp_error(mp); cancel_skips((A));
23832 @<Process a |skip_to| command and |goto done|@>=
23835 if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23836 skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23838 if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23839 else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23840 mp->skip_table[c]=mp->nl-1; goto DONE;
23843 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23845 if ( mp->cur_cmd==colon ) {
23846 if ( c==256 ) mp->bch_label=mp->nl;
23847 else mp_set_tag(mp, c,lig_tag,mp->nl);
23848 } else if ( mp->skip_table[c]<undefined_label ) {
23849 mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23851 mp->lll=qo(skip_byte(mp->ll));
23852 if ( mp->nl-mp->ll>128 ) {
23853 skip_error(mp->ll); goto CONTINUE;
23855 skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23856 } while (mp->lll!=0);
23861 @ @<Compile a ligature/kern...@>=
23863 next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23864 if ( mp->cur_mod<128 ) { /* ligature op */
23865 op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23867 mp_get_x_next(mp); mp_scan_expression(mp);
23868 if ( mp->cur_type!=mp_known ) {
23869 exp_err("Improper kern");
23871 help2("The amount of kern should be a known numeric value.")
23872 ("I'm zeroing this one. Proceed, with fingers crossed.");
23873 mp_put_get_flush_error(mp, 0);
23875 mp->kern[mp->nk]=mp->cur_exp;
23877 while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23879 if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23882 op_byte(mp->nl)=kern_flag+(k / 256);
23883 rem_byte(mp->nl)=qi((k % 256));
23885 mp->lk_started=true;
23888 @ @d missing_extensible_punctuation(A)
23889 { mp_missing_err(mp, (A));
23890 @.Missing `\char`\#'@>
23891 help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23894 @<Define an extensible recipe@>=
23896 if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23897 c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23898 if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23899 ext_top(mp->ne)=qi(mp_get_code(mp));
23900 if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23901 ext_mid(mp->ne)=qi(mp_get_code(mp));
23902 if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23903 ext_bot(mp->ne)=qi(mp_get_code(mp));
23904 if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23905 ext_rep(mp->ne)=qi(mp_get_code(mp));
23909 @ The header could contain ASCII zeroes, so can't use |strdup|.
23911 @<Store a list of header bytes@>=
23913 if ( j>=mp->header_size ) {
23914 int l = mp->header_size + (mp->header_size >> 2);
23915 char *t = xmalloc(l,sizeof(char));
23917 memcpy(t,mp->header_byte,mp->header_size);
23918 xfree (mp->header_byte);
23919 mp->header_byte = t;
23920 mp->header_size = l;
23922 mp->header_byte[j]=mp_get_code(mp);
23923 incr(j); incr(mp->header_last);
23924 } while (mp->cur_cmd==comma)
23926 @ @<Store a list of font dimensions@>=
23928 if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23929 while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23930 mp_get_x_next(mp); mp_scan_expression(mp);
23931 if ( mp->cur_type!=mp_known ){
23932 exp_err("Improper font parameter");
23933 @.Improper font parameter@>
23934 help1("I'm zeroing this one. Proceed, with fingers crossed.");
23935 mp_put_get_flush_error(mp, 0);
23937 mp->param[j]=mp->cur_exp; incr(j);
23938 } while (mp->cur_cmd==comma)
23940 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23941 All that remains is to output it in the correct format.
23943 An interesting problem needs to be solved in this connection, because
23944 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23945 and 64~italic corrections. If the data has more distinct values than
23946 this, we want to meet the necessary restrictions by perturbing the
23947 given values as little as possible.
23949 \MP\ solves this problem in two steps. First the values of a given
23950 kind (widths, heights, depths, or italic corrections) are sorted;
23951 then the list of sorted values is perturbed, if necessary.
23953 The sorting operation is facilitated by having a special node of
23954 essentially infinite |value| at the end of the current list.
23956 @<Initialize table entries...@>=
23957 value(inf_val)=fraction_four;
23959 @ Straight linear insertion is good enough for sorting, since the lists
23960 are usually not terribly long. As we work on the data, the current list
23961 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23962 list will be in increasing order of their |value| fields.
23964 Given such a list, the |sort_in| function takes a value and returns a pointer
23965 to where that value can be found in the list. The value is inserted in
23966 the proper place, if necessary.
23968 At the time we need to do these operations, most of \MP's work has been
23969 completed, so we will have plenty of memory to play with. The value nodes
23970 that are allocated for sorting will never be returned to free storage.
23972 @d clear_the_list link(temp_head)=inf_val
23974 @c pointer mp_sort_in (MP mp,scaled v) {
23975 pointer p,q,r; /* list manipulation registers */
23979 if ( v<=value(q) ) break;
23982 if ( v<value(q) ) {
23983 r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23988 @ Now we come to the interesting part, where we reduce the list if necessary
23989 until it has the required size. The |min_cover| routine is basic to this
23990 process; it computes the minimum number~|m| such that the values of the
23991 current sorted list can be covered by |m|~intervals of width~|d|. It
23992 also sets the global value |perturbation| to the smallest value $d'>d$
23993 such that the covering found by this algorithm would be different.
23995 In particular, |min_cover(0)| returns the number of distinct values in the
23996 current list and sets |perturbation| to the minimum distance between
23999 @c integer mp_min_cover (MP mp,scaled d) {
24000 pointer p; /* runs through the current list */
24001 scaled l; /* the least element covered by the current interval */
24002 integer m; /* lower bound on the size of the minimum cover */
24003 m=0; p=link(temp_head); mp->perturbation=el_gordo;
24004 while ( p!=inf_val ){
24005 incr(m); l=value(p);
24006 do { p=link(p); } while (value(p)<=l+d);
24007 if ( value(p)-l<mp->perturbation )
24008 mp->perturbation=value(p)-l;
24014 scaled perturbation; /* quantity related to \.{TFM} rounding */
24015 integer excess; /* the list is this much too long */
24017 @ The smallest |d| such that a given list can be covered with |m| intervals
24018 is determined by the |threshold| routine, which is sort of an inverse
24019 to |min_cover|. The idea is to increase the interval size rapidly until
24020 finding the range, then to go sequentially until the exact borderline has
24023 @c scaled mp_threshold (MP mp,integer m) {
24024 scaled d; /* lower bound on the smallest interval size */
24025 mp->excess=mp_min_cover(mp, 0)-m;
24026 if ( mp->excess<=0 ) {
24030 d=mp->perturbation;
24031 } while (mp_min_cover(mp, d+d)>m);
24032 while ( mp_min_cover(mp, d)>m )
24033 d=mp->perturbation;
24038 @ The |skimp| procedure reduces the current list to at most |m| entries,
24039 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
24040 is the |k|th distinct value on the resulting list, and it sets
24041 |perturbation| to the maximum amount by which a |value| field has
24042 been changed. The size of the resulting list is returned as the
24045 @c integer mp_skimp (MP mp,integer m) {
24046 scaled d; /* the size of intervals being coalesced */
24047 pointer p,q,r; /* list manipulation registers */
24048 scaled l; /* the least value in the current interval */
24049 scaled v; /* a compromise value */
24050 d=mp_threshold(mp, m); mp->perturbation=0;
24051 q=temp_head; m=0; p=link(temp_head);
24052 while ( p!=inf_val ) {
24053 incr(m); l=value(p); info(p)=m;
24054 if ( value(link(p))<=l+d ) {
24055 @<Replace an interval of values by its midpoint@>;
24062 @ @<Replace an interval...@>=
24065 p=link(p); info(p)=m;
24066 decr(mp->excess); if ( mp->excess==0 ) d=0;
24067 } while (value(link(p))<=l+d);
24068 v=l+halfp(value(p)-l);
24069 if ( value(p)-v>mp->perturbation )
24070 mp->perturbation=value(p)-v;
24073 r=link(r); value(r)=v;
24075 link(q)=p; /* remove duplicate values from the current list */
24078 @ A warning message is issued whenever something is perturbed by
24079 more than 1/16\thinspace pt.
24081 @c void mp_tfm_warning (MP mp,small_number m) {
24082 mp_print_nl(mp, "(some ");
24083 mp_print(mp, mp->int_name[m]);
24084 @.some charwds...@>
24085 @.some chardps...@>
24086 @.some charhts...@>
24087 @.some charics...@>
24088 mp_print(mp, " values had to be adjusted by as much as ");
24089 mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
24092 @ Here's an example of how we use these routines.
24093 The width data needs to be perturbed only if there are 256 distinct
24094 widths, but \MP\ must check for this case even though it is
24097 An integer variable |k| will be defined when we use this code.
24098 The |dimen_head| array will contain pointers to the sorted
24099 lists of dimensions.
24101 @<Massage the \.{TFM} widths@>=
24103 for (k=mp->bc;k<=mp->ec;k++) {
24104 if ( mp->char_exists[k] )
24105 mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
24107 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
24108 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24111 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24113 @ Heights, depths, and italic corrections are different from widths
24114 not only because their list length is more severely restricted, but
24115 also because zero values do not need to be put into the lists.
24117 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24119 for (k=mp->bc;k<=mp->ec;k++) {
24120 if ( mp->char_exists[k] ) {
24121 if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24122 else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24125 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
24126 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24128 for (k=mp->bc;k<=mp->ec;k++) {
24129 if ( mp->char_exists[k] ) {
24130 if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24131 else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24134 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
24135 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24137 for (k=mp->bc;k<=mp->ec;k++) {
24138 if ( mp->char_exists[k] ) {
24139 if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24140 else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24143 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
24144 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24146 @ @<Initialize table entries...@>=
24147 value(zero_val)=0; info(zero_val)=0;
24149 @ Bytes 5--8 of the header are set to the design size, unless the user has
24150 some crazy reason for specifying them differently.
24152 Error messages are not allowed at the time this procedure is called,
24153 so a warning is printed instead.
24155 The value of |max_tfm_dimen| is calculated so that
24156 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24157 < \\{three\_bytes}.$$
24159 @d three_bytes 0100000000 /* $2^{24}$ */
24162 void mp_fix_design_size (MP mp) {
24163 scaled d; /* the design size */
24164 d=mp->internal[mp_design_size];
24165 if ( (d<unity)||(d>=fraction_half) ) {
24167 mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24168 @.illegal design size...@>
24169 d=040000000; mp->internal[mp_design_size]=d;
24171 if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24172 if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24173 mp->header_byte[4]=d / 04000000;
24174 mp->header_byte[5]=(d / 4096) % 256;
24175 mp->header_byte[6]=(d / 16) % 256;
24176 mp->header_byte[7]=(d % 16)*16;
24178 mp->max_tfm_dimen=16*mp->internal[mp_design_size]-mp->internal[mp_design_size] / 010000000;
24179 if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24182 @ The |dimen_out| procedure computes a |fix_word| relative to the
24183 design size. If the data was out of range, it is corrected and the
24184 global variable |tfm_changed| is increased by~one.
24186 @c integer mp_dimen_out (MP mp,scaled x) {
24187 if ( abs(x)>mp->max_tfm_dimen ) {
24188 incr(mp->tfm_changed);
24189 if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
24191 x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24197 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24198 integer tfm_changed; /* the number of data entries that were out of bounds */
24200 @ If the user has not specified any of the first four header bytes,
24201 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24202 from the |tfm_width| data relative to the design size.
24205 @c void mp_fix_check_sum (MP mp) {
24206 eight_bits k; /* runs through character codes */
24207 eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24208 integer x; /* hash value used in check sum computation */
24209 if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24210 mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24211 @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24212 mp->header_byte[0]=B1; mp->header_byte[1]=B2;
24213 mp->header_byte[2]=B3; mp->header_byte[3]=B4;
24218 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24219 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24220 for (k=mp->bc;k<=mp->ec;k++) {
24221 if ( mp->char_exists[k] ) {
24222 x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24223 B1=(B1+B1+x) % 255;
24224 B2=(B2+B2+x) % 253;
24225 B3=(B3+B3+x) % 251;
24226 B4=(B4+B4+x) % 247;
24230 @ Finally we're ready to actually write the \.{TFM} information.
24231 Here are some utility routines for this purpose.
24233 @d tfm_out(A) fputc((A),mp->tfm_file) /* output one byte to |tfm_file| */
24235 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24236 tfm_out(x / 256); tfm_out(x % 256);
24238 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24239 if ( x>=0 ) tfm_out(x / three_bytes);
24241 x=x+010000000000; /* use two's complement for negative values */
24243 tfm_out((x / three_bytes) + 128);
24245 x=x % three_bytes; tfm_out(x / unity);
24246 x=x % unity; tfm_out(x / 0400);
24249 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24250 tfm_out(qo(x.b0)); tfm_out(qo(x.b1));
24251 tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24254 @ @<Finish the \.{TFM} file@>=
24255 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24256 mp_pack_job_name(mp, ".tfm");
24257 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24258 mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24259 mp->metric_file_name=xstrdup(mp->name_of_file);
24260 @<Output the subfile sizes and header bytes@>;
24261 @<Output the character information bytes, then
24262 output the dimensions themselves@>;
24263 @<Output the ligature/kern program@>;
24264 @<Output the extensible character recipes and the font metric parameters@>;
24265 if ( mp->internal[mp_tracing_stats]>0 )
24266 @<Log the subfile sizes of the \.{TFM} file@>;
24267 mp_print_nl(mp, "Font metrics written on ");
24268 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24269 @.Font metrics written...@>
24270 fclose(mp->tfm_file)
24272 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24275 @<Output the subfile sizes and header bytes@>=
24277 LH=(k+3) / 4; /* this is the number of header words */
24278 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24279 @<Compute the ligature/kern program offset and implant the
24280 left boundary label@>;
24281 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24282 +lk_offset+mp->nk+mp->ne+mp->np);
24283 /* this is the total number of file words that will be output */
24284 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec);
24285 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24286 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset);
24287 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24288 mp_tfm_two(mp, mp->np);
24289 for (k=0;k< 4*LH;k++) {
24290 tfm_out(mp->header_byte[k]);
24293 @ @<Output the character information bytes...@>=
24294 for (k=mp->bc;k<=mp->ec;k++) {
24295 if ( ! mp->char_exists[k] ) {
24296 mp_tfm_four(mp, 0);
24298 tfm_out(info(mp->tfm_width[k])); /* the width index */
24299 tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24300 tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24301 tfm_out(mp->char_remainder[k]);
24305 for (k=1;k<=4;k++) {
24306 mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24307 while ( p!=inf_val ) {
24308 mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24313 @ We need to output special instructions at the beginning of the
24314 |lig_kern| array in order to specify the right boundary character
24315 and/or to handle starting addresses that exceed 255. The |label_loc|
24316 and |label_char| arrays have been set up to record all the
24317 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24318 \le|label_loc|[|label_ptr]|$.
24320 @<Compute the ligature/kern program offset...@>=
24321 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24322 if ((mp->bchar<0)||(mp->bchar>255))
24323 { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24324 else { mp->lk_started=true; lk_offset=1; };
24325 @<Find the minimum |lk_offset| and adjust all remainders@>;
24326 if ( mp->bch_label<undefined_label )
24327 { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24328 op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24329 rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24330 incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24333 @ @<Find the minimum |lk_offset|...@>=
24334 k=mp->label_ptr; /* pointer to the largest unallocated label */
24335 if ( mp->label_loc[k]+lk_offset>255 ) {
24336 lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24338 mp->char_remainder[mp->label_char[k]]=lk_offset;
24339 while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24340 decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24342 incr(lk_offset); decr(k);
24343 } while (! (lk_offset+mp->label_loc[k]<256));
24344 /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24346 if ( lk_offset>0 ) {
24348 mp->char_remainder[mp->label_char[k]]
24349 =mp->char_remainder[mp->label_char[k]]+lk_offset;
24354 @ @<Output the ligature/kern program@>=
24355 for (k=0;k<= 255;k++ ) {
24356 if ( mp->skip_table[k]<undefined_label ) {
24357 mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24358 @.local label l:: was missing@>
24359 cancel_skips(mp->skip_table[k]);
24362 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24363 tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24365 for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24366 mp->ll=mp->label_loc[mp->label_ptr];
24367 if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0); }
24368 else { tfm_out(255); tfm_out(mp->bchar); };
24369 mp_tfm_two(mp, mp->ll+lk_offset);
24371 decr(mp->label_ptr);
24372 } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24375 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24376 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24378 @ @<Output the extensible character recipes...@>=
24379 for (k=0;k<=mp->ne-1;k++)
24380 mp_tfm_qqqq(mp, mp->exten[k]);
24381 for (k=1;k<=mp->np;k++) {
24383 if ( abs(mp->param[1])<fraction_half ) {
24384 mp_tfm_four(mp, mp->param[1]*16);
24386 incr(mp->tfm_changed);
24387 if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24388 else mp_tfm_four(mp, -el_gordo);
24391 mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24394 if ( mp->tfm_changed>0 ) {
24395 if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24396 @.a font metric dimension...@>
24398 mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24399 @.font metric dimensions...@>
24400 mp_print(mp, " font metric dimensions");
24402 mp_print(mp, " had to be decreased)");
24405 @ @<Log the subfile sizes of the \.{TFM} file@>=
24409 if ( mp->bch_label<undefined_label ) decr(mp->nl);
24410 snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24411 mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24415 @* \[43] Reading font metric data.
24417 \MP\ isn't a typesetting program but it does need to find the bounding box
24418 of a sequence of typeset characters. Thus it needs to read \.{TFM} files as
24419 well as write them.
24424 @ All the width, height, and depth information is stored in an array called
24425 |font_info|. This array is allocated sequentially and each font is stored
24426 as a series of |char_info| words followed by the width, height, and depth
24427 tables. Since |font_name| entries are permanent, their |str_ref| values are
24428 set to |max_str_ref|.
24431 typedef unsigned int font_number; /* |0..font_max| */
24433 @ The |font_info| array is indexed via a group directory arrays.
24434 For example, the |char_info| data for character~|c| in font~|f| will be
24435 in |font_info[char_base[f]+c].qqqq|.
24438 font_number font_max; /* maximum font number for included text fonts */
24439 size_t font_mem_size; /* number of words for \.{TFM} information for text fonts */
24440 memory_word *font_info; /* height, width, and depth data */
24441 char **font_enc_name; /* encoding names, if any */
24442 boolean *font_ps_name_fixed; /* are the postscript names fixed already? */
24443 int next_fmem; /* next unused entry in |font_info| */
24444 font_number last_fnum; /* last font number used so far */
24445 scaled *font_dsize; /* 16 times the ``design'' size in \ps\ points */
24446 char **font_name; /* name as specified in the \&{infont} command */
24447 char **font_ps_name; /* PostScript name for use when |internal[mp_prologues]>0| */
24448 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24449 eight_bits *font_bc;
24450 eight_bits *font_ec; /* first and last character code */
24451 int *char_base; /* base address for |char_info| */
24452 int *width_base; /* index for zeroth character width */
24453 int *height_base; /* index for zeroth character height */
24454 int *depth_base; /* index for zeroth character depth */
24455 pointer *font_sizes;
24457 @ @<Allocate or initialize ...@>=
24458 mp->font_mem_size = 10000;
24459 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24460 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24461 mp->font_enc_name = NULL;
24462 mp->font_ps_name_fixed = NULL;
24463 mp->font_dsize = NULL;
24464 mp->font_name = NULL;
24465 mp->font_ps_name = NULL;
24466 mp->font_bc = NULL;
24467 mp->font_ec = NULL;
24468 mp->last_fnum = null_font;
24469 mp->char_base = NULL;
24470 mp->width_base = NULL;
24471 mp->height_base = NULL;
24472 mp->depth_base = NULL;
24473 mp->font_sizes = null;
24475 @ @<Dealloc variables@>=
24476 xfree(mp->font_info);
24477 xfree(mp->font_enc_name);
24478 xfree(mp->font_ps_name_fixed);
24479 xfree(mp->font_dsize);
24480 xfree(mp->font_name);
24481 xfree(mp->font_ps_name);
24482 xfree(mp->font_bc);
24483 xfree(mp->font_ec);
24484 xfree(mp->char_base);
24485 xfree(mp->width_base);
24486 xfree(mp->height_base);
24487 xfree(mp->depth_base);
24488 xfree(mp->font_sizes);
24492 void mp_reallocate_fonts (MP mp, font_number l) {
24494 XREALLOC(mp->font_enc_name, l, char *);
24495 XREALLOC(mp->font_ps_name_fixed, l, boolean);
24496 XREALLOC(mp->font_dsize, l, scaled);
24497 XREALLOC(mp->font_name, l, char *);
24498 XREALLOC(mp->font_ps_name, l, char *);
24499 XREALLOC(mp->font_bc, l, eight_bits);
24500 XREALLOC(mp->font_ec, l, eight_bits);
24501 XREALLOC(mp->char_base, l, int);
24502 XREALLOC(mp->width_base, l, int);
24503 XREALLOC(mp->height_base, l, int);
24504 XREALLOC(mp->depth_base, l, int);
24505 XREALLOC(mp->font_sizes, l, pointer);
24506 for (f=(mp->last_fnum+1);f<=l;f++) {
24507 mp->font_enc_name[f]=NULL;
24508 mp->font_ps_name_fixed[f] = false;
24509 mp->font_name[f]=NULL;
24510 mp->font_ps_name[f]=NULL;
24511 mp->font_sizes[f]=null;
24516 @ @<Declare |mp_reallocate| functions@>=
24517 void mp_reallocate_fonts (MP mp, font_number l);
24520 @ A |null_font| containing no characters is useful for error recovery. Its
24521 |font_name| entry starts out empty but is reset each time an erroneous font is
24522 found. This helps to cut down on the number of duplicate error messages without
24523 wasting a lot of space.
24525 @d null_font 0 /* the |font_number| for an empty font */
24527 @<Set initial...@>=
24528 mp->font_dsize[null_font]=0;
24529 mp->font_bc[null_font]=1;
24530 mp->font_ec[null_font]=0;
24531 mp->char_base[null_font]=0;
24532 mp->width_base[null_font]=0;
24533 mp->height_base[null_font]=0;
24534 mp->depth_base[null_font]=0;
24536 mp->last_fnum=null_font;
24537 mp->last_ps_fnum=null_font;
24538 mp->font_name[null_font]="nullfont";
24539 mp->font_ps_name[null_font]="";
24541 @ Each |char_info| word is of type |four_quarters|. The |b0| field contains
24542 the |width index|; the |b1| field contains the height
24543 index; the |b2| fields contains the depth index, and the |b3| field used only
24544 for temporary storage. (It is used to keep track of which characters occur in
24545 an edge structure that is being shipped out.)
24546 The corresponding words in the width, height, and depth tables are stored as
24547 |scaled| values in units of \ps\ points.
24549 With the macros below, the |char_info| word for character~|c| in font~|f| is
24550 |char_info(f)(c)| and the width is
24551 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24553 @d char_info_end(A) (A)].qqqq
24554 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24555 @d char_width_end(A) (A).b0].sc
24556 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24557 @d char_height_end(A) (A).b1].sc
24558 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24559 @d char_depth_end(A) (A).b2].sc
24560 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24561 @d ichar_exists(A) ((A).b0>0)
24563 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24564 A preliminary name is obtained here from the \.{TFM} name as given in the
24565 |fname| argument. This gets updated later from an external table if necessary.
24567 @<Declare text measuring subroutines@>=
24568 @<Declare subroutines for parsing file names@>;
24569 font_number mp_read_font_info (MP mp, char*fname) {
24570 boolean file_opened; /* has |tfm_infile| been opened? */
24571 font_number n; /* the number to return */
24572 halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24573 size_t whd_size; /* words needed for heights, widths, and depths */
24574 int i,ii; /* |font_info| indices */
24575 int jj; /* counts bytes to be ignored */
24576 scaled z; /* used to compute the design size */
24578 /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24579 eight_bits h_and_d; /* height and depth indices being unpacked */
24580 int tfbyte; /* a byte read from the file */
24582 @<Open |tfm_infile| for input@>;
24583 @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24584 otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24586 @<Complain that the \.{TFM} file is bad@>;
24588 if ( file_opened ) fclose(mp->tfm_infile);
24589 if ( n!=null_font ) {
24590 mp->font_ps_name[n]=fname;
24591 mp->font_name[n]=fname;
24596 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24597 precisely what is wrong if it does find a problem. Programs called \.{TFtoPL}
24598 @.TFtoPL@> @.PLtoTF@>
24599 and \.{PLtoTF} can be used to debug \.{TFM} files.
24601 @<Complain that the \.{TFM} file is bad@>=
24602 print_err("Font ");
24603 mp_print(mp, fname);
24604 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24605 else mp_print(mp, " not usable: TFM file not found");
24606 help3("I wasn't able to read the size data for this font so this")
24607 ("`infont' operation won't produce anything. If the font name")
24608 ("is right, you might ask an expert to make a TFM file");
24610 mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24613 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24614 @<Read the \.{TFM} size fields@>;
24615 @<Use the size fields to allocate space in |font_info|@>;
24616 @<Read the \.{TFM} header@>;
24617 @<Read the character data and the width, height, and depth tables and
24620 @ A bad \.{TFM} file can be shorter than it claims to be. The code given here
24621 might try to read past the end of the file if this happens. Changes will be
24622 needed if it causes a system error to refer to |tfm_infile^| or call
24623 |get_tfm_infile| when |eof(tfm_infile)| is true. For example, the definition
24624 @^system dependencies@>
24625 of |tfget| could be changed to
24626 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24628 @d tfget {tfbyte = fgetc(mp->tfm_infile); }
24629 @d read_two(A) { (A)=tfbyte;
24630 if ( (A)>127 ) goto BAD_TFM;
24631 tfget; (A)=(A)*0400+tfbyte;
24633 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24635 @<Read the \.{TFM} size fields@>=
24636 tfget; read_two(lf);
24637 tfget; read_two(tfm_lh);
24638 tfget; read_two(bc);
24639 tfget; read_two(ec);
24640 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24641 tfget; read_two(nw);
24642 tfget; read_two(nh);
24643 tfget; read_two(nd);
24644 whd_size=(ec+1-bc)+nw+nh+nd;
24645 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24648 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24649 necessary to apply the |so| and |qo| macros when looking up the width of a
24650 character in the string pool. In order to ensure nonnegative |char_base|
24651 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24654 @<Use the size fields to allocate space in |font_info|@>=
24655 if ( mp->next_fmem<bc) mp->next_fmem=bc; /* ensure nonnegative |char_base| */
24656 if (mp->last_fnum==mp->font_max)
24657 mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24658 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24659 size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24660 memory_word *font_info;
24661 font_info = xmalloc ((l+1),sizeof(memory_word));
24662 memset (font_info,0,sizeof(memory_word)*(l+1));
24663 memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24664 xfree(mp->font_info);
24665 mp->font_info = font_info;
24666 mp->font_mem_size = l;
24668 incr(mp->last_fnum);
24672 mp->char_base[n]=mp->next_fmem-bc;
24673 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24674 mp->height_base[n]=mp->width_base[n]+nw;
24675 mp->depth_base[n]=mp->height_base[n]+nh;
24676 mp->next_fmem=mp->next_fmem+whd_size;
24679 @ @<Read the \.{TFM} header@>=
24680 if ( tfm_lh<2 ) goto BAD_TFM;
24682 tfget; read_two(z);
24683 tfget; z=z*0400+tfbyte;
24684 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24685 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24686 /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24687 tf_ignore(4*(tfm_lh-2))
24689 @ @<Read the character data and the width, height, and depth tables...@>=
24690 ii=mp->width_base[n];
24691 i=mp->char_base[n]+bc;
24693 tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24694 tfget; h_and_d=tfbyte;
24695 mp->font_info[i].qqqq.b1=h_and_d / 16;
24696 mp->font_info[i].qqqq.b2=h_and_d % 16;
24700 while ( i<mp->next_fmem ) {
24701 @<Read a four byte dimension, scale it by the design size, store it in
24702 |font_info[i]|, and increment |i|@>;
24704 if (feof(mp->tfm_infile) ) goto BAD_TFM;
24707 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24708 interpreted as an integer, and this includes a scale factor of $2^{20}$. Thus
24709 we can multiply it by sixteen and think of it as a |fraction| that has been
24710 divided by sixteen. This cancels the extra scale factor contained in
24713 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24716 if ( d>=0200 ) d=d-0400;
24717 tfget; d=d*0400+tfbyte;
24718 tfget; d=d*0400+tfbyte;
24719 tfget; d=d*0400+tfbyte;
24720 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24724 @ This function does no longer use the file name parser, because |fname| is
24725 a C string already.
24726 @<Open |tfm_infile| for input@>=
24728 mp_ptr_scan_file(mp, fname);
24729 if ( strlen(mp->cur_area)==0 ) { xfree(mp->cur_area); mp->cur_area=xstrdup(MP_font_area);}
24730 if ( strlen(mp->cur_ext)==0 ) { xfree(mp->cur_ext); mp->cur_ext=xstrdup(".tfm"); }
24732 mp->tfm_infile = mp_open_file(mp, mp->name_of_file, "rb",mp_filetype_metrics);
24733 if ( !mp->tfm_infile ) goto BAD_TFM;
24736 @ When we have a font name and we don't know whether it has been loaded yet,
24737 we scan the |font_name| array before calling |read_font_info|.
24739 @<Declare text measuring subroutines@>=
24740 font_number mp_find_font (MP mp, char *f) {
24742 for (n=0;n<=mp->last_fnum;n++) {
24743 if (mp_xstrcmp(f,mp->font_name[n])==0 )
24746 return mp_read_font_info(mp, f);
24749 @ One simple application of |find_font| is the implementation of the |font_size|
24750 operator that gets the design size for a given font name.
24752 @<Find the design size of the font whose name is |cur_exp|@>=
24753 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24755 @ If we discover that the font doesn't have a requested character, we omit it
24756 from the bounding box computation and expect the \ps\ interpreter to drop it.
24757 This routine issues a warning message if the user has asked for it.
24759 @<Declare text measuring subroutines@>=
24760 void mp_lost_warning (MP mp,font_number f, pool_pointer k) {
24761 if ( mp->internal[mp_tracing_lost_chars]>0 ) {
24762 mp_begin_diagnostic(mp);
24763 if ( mp->selector==log_only ) incr(mp->selector);
24764 mp_print_nl(mp, "Missing character: There is no ");
24765 @.Missing character@>
24766 mp_print_str(mp, mp->str_pool[k]);
24767 mp_print(mp, " in font ");
24768 mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!');
24769 mp_end_diagnostic(mp, false);
24773 @ The whole purpose of saving the height, width, and depth information is to be
24774 able to find the bounding box of an item of text in an edge structure. The
24775 |set_text_box| procedure takes a text node and adds this information.
24777 @<Declare text measuring subroutines@>=
24778 void mp_set_text_box (MP mp,pointer p) {
24779 font_number f; /* |font_n(p)| */
24780 ASCII_code bc,ec; /* range of valid characters for font |f| */
24781 pool_pointer k,kk; /* current character and character to stop at */
24782 four_quarters cc; /* the |char_info| for the current character */
24783 scaled h,d; /* dimensions of the current character */
24785 height_val(p)=-el_gordo;
24786 depth_val(p)=-el_gordo;
24790 kk=str_stop(text_p(p));
24791 k=mp->str_start[text_p(p)];
24793 @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24795 @<Set the height and depth to zero if the bounding box is empty@>;
24798 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24800 if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24801 mp_lost_warning(mp, f,k);
24803 cc=char_info(f)(mp->str_pool[k]);
24804 if ( ! ichar_exists(cc) ) {
24805 mp_lost_warning(mp, f,k);
24807 width_val(p)=width_val(p)+char_width(f)(cc);
24808 h=char_height(f)(cc);
24809 d=char_depth(f)(cc);
24810 if ( h>height_val(p) ) height_val(p)=h;
24811 if ( d>depth_val(p) ) depth_val(p)=d;
24817 @ Let's hope modern compilers do comparisons correctly when the difference would
24820 @<Set the height and depth to zero if the bounding box is empty@>=
24821 if ( height_val(p)<-depth_val(p) ) {
24826 @ The new primitives fontmapfile and fontmapline.
24828 @<Declare action procedures for use by |do_statement|@>=
24829 void mp_do_mapfile (MP mp) ;
24830 void mp_do_mapline (MP mp) ;
24832 @ @c void mp_do_mapfile (MP mp) {
24833 mp_get_x_next(mp); mp_scan_expression(mp);
24834 if ( mp->cur_type!=mp_string_type ) {
24835 @<Complain about improper map operation@>;
24837 mp_map_file(mp,mp->cur_exp);
24840 void mp_do_mapline (MP mp) {
24841 mp_get_x_next(mp); mp_scan_expression(mp);
24842 if ( mp->cur_type!=mp_string_type ) {
24843 @<Complain about improper map operation@>;
24845 mp_map_line(mp,mp->cur_exp);
24849 @ @<Complain about improper map operation@>=
24851 exp_err("Unsuitable expression");
24852 help1("Only known strings can be map files or map lines.");
24853 mp_put_get_error(mp);
24856 @ This is temporary.
24858 @d ps_room(A) mp_ps_room(mp,A)
24860 @ To print |scaled| value to PDF output we need some subroutines to ensure
24863 @d max_integer 0x7FFFFFFF /* $2^{31}-1$ */
24866 scaled one_bp; /* scaled value corresponds to 1bp */
24867 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24868 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24869 integer ten_pow[10]; /* $10^0..10^9$ */
24870 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24873 mp->one_bp = 65782; /* 65781.76 */
24874 mp->one_hundred_bp = 6578176;
24875 mp->one_hundred_inch = 473628672;
24876 mp->ten_pow[0] = 1;
24877 for (i = 1;i<= 9; i++ ) {
24878 mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24881 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24883 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer dd) {
24887 if ( s < 0 ) { sign = -sign; s = -s; }
24888 if ( m < 0 ) { sign = -sign; m = -m; }
24890 mp_confusion(mp, "arithmetic: divided by zero");
24891 else if ( m >= (max_integer / 10) )
24892 mp_confusion(mp, "arithmetic: number too big");
24895 for (i = 1;i<=dd;i++) {
24896 q = 10*q + (10*r) / m;
24899 if ( 2*r >= m ) { incr(q); r = r - m; }
24900 mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24904 @* \[44] Shipping pictures out.
24905 The |ship_out| procedure, to be described below, is given a pointer to
24906 an edge structure. Its mission is to output a file containing the \ps\
24907 description of an edge structure.
24909 @ Each time an edge structure is shipped out we write a new \ps\ output
24910 file named according to the current \&{charcode}.
24911 @:char_code_}{\&{charcode} primitive@>
24913 @<Declare the \ps\ output procedures@>=
24914 void mp_open_output_file (MP mp) ;
24916 @ @c void mp_open_output_file (MP mp) {
24917 integer c; /* \&{charcode} rounded to the nearest integer */
24918 int old_setting; /* previous |selector| setting */
24919 pool_pointer i; /* indexes into |filename_template| */
24920 integer cc; /* a temporary integer for template building */
24921 integer f,g=0; /* field widths */
24922 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24923 c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
24924 if ( mp->filename_template==0 ) {
24925 char *s; /* a file extension derived from |c| */
24929 @<Use |c| to compute the file extension |s|@>;
24930 mp_pack_job_name(mp, s);
24932 while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24933 mp_prompt_file_name(mp, "file name for output",s);
24934 } else { /* initializations */
24935 str_number s, n; /* a file extension derived from |c| */
24936 old_setting=mp->selector;
24937 mp->selector=new_string;
24939 i = mp->str_start[mp->filename_template];
24940 n = rts(""); /* initialize */
24941 while ( i<str_stop(mp->filename_template) ) {
24942 if ( mp->str_pool[i]=='%' ) {
24945 if ( i<str_stop(mp->filename_template) ) {
24946 if ( mp->str_pool[i]=='j' ) {
24947 mp_print(mp, mp->job_name);
24948 } else if ( mp->str_pool[i]=='d' ) {
24949 cc= mp_round_unscaled(mp, mp->internal[mp_day]);
24950 print_with_leading_zeroes(cc);
24951 } else if ( mp->str_pool[i]=='m' ) {
24952 cc= mp_round_unscaled(mp, mp->internal[mp_month]);
24953 print_with_leading_zeroes(cc);
24954 } else if ( mp->str_pool[i]=='y' ) {
24955 cc= mp_round_unscaled(mp, mp->internal[mp_year]);
24956 print_with_leading_zeroes(cc);
24957 } else if ( mp->str_pool[i]=='H' ) {
24958 cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24959 print_with_leading_zeroes(cc);
24960 } else if ( mp->str_pool[i]=='M' ) {
24961 cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24962 print_with_leading_zeroes(cc);
24963 } else if ( mp->str_pool[i]=='c' ) {
24964 if ( c<0 ) mp_print(mp, "ps");
24965 else print_with_leading_zeroes(c);
24966 } else if ( (mp->str_pool[i]>='0') &&
24967 (mp->str_pool[i]<='9') ) {
24969 f = (f*10) + mp->str_pool[i]-'0';
24972 mp_print_str(mp, mp->str_pool[i]);
24976 if ( mp->str_pool[i]=='.' )
24978 n = mp_make_string(mp);
24979 mp_print_str(mp, mp->str_pool[i]);
24983 s = mp_make_string(mp);
24984 mp->selector= old_setting;
24985 if (length(n)==0) {
24989 mp_pack_file_name(mp, str(n),"",str(s));
24990 while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24991 mp_prompt_file_name(mp, "file name for output",str(s));
24995 @<Store the true output file name if appropriate@>;
24996 @<Begin the progress report for the output of picture~|c|@>;
24999 @ The file extension created here could be up to five characters long in
25000 extreme cases so it may have to be shortened on some systems.
25001 @^system dependencies@>
25003 @<Use |c| to compute the file extension |s|@>=
25006 snprintf(s,7,".%i",(int)c);
25009 @ The user won't want to see all the output file names so we only save the
25010 first and last ones and a count of how many there were. For this purpose
25011 files are ordered primarily by \&{charcode} and secondarily by order of
25013 @:char_code_}{\&{charcode} primitive@>
25015 @<Store the true output file name if appropriate@>=
25016 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
25017 mp->first_output_code=c;
25018 xfree(mp->first_file_name);
25019 mp->first_file_name=xstrdup(mp->name_of_file);
25021 if ( c>=mp->last_output_code ) {
25022 mp->last_output_code=c;
25023 xfree(mp->last_file_name);
25024 mp->last_file_name=xstrdup(mp->name_of_file);
25028 char * first_file_name;
25029 char * last_file_name; /* full file names */
25030 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
25031 @:char_code_}{\&{charcode} primitive@>
25032 integer total_shipped; /* total number of |ship_out| operations completed */
25035 mp->first_file_name=xstrdup("");
25036 mp->last_file_name=xstrdup("");
25037 mp->first_output_code=32768;
25038 mp->last_output_code=-32768;
25039 mp->total_shipped=0;
25041 @ @<Dealloc variables@>=
25042 xfree(mp->first_file_name);
25043 xfree(mp->last_file_name);
25045 @ @<Begin the progress report for the output of picture~|c|@>=
25046 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
25047 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
25048 mp_print_char(mp, '[');
25049 if ( c>=0 ) mp_print_int(mp, c)
25051 @ @<End progress report@>=
25052 mp_print_char(mp, ']');
25054 incr(mp->total_shipped)
25056 @ @<Explain what output files were written@>=
25057 if ( mp->total_shipped>0 ) {
25058 mp_print_nl(mp, "");
25059 mp_print_int(mp, mp->total_shipped);
25060 mp_print(mp, " output file");
25061 if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
25062 mp_print(mp, " written: ");
25063 mp_print(mp, mp->first_file_name);
25064 if ( mp->total_shipped>1 ) {
25065 if ( 31+strlen(mp->first_file_name)+
25066 strlen(mp->last_file_name)> (unsigned)mp->max_print_line)
25068 mp_print(mp, " .. ");
25069 mp_print(mp, mp->last_file_name);
25073 @ A text node may specify an arbitrary transformation but the usual case
25074 involves only shifting, scaling, and occasionally rotation. The purpose
25075 of |choose_scale| is to select a scale factor so that the remaining
25076 transformation is as ``nice'' as possible. The definition of ``nice''
25077 is somewhat arbitrary but shifting and $90^\circ$ rotation are especially
25078 nice because they work out well for bitmap fonts. The code here selects
25079 a scale factor equal to $1/\sqrt2$ times the Frobenius norm of the
25080 non-shifting part of the transformation matrix. It is careful to avoid
25081 additions that might cause undetected overflow.
25083 @<Declare the \ps\ output procedures@>=
25084 scaled mp_choose_scale (MP mp,pointer p) ;
25086 @ @c scaled mp_choose_scale (MP mp,pointer p) {
25087 /* |p| should point to a text node */
25088 scaled a,b,c,d,ad,bc; /* temporary values */
25093 if ( (a<0) ) negate(a);
25094 if ( (b<0) ) negate(b);
25095 if ( (c<0) ) negate(c);
25096 if ( (d<0) ) negate(d);
25099 return mp_pyth_add(mp, mp_pyth_add(mp, d+ad,ad), mp_pyth_add(mp, c+bc,bc));
25102 @ There may be many sizes of one font and we need to keep track of the
25103 characters used for each size. This is done by keeping a linked list of
25104 sizes for each font with a counter in each text node giving the appropriate
25105 position in the size list for its font.
25107 @d sc_factor(A) mp->mem[(A)+1].sc /* the scale factor stored in a font size node */
25108 @d font_size_size 2 /* size of a font size node */
25110 @ @<Internal library declarations@>=
25111 boolean mp_has_font_size(MP mp, font_number f );
25114 boolean mp_has_font_size(MP mp, font_number f ) {
25115 return (mp->font_sizes[f]!=null);
25119 @ The potential overflow here is caused by the fact the returned value
25120 has to fit in a |name_type|, which is a quarterword.
25122 @d fscale_tolerance 65 /* that's $.001\times2^{16}$ */
25124 @<Declare the \ps\ output procedures@>=
25125 quarterword mp_size_index (MP mp, font_number f, scaled s) {
25126 pointer p,q; /* the previous and current font size nodes */
25127 quarterword i; /* the size index for |q| */
25128 q=mp->font_sizes[f];
25130 while ( q!=null ) {
25131 if ( abs(s-sc_factor(q))<=fscale_tolerance )
25134 { p=q; q=link(q); incr(i); };
25135 if ( i==max_quarterword )
25136 mp_overflow(mp, "sizes per font",max_quarterword);
25137 @:MetaPost capacity exceeded sizes per font}{\quad sizes per font@>
25139 q=mp_get_node(mp, font_size_size);
25141 if ( i==0 ) mp->font_sizes[f]=q; else link(p)=q;
25145 @ @<Internal library ...@>=
25146 scaled mp_indexed_size (MP mp,font_number f, quarterword j);
25149 scaled mp_indexed_size (MP mp,font_number f, quarterword j) {
25150 pointer p; /* a font size node */
25151 quarterword i; /* the size index for |p| */
25152 p=mp->font_sizes[f];
25154 if ( p==null ) mp_confusion(mp, "size");
25156 incr(i); p=link(p);
25157 if ( p==null ) mp_confusion(mp, "size");
25159 return sc_factor(p);
25162 @ @<Declare the \ps\ output procedures@>=
25163 void mp_clear_sizes (MP mp) ;
25165 @ @c void mp_clear_sizes (MP mp) {
25166 font_number f; /* the font whose size list is being cleared */
25167 pointer p; /* current font size nodes */
25168 for (f=null_font+1;f<=mp->last_fnum;f++) {
25169 while ( mp->font_sizes[f]!=null ) {
25170 p=mp->font_sizes[f];
25171 mp->font_sizes[f]=link(p);
25172 mp_free_node(mp, p,font_size_size);
25177 @ The \&{special} command saves up lines of text to be printed during the next
25178 |ship_out| operation. The saved items are stored as a list of capsule tokens.
25181 pointer last_pending; /* the last token in a list of pending specials */
25184 mp->last_pending=spec_head;
25186 @ @<Cases of |do_statement|...@>=
25187 case special_command:
25188 if ( mp->cur_mod==0 ) mp_do_special(mp); else
25189 if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else
25193 @ @<Declare action procedures for use by |do_statement|@>=
25194 void mp_do_special (MP mp) ;
25196 @ @c void mp_do_special (MP mp) {
25197 mp_get_x_next(mp); mp_scan_expression(mp);
25198 if ( mp->cur_type!=mp_string_type ) {
25199 @<Complain about improper special operation@>;
25201 link(mp->last_pending)=mp_stash_cur_exp(mp);
25202 mp->last_pending=link(mp->last_pending);
25203 link(mp->last_pending)=null;
25207 @ @<Complain about improper special operation@>=
25209 exp_err("Unsuitable expression");
25210 help1("Only known strings are allowed for output as specials.");
25211 mp_put_get_error(mp);
25214 @ On the export side, we need an extra object type for special strings.
25216 @<Graphical object codes@>=
25219 @ @<Export pending specials@>=
25221 while ( p!=null ) {
25222 hq = mp_new_graphic_object(mp,mp_special_code);
25223 gr_pre_script(hq) = str(value(p));
25224 if (hh->body==NULL) hh->body=hq; else gr_link(hp) = hq;
25228 mp_flush_token_list(mp, link(spec_head));
25229 link(spec_head)=null;
25230 mp->last_pending=spec_head
25232 @ We are now ready for the main output procedure. Note that the |selector|
25233 setting is saved in a global variable so that |begin_diagnostic| can access it.
25235 @<Declare the \ps\ output procedures@>=
25236 void mp_ship_out (MP mp, pointer h) ;
25239 @d gr_type(A) (A)->_type_field
25240 @d gr_link(A) (A)->_link_field
25241 @d gr_name_type(A) (A)->name_type_field
25242 @d gr_path_p(A) (A)->path_p_field
25243 @d gr_htap_p(A) (A)->htap_p_field
25244 @d gr_pen_p(A) (A)->pen_p_field
25245 @d gr_ljoin_val(A) (A)->ljoin_field
25246 @d gr_lcap_val(A) (A)->lcap_field
25247 @d gr_dash_scale(A) (A)->dash_scale_field
25248 @d gr_miterlim_val(A) (A)->miterlim_field
25249 @d gr_pre_script(A) (A)->pre_script_field
25250 @d gr_post_script(A) (A)->post_script_field
25251 @d gr_dash_p(A) (A)->dash_p_field
25252 @d gr_text_p(A) (A)->text_p_field
25253 @d gr_font_n(A) (A)->font_n_field
25254 @d gr_width_val(A) (A)->width_field
25255 @d gr_height_val(A) (A)->height_field
25256 @d gr_depth_val(A) (A)->depth_field
25257 @d gr_tx_val(A) (A)->tx_field
25258 @d gr_ty_val(A) (A)->ty_field
25259 @d gr_txx_val(A) (A)->txx_field
25260 @d gr_txy_val(A) (A)->txy_field
25261 @d gr_tyx_val(A) (A)->tyx_field
25262 @d gr_tyy_val(A) (A)->tyy_field
25265 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25266 pointer p; /* the current graphical object */
25267 integer t; /* a temporary value */
25268 font_number f; /* fonts used in a text node or as loop counters */
25269 struct mp_edge_object *hh; /* the first graphical object */
25270 struct mp_graphic_object *hp; /* the current graphical object */
25271 struct mp_graphic_object *hq; /* something |hp| points to */
25272 int prologues = mp->internal[mp_prologues];
25273 mp_open_output_file(mp);
25274 mp->non_ps_setting=mp->selector;
25275 mp->selector=ps_file_only;
25276 mp_set_bbox(mp, h, true);
25277 mp_print_initial_comment(mp, minx_val(h),miny_val(h),maxx_val(h),maxy_val(h));
25278 @<Unmark all marked characters@>;
25279 mp_reload_encodings(mp);
25280 @<Scan all the text nodes and mark the used characters@>;
25281 if ( prologues==two || prologues==three ) {
25282 mp_print_improved_prologue(mp, h);
25284 mp_print_prologue(mp, h);
25286 hh = mp_xmalloc(mp,1,sizeof(struct mp_edge_object));
25288 @<Export pending specials@>;
25289 p=link(dummy_loc(h));
25290 while ( p!=null ) {
25291 hq = mp_new_graphic_object(mp,type(p));
25294 gr_pen_p(hq) = mp_export_knot_list(mp,pen_p(p));
25295 if ((pen_p(p)==null) || pen_is_elliptical(pen_p(p))) {
25296 gr_path_p(hq) = mp_export_knot_list(mp,path_p(p));
25299 pc = mp_copy_path(mp, path_p(p));
25300 pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25301 gr_path_p(hq) = mp_export_knot_list(mp,pp);
25302 mp_toss_knot_list(mp, pp);
25303 pc = mp_htap_ypoc(mp, path_p(p));
25304 pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25305 gr_htap_p(hq) = mp_export_knot_list(mp,pp);
25306 mp_toss_knot_list(mp, pp);
25308 @<Export object color@>;
25309 @<Export object scripts@>;
25310 gr_ljoin_val(hq) = ljoin_val(p);
25311 gr_miterlim_val(hq) = miterlim_val(p);
25313 case mp_stroked_code:
25314 gr_pen_p(hq) = mp_export_knot_list(mp,pen_p(p));
25315 if (pen_is_elliptical(pen_p(p))) {
25316 gr_path_p(hq) = mp_export_knot_list(mp,path_p(p));
25319 pc=mp_copy_path(mp, path_p(p));
25321 if ( left_type(pc)!=mp_endpoint ) {
25322 left_type(mp_insert_knot(mp, pc,x_coord(pc),y_coord(pc)))=mp_endpoint;
25323 right_type(pc)=mp_endpoint;
25327 pc=mp_make_envelope(mp,pc,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25328 gr_path_p(hq) = mp_export_knot_list(mp,pc);
25329 mp_toss_knot_list(mp, pc);
25331 @<Export object color@>;
25332 @<Export object scripts@>;
25333 gr_ljoin_val(hq) = ljoin_val(p);
25334 gr_miterlim_val(hq) = miterlim_val(p);
25335 gr_lcap_val(hq) = lcap_val(p);
25336 gr_dash_scale(hq) = dash_scale(p);
25337 gr_dash_p(hq) = mp_export_dashes(mp,dash_p(p));
25340 gr_text_p(hq) = str(text_p(p));
25341 gr_font_n(hq) = font_n(p);
25342 @<Export object color@>;
25343 @<Export object scripts@>;
25344 gr_width_val(hq) = width_val(p);
25345 gr_height_val(hq) = height_val(p);
25346 gr_depth_val(hq) = depth_val(p);
25347 gr_tx_val(hq) = tx_val(p);
25348 gr_ty_val(hq) = ty_val(p);
25349 gr_txx_val(hq) = txx_val(p);
25350 gr_txy_val(hq) = txy_val(p);
25351 gr_tyx_val(hq) = tyx_val(p);
25352 gr_tyy_val(hq) = tyy_val(p);
25354 case mp_start_clip_code:
25355 case mp_start_bounds_code:
25356 gr_path_p(hq) = mp_export_knot_list(mp,path_p(p));
25358 case mp_stop_clip_code:
25359 case mp_stop_bounds_code:
25360 /* nothing to do here */
25363 if (hh->body==NULL) hh->body=hq; else gr_link(hp) = hq;
25367 mp_gr_ship_out (mp, hh->body);
25369 fclose(mp->ps_file);
25370 mp->selector=mp->non_ps_setting;
25371 if ( mp->internal[mp_prologues]<=0 ) mp_clear_sizes(mp);
25372 @<End progress report@>;
25373 if ( mp->internal[mp_tracing_output]>0 )
25374 mp_print_edges(mp, h," (just shipped out)",true);
25378 @d gr_color_model(A) (A)->color_model_field
25379 @d gr_red_val(A) (A)->color_field.rgb._red_val
25380 @d gr_green_val(A) (A)->color_field.rgb._green_val
25381 @d gr_blue_val(A) (A)->color_field.rgb._blue_val
25382 @d gr_cyan_val(A) (A)->color_field.cmyk._cyan_val
25383 @d gr_magenta_val(A) (A)->color_field.cmyk._magenta_val
25384 @d gr_yellow_val(A) (A)->color_field.cmyk._yellow_val
25385 @d gr_black_val(A) (A)->color_field.cmyk._black_val
25386 @d gr_grey_val(A) (A)->color_field.grey._grey_val
25388 @<Export object color@>=
25389 gr_color_model(hq) = color_model(p);
25390 gr_cyan_val(hq) = cyan_val(p);
25391 gr_magenta_val(hq) = magenta_val(p);
25392 gr_yellow_val(hq) = yellow_val(p);
25393 gr_black_val(hq) = black_val(p);
25394 gr_red_val(hq) = red_val(p);
25395 gr_green_val(hq) = green_val(p);
25396 gr_blue_val(hq) = blue_val(p);
25397 gr_grey_val(hq) = grey_val(p)
25400 @ @<Export object scripts@>=
25401 if (pre_script(p)!=null)
25402 gr_pre_script(hq) = str(pre_script(p));
25403 if (post_script(p)!=null)
25404 gr_post_script(hq) = str(post_script(p));
25406 @ @<Internal library declarations@>=
25407 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size);
25410 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size) {
25412 p=link(dummy_loc(h));
25413 while ( p!=null ) {
25414 if ( type(p)==mp_text_code ) {
25415 if ( font_n(p)!=null_font ) {
25416 if ( name_type(p)==next_size )
25417 mp_mark_string_chars(mp, font_n(p),text_p(p));
25424 @ @<Unmark all marked characters@>=
25425 for (f=null_font+1;f<=mp->last_fnum;f++) {
25426 if ( mp->font_sizes[f]!=null ) {
25427 mp_unmark_font(mp, f);
25428 mp->font_sizes[f]=null;
25432 @ @<Scan all the text nodes and mark the used ...@>=
25433 p=link(dummy_loc(h));
25434 while ( p!=null ) {
25435 if ( type(p)==mp_text_code ) {
25437 if (f!=null_font ) {
25438 switch (prologues) {
25441 mp->font_sizes[f] = mp_void;
25442 mp_mark_string_chars(mp, f,text_p(p));
25443 if (mp_has_fm_entry(mp,f,NULL) ) {
25444 if (mp->font_enc_name[f]==NULL )
25445 mp->font_enc_name[f] = mp_fm_encoding_name(mp,f);
25446 mp->font_ps_name[f] = mp_fm_font_name(mp,f);
25450 mp->font_sizes[f]=mp_void;
25453 name_type(p)=mp_size_index(mp, f,mp_choose_scale(mp, p));
25454 if ( name_type(p)==0 )
25455 mp_mark_string_chars(mp, f,text_p(p));
25462 @ Now that we've finished |ship_out|, let's look at the other commands
25463 by which a user can send things to the \.{GF} file.
25465 @ @<Determine if a character has been shipped out@>=
25467 mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25468 if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25469 boolean_reset(mp->char_exists[mp->cur_exp]);
25470 mp->cur_type=mp_boolean_type;
25476 @ @<Allocate or initialize ...@>=
25477 mp_backend_initialize(mp);
25480 mp_backend_free(mp);
25483 @* \[45] Dumping and undumping the tables.
25484 After \.{INIMP} has seen a collection of macros, it
25485 can write all the necessary information on an auxiliary file so
25486 that production versions of \MP\ are able to initialize their
25487 memory at high speed. The present section of the program takes
25488 care of such output and input. We shall consider simultaneously
25489 the processes of storing and restoring,
25490 so that the inverse relation between them is clear.
25493 The global variable |mem_ident| is a string that is printed right
25494 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25495 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25496 for example, `\.{(mem=plain 90.4.14)}', showing the year,
25497 month, and day that the mem file was created. We have |mem_ident=0|
25498 before \MP's tables are loaded.
25504 mp->mem_ident=NULL;
25506 @ @<Initialize table entries...@>=
25507 mp->mem_ident=xstrdup(" (INIMP)");
25509 @ @<Declare act...@>=
25510 void mp_store_mem_file (MP mp) ;
25512 @ @c void mp_store_mem_file (MP mp) {
25513 integer k; /* all-purpose index */
25514 pointer p,q; /* all-purpose pointers */
25515 integer x; /* something to dump */
25516 four_quarters w; /* four ASCII codes */
25518 @<Create the |mem_ident|, open the mem file,
25519 and inform the user that dumping has begun@>;
25520 @<Dump constants for consistency check@>;
25521 @<Dump the string pool@>;
25522 @<Dump the dynamic memory@>;
25523 @<Dump the table of equivalents and the hash table@>;
25524 @<Dump a few more things and the closing check word@>;
25525 @<Close the mem file@>;
25528 @ Corresponding to the procedure that dumps a mem file, we also have a function
25529 that reads~one~in. The function returns |false| if the dumped mem is
25530 incompatible with the present \MP\ table sizes, etc.
25532 @d off_base 6666 /* go here if the mem file is unacceptable */
25533 @d too_small(A) { wake_up_terminal;
25534 wterm_ln("---! Must increase the "); wterm((A));
25535 @.Must increase the x@>
25540 boolean mp_load_mem_file (MP mp) {
25541 integer k; /* all-purpose index */
25542 pointer p,q; /* all-purpose pointers */
25543 integer x; /* something undumped */
25544 str_number s; /* some temporary string */
25545 four_quarters w; /* four ASCII codes */
25547 @<Undump constants for consistency check@>;
25548 @<Undump the string pool@>;
25549 @<Undump the dynamic memory@>;
25550 @<Undump the table of equivalents and the hash table@>;
25551 @<Undump a few more things and the closing check word@>;
25552 return true; /* it worked! */
25555 wterm_ln("(Fatal mem file error; I'm stymied)\n");
25556 @.Fatal mem file error@>
25560 @ @<Declarations@>=
25561 boolean mp_load_mem_file (MP mp) ;
25563 @ Mem files consist of |memory_word| items, and we use the following
25564 macros to dump words of different types:
25566 @d dump_wd(A) { WW=(A); fwrite(&WW,sizeof(WW),1,mp->mem_file); }
25567 @d dump_int(A) { int cint=(A); fwrite(&cint,sizeof(cint),1,mp->mem_file); }
25568 @d dump_hh(A) { WW.hh=(A); fwrite(&WW,sizeof(WW),1,mp->mem_file); }
25569 @d dump_qqqq(A) { WW.qqqq=(A); fwrite(&WW,sizeof(WW),1,mp->mem_file); }
25570 @d dump_string(A) { dump_int(strlen(A)+1);
25571 fwrite(A,strlen(A)+1,1,mp->mem_file); }
25574 FILE * mem_file; /* for input or output of mem information */
25576 @ The inverse macros are slightly more complicated, since we need to check
25577 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
25578 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
25580 @d undump_wd(A) { fread(&WW,sizeof(WW),1,mp->mem_file); A=WW; }
25581 @d undump_int(A) { int cint; fread(&cint,sizeof(cint),1,mp->mem_file); A=cint; }
25582 @d undump_hh(A) { fread(&WW,sizeof(WW),1,mp->mem_file); A=WW.hh; }
25583 @d undump_qqqq(A) { fread(&WW,sizeof(WW),1,mp->mem_file); A=WW.qqqq; }
25584 @d undump_strings(A,B,C) {
25585 undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else C=str(x); }
25586 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else C=x; }
25587 @d undump_size(A,B,C,D) { undump_int(x);
25588 if (x<(A)) goto OFF_BASE;
25589 if (x>(B)) { too_small((C)); } else { D=x;} }
25590 @d undump_string(A) { integer XX=0; undump_int(XX);
25591 A = xmalloc(XX,sizeof(char));
25592 fread(A,XX,1,mp->mem_file); }
25594 @ The next few sections of the program should make it clear how we use the
25595 dump/undump macros.
25597 @<Dump constants for consistency check@>=
25598 dump_int(mp->mem_top);
25599 dump_int(mp->hash_size);
25600 dump_int(mp->hash_prime)
25601 dump_int(mp->param_size);
25602 dump_int(mp->max_in_open);
25604 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
25605 strings to the string pool; therefore \.{INIMP} and \MP\ will have
25606 the same strings. (And it is, of course, a good thing that they do.)
25610 @<Undump constants for consistency check@>=
25611 undump_int(x); mp->mem_top = x;
25612 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
25613 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
25614 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
25615 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
25617 @ We do string pool compaction to avoid dumping unused strings.
25620 w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
25621 w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
25624 @<Dump the string pool@>=
25625 mp_do_compaction(mp, mp->pool_size);
25626 dump_int(mp->pool_ptr);
25627 dump_int(mp->max_str_ptr);
25628 dump_int(mp->str_ptr);
25630 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) )
25633 while ( k<=mp->max_str_ptr ) {
25634 dump_int(mp->next_str[k]); incr(k);
25638 dump_int(mp->str_start[k]); /* TODO: valgrind warning here */
25639 if ( k==mp->str_ptr ) {
25646 while (k+4<mp->pool_ptr ) {
25647 dump_four_ASCII; k=k+4;
25649 k=mp->pool_ptr-4; dump_four_ASCII;
25650 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
25651 mp_print(mp, " strings of total length ");
25652 mp_print_int(mp, mp->pool_ptr)
25654 @ @d undump_four_ASCII
25656 mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
25657 mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
25659 @<Undump the string pool@>=
25660 undump_int(mp->pool_ptr);
25661 mp_reallocate_pool(mp, mp->pool_ptr) ;
25662 undump_int(mp->max_str_ptr);
25663 mp_reallocate_strings (mp,mp->max_str_ptr) ;
25664 undump(0,mp->max_str_ptr,mp->str_ptr);
25665 undump(0,mp->max_str_ptr+1,s);
25666 for (k=0;k<=s-1;k++)
25667 mp->next_str[k]=k+1;
25668 for (k=s;k<=mp->max_str_ptr;k++)
25669 undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
25670 mp->fixed_str_use=0;
25673 undump(0,mp->pool_ptr,mp->str_start[k]);
25674 if ( k==mp->str_ptr ) break;
25675 mp->str_ref[k]=max_str_ref;
25676 incr(mp->fixed_str_use);
25677 mp->last_fixed_str=k; k=mp->next_str[k];
25680 while ( k+4<mp->pool_ptr ) {
25681 undump_four_ASCII; k=k+4;
25683 k=mp->pool_ptr-4; undump_four_ASCII;
25684 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
25685 mp->max_pool_ptr=mp->pool_ptr;
25686 mp->strs_used_up=mp->fixed_str_use;
25687 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
25688 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
25689 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
25691 @ By sorting the list of available spaces in the variable-size portion of
25692 |mem|, we are usually able to get by without having to dump very much
25693 of the dynamic memory.
25695 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
25696 information even when it has not been gathering statistics.
25698 @<Dump the dynamic memory@>=
25699 mp_sort_avail(mp); mp->var_used=0;
25700 dump_int(mp->lo_mem_max); dump_int(mp->rover);
25701 p=0; q=mp->rover; x=0;
25703 for (k=p;k<= q+1;k++)
25704 dump_wd(mp->mem[k]);
25705 x=x+q+2-p; mp->var_used=mp->var_used+q-p;
25706 p=q+node_size(q); q=rlink(q);
25707 } while (q!=mp->rover);
25708 mp->var_used=mp->var_used+mp->lo_mem_max-p;
25709 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
25710 for (k=p;k<= mp->lo_mem_max;k++ )
25711 dump_wd(mp->mem[k]);
25712 x=x+mp->lo_mem_max+1-p;
25713 dump_int(mp->hi_mem_min); dump_int(mp->avail);
25714 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ )
25715 dump_wd(mp->mem[k]);
25716 x=x+mp->mem_end+1-mp->hi_mem_min;
25718 while ( p!=null ) {
25719 decr(mp->dyn_used); p=link(p);
25721 dump_int(mp->var_used); dump_int(mp->dyn_used);
25722 mp_print_ln(mp); mp_print_int(mp, x);
25723 mp_print(mp, " memory locations dumped; current usage is ");
25724 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
25726 @ @<Undump the dynamic memory@>=
25727 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
25728 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
25731 for (k=p;k<= q+1; k++)
25732 undump_wd(mp->mem[k]);
25734 if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) )
25737 } while (q!=mp->rover);
25738 for (k=p;k<=mp->lo_mem_max;k++ )
25739 undump_wd(mp->mem[k]);
25740 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
25741 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
25742 for (k=mp->hi_mem_min;k<= mp->mem_end;k++)
25743 undump_wd(mp->mem[k]);
25744 undump_int(mp->var_used); undump_int(mp->dyn_used)
25746 @ A different scheme is used to compress the hash table, since its lower region
25747 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
25748 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
25749 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
25751 @<Dump the table of equivalents and the hash table@>=
25752 dump_int(mp->hash_used);
25753 mp->st_count=frozen_inaccessible-1-mp->hash_used;
25754 for (p=1;p<=mp->hash_used;p++) {
25755 if ( text(p)!=0 ) {
25756 dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
25759 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
25760 dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
25762 dump_int(mp->st_count);
25763 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
25765 @ @<Undump the table of equivalents and the hash table@>=
25766 undump(1,frozen_inaccessible,mp->hash_used);
25769 undump(p+1,mp->hash_used,p);
25770 undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25771 } while (p!=mp->hash_used);
25772 for (p=mp->hash_used+1;p<=(int)hash_end;p++ ) {
25773 undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25775 undump_int(mp->st_count)
25777 @ We have already printed a lot of statistics, so we set |mp_tracing_stats:=0|
25778 to prevent them appearing again.
25780 @<Dump a few more things and the closing check word@>=
25781 dump_int(mp->max_internal);
25782 dump_int(mp->int_ptr);
25783 for (k=1;k<= mp->int_ptr;k++ ) {
25784 dump_int(mp->internal[k]);
25785 dump_string(mp->int_name[k]);
25787 dump_int(mp->start_sym);
25788 dump_int(mp->interaction);
25789 dump_string(mp->mem_ident);
25790 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
25791 mp->internal[mp_tracing_stats]=0
25793 @ @<Undump a few more things and the closing check word@>=
25795 if (x>mp->max_internal) mp_grow_internals(mp,x);
25796 undump_int(mp->int_ptr);
25797 for (k=1;k<= mp->int_ptr;k++) {
25798 undump_int(mp->internal[k]);
25799 undump_string(mp->int_name[k]);
25801 undump(0,frozen_inaccessible,mp->start_sym);
25802 if (mp->interaction==mp_unspecified_mode) {
25803 undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
25805 undump(mp_unspecified_mode,mp_error_stop_mode,x);
25807 undump_string(mp->mem_ident);
25808 undump(1,hash_end,mp->bg_loc);
25809 undump(1,hash_end,mp->eg_loc);
25810 undump_int(mp->serial_no);
25812 if ( (x!=69073)|| feof(mp->mem_file) ) goto OFF_BASE
25814 @ @<Create the |mem_ident|...@>=
25816 xfree(mp->mem_ident);
25817 mp->mem_ident = xmalloc(256,1);
25818 snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)",
25820 (int)(mp_round_unscaled(mp, mp->internal[mp_year]) % 100),
25821 (int)mp_round_unscaled(mp, mp->internal[mp_month]),
25822 (int)mp_round_unscaled(mp, mp->internal[mp_day]));
25823 mp_pack_job_name(mp, mem_extension);
25824 while (! mp_w_open_out(mp, &mp->mem_file) )
25825 mp_prompt_file_name(mp, "mem file name", mem_extension);
25826 mp_print_nl(mp, "Beginning to dump on file ");
25827 @.Beginning to dump...@>
25828 mp_print(mp, mp->name_of_file);
25829 mp_print_nl(mp, mp->mem_ident);
25832 @ @<Dealloc variables@>=
25833 xfree(mp->mem_ident);
25835 @ @<Close the mem file@>=
25836 fclose(mp->mem_file)
25838 @* \[46] The main program.
25839 This is it: the part of \MP\ that executes all those procedures we have
25842 Well---almost. We haven't put the parsing subroutines into the
25843 program yet; and we'd better leave space for a few more routines that may
25844 have been forgotten.
25846 @c @<Declare the basic parsing subroutines@>;
25847 @<Declare miscellaneous procedures that were declared |forward|@>;
25848 @<Last-minute procedures@>
25850 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
25852 has to be run first; it initializes everything from scratch, without
25853 reading a mem file, and it has the capability of dumping a mem file.
25854 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
25856 to input a mem file in order to get started. \.{VIRMP} typically has
25857 a bit more memory capacity than \.{INIMP}, because it does not need the
25858 space consumed by the dumping/undumping routines and the numerous calls on
25861 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
25862 the best implementations therefore allow for production versions of \MP\ that
25863 not only avoid the loading routine for \PASCAL\ object code, they also have
25864 a mem file pre-loaded.
25867 boolean ini_version; /* are we iniMP? */
25869 @ @<Option variables@>=
25870 int ini_version; /* are we iniMP? */
25872 @ @<Set |ini_version|@>=
25873 mp->ini_version = (opt->ini_version ? true : false);
25875 @ Here we do whatever is needed to complete \MP's job gracefully on the
25876 local operating system. The code here might come into play after a fatal
25877 error; it must therefore consist entirely of ``safe'' operations that
25878 cannot produce error messages. For example, it would be a mistake to call
25879 |str_room| or |make_string| at this time, because a call on |overflow|
25880 might lead to an infinite loop.
25881 @^system dependencies@>
25883 This program doesn't bother to close the input files that may still be open.
25885 @<Last-minute...@>=
25886 void mp_close_files_and_terminate (MP mp) {
25887 integer k; /* all-purpose index */
25888 integer LH; /* the length of the \.{TFM} header, in words */
25889 int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
25890 pointer p; /* runs through a list of \.{TFM} dimensions */
25891 @<Close all open files in the |rd_file| and |wr_file| arrays@>;
25892 if ( mp->internal[mp_tracing_stats]>0 )
25893 @<Output statistics about this job@>;
25895 @<Do all the finishing work on the \.{TFM} file@>;
25896 @<Explain what output files were written@>;
25897 if ( mp->log_opened ){
25899 fclose(mp->log_file); mp->selector=mp->selector-2;
25900 if ( mp->selector==term_only ) {
25901 mp_print_nl(mp, "Transcript written on ");
25902 @.Transcript written...@>
25903 mp_print(mp, mp->log_name); mp_print_char(mp, '.');
25909 @ @<Declarations@>=
25910 void mp_close_files_and_terminate (MP mp) ;
25912 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
25913 if (mp->rd_fname!=NULL) {
25914 for (k=0;k<=(int)mp->read_files-1;k++ ) {
25915 if ( mp->rd_fname[k]!=NULL ) {
25916 fclose(mp->rd_file[k]);
25920 if (mp->wr_fname!=NULL) {
25921 for (k=0;k<=(int)mp->write_files-1;k++) {
25922 if ( mp->wr_fname[k]!=NULL ) {
25923 fclose(mp->wr_file[k]);
25929 for (k=0;k<(int)mp->max_read_files;k++ ) {
25930 if ( mp->rd_fname[k]!=NULL ) {
25931 fclose(mp->rd_file[k]);
25932 mp_xfree(mp->rd_fname[k]);
25935 mp_xfree(mp->rd_file);
25936 mp_xfree(mp->rd_fname);
25937 for (k=0;k<(int)mp->max_write_files;k++) {
25938 if ( mp->wr_fname[k]!=NULL ) {
25939 fclose(mp->wr_file[k]);
25940 mp_xfree(mp->wr_fname[k]);
25943 mp_xfree(mp->wr_file);
25944 mp_xfree(mp->wr_fname);
25947 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
25949 We reclaim all of the variable-size memory at this point, so that
25950 there is no chance of another memory overflow after the memory capacity
25951 has already been exceeded.
25953 @<Do all the finishing work on the \.{TFM} file@>=
25954 if ( mp->internal[mp_fontmaking]>0 ) {
25955 @<Make the dynamic memory into one big available node@>;
25956 @<Massage the \.{TFM} widths@>;
25957 mp_fix_design_size(mp); mp_fix_check_sum(mp);
25958 @<Massage the \.{TFM} heights, depths, and italic corrections@>;
25959 mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
25960 @<Finish the \.{TFM} file@>;
25963 @ @<Make the dynamic memory into one big available node@>=
25964 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
25965 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
25966 node_size(mp->rover)=mp->lo_mem_max-mp->rover;
25967 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
25968 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
25970 @ The present section goes directly to the log file instead of using
25971 |print| commands, because there's no need for these strings to take
25972 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
25974 @<Output statistics...@>=
25975 if ( mp->log_opened ) {
25978 wlog_ln("Here is how much of MetaPost's memory you used:");
25979 @.Here is how much...@>
25980 snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
25981 (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
25982 (int)(mp->max_strings-1-mp->init_str_use));
25984 snprintf(s,128," %i string characters out of %i",
25985 (int)mp->max_pl_used-mp->init_pool_ptr,
25986 (int)mp->pool_size-mp->init_pool_ptr);
25988 snprintf(s,128," %i words of memory out of %i",
25989 (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
25990 (int)mp->mem_end+1);
25992 snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
25994 snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
25995 (int)mp->max_in_stack,(int)mp->int_ptr,
25996 (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
25997 (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
25999 snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
26000 (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
26004 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
26007 @<Last-minute...@>=
26008 void mp_final_cleanup (MP mp) {
26009 small_number c; /* 0 for \&{end}, 1 for \&{dump} */
26011 if ( mp->job_name==NULL ) mp_open_log_file(mp);
26012 while ( mp->input_ptr>0 ) {
26013 if ( token_state ) mp_end_token_list(mp);
26014 else mp_end_file_reading(mp);
26016 while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
26017 while ( mp->open_parens>0 ) {
26018 mp_print(mp, " )"); decr(mp->open_parens);
26020 while ( mp->cond_ptr!=null ) {
26021 mp_print_nl(mp, "(end occurred when ");
26022 @.end occurred...@>
26023 mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
26024 /* `\.{if}' or `\.{elseif}' or `\.{else}' */
26025 if ( mp->if_line!=0 ) {
26026 mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
26028 mp_print(mp, " was incomplete)");
26029 mp->if_line=if_line_field(mp->cond_ptr);
26030 mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
26032 if ( mp->history!=mp_spotless )
26033 if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
26034 if ( mp->selector==term_and_log ) {
26035 mp->selector=term_only;
26036 mp_print_nl(mp, "(see the transcript file for additional information)");
26037 @.see the transcript file...@>
26038 mp->selector=term_and_log;
26041 if (mp->ini_version) {
26042 mp_store_mem_file(mp); return;
26044 mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
26045 @.dump...only by INIMP@>
26049 @ @<Declarations@>=
26050 void mp_final_cleanup (MP mp) ;
26051 void mp_init_prim (MP mp) ;
26052 void mp_init_tab (MP mp) ;
26054 @ @<Last-minute...@>=
26055 void mp_init_prim (MP mp) { /* initialize all the primitives */
26059 void mp_init_tab (MP mp) { /* initialize other tables */
26060 integer k; /* all-purpose index */
26061 @<Initialize table entries (done by \.{INIMP} only)@>;
26065 @ When we begin the following code, \MP's tables may still contain garbage;
26066 the strings might not even be present. Thus we must proceed cautiously to get
26069 But when we finish this part of the program, \MP\ is ready to call on the
26070 |main_control| routine to do its work.
26072 @<Get the first line...@>=
26074 @<Initialize the input routines@>;
26075 if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
26076 if ( mp->mem_ident!=NULL ) {
26077 mp_do_initialize(mp); /* erase preloaded mem */
26079 if ( ! mp_open_mem_file(mp) ) return mp_fatal_error_stop;
26080 if ( ! mp_load_mem_file(mp) ) {
26081 fclose( mp->mem_file); return mp_fatal_error_stop;
26083 fclose( mp->mem_file);
26084 while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
26086 mp->buffer[limit]='%';
26087 mp_fix_date_and_time(mp);
26088 mp->sys_random_seed = (scaled)(mp->get_random_seed)(mp);
26089 mp_init_randoms(mp, mp->sys_random_seed);
26090 @<Initialize the print |selector|...@>;
26091 if ( loc<limit ) if ( mp->buffer[loc]!='\\' )
26092 mp_start_input(mp); /* \&{input} assumed */
26095 @ @<Run inimpost commands@>=
26097 mp_get_strings_started(mp);
26098 mp_init_tab(mp); /* initialize the tables */
26099 mp_init_prim(mp); /* call |primitive| for each primitive */
26100 mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
26101 mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
26102 mp_fix_date_and_time(mp);
26106 @* \[47] Debugging.
26107 Once \MP\ is working, you should be able to diagnose most errors with
26108 the \.{show} commands and other diagnostic features. But for the initial
26109 stages of debugging, and for the revelation of really deep mysteries, you
26110 can compile \MP\ with a few more aids, including the \PASCAL\ runtime
26111 checks and its debugger. An additional routine called |debug_help|
26112 will also come into play when you type `\.D' after an error message;
26113 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
26115 @^system dependencies@>
26117 The interface to |debug_help| is primitive, but it is good enough when used
26118 with a \PASCAL\ debugger that allows you to set breakpoints and to read
26119 variables and change their values. After getting the prompt `\.{debug \#}', you
26120 type either a negative number (this exits |debug_help|), or zero (this
26121 goes to a location where you can set a breakpoint, thereby entering into
26122 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
26123 an argument |n|. The meaning of |m| and |n| will be clear from the
26124 program below. (If |m=13|, there is an additional argument, |l|.)
26127 @<Last-minute...@>=
26128 void mp_debug_help (MP mp) { /* routine to display various things */
26133 mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
26136 fscanf(mp->term_in,"%i",&m);
26140 fscanf(mp->term_in,"%i",&n);
26142 @<Numbered cases for |debug_help|@>;
26143 default: mp_print(mp, "?"); break;
26148 @ @<Numbered cases...@>=
26149 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
26151 case 2: mp_print_int(mp, info(n));
26153 case 3: mp_print_int(mp, link(n));
26155 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
26157 case 5: mp_print_variable_name(mp, n);
26159 case 6: mp_print_int(mp, mp->internal[n]);
26161 case 7: mp_do_show_dependencies(mp);
26163 case 9: mp_show_token_list(mp, n,null,100000,0);
26165 case 10: mp_print_str(mp, n);
26167 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
26169 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26171 case 13: l = 0; fscanf(mp->term_in,"%i",&l); mp_print_cmd_mod(mp, n,l);
26173 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26175 case 15: mp->panicking=! mp->panicking;
26179 @ Saving the filename template
26181 @<Save the filename template@>=
26183 if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26184 if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26186 mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26190 @* \[48] System-dependent changes.
26191 This section should be replaced, if necessary, by any special
26192 modification of the program
26193 that are necessary to make \MP\ work at a particular installation.
26194 It is usually best to design your change file so that all changes to
26195 previous sections preserve the section numbering; then everybody's version
26196 will be consistent with the published program. More extensive changes,
26197 which introduce new sections, can be inserted here; then only the index
26198 itself will get a new section number.
26199 @^system dependencies@>
26202 Here is where you can find all uses of each identifier in the program,
26203 with underlined entries pointing to where the identifier was defined.
26204 If the identifier is only one letter long, however, you get to see only
26205 the underlined entries. {\sl All references are to section numbers instead of
26208 This index also lists error messages and other aspects of the program
26209 that you might want to look up some day. For example, the entry
26210 for ``system dependencies'' lists all sections that should receive
26211 special attention from people who are installing \MP\ in a new
26212 operating environment. A list of various things that can't happen appears
26213 under ``this can't happen''.
26214 Approximately 25 sections are listed under ``inner loop''; these account
26215 for more than 60\pct! of \MP's running time, exclusive of input and output.