3 % Copyright 2008 Taco Hoekwater.
5 % This program is free software: you can redistribute it and/or modify
6 % it under the terms of the GNU General Public License as published by
7 % the Free Software Foundation, either version 2 of the License, or
8 % (at your option) any later version.
10 % This program is distributed in the hope that it will be useful,
11 % but WITHOUT ANY WARRANTY; without even the implied warranty of
12 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 % GNU General Public License for more details.
15 % You should have received a copy of the GNU General Public License
16 % along with this program. If not, see <http://www.gnu.org/licenses/>.
18 % TeX is a trademark of the American Mathematical Society.
19 % METAFONT is a trademark of Addison-Wesley Publishing Company.
20 % PostScript is a trademark of Adobe Systems Incorporated.
22 % Here is TeX material that gets inserted after \input webmac
23 \def\hang{\hangindent 3em\noindent\ignorespaces}
24 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
26 \def\psqrt#1{\sqrt{\mathstrut#1}}
28 \def\pct!{{\char`\%}} % percent sign in ordinary text
29 \font\tenlogo=logo10 % font used for the METAFONT logo
31 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
32 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
33 \def\[#1]{\ignorespaces} % left over from pascal web
34 \def\<#1>{$\langle#1\rangle$}
35 \def\section{\mathhexbox278}
36 \let\swap=\leftrightarrow
37 \def\round{\mathop{\rm round}\nolimits}
38 \mathchardef\vb="026A % synonym for `\|'
40 \def\(#1){} % this is used to make section names sort themselves better
41 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
48 This is \MP\ by John Hobby, a graphics-language processor based on D. E. Knuth's \MF.
50 Much of the original Pascal version of this program was copied with
51 permission from MF.web Version 1.9. It interprets a language very
52 similar to D.E. Knuth's METAFONT, but with changes designed to make it
53 more suitable for PostScript output.
55 The main purpose of the following program is to explain the algorithms of \MP\
56 as clearly as possible. However, the program has been written so that it
57 can be tuned to run efficiently in a wide variety of operating environments
58 by making comparatively few changes. Such flexibility is possible because
59 the documentation that follows is written in the \.{WEB} language, which is
60 at a higher level than C.
62 A large piece of software like \MP\ has inherent complexity that cannot
63 be reduced below a certain level of difficulty, although each individual
64 part is fairly simple by itself. The \.{WEB} language is intended to make
65 the algorithms as readable as possible, by reflecting the way the
66 individual program pieces fit together and by providing the
67 cross-references that connect different parts. Detailed comments about
68 what is going on, and about why things were done in certain ways, have
69 been liberally sprinkled throughout the program. These comments explain
70 features of the implementation, but they rarely attempt to explain the
71 \MP\ language itself, since the reader is supposed to be familiar with
72 {\sl The {\logos METAFONT\/}book} as well as the manual
74 @:METAFONTbook}{\sl The {\logos METAFONT\/}book}@>
75 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
76 AT\AM T Bell Laboratories.
78 @ The present implementation is a preliminary version, but the possibilities
79 for new features are limited by the desire to remain as nearly compatible
80 with \MF\ as possible.
82 On the other hand, the \.{WEB} description can be extended without changing
83 the core of the program, and it has been designed so that such
84 extensions are not extremely difficult to make.
85 The |banner| string defined here should be changed whenever \MP\
86 undergoes any modifications, so that it will be clear which version of
87 \MP\ might be the guilty party when a problem arises.
89 @^system dependencies@>
91 @d default_banner "This is MetaPost, Version 1.086" /* printed when \MP\ starts */
96 #define metapost_version "1.086"
97 #define metapost_magic (('M'*256) + 'P')*65536 + 1086
99 @ The external library header for \MP\ is |mplib.h|. It contains a
100 few typedefs and the header defintions for the externally used
103 The most important of the typedefs is the definition of the structure
104 |MP_options|, that acts as a small, configurable front-end to the fairly
105 large |MP_instance| structure.
108 typedef struct MP_instance * MP;
110 typedef struct MP_options {
113 @<Exported function headers@>
115 @ The internal header file is much longer: it not only lists the complete
116 |MP_instance|, but also a lot of functions that have to be available to
117 the \ps\ backend, that is defined in a separate \.{WEB} file.
119 The variables from |MP_options| are included inside the |MP_instance|
124 typedef struct psout_data_struct * psout_data;
132 @<Types in the outer block@>
133 @<Constants in the outer block@>
134 # ifndef LIBAVL_ALLOCATOR
135 # define LIBAVL_ALLOCATOR
136 struct libavl_allocator {
137 void *(*libavl_malloc) (struct libavl_allocator *, size_t libavl_size);
138 void (*libavl_free) (struct libavl_allocator *, void *libavl_block);
141 typedef struct MP_instance {
145 @<Internal library declarations@>
155 #include <unistd.h> /* for access() */
157 #include <time.h> /* for struct tm \& co */
159 #include "psout.h" /* external header */
160 #include "mpmp.h" /* internal header */
161 #include "mppsout.h" /* internal header */
162 extern font_number mp_read_font_info (MP mp, char *fname); /* tfmin.w */
165 @<Basic printing procedures@>
166 @<Error handling procedures@>
168 @ Here are the functions that set up the \MP\ instance.
171 MP_options *mp_options (void);
172 MP mp_initialize (MP_options *opt);
175 MP_options *mp_options (void) {
177 size_t l = sizeof(MP_options);
181 opt->ini_version = true;
186 @ @<Internal library declarations@>=
187 @<Declare subroutines for parsing file names@>
189 @ The whole instance structure is initialized with zeroes,
190 this greatly reduces the number of statements needed in
191 the |Allocate or initialize variables| block.
193 @d set_callback_option(A) do { mp->A = mp_##A;
194 if (opt->A!=NULL) mp->A = opt->A;
198 static MP mp_do_new (jmp_buf *buf) {
199 MP mp = malloc(sizeof(MP_instance));
204 memset(mp,0,sizeof(MP_instance));
210 static void mp_free (MP mp) {
211 int k; /* loop variable */
212 @<Dealloc variables@>
213 if (mp->noninteractive) {
214 @<Finish non-interactive use@>;
221 static void mp_do_initialize ( MP mp) {
222 @<Local variables for initialization@>
223 @<Set initial values of key variables@>
226 @ This procedure gets things started properly.
228 MP mp_initialize (MP_options *opt) {
230 jmp_buf *buf = malloc(sizeof(jmp_buf));
231 if (buf == NULL || setjmp(*buf) != 0)
236 mp->userdata=opt->userdata;
237 @<Set |ini_version|@>;
238 mp->noninteractive=opt->noninteractive;
239 set_callback_option(find_file);
240 set_callback_option(open_file);
241 set_callback_option(read_ascii_file);
242 set_callback_option(read_binary_file);
243 set_callback_option(close_file);
244 set_callback_option(eof_file);
245 set_callback_option(flush_file);
246 set_callback_option(write_ascii_file);
247 set_callback_option(write_binary_file);
248 set_callback_option(shipout_backend);
249 if (opt->banner && *(opt->banner)) {
250 mp->banner = xstrdup(opt->banner);
252 mp->banner = xstrdup(default_banner);
254 if (opt->command_line && *(opt->command_line))
255 mp->command_line = xstrdup(opt->command_line);
256 if (mp->noninteractive) {
257 @<Prepare function pointers for non-interactive use@>;
259 /* open the terminal for output */
261 @<Find constant sizes@>;
262 @<Allocate or initialize variables@>
263 mp_reallocate_memory(mp,mp->mem_max);
264 mp_reallocate_paths(mp,1000);
265 mp_reallocate_fonts(mp,8);
266 mp->history=mp_fatal_error_stop; /* in case we quit during initialization */
267 @<Check the ``constant'' values...@>;
270 mp_snprintf(ss,256,"Ouch---my internal constants have been clobbered!\n"
271 "---case %i",(int)mp->bad);
272 do_fprintf(mp->err_out,(char *)ss);
276 mp_do_initialize(mp); /* erase preloaded mem */
277 if (mp->ini_version) {
278 @<Run inimpost commands@>;
280 if (!mp->noninteractive) {
281 @<Initialize the output routines@>;
282 @<Get the first line of input and prepare to start@>;
283 @<Initializations after first line is read@>;
285 mp->history=mp_spotless;
290 @ @<Initializations after first line is read@>=
292 mp_init_map_file(mp, mp->troff_mode);
293 mp->history=mp_spotless; /* ready to go! */
294 if (mp->troff_mode) {
295 mp->internal[mp_gtroffmode]=unity;
296 mp->internal[mp_prologues]=unity;
298 if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
299 mp->cur_sym=mp->start_sym; mp_back_input(mp);
302 @ @<Exported function headers@>=
303 extern MP_options *mp_options (void);
304 extern MP mp_initialize (MP_options *opt) ;
305 extern int mp_status(MP mp);
306 extern void *mp_userdata(MP mp);
309 int mp_status(MP mp) { return mp->history; }
312 void *mp_userdata(MP mp) { return mp->userdata; }
314 @ The overall \MP\ program begins with the heading just shown, after which
315 comes a bunch of procedure declarations and function declarations.
316 Finally we will get to the main program, which begins with the
317 comment `|start_here|'. If you want to skip down to the
318 main program now, you can look up `|start_here|' in the index.
319 But the author suggests that the best way to understand this program
320 is to follow pretty much the order of \MP's components as they appear in the
321 \.{WEB} description you are now reading, since the present ordering is
322 intended to combine the advantages of the ``bottom up'' and ``top down''
323 approaches to the problem of understanding a somewhat complicated system.
325 @ Some of the code below is intended to be used only when diagnosing the
326 strange behavior that sometimes occurs when \MP\ is being installed or
327 when system wizards are fooling around with \MP\ without quite knowing
328 what they are doing. Such code will not normally be compiled; it is
329 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
331 @ This program has two important variations: (1) There is a long and slow
332 version called \.{INIMP}, which does the extra calculations needed to
334 initialize \MP's internal tables; and (2)~there is a shorter and faster
335 production version, which cuts the initialization to a bare minimum.
337 Which is which is decided at runtime.
339 @ The following parameters can be changed at compile time to extend or
340 reduce \MP's capacity. They may have different values in \.{INIMP} and
341 in production versions of \MP.
343 @^system dependencies@>
346 #define file_name_size 255 /* file names shouldn't be longer than this */
347 #define bistack_size 1500 /* size of stack for bisection algorithms;
348 should probably be left at this value */
350 @ Like the preceding parameters, the following quantities can be changed
351 to extend or reduce \MP's capacity. But if they are changed,
352 it is necessary to rerun the initialization program \.{INIMP}
354 to generate new tables for the production \MP\ program.
355 One can't simply make helter-skelter changes to the following constants,
356 since certain rather complex initialization
357 numbers are computed from them.
360 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
361 int pool_size; /* maximum number of characters in strings, including all
362 error messages and help texts, and the names of all identifiers */
363 int mem_max; /* greatest index in \MP's internal |mem| array;
364 must be strictly less than |max_halfword|;
365 must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
366 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
367 must not be greater than |mem_max| */
368 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
370 @ @<Option variables@>=
371 int error_line; /* width of context lines on terminal error messages */
372 int half_error_line; /* width of first lines of contexts in terminal
373 error messages; should be between 30 and |error_line-15| */
374 int max_print_line; /* width of longest text lines output; should be at least 60 */
375 unsigned hash_size; /* maximum number of symbolic tokens,
376 must be less than |max_halfword-3*param_size| */
377 int param_size; /* maximum number of simultaneous macro parameters */
378 int max_in_open; /* maximum number of input files and error insertions that
379 can be going on simultaneously */
380 int main_memory; /* only for options, to set up |mem_max| and |mem_top| */
381 void *userdata; /* this allows the calling application to setup local */
382 char *banner; /* the banner that is printed to the screen and log */
384 @ @<Dealloc variables@>=
388 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
393 set_value(mp->error_line,opt->error_line,79);
394 set_value(mp->half_error_line,opt->half_error_line,50);
395 if (mp->half_error_line>mp->error_line-15 )
396 mp->half_error_line = mp->error_line-15;
397 set_value(mp->max_print_line,opt->max_print_line,100);
399 @ In case somebody has inadvertently made bad settings of the ``constants,''
400 \MP\ checks them using a global variable called |bad|.
402 This is the second of many sections of \MP\ where global variables are
406 integer bad; /* is some ``constant'' wrong? */
408 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
409 or something similar. (We can't do that until |max_halfword| has been defined.)
411 In case you are wondering about the non-consequtive values of |bad|: some
412 of the things that used to be WEB constants are now runtime variables
413 with checking at assignment time.
415 @<Check the ``constant'' values for consistency@>=
417 if ( mp->mem_top<=1100 ) mp->bad=4;
419 @ Some |goto| labels are used by the following definitions. The label
420 `|restart|' is occasionally used at the very beginning of a procedure; and
421 the label `|reswitch|' is occasionally used just prior to a |case|
422 statement in which some cases change the conditions and we wish to branch
423 to the newly applicable case. Loops that are set up with the |loop|
424 construction defined below are commonly exited by going to `|done|' or to
425 `|found|' or to `|not_found|', and they are sometimes repeated by going to
426 `|continue|'. If two or more parts of a subroutine start differently but
427 end up the same, the shared code may be gathered together at
430 @ Here are some macros for common programming idioms.
432 @d incr(A) (A)=(A)+1 /* increase a variable by unity */
433 @d decr(A) (A)=(A)-1 /* decrease a variable by unity */
434 @d negate(A) (A)=-(A) /* change the sign of a variable */
435 @d double(A) (A)=(A)+(A)
437 @d do_nothing /* empty statement */
439 @* \[2] The character set.
440 In order to make \MP\ readily portable to a wide variety of
441 computers, all of its input text is converted to an internal eight-bit
442 code that includes standard ASCII, the ``American Standard Code for
443 Information Interchange.'' This conversion is done immediately when each
444 character is read in. Conversely, characters are converted from ASCII to
445 the user's external representation just before they are output to a
449 Such an internal code is relevant to users of \MP\ only with respect to
450 the \&{char} and \&{ASCII} operations, and the comparison of strings.
452 @ Characters of text that have been converted to \MP's internal form
453 are said to be of type |ASCII_code|, which is a subrange of the integers.
456 typedef unsigned char ASCII_code; /* eight-bit numbers */
458 @ The present specification of \MP\ has been written under the assumption
459 that the character set contains at least the letters and symbols associated
460 with ASCII codes 040 through 0176; all of these characters are now
461 available on most computer terminals.
464 typedef unsigned char text_char; /* the data type of characters in text files */
466 @ @<Local variables for init...@>=
469 @ The \MP\ processor converts between ASCII code and
470 the user's external character set by means of arrays |xord| and |xchr|
471 that are analogous to Pascal's |ord| and |chr| functions.
474 #define xchr(A) mp->xchr[(A)]
475 #define xord(A) mp->xord[(A)]
478 ASCII_code xord[256]; /* specifies conversion of input characters */
479 text_char xchr[256]; /* specifies conversion of output characters */
481 @ The core system assumes all 8-bit is acceptable. If it is not,
482 a change file has to alter the below section.
483 @^system dependencies@>
485 Additionally, people with extended character sets can
486 assign codes arbitrarily, giving an |xchr| equivalent to whatever
487 characters the users of \MP\ are allowed to have in their input files.
488 Appropriate changes to \MP's |char_class| table should then be made.
489 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
490 codes, called the |char_class|.) Such changes make portability of programs
491 more difficult, so they should be introduced cautiously if at all.
492 @^character set dependencies@>
493 @^system dependencies@>
496 for (i=0;i<=0377;i++) { xchr(i)=(text_char)i; }
498 @ The following system-independent code makes the |xord| array contain a
499 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
500 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
501 |j| or more; hence, standard ASCII code numbers will be used instead of
502 codes below 040 in case there is a coincidence.
505 for (i=0;i<=255;i++) {
508 for (i=0200;i<=0377;i++) { xord(xchr(i))=(ASCII_code)i;}
509 for (i=0;i<=0176;i++) { xord(xchr(i))=(ASCII_code)i;}
511 @* \[3] Input and output.
512 The bane of portability is the fact that different operating systems treat
513 input and output quite differently, perhaps because computer scientists
514 have not given sufficient attention to this problem. People have felt somehow
515 that input and output are not part of ``real'' programming. Well, it is true
516 that some kinds of programming are more fun than others. With existing
517 input/output conventions being so diverse and so messy, the only sources of
518 joy in such parts of the code are the rare occasions when one can find a
519 way to make the program a little less bad than it might have been. We have
520 two choices, either to attack I/O now and get it over with, or to postpone
521 I/O until near the end. Neither prospect is very attractive, so let's
524 The basic operations we need to do are (1)~inputting and outputting of
525 text, to or from a file or the user's terminal; (2)~inputting and
526 outputting of eight-bit bytes, to or from a file; (3)~instructing the
527 operating system to initiate (``open'') or to terminate (``close'') input or
528 output from a specified file; (4)~testing whether the end of an input
529 file has been reached; (5)~display of bits on the user's screen.
530 The bit-display operation will be discussed in a later section; we shall
531 deal here only with more traditional kinds of I/O.
533 @ Finding files happens in a slightly roundabout fashion: the \MP\
534 instance object contains a field that holds a function pointer that finds a
535 file, and returns its name, or NULL. For this, it receives three
536 parameters: the non-qualified name |fname|, the intended |fopen|
537 operation type |fmode|, and the type of the file |ftype|.
539 The file types that are passed on in |ftype| can be used to
540 differentiate file searches if a library like kpathsea is used,
541 the fopen mode is passed along for the same reason.
544 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
546 @ @<Exported types@>=
548 mp_filetype_terminal = 0, /* the terminal */
549 mp_filetype_error, /* the terminal */
550 mp_filetype_program , /* \MP\ language input */
551 mp_filetype_log, /* the log file */
552 mp_filetype_postscript, /* the postscript output */
553 mp_filetype_memfile, /* memory dumps */
554 mp_filetype_metrics, /* TeX font metric files */
555 mp_filetype_fontmap, /* PostScript font mapping files */
556 mp_filetype_font, /* PostScript type1 font programs */
557 mp_filetype_encoding, /* PostScript font encoding files */
558 mp_filetype_text /* first text file for readfrom and writeto primitives */
560 typedef char *(*mp_file_finder)(MP, const char *, const char *, int);
561 typedef void *(*mp_file_opener)(MP, const char *, const char *, int);
562 typedef char *(*mp_file_reader)(MP, void *, size_t *);
563 typedef void (*mp_binfile_reader)(MP, void *, void **, size_t *);
564 typedef void (*mp_file_closer)(MP, void *);
565 typedef int (*mp_file_eoftest)(MP, void *);
566 typedef void (*mp_file_flush)(MP, void *);
567 typedef void (*mp_file_writer)(MP, void *, const char *);
568 typedef void (*mp_binfile_writer)(MP, void *, void *, size_t);
570 @ @<Option variables@>=
571 mp_file_finder find_file;
572 mp_file_opener open_file;
573 mp_file_reader read_ascii_file;
574 mp_binfile_reader read_binary_file;
575 mp_file_closer close_file;
576 mp_file_eoftest eof_file;
577 mp_file_flush flush_file;
578 mp_file_writer write_ascii_file;
579 mp_binfile_writer write_binary_file;
581 @ The default function for finding files is |mp_find_file|. It is
582 pretty stupid: it will only find files in the current directory.
584 This function may disappear altogether, it is currently only
585 used for the default font map file.
588 static char *mp_find_file (MP mp, const char *fname, const char *fmode, int ftype) {
590 if (fmode[0] != 'r' || (! access (fname,R_OK)) || ftype) {
591 return mp_strdup(fname);
596 @ Because |mp_find_file| is used so early, it has to be in the helpers
600 static char *mp_find_file (MP mp, const char *fname, const char *fmode, int ftype) ;
601 static void *mp_open_file (MP mp , const char *fname, const char *fmode, int ftype) ;
602 static char *mp_read_ascii_file (MP mp, void *f, size_t *size) ;
603 static void mp_read_binary_file (MP mp, void *f, void **d, size_t *size) ;
604 static void mp_close_file (MP mp, void *f) ;
605 static int mp_eof_file (MP mp, void *f) ;
606 static void mp_flush_file (MP mp, void *f) ;
607 static void mp_write_ascii_file (MP mp, void *f, const char *s) ;
608 static void mp_write_binary_file (MP mp, void *f, void *s, size_t t) ;
610 @ The function to open files can now be very short.
613 void *mp_open_file(MP mp, const char *fname, const char *fmode, int ftype) {
616 realmode[0] = *fmode;
619 if (ftype==mp_filetype_terminal) {
620 return (fmode[0] == 'r' ? stdin : stdout);
621 } else if (ftype==mp_filetype_error) {
623 } else if (fname != NULL && (fmode[0] != 'r' || (! access (fname,R_OK)))) {
624 return (void *)fopen(fname, realmode);
629 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
632 char name_of_file[file_name_size+1]; /* the name of a system file */
633 int name_length;/* this many characters are actually
634 relevant in |name_of_file| (the rest are blank) */
636 @ @<Option variables@>=
637 int print_found_names; /* configuration parameter */
639 @ If this parameter is true, the terminal and log will report the found
640 file names for input files instead of the requested ones.
641 It is off by default because it creates an extra filename lookup.
643 @<Allocate or initialize ...@>=
644 mp->print_found_names = (opt->print_found_names>0 ? true : false);
646 @ \MP's file-opening procedures return |false| if no file identified by
647 |name_of_file| could be opened.
649 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
650 It is not used for opening a mem file for read, because that file name
654 if (mp->print_found_names) {
655 char *s = (mp->find_file)(mp,mp->name_of_file,A,ftype);
657 *f = (mp->open_file)(mp,mp->name_of_file,A, ftype);
658 strncpy(mp->name_of_file,s,file_name_size);
664 *f = (mp->open_file)(mp,mp->name_of_file,A, ftype);
667 return (*f ? true : false)
670 static boolean mp_a_open_in (MP mp, void **f, int ftype) {
671 /* open a text file for input */
675 boolean mp_w_open_in (MP mp, void **f) {
676 /* open a word file for input */
677 *f = (mp->open_file)(mp,mp->name_of_file,"r",mp_filetype_memfile);
678 return (*f ? true : false);
681 static boolean mp_a_open_out (MP mp, void **f, int ftype) {
682 /* open a text file for output */
686 static boolean mp_b_open_out (MP mp, void **f, int ftype) {
687 /* open a binary file for output */
691 boolean mp_w_open_out (MP mp, void **f) {
692 /* open a word file for output */
693 int ftype = mp_filetype_memfile;
697 @ @<Internal library ...@>=
698 boolean mp_w_open_out (MP mp, void **f);
701 static char *mp_read_ascii_file (MP mp, void *ff, size_t *size) {
703 size_t len = 0, lim = 128;
705 FILE *f = (FILE *)ff;
707 (void) mp; /* for -Wunused */
714 if (s==NULL) return NULL;
715 while (c!=EOF && c!='\n' && c!='\r') {
717 s =realloc(s, (lim+(lim>>2)));
718 if (s==NULL) return NULL;
726 if (c!=EOF && c!='\n')
735 void mp_write_ascii_file (MP mp, void *f, const char *s) {
743 void mp_read_binary_file (MP mp, void *f, void **data, size_t *size) {
747 len = fread(*data,1,*size,(FILE *)f);
752 void mp_write_binary_file (MP mp, void *f, void *s, size_t size) {
755 (void)fwrite(s,size,1,(FILE *)f);
760 void mp_close_file (MP mp, void *f) {
767 int mp_eof_file (MP mp, void *f) {
770 return feof((FILE *)f);
776 void mp_flush_file (MP mp, void *f) {
782 @ Input from text files is read one line at a time, using a routine called
783 |input_ln|. This function is defined in terms of global variables called
784 |buffer|, |first|, and |last| that will be described in detail later; for
785 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
786 values, and that |first| and |last| are indices into this array
787 representing the beginning and ending of a line of text.
790 size_t buf_size; /* maximum number of characters simultaneously present in
791 current lines of open files */
792 ASCII_code *buffer; /* lines of characters being read */
793 size_t first; /* the first unused position in |buffer| */
794 size_t last; /* end of the line just input to |buffer| */
795 size_t max_buf_stack; /* largest index used in |buffer| */
797 @ @<Allocate or initialize ...@>=
799 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
801 @ @<Dealloc variables@>=
805 static void mp_reallocate_buffer(MP mp, size_t l) {
807 if (l>max_halfword) {
808 mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
810 buffer = xmalloc((l+1),sizeof(ASCII_code));
811 memcpy(buffer,mp->buffer,(mp->buf_size+1));
813 mp->buffer = buffer ;
817 @ The |input_ln| function brings the next line of input from the specified
818 field into available positions of the buffer array and returns the value
819 |true|, unless the file has already been entirely read, in which case it
820 returns |false| and sets |last:=first|. In general, the |ASCII_code|
821 numbers that represent the next line of the file are input into
822 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
823 global variable |last| is set equal to |first| plus the length of the
824 line. Trailing blanks are removed from the line; thus, either |last=first|
825 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
828 The variable |max_buf_stack|, which is used to keep track of how large
829 the |buf_size| parameter must be to accommodate the present job, is
830 also kept up to date by |input_ln|.
833 static boolean mp_input_ln (MP mp, void *f ) {
834 /* inputs the next line or returns |false| */
837 mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
838 s = (mp->read_ascii_file)(mp,f, &size);
842 mp->last = mp->first+size;
843 if ( mp->last>=mp->max_buf_stack ) {
844 mp->max_buf_stack=mp->last+1;
845 while ( mp->max_buf_stack>=mp->buf_size ) {
846 mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
849 memcpy((mp->buffer+mp->first),s,size);
850 /* while ( mp->buffer[mp->last]==' ' ) mp->last--; */
856 @ The user's terminal acts essentially like other files of text, except
857 that it is used both for input and for output. When the terminal is
858 considered an input file, the file variable is called |term_in|, and when it
859 is considered an output file the file variable is |term_out|.
860 @^system dependencies@>
863 void * term_in; /* the terminal as an input file */
864 void * term_out; /* the terminal as an output file */
865 void * err_out; /* the terminal as an output file */
867 @ Here is how to open the terminal files. In the default configuration,
868 nothing happens except that the command line (if there is one) is copied
869 to the input buffer. The variable |command_line| will be filled by the
870 |main| procedure. The copying can not be done earlier in the program
871 logic because in the |INI| version, the |buffer| is also used for primitive
874 @d t_open_out do {/* open the terminal for text output */
875 mp->term_out = (mp->open_file)(mp,"terminal", "w", mp_filetype_terminal);
876 mp->err_out = (mp->open_file)(mp,"error", "w", mp_filetype_error);
878 @d t_open_in do { /* open the terminal for text input */
879 mp->term_in = (mp->open_file)(mp,"terminal", "r", mp_filetype_terminal);
880 if (mp->command_line!=NULL) {
881 mp->last = strlen(mp->command_line);
882 strncpy((char *)mp->buffer,mp->command_line,mp->last);
883 xfree(mp->command_line);
889 @<Option variables@>=
892 @ Sometimes it is necessary to synchronize the input/output mixture that
893 happens on the user's terminal, and three system-dependent
894 procedures are used for this
895 purpose. The first of these, |update_terminal|, is called when we want
896 to make sure that everything we have output to the terminal so far has
897 actually left the computer's internal buffers and been sent.
898 The second, |clear_terminal|, is called when we wish to cancel any
899 input that the user may have typed ahead (since we are about to
900 issue an unexpected error message). The third, |wake_up_terminal|,
901 is supposed to revive the terminal if the user has disabled it by
902 some instruction to the operating system. The following macros show how
903 these operations can be specified:
904 @^system dependencies@>
907 #define update_terminal (mp->flush_file)(mp,mp->term_out) /* empty the terminal output buffer */
908 #define clear_terminal do_nothing /* clear the terminal input buffer */
909 #define wake_up_terminal (mp->flush_file)(mp,mp->term_out)
910 /* cancel the user's cancellation of output */
912 @ We need a special routine to read the first line of \MP\ input from
913 the user's terminal. This line is different because it is read before we
914 have opened the transcript file; there is sort of a ``chicken and
915 egg'' problem here. If the user types `\.{input cmr10}' on the first
916 line, or if some macro invoked by that line does such an \.{input},
917 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
918 commands are performed during the first line of terminal input, the transcript
919 file will acquire its default name `\.{mpout.log}'. (The transcript file
920 will not contain error messages generated by the first line before the
921 first \.{input} command.)
923 The first line is even more special. It's nice to let the user start
924 running a \MP\ job by typing a command line like `\.{MP cmr10}'; in
925 such a case, \MP\ will operate as if the first line of input were
926 `\.{cmr10}', i.e., the first line will consist of the remainder of the
927 command line, after the part that invoked \MP.
929 @ Different systems have different ways to get started. But regardless of
930 what conventions are adopted, the routine that initializes the terminal
931 should satisfy the following specifications:
933 \yskip\textindent{1)}It should open file |term_in| for input from the
934 terminal. (The file |term_out| will already be open for output to the
937 \textindent{2)}If the user has given a command line, this line should be
938 considered the first line of terminal input. Otherwise the
939 user should be prompted with `\.{**}', and the first line of input
940 should be whatever is typed in response.
942 \textindent{3)}The first line of input, which might or might not be a
943 command line, should appear in locations |first| to |last-1| of the
946 \textindent{4)}The global variable |loc| should be set so that the
947 character to be read next by \MP\ is in |buffer[loc]|. This
948 character should not be blank, and we should have |loc<last|.
950 \yskip\noindent(It may be necessary to prompt the user several times
951 before a non-blank line comes in. The prompt is `\.{**}' instead of the
952 later `\.*' because the meaning is slightly different: `\.{input}' need
953 not be typed immediately after~`\.{**}'.)
955 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
958 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
961 loc = 0; mp->first = 0;
965 if (!mp->noninteractive) {
966 wake_up_terminal; do_fprintf(mp->term_out,"**"); update_terminal;
969 if ( ! mp_input_ln(mp, mp->term_in ) ) { /* this shouldn't happen */
970 do_fprintf(mp->term_out,"\n! End of file on the terminal... why?");
971 @.End of file on the terminal@>
974 loc=(halfword)mp->first;
975 while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') )
977 if ( loc<(int)mp->last ) {
978 return true; /* return unless the line was all blank */
980 if (!mp->noninteractive) {
981 do_fprintf(mp->term_out,"Please type the name of your input file.\n");
987 static boolean mp_init_terminal (MP mp) ;
990 @* \[4] String handling.
991 Symbolic token names and diagnostic messages are variable-length strings
992 of eight-bit characters. Many strings \MP\ uses are simply literals
993 in the compiled source, like the error messages and the names of the
994 internal parameters. Other strings are used or defined from the \MP\ input
995 language, and these have to be interned.
997 \MP\ uses strings more extensively than \MF\ does, but the necessary
998 operations can still be handled with a fairly simple data structure.
999 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
1000 of the strings, and the array |str_start| contains indices of the starting
1001 points of each string. Strings are referred to by integer numbers, so that
1002 string number |s| comprises the characters |str_pool[j]| for
1003 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|. The string pool
1004 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
1005 location. The first string number not currently in use is |str_ptr|
1006 and |next_str[str_ptr]| begins a list of free string numbers. String
1007 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
1008 string currently being constructed.
1010 String numbers 0 to 255 are reserved for strings that correspond to single
1011 ASCII characters. This is in accordance with the conventions of \.{WEB},
1013 which converts single-character strings into the ASCII code number of the
1014 single character involved, while it converts other strings into integers
1015 and builds a string pool file. Thus, when the string constant \.{"."} appears
1016 in the program below, \.{WEB} converts it into the integer 46, which is the
1017 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
1018 into some integer greater than~255. String number 46 will presumably be the
1019 single character `\..'\thinspace; but some ASCII codes have no standard visible
1020 representation, and \MP\ may need to be able to print an arbitrary
1021 ASCII character, so the first 256 strings are used to specify exactly what
1022 should be printed for each of the 256 possibilities.
1025 typedef int pool_pointer; /* for variables that point into |str_pool| */
1026 typedef int str_number; /* for variables that point into |str_start| */
1029 ASCII_code *str_pool; /* the characters */
1030 pool_pointer *str_start; /* the starting pointers */
1031 str_number *next_str; /* for linking strings in order */
1032 pool_pointer pool_ptr; /* first unused position in |str_pool| */
1033 str_number str_ptr; /* number of the current string being created */
1034 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
1035 str_number init_str_use; /* the initial number of strings in use */
1036 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
1037 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
1039 @ @<Allocate or initialize ...@>=
1040 mp->str_pool = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
1041 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
1042 mp->next_str = xmalloc ((mp->max_strings+1),sizeof(str_number));
1044 @ @<Dealloc variables@>=
1045 xfree(mp->str_pool);
1046 xfree(mp->str_start);
1047 xfree(mp->next_str);
1049 @ Most printing is done from |char *|s, but sometimes not. Here are
1050 functions that convert an internal string into a |char *| for use
1051 by the printing routines, and vice versa.
1053 @d str(A) mp_str(mp,A)
1054 @d rts(A) mp_rts(mp,A)
1058 int mp_xstrcmp (const char *a, const char *b);
1059 char * mp_str (MP mp, str_number s);
1062 static str_number mp_rts (MP mp, const char *s);
1063 static str_number mp_make_string (MP mp);
1066 int mp_xstrcmp (const char *a, const char *b) {
1067 if (a==NULL && b==NULL)
1076 @ The attempt to catch interrupted strings that is in |mp_rts|, is not
1077 very good: it does not handle nesting over more than one level.
1080 char * mp_str (MP mp, str_number ss) {
1083 if (ss==mp->str_ptr) {
1086 len = (size_t)length(ss);
1087 s = xmalloc(len+1,sizeof(char));
1088 strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1093 str_number mp_rts (MP mp, const char *s) {
1094 int r; /* the new string */
1095 int old; /* a possible string in progress */
1099 } else if (strlen(s)==1) {
1103 str_room((integer)strlen(s));
1104 if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1105 old = mp_make_string(mp);
1110 r = mp_make_string(mp);
1112 str_room(length(old));
1113 while (i<length(old)) {
1114 append_char((mp->str_start[old]+i));
1116 mp_flush_string(mp,old);
1122 @ Except for |strs_used_up|, the following string statistics are only
1123 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1127 integer strs_used_up; /* strings in use or unused but not reclaimed */
1128 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1129 integer strs_in_use; /* total number of strings actually in use */
1130 integer max_pl_used; /* maximum |pool_in_use| so far */
1131 integer max_strs_used; /* maximum |strs_in_use| so far */
1133 @ Several of the elementary string operations are performed using \.{WEB}
1134 macros instead of functions, because many of the
1135 operations are done quite frequently and we want to avoid the
1136 overhead of procedure calls. For example, here is
1137 a simple macro that computes the length of a string.
1140 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string \# */
1141 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1143 @ The length of the current string is called |cur_length|. If we decide that
1144 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1145 |cur_length| becomes zero.
1147 @d cur_length (mp->pool_ptr - mp->str_start[mp->str_ptr])
1148 @d flush_cur_string mp->pool_ptr=mp->str_start[mp->str_ptr]
1150 @ Strings are created by appending character codes to |str_pool|.
1151 The |append_char| macro, defined here, does not check to see if the
1152 value of |pool_ptr| has gotten too high; this test is supposed to be
1153 made before |append_char| is used.
1155 To test if there is room to append |l| more characters to |str_pool|,
1156 we shall write |str_room(l)|, which tries to make sure there is enough room
1157 by compacting the string pool if necessary. If this does not work,
1158 |do_compaction| aborts \MP\ and gives an apologetic error message.
1160 @d append_char(A) /* put |ASCII_code| \# at the end of |str_pool| */
1161 { mp->str_pool[mp->pool_ptr]=(ASCII_code)(A); incr(mp->pool_ptr);
1163 @d str_room(A) /* make sure that the pool hasn't overflowed */
1164 { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1165 if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1166 else mp->max_pool_ptr=mp->pool_ptr+(A); }
1169 @ The following routine is similar to |str_room(1)| but it uses the
1170 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1171 string space is exhausted.
1174 static void mp_unit_str_room (MP mp);
1177 void mp_unit_str_room (MP mp) {
1178 if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1179 if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1182 @ \MP's string expressions are implemented in a brute-force way: Every
1183 new string or substring that is needed is simply copied into the string pool.
1184 Space is eventually reclaimed by a procedure called |do_compaction| with
1185 the aid of a simple system system of reference counts.
1186 @^reference counts@>
1188 The number of references to string number |s| will be |str_ref[s]|. The
1189 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1190 positive number of references; such strings will never be recycled. If
1191 a string is ever referred to more than 126 times, simultaneously, we
1192 put it in this category. Hence a single byte suffices to store each |str_ref|.
1194 @d max_str_ref 127 /* ``infinite'' number of references */
1195 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]); }
1200 @ @<Allocate or initialize ...@>=
1201 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1203 @ @<Dealloc variables@>=
1206 @ Here's what we do when a string reference disappears:
1208 @d delete_str_ref(A) {
1209 if ( mp->str_ref[(A)]<max_str_ref ) {
1210 if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]);
1211 else mp_flush_string(mp, (A));
1216 static void mp_flush_string (MP mp,str_number s) ;
1218 @ We can't flush the first set of static strings at all, so there
1219 is no point in trying
1222 void mp_flush_string (MP mp,str_number s) {
1224 mp->pool_in_use=mp->pool_in_use-length(s);
1225 decr(mp->strs_in_use);
1226 if ( mp->next_str[s]!=mp->str_ptr ) {
1230 decr(mp->strs_used_up);
1232 mp->pool_ptr=mp->str_start[mp->str_ptr];
1236 @ C literals cannot be simply added, they need to be set so they can't
1239 @d intern(A) mp_intern(mp,(A))
1242 str_number mp_intern (MP mp, const char *s) {
1245 mp->str_ref[r] = max_str_ref;
1250 static str_number mp_intern (MP mp, const char *s);
1253 @ Once a sequence of characters has been appended to |str_pool|, it
1254 officially becomes a string when the function |make_string| is called.
1255 This function returns the identification number of the new string as its
1258 When getting the next unused string number from the linked list, we pretend
1260 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1261 are linked sequentially even though the |next_str| entries have not been
1262 initialized yet. We never allow |str_ptr| to reach |mp->max_strings|;
1263 |do_compaction| is responsible for making sure of this.
1266 static str_number mp_make_string (MP mp);
1269 str_number mp_make_string (MP mp) { /* current string enters the pool */
1270 str_number s; /* the new string */
1273 mp->str_ptr=mp->next_str[s];
1274 if ( mp->str_ptr>mp->max_str_ptr ) {
1275 if ( mp->str_ptr==mp->max_strings ) {
1277 mp_do_compaction(mp, 0);
1280 mp->max_str_ptr=mp->str_ptr;
1281 mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1285 mp->str_start[mp->str_ptr]=mp->pool_ptr;
1286 incr(mp->strs_used_up);
1287 incr(mp->strs_in_use);
1288 mp->pool_in_use=mp->pool_in_use+length(s);
1289 if ( mp->pool_in_use>mp->max_pl_used )
1290 mp->max_pl_used=mp->pool_in_use;
1291 if ( mp->strs_in_use>mp->max_strs_used )
1292 mp->max_strs_used=mp->strs_in_use;
1296 @ The most interesting string operation is string pool compaction. The idea
1297 is to recover unused space in the |str_pool| array by recopying the strings
1298 to close the gaps created when some strings become unused. All string
1299 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1300 numbers after |str_ptr|. If this fails to free enough pool space we issue an
1301 |overflow| error unless |needed=mp->pool_size|. Calling |do_compaction|
1302 with |needed=mp->pool_size| supresses all overflow tests.
1304 The compaction process starts with |last_fixed_str| because all lower numbered
1305 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1308 str_number last_fixed_str; /* last permanently allocated string */
1309 str_number fixed_str_use; /* number of permanently allocated strings */
1311 @ @<Internal library ...@>=
1312 void mp_do_compaction (MP mp, pool_pointer needed) ;
1315 void mp_do_compaction (MP mp, pool_pointer needed) {
1316 str_number str_use; /* a count of strings in use */
1317 str_number r,s,t; /* strings being manipulated */
1318 pool_pointer p,q; /* destination and source for copying string characters */
1319 @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1320 r=mp->last_fixed_str;
1323 while ( s!=mp->str_ptr ) {
1324 while ( mp->str_ref[s]==0 ) {
1325 @<Advance |s| and add the old |s| to the list of free string numbers;
1326 then |break| if |s=str_ptr|@>;
1328 r=s; s=mp->next_str[s];
1330 @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1331 after the end of the string@>;
1334 @<Move the current string back so that it starts at |p|@>;
1335 if ( needed<mp->pool_size ) {
1336 @<Make sure that there is room for another string with |needed| characters@>;
1338 @<Account for the compaction and make sure the statistics agree with the
1340 mp->strs_used_up=str_use;
1343 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1344 t=mp->next_str[mp->last_fixed_str];
1345 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1346 incr(mp->fixed_str_use);
1347 mp->last_fixed_str=t;
1350 str_use=mp->fixed_str_use
1352 @ Because of the way |flush_string| has been written, it should never be
1353 necessary to |break| here. The extra line of code seems worthwhile to
1354 preserve the generality of |do_compaction|.
1356 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1361 mp->next_str[t]=mp->next_str[mp->str_ptr];
1362 mp->next_str[mp->str_ptr]=t;
1363 if ( s==mp->str_ptr ) goto DONE;
1366 @ The string currently starts at |str_start[r]| and ends just before
1367 |str_start[s]|. We don't change |str_start[s]| because it might be needed
1368 to locate the next string.
1370 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1373 while ( q<mp->str_start[s] ) {
1374 mp->str_pool[p]=mp->str_pool[q];
1378 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated. When
1379 we do this, anything between them should be moved.
1381 @ @<Move the current string back so that it starts at |p|@>=
1382 q=mp->str_start[mp->str_ptr];
1383 mp->str_start[mp->str_ptr]=p;
1384 while ( q<mp->pool_ptr ) {
1385 mp->str_pool[p]=mp->str_pool[q];
1390 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1392 @<Make sure that there is room for another string with |needed| char...@>=
1393 if ( str_use>=mp->max_strings-1 )
1394 mp_reallocate_strings (mp,str_use);
1395 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1396 mp_reallocate_pool(mp, mp->pool_ptr+needed);
1397 mp->max_pool_ptr=mp->pool_ptr+needed;
1400 @ @<Internal library ...@>=
1401 void mp_reallocate_strings (MP mp, str_number str_use) ;
1402 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1405 void mp_reallocate_strings (MP mp, str_number str_use) {
1406 while ( str_use>=mp->max_strings-1 ) {
1407 int l = mp->max_strings + (mp->max_strings/4);
1408 XREALLOC (mp->str_ref, l, int);
1409 XREALLOC (mp->str_start, l, pool_pointer);
1410 XREALLOC (mp->next_str, l, str_number);
1411 mp->max_strings = l;
1414 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1415 while ( needed>mp->pool_size ) {
1416 int l = mp->pool_size + (mp->pool_size/4);
1417 XREALLOC (mp->str_pool, l, ASCII_code);
1422 @ @<Account for the compaction and make sure the statistics agree with...@>=
1423 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1424 mp_confusion(mp, "string");
1425 @:this can't happen string}{\quad string@>
1426 incr(mp->pact_count);
1427 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1428 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1430 @ A few more global variables are needed to keep track of statistics when
1431 |stat| $\ldots$ |tats| blocks are not commented out.
1434 integer pact_count; /* number of string pool compactions so far */
1435 integer pact_chars; /* total number of characters moved during compactions */
1436 integer pact_strs; /* total number of strings moved during compactions */
1438 @ @<Initialize compaction statistics@>=
1443 @ The following subroutine compares string |s| with another string of the
1444 same length that appears in |buffer| starting at position |k|;
1445 the result is |true| if and only if the strings are equal.
1448 static boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1449 /* test equality of strings */
1450 pool_pointer j; /* running index */
1452 while ( j<str_stop(s) ) {
1453 if ( mp->str_pool[j++]!=mp->buffer[k++] )
1459 @ Here is a similar routine, but it compares two strings in the string pool,
1460 and it does not assume that they have the same length. If the first string
1461 is lexicographically greater than, less than, or equal to the second,
1462 the result is respectively positive, negative, or zero.
1465 static integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1466 /* test equality of strings */
1467 pool_pointer j,k; /* running indices */
1468 integer ls,lt; /* lengths */
1469 integer l; /* length remaining to test */
1470 ls=length(s); lt=length(t);
1471 if ( ls<=lt ) l=ls; else l=lt;
1472 j=mp->str_start[s]; k=mp->str_start[t];
1474 if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1475 return (mp->str_pool[j]-mp->str_pool[k]);
1482 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1483 and |str_ptr| are computed by the \.{INIMP} program, based in part
1484 on the information that \.{WEB} has output while processing \MP.
1489 void mp_get_strings_started (MP mp) {
1490 /* initializes the string pool,
1491 but returns |false| if something goes wrong */
1492 int k; /* small indices or counters */
1493 str_number g; /* a new string */
1494 mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1497 mp->pool_in_use=0; mp->strs_in_use=0;
1498 mp->max_pl_used=0; mp->max_strs_used=0;
1499 @<Initialize compaction statistics@>;
1501 @<Make the first 256 strings@>;
1502 g=mp_make_string(mp); /* string 256 == "" */
1503 mp->str_ref[g]=max_str_ref;
1504 mp->last_fixed_str=mp->str_ptr-1;
1505 mp->fixed_str_use=mp->str_ptr;
1510 static void mp_get_strings_started (MP mp);
1512 @ The first 256 strings will consist of a single character only.
1514 @<Make the first 256...@>=
1515 for (k=0;k<=255;k++) {
1517 g=mp_make_string(mp);
1518 mp->str_ref[g]=max_str_ref;
1521 @ The first 128 strings will contain 95 standard ASCII characters, and the
1522 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1523 unless a system-dependent change is made here. Installations that have
1524 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1525 would like string 032 to be printed as the single character 032 instead
1526 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1527 even people with an extended character set will want to represent string
1528 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1529 to produce visible strings instead of tabs or line-feeds or carriage-returns
1530 or bell-rings or characters that are treated anomalously in text files.
1532 The boolean expression defined here should be |true| unless \MP\ internal
1533 code number~|k| corresponds to a non-troublesome visible symbol in the
1534 local character set.
1535 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1536 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1538 @^character set dependencies@>
1539 @^system dependencies@>
1541 @<Character |k| cannot be printed@>=
1544 @* \[5] On-line and off-line printing.
1545 Messages that are sent to a user's terminal and to the transcript-log file
1546 are produced by several `|print|' procedures. These procedures will
1547 direct their output to a variety of places, based on the setting of
1548 the global variable |selector|, which has the following possible
1552 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1555 \hang |log_only|, prints only on the transcript file.
1557 \hang |term_only|, prints only on the terminal.
1559 \hang |no_print|, doesn't print at all. This is used only in rare cases
1560 before the transcript file is open.
1562 \hang |pseudo|, puts output into a cyclic buffer that is used
1563 by the |show_context| routine; when we get to that routine we shall discuss
1564 the reasoning behind this curious mode.
1566 \hang |new_string|, appends the output to the current string in the
1569 \hang |>=write_file| prints on one of the files used for the \&{write}
1570 @:write_}{\&{write} primitive@>
1574 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1575 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1576 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|. These
1577 relations are not used when |selector| could be |pseudo|, or |new_string|.
1578 We need not check for unprintable characters when |selector<pseudo|.
1580 Three additional global variables, |tally|, |term_offset| and |file_offset|
1581 record the number of characters that have been printed
1582 since they were most recently cleared to zero. We use |tally| to record
1583 the length of (possibly very long) stretches of printing; |term_offset|,
1584 and |file_offset|, on the other hand, keep track of how many
1585 characters have appeared so far on the current line that has been output
1586 to the terminal, the transcript file, or the \ps\ output file, respectively.
1588 @d new_string 0 /* printing is deflected to the string pool */
1589 @d pseudo 2 /* special |selector| setting for |show_context| */
1590 @d no_print 3 /* |selector| setting that makes data disappear */
1591 @d term_only 4 /* printing is destined for the terminal only */
1592 @d log_only 5 /* printing is destined for the transcript file only */
1593 @d term_and_log 6 /* normal |selector| setting */
1594 @d write_file 7 /* first write file selector */
1597 void * log_file; /* transcript of \MP\ session */
1598 void * ps_file; /* the generic font output goes here */
1599 unsigned int selector; /* where to print a message */
1600 unsigned char dig[23]; /* digits in a number, for rounding */
1601 integer tally; /* the number of characters recently printed */
1602 unsigned int term_offset;
1603 /* the number of characters on the current terminal line */
1604 unsigned int file_offset;
1605 /* the number of characters on the current file line */
1606 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1607 integer trick_count; /* threshold for pseudoprinting, explained later */
1608 integer first_count; /* another variable for pseudoprinting */
1610 @ @<Allocate or initialize ...@>=
1611 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1613 @ @<Dealloc variables@>=
1614 xfree(mp->trick_buf);
1616 @ @<Initialize the output routines@>=
1617 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0;
1619 @ Macro abbreviations for output to the terminal and to the log file are
1620 defined here for convenience. Some systems need special conventions
1621 for terminal output, and it is possible to adhere to those conventions
1622 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1623 @^system dependencies@>
1626 #define do_fprintf(f,b) (mp->write_ascii_file)(mp,f,b)
1627 #define wterm(A) do_fprintf(mp->term_out,(A))
1628 #define wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]='\0'; wterm((char *)ss);}
1629 #define wterm_cr do_fprintf(mp->term_out,"\n")
1630 #define wterm_ln(A) { wterm_cr; do_fprintf(mp->term_out,(A)); }
1631 #define wlog(A) do_fprintf(mp->log_file,(A))
1632 #define wlog_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]='\0'; wlog((char *)ss);}
1633 #define wlog_cr do_fprintf(mp->log_file, "\n")
1634 #define wlog_ln(A) { wlog_cr; do_fprintf(mp->log_file,(A)); }
1637 @ To end a line of text output, we call |print_ln|. Cases |0..max_write_files|
1638 use an array |wr_file| that will be declared later.
1640 @d mp_print_text(A) mp_print_str(mp,text((A)))
1642 @<Internal library ...@>=
1643 void mp_print (MP mp, const char *s);
1644 void mp_print_ln (MP mp);
1645 void mp_print_visible_char (MP mp, ASCII_code s);
1646 void mp_print_char (MP mp, ASCII_code k);
1647 void mp_print_str (MP mp, str_number s);
1648 void mp_print_nl (MP mp, const char *s);
1649 void mp_print_two (MP mp,scaled x, scaled y) ;
1650 void mp_print_scaled (MP mp,scaled s);
1652 @ @<Basic print...@>=
1653 void mp_print_ln (MP mp) { /* prints an end-of-line */
1654 switch (mp->selector) {
1657 mp->term_offset=0; mp->file_offset=0;
1660 wlog_cr; mp->file_offset=0;
1663 wterm_cr; mp->term_offset=0;
1670 do_fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1672 } /* note that |tally| is not affected */
1674 @ The |print_visible_char| procedure sends one character to the desired
1675 destination, using the |xchr| array to map it into an external character
1676 compatible with |input_ln|. (It assumes that it is always called with
1677 a visible ASCII character.) All printing comes through |print_ln| or
1678 |print_char|, which ultimately calls |print_visible_char|, hence these
1679 routines are the ones that limit lines to at most |max_print_line| characters.
1680 But we must make an exception for the \ps\ output file since it is not safe
1681 to cut up lines arbitrarily in \ps.
1683 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1684 |do_compaction| and |do_compaction| can call the error routines. Actually,
1685 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1687 @<Basic printing...@>=
1688 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1689 switch (mp->selector) {
1691 wterm_chr(xchr(s)); wlog_chr(xchr(s));
1692 incr(mp->term_offset); incr(mp->file_offset);
1693 if ( mp->term_offset==(unsigned)mp->max_print_line ) {
1694 wterm_cr; mp->term_offset=0;
1696 if ( mp->file_offset==(unsigned)mp->max_print_line ) {
1697 wlog_cr; mp->file_offset=0;
1701 wlog_chr(xchr(s)); incr(mp->file_offset);
1702 if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1705 wterm_chr(xchr(s)); incr(mp->term_offset);
1706 if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1711 if ( mp->tally<mp->trick_count )
1712 mp->trick_buf[mp->tally % mp->error_line]=s;
1715 if ( mp->pool_ptr>=mp->max_pool_ptr ) {
1716 mp_unit_str_room(mp);
1717 if ( mp->pool_ptr>=mp->pool_size )
1718 goto DONE; /* drop characters if string space is full */
1723 { text_char ss[2]; ss[0] = xchr(s); ss[1]=0;
1724 do_fprintf(mp->wr_file[(mp->selector-write_file)],(char *)ss);
1731 @ The |print_char| procedure sends one character to the desired destination.
1732 File names and string expressions might contain |ASCII_code| values that
1733 can't be printed using |print_visible_char|. These characters will be
1734 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1735 (This procedure assumes that it is safe to bypass all checks for unprintable
1736 characters when |selector| is in the range |0..max_write_files-1|.
1737 The user might want to write unprintable characters.
1739 @<Basic printing...@>=
1740 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1741 if ( mp->selector<pseudo || mp->selector>=write_file) {
1742 mp_print_visible_char(mp, k);
1743 } else if ( @<Character |k| cannot be printed@> ) {
1746 mp_print_visible_char(mp, k+0100);
1747 } else if ( k<0200 ) {
1748 mp_print_visible_char(mp, k-0100);
1750 int l; /* small index or counter */
1752 mp_print_visible_char(mp, xord(l<10 ? l+'0' : l-10+'a'));
1754 mp_print_visible_char(mp, xord(l<10 ? l+'0' : l-10+'a'));
1757 mp_print_visible_char(mp, k);
1761 @ An entire string is output by calling |print|. Note that if we are outputting
1762 the single standard ASCII character \.c, we could call |print("c")|, since
1763 |"c"=99| is the number of a single-character string, as explained above. But
1764 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1765 routine when it knows that this is safe. (The present implementation
1766 assumes that it is always safe to print a visible ASCII character.)
1767 @^system dependencies@>
1770 static void mp_do_print (MP mp, const char *ss, size_t len) { /* prints string |s| */
1773 mp_print_char(mp, xord((int)ss[j])); j++;
1779 void mp_print (MP mp, const char *ss) {
1780 if (ss==NULL) return;
1781 mp_do_print(mp, ss,strlen(ss));
1783 void mp_print_str (MP mp, str_number s) {
1784 pool_pointer j; /* current character code position */
1785 if ( (s<0)||(s>mp->max_str_ptr) ) {
1786 mp_do_print(mp,"???",3); /* this can't happen */
1790 mp_do_print(mp, (char *)(mp->str_pool+j), (size_t)(str_stop(s)-j));
1794 @ Here is the very first thing that \MP\ prints: a headline that identifies
1795 the version number and base name. The |term_offset| variable is temporarily
1796 incorrect, but the discrepancy is not serious since we assume that the banner
1797 and mem identifier together will occupy at most |max_print_line|
1798 character positions.
1800 @<Initialize the output...@>=
1802 if (mp->mem_ident!=NULL)
1803 mp_print(mp,mp->mem_ident);
1807 @ The procedure |print_nl| is like |print|, but it makes sure that the
1808 string appears at the beginning of a new line.
1811 void mp_print_nl (MP mp, const char *s) { /* prints string |s| at beginning of line */
1812 switch(mp->selector) {
1814 if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1817 if ( mp->file_offset>0 ) mp_print_ln(mp);
1820 if ( mp->term_offset>0 ) mp_print_ln(mp);
1826 } /* there are no other cases */
1830 @ The following procedure, which prints out the decimal representation of a
1831 given integer |n|, assumes that all integers fit nicely into a |int|.
1832 @^system dependencies@>
1835 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1837 mp_snprintf(s,12,"%d", (int)n);
1841 @ @<Internal library ...@>=
1842 void mp_print_int (MP mp,integer n);
1844 @ \MP\ also makes use of a trivial procedure to print two digits. The
1845 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1848 static void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1850 mp_print_char(mp, xord('0'+(n / 10)));
1851 mp_print_char(mp, xord('0'+(n % 10)));
1856 static void mp_print_dd (MP mp,integer n);
1858 @ Here is a procedure that asks the user to type a line of input,
1859 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1860 The input is placed into locations |first| through |last-1| of the
1861 |buffer| array, and echoed on the transcript file if appropriate.
1863 This procedure is never called when |interaction<mp_scroll_mode|.
1865 @d prompt_input(A) do {
1866 if (!mp->noninteractive) {
1867 wake_up_terminal; mp_print(mp, (A));
1870 } while (0) /* prints a string and gets a line of input */
1873 void mp_term_input (MP mp) { /* gets a line from the terminal */
1874 size_t k; /* index into |buffer| */
1875 if (mp->noninteractive) {
1876 if (!mp_input_ln(mp, mp->term_in ))
1877 longjmp(*(mp->jump_buf),1); /* chunk finished */
1878 mp->buffer[mp->last]=xord('%');
1880 update_terminal; /* Now the user sees the prompt for sure */
1881 if (!mp_input_ln(mp, mp->term_in )) {
1882 mp_fatal_error(mp, "End of file on the terminal!");
1883 @.End of file on the terminal@>
1885 mp->term_offset=0; /* the user's line ended with \<\rm return> */
1886 decr(mp->selector); /* prepare to echo the input */
1887 if ( mp->last!=mp->first ) {
1888 for (k=mp->first;k<=mp->last-1;k++) {
1889 mp_print_char(mp, mp->buffer[k]);
1893 mp->buffer[mp->last]=xord('%');
1894 incr(mp->selector); /* restore previous status */
1898 @* \[6] Reporting errors.
1899 When something anomalous is detected, \MP\ typically does something like this:
1900 $$\vbox{\halign{#\hfil\cr
1901 |print_err("Something anomalous has been detected");|\cr
1902 |help3("This is the first line of my offer to help.")|\cr
1903 |("This is the second line. I'm trying to")|\cr
1904 |("explain the best way for you to proceed.");|\cr
1906 A two-line help message would be given using |help2|, etc.; these informal
1907 helps should use simple vocabulary that complements the words used in the
1908 official error message that was printed. (Outside the U.S.A., the help
1909 messages should preferably be translated into the local vernacular. Each
1910 line of help is at most 60 characters long, in the present implementation,
1911 so that |max_print_line| will not be exceeded.)
1913 The |print_err| procedure supplies a `\.!' before the official message,
1914 and makes sure that the terminal is awake if a stop is going to occur.
1915 The |error| procedure supplies a `\..' after the official message, then it
1916 shows the location of the error; and if |interaction=error_stop_mode|,
1917 it also enters into a dialog with the user, during which time the help
1918 message may be printed.
1919 @^system dependencies@>
1921 @ The global variable |interaction| has four settings, representing increasing
1922 amounts of user interaction:
1925 enum mp_interaction_mode {
1926 mp_unspecified_mode=0, /* extra value for command-line switch */
1927 mp_batch_mode, /* omits all stops and omits terminal output */
1928 mp_nonstop_mode, /* omits all stops */
1929 mp_scroll_mode, /* omits error stops */
1930 mp_error_stop_mode /* stops at every opportunity to interact */
1933 @ @<Option variables@>=
1934 int interaction; /* current level of interaction */
1935 int noninteractive; /* do we have a terminal? */
1937 @ Set it here so it can be overwritten by the commandline
1939 @<Allocate or initialize ...@>=
1940 mp->interaction=opt->interaction;
1941 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode)
1942 mp->interaction=mp_error_stop_mode;
1943 if (mp->interaction<mp_unspecified_mode)
1944 mp->interaction=mp_batch_mode;
1948 @d print_err(A) mp_print_err(mp,(A))
1951 void mp_print_err(MP mp, const char * A);
1954 void mp_print_err(MP mp, const char * A) {
1955 if ( mp->interaction==mp_error_stop_mode )
1957 mp_print_nl(mp, "! ");
1963 @ \MP\ is careful not to call |error| when the print |selector| setting
1964 might be unusual. The only possible values of |selector| at the time of
1967 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1968 and |log_file| not yet open);
1970 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1972 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1974 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1976 @<Initialize the print |selector| based on |interaction|@>=
1977 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1979 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1980 routine is active when |error| is called; this ensures that |get_next|
1981 will never be called recursively.
1984 The global variable |history| records the worst level of error that
1985 has been detected. It has four possible values: |spotless|, |warning_issued|,
1986 |error_message_issued|, and |fatal_error_stop|.
1988 Another global variable, |error_count|, is increased by one when an
1989 |error| occurs without an interactive dialog, and it is reset to zero at
1990 the end of every statement. If |error_count| reaches 100, \MP\ decides
1991 that there is no point in continuing further.
1994 enum mp_history_state {
1995 mp_spotless=0, /* |history| value when nothing has been amiss yet */
1996 mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
1997 mp_error_message_issued, /* |history| value when |error| has been called */
1998 mp_fatal_error_stop, /* |history| value when termination was premature */
1999 mp_system_error_stop /* |history| value when termination was due to disaster */
2003 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2004 int history; /* has the source input been clean so far? */
2005 int error_count; /* the number of scrolled errors since the last statement ended */
2007 @ The value of |history| is initially |fatal_error_stop|, but it will
2008 be changed to |spotless| if \MP\ survives the initialization process.
2010 @<Allocate or ...@>=
2011 mp->deletions_allowed=true; /* |history| is initialized elsewhere */
2013 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2014 error procedures near the beginning of the program. But the error procedures
2015 in turn use some other procedures, which need to be declared |forward|
2016 before we get to |error| itself.
2018 It is possible for |error| to be called recursively if some error arises
2019 when |get_next| is being used to delete a token, and/or if some fatal error
2020 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2022 is never more than two levels deep.
2025 static void mp_get_next (MP mp);
2026 static void mp_term_input (MP mp);
2027 static void mp_show_context (MP mp);
2028 static void mp_begin_file_reading (MP mp);
2029 static void mp_open_log_file (MP mp);
2030 static void mp_clear_for_error_prompt (MP mp);
2033 void mp_normalize_selector (MP mp);
2035 @ Individual lines of help are recorded in the array |help_line|, which
2036 contains entries in positions |0..(help_ptr-1)|. They should be printed
2037 in reverse order, i.e., with |help_line[0]| appearing last.
2039 @d hlp1(A) mp->help_line[0]=A; }
2040 @d hlp2(A,B) mp->help_line[1]=A; hlp1(B)
2041 @d hlp3(A,B,C) mp->help_line[2]=A; hlp2(B,C)
2042 @d hlp4(A,B,C,D) mp->help_line[3]=A; hlp3(B,C,D)
2043 @d hlp5(A,B,C,D,E) mp->help_line[4]=A; hlp4(B,C,D,E)
2044 @d hlp6(A,B,C,D,E,F) mp->help_line[5]=A; hlp5(B,C,D,E,F)
2045 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2046 @d help1 { mp->help_ptr=1; hlp1 /* use this with one help line */
2047 @d help2 { mp->help_ptr=2; hlp2 /* use this with two help lines */
2048 @d help3 { mp->help_ptr=3; hlp3 /* use this with three help lines */
2049 @d help4 { mp->help_ptr=4; hlp4 /* use this with four help lines */
2050 @d help5 { mp->help_ptr=5; hlp5 /* use this with five help lines */
2051 @d help6 { mp->help_ptr=6; hlp6 /* use this with six help lines */
2054 const char * help_line[6]; /* helps for the next |error| */
2055 unsigned int help_ptr; /* the number of help lines present */
2056 boolean use_err_help; /* should the |err_help| string be shown? */
2057 str_number err_help; /* a string set up by \&{errhelp} */
2058 str_number filename_template; /* a string set up by \&{filenametemplate} */
2060 @ @<Allocate or ...@>=
2061 mp->use_err_help=false;
2063 @ The |jump_out| procedure just cuts across all active procedure levels and
2064 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2065 whole program. It is used when there is no recovery from a particular error.
2067 The program uses a |jump_buf| to handle this, this is initialized at three
2068 spots: the start of |mp_new|, the start of |mp_initialize|, and the start
2069 of |mp_run|. Those are the only library enty points.
2071 @^system dependencies@>
2076 @ If the array of internals is still |NULL| when |jump_out| is called, a
2077 crash occured during initialization, and it is not safe to run the normal
2081 static void mp_jump_out (MP mp) {
2082 if (mp->internal!=NULL && mp->history < mp_system_error_stop)
2083 mp_close_files_and_terminate(mp);
2084 longjmp(*(mp->jump_buf),1);
2087 @ Here now is the general |error| routine.
2090 void mp_error (MP mp) { /* completes the job of error reporting */
2091 ASCII_code c; /* what the user types */
2092 integer s1,s2,s3; /* used to save global variables when deleting tokens */
2093 pool_pointer j; /* character position being printed */
2094 if ( mp->history<mp_error_message_issued )
2095 mp->history=mp_error_message_issued;
2096 mp_print_char(mp, xord('.')); mp_show_context(mp);
2097 if ((!mp->noninteractive) && (mp->interaction==mp_error_stop_mode )) {
2098 @<Get user's advice and |return|@>;
2100 incr(mp->error_count);
2101 if ( mp->error_count==100 ) {
2102 mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2103 @.That makes 100 errors...@>
2104 mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2106 @<Put help message on the transcript file@>;
2108 void mp_warn (MP mp, const char *msg) {
2109 unsigned saved_selector = mp->selector;
2110 mp_normalize_selector(mp);
2111 mp_print_nl(mp,"Warning: ");
2114 mp->selector = saved_selector;
2117 @ @<Exported function ...@>=
2118 extern void mp_error (MP mp);
2119 extern void mp_warn (MP mp, const char *msg);
2122 @ @<Get user's advice...@>=
2125 mp_clear_for_error_prompt(mp); prompt_input("? ");
2127 if ( mp->last==mp->first ) return;
2128 c=mp->buffer[mp->first];
2129 if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2130 @<Interpret code |c| and |return| if done@>;
2133 @ It is desirable to provide an `\.E' option here that gives the user
2134 an easy way to return from \MP\ to the system editor, with the offending
2135 line ready to be edited. But such an extension requires some system
2136 wizardry, so the present implementation simply types out the name of the
2138 edited and the relevant line number.
2139 @^system dependencies@>
2142 typedef void (*mp_editor_cmd)(MP, char *, int);
2144 @ @<Option variables@>=
2145 mp_editor_cmd run_editor;
2147 @ @<Allocate or initialize ...@>=
2148 set_callback_option(run_editor);
2151 static void mp_run_editor (MP mp, char *fname, int fline);
2154 void mp_run_editor (MP mp, char *fname, int fline) {
2155 mp_print_nl(mp, "You want to edit file ");
2156 @.You want to edit file x@>
2157 mp_print(mp, fname);
2158 mp_print(mp, " at line ");
2159 mp_print_int(mp, fline);
2160 mp->interaction=mp_scroll_mode;
2165 There is a secret `\.D' option available when the debugging routines haven't
2169 @<Interpret code |c| and |return| if done@>=
2171 case '0': case '1': case '2': case '3': case '4':
2172 case '5': case '6': case '7': case '8': case '9':
2173 if ( mp->deletions_allowed ) {
2174 @<Delete |c-"0"| tokens and |continue|@>;
2178 if ( mp->file_ptr>0 ){
2179 (mp->run_editor)(mp,
2180 str(mp->input_stack[mp->file_ptr].name_field),
2185 @<Print the help information and |continue|@>;
2188 @<Introduce new material from the terminal and |return|@>;
2190 case 'Q': case 'R': case 'S':
2191 @<Change the interaction level and |return|@>;
2194 mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2199 @<Print the menu of available options@>
2201 @ @<Print the menu...@>=
2203 mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2204 @.Type <return> to proceed...@>
2205 mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2206 mp_print_nl(mp, "I to insert something, ");
2207 if ( mp->file_ptr>0 )
2208 mp_print(mp, "E to edit your file,");
2209 if ( mp->deletions_allowed )
2210 mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2211 mp_print_nl(mp, "H for help, X to quit.");
2214 @ Here the author of \MP\ apologizes for making use of the numerical
2215 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2216 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2217 @^Knuth, Donald Ervin@>
2219 @<Change the interaction...@>=
2221 mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2222 mp_print(mp, "OK, entering ");
2224 case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2225 case 'R': mp_print(mp, "nonstopmode"); break;
2226 case 'S': mp_print(mp, "scrollmode"); break;
2227 } /* there are no other cases */
2228 mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2231 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2232 contain the material inserted by the user; otherwise another prompt will
2233 be given. In order to understand this part of the program fully, you need
2234 to be familiar with \MP's input stacks.
2236 @<Introduce new material...@>=
2238 mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2239 if ( mp->last>mp->first+1 ) {
2240 loc=(halfword)(mp->first+1); mp->buffer[mp->first]=xord(' ');
2242 prompt_input("insert>"); loc=(halfword)mp->first;
2245 mp->first=mp->last+1; mp->cur_input.limit_field=(halfword)mp->last; return;
2248 @ We allow deletion of up to 99 tokens at a time.
2250 @<Delete |c-"0"| tokens...@>=
2252 s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2253 if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2254 c=xord(c*10+mp->buffer[mp->first+1]-'0'*11);
2258 mp_get_next(mp); /* one-level recursive call of |error| is possible */
2259 @<Decrease the string reference count, if the current token is a string@>;
2262 mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2263 help2("I have just deleted some text, as you asked.",
2264 "You can now delete more, or insert, or whatever.");
2265 mp_show_context(mp);
2269 @ @<Print the help info...@>=
2271 if ( mp->use_err_help ) {
2272 @<Print the string |err_help|, possibly on several lines@>;
2273 mp->use_err_help=false;
2275 if ( mp->help_ptr==0 ) {
2276 help2("Sorry, I don't know how to help in this situation.",
2277 "Maybe you should try asking a human?");
2280 decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2281 } while (mp->help_ptr!=0);
2283 help4("Sorry, I already gave what help I could...",
2284 "Maybe you should try asking a human?",
2285 "An error might have occurred before I noticed any problems.",
2286 "``If all else fails, read the instructions.''");
2290 @ @<Print the string |err_help|, possibly on several lines@>=
2291 j=mp->str_start[mp->err_help];
2292 while ( j<str_stop(mp->err_help) ) {
2293 if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2294 else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2295 else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2296 else { j++; mp_print_char(mp, xord('%')); };
2300 @ @<Put help message on the transcript file@>=
2301 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2302 if ( mp->use_err_help ) {
2303 mp_print_nl(mp, "");
2304 @<Print the string |err_help|, possibly on several lines@>;
2306 while ( mp->help_ptr>0 ){
2307 decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2311 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2314 @ In anomalous cases, the print selector might be in an unknown state;
2315 the following subroutine is called to fix things just enough to keep
2316 running a bit longer.
2319 void mp_normalize_selector (MP mp) {
2320 if ( mp->log_opened ) mp->selector=term_and_log;
2321 else mp->selector=term_only;
2322 if ( mp->job_name==NULL) mp_open_log_file(mp);
2323 if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2326 @ The following procedure prints \MP's last words before dying.
2328 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2329 mp->interaction=mp_scroll_mode; /* no more interaction */
2330 if ( mp->log_opened ) mp_error(mp);
2331 mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2335 void mp_fatal_error (MP mp, const char *s) { /* prints |s|, and that's it */
2336 mp_normalize_selector(mp);
2337 print_err("Emergency stop"); help1(s); succumb;
2341 @ @<Exported function ...@>=
2342 extern void mp_fatal_error (MP mp, const char *s);
2345 @ Here is the most dreaded error message.
2348 void mp_overflow (MP mp, const char *s, integer n) { /* stop due to finiteness */
2350 mp_normalize_selector(mp);
2351 mp_snprintf(msg, 256, "MetaPost capacity exceeded, sorry [%s=%d]",s,(int)n);
2352 @.MetaPost capacity exceeded ...@>
2354 help2("If you really absolutely need more capacity,",
2355 "you can ask a wizard to enlarge me.");
2359 @ @<Internal library declarations@>=
2360 void mp_overflow (MP mp, const char *s, integer n);
2362 @ The program might sometime run completely amok, at which point there is
2363 no choice but to stop. If no previous error has been detected, that's bad
2364 news; a message is printed that is really intended for the \MP\
2365 maintenance person instead of the user (unless the user has been
2366 particularly diabolical). The index entries for `this can't happen' may
2367 help to pinpoint the problem.
2370 @<Internal library ...@>=
2371 void mp_confusion (MP mp, const char *s);
2373 @ Consistency check violated; |s| tells where.
2375 void mp_confusion (MP mp, const char *s) {
2377 mp_normalize_selector(mp);
2378 if ( mp->history<mp_error_message_issued ) {
2379 mp_snprintf(msg, 256, "This can't happen (%s)",s);
2380 @.This can't happen@>
2382 help1("I'm broken. Please show this to someone who can fix can fix");
2384 print_err("I can\'t go on meeting you like this");
2385 @.I can't go on...@>
2386 help2("One of your faux pas seems to have wounded me deeply...",
2387 "in fact, I'm barely conscious. Please fix it and try again.");
2392 @ Users occasionally want to interrupt \MP\ while it's running.
2393 If the runtime system allows this, one can implement
2394 a routine that sets the global variable |interrupt| to some nonzero value
2395 when such an interrupt is signaled. Otherwise there is probably at least
2396 a way to make |interrupt| nonzero using the C debugger.
2397 @^system dependencies@>
2400 @d check_interrupt { if ( mp->interrupt!=0 )
2401 mp_pause_for_instructions(mp); }
2404 integer interrupt; /* should \MP\ pause for instructions? */
2405 boolean OK_to_interrupt; /* should interrupts be observed? */
2406 integer run_state; /* are we processing input ?*/
2407 boolean finished; /* set true by |close_files_and_terminate| */
2409 @ @<Allocate or ...@>=
2410 mp->OK_to_interrupt=true;
2413 @ When an interrupt has been detected, the program goes into its
2414 highest interaction level and lets the user have the full flexibility of
2415 the |error| routine. \MP\ checks for interrupts only at times when it is
2419 static void mp_pause_for_instructions (MP mp) {
2420 if ( mp->OK_to_interrupt ) {
2421 mp->interaction=mp_error_stop_mode;
2422 if ( (mp->selector==log_only)||(mp->selector==no_print) )
2424 print_err("Interruption");
2427 "Try to insert some instructions for me (e.g.,`I show x'),",
2428 "unless you just want to quit by typing `X'.");
2429 mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2434 @ Many of \MP's error messages state that a missing token has been
2435 inserted behind the scenes. We can save string space and program space
2436 by putting this common code into a subroutine.
2439 static void mp_missing_err (MP mp, const char *s) {
2441 mp_snprintf(msg, 256, "Missing `%s' has been inserted", s);
2442 @.Missing...inserted@>
2446 @* \[7] Arithmetic with scaled numbers.
2447 The principal computations performed by \MP\ are done entirely in terms of
2448 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2449 program can be carried out in exactly the same way on a wide variety of
2450 computers, including some small ones.
2453 But C does not rigidly define the |/| operation in the case of negative
2454 dividends; for example, the result of |(-2*n-1) / 2| is |-(n+1)| on some
2455 computers and |-n| on others (is this true ?). There are two principal
2456 types of arithmetic: ``translation-preserving,'' in which the identity
2457 |(a+q*b)/b=(a/b)+q| is valid; and ``negation-preserving,'' in which
2458 |(-a)/b=-(a/b)|. This leads to two \MP s, which can produce
2459 different results, although the differences should be negligible when the
2460 language is being used properly. The \TeX\ processor has been defined
2461 carefully so that both varieties of arithmetic will produce identical
2462 output, but it would be too inefficient to constrain \MP\ in a similar way.
2464 @d el_gordo 0x7fffffff /* $2^{31}-1$, the largest value that \MP\ likes */
2467 @ One of \MP's most common operations is the calculation of
2468 $\lfloor{a+b\over2}\rfloor$,
2469 the midpoint of two given integers |a| and~|b|. The most decent way to do
2470 this is to write `|(a+b)/2|'; but on many machines it is more efficient
2471 to calculate `|(a+b)>>1|'.
2473 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2474 in this program. If \MP\ is being implemented with languages that permit
2475 binary shifting, the |half| macro should be changed to make this operation
2476 as efficient as possible. Since some systems have shift operators that can
2477 only be trusted to work on positive numbers, there is also a macro |halfp|
2478 that is used only when the quantity being halved is known to be positive
2481 @d half(A) ((A) / 2)
2482 @d halfp(A) (integer)((unsigned)(A) >> 1)
2484 @ A single computation might use several subroutine calls, and it is
2485 desirable to avoid producing multiple error messages in case of arithmetic
2486 overflow. So the routines below set the global variable |arith_error| to |true|
2487 instead of reporting errors directly to the user.
2488 @^overflow in arithmetic@>
2491 boolean arith_error; /* has arithmetic overflow occurred recently? */
2493 @ @<Allocate or ...@>=
2494 mp->arith_error=false;
2496 @ At crucial points the program will say |check_arith|, to test if
2497 an arithmetic error has been detected.
2499 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2502 static void mp_clear_arith (MP mp) {
2503 print_err("Arithmetic overflow");
2504 @.Arithmetic overflow@>
2505 help4("Uh, oh. A little while ago one of the quantities that I was",
2506 "computing got too large, so I'm afraid your answers will be",
2507 "somewhat askew. You'll probably have to adopt different",
2508 "tactics next time. But I shall try to carry on anyway.");
2510 mp->arith_error=false;
2513 @ Addition is not always checked to make sure that it doesn't overflow,
2514 but in places where overflow isn't too unlikely the |slow_add| routine
2517 @c static integer mp_slow_add (MP mp,integer x, integer y) {
2519 if ( y<=el_gordo-x ) {
2522 mp->arith_error=true;
2525 } else if ( -y<=el_gordo+x ) {
2528 mp->arith_error=true;
2533 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2534 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2535 positions from the right end of a binary computer word.
2537 @d quarter_unit 040000 /* $2^{14}$, represents 0.250000 */
2538 @d half_unit 0100000 /* $2^{15}$, represents 0.50000 */
2539 @d three_quarter_unit 0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2540 @d unity 0200000 /* $2^{16}$, represents 1.00000 */
2541 @d two 0400000 /* $2^{17}$, represents 2.00000 */
2542 @d three 0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2545 typedef integer scaled; /* this type is used for scaled integers */
2547 @ The following function is used to create a scaled integer from a given decimal
2548 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2549 given in |dig[i]|, and the calculation produces a correctly rounded result.
2552 static scaled mp_round_decimals (MP mp,quarterword k) {
2553 /* converts a decimal fraction */
2554 unsigned a = 0; /* the accumulator */
2556 a=(a+mp->dig[k]*two) / 10;
2558 return (scaled)halfp(a+1);
2561 @ Conversely, here is a procedure analogous to |print_int|. If the output
2562 of this procedure is subsequently read by \MP\ and converted by the
2563 |round_decimals| routine above, it turns out that the original value will
2564 be reproduced exactly. A decimal point is printed only if the value is
2565 not an integer. If there is more than one way to print the result with
2566 the optimum number of digits following the decimal point, the closest
2567 possible value is given.
2569 The invariant relation in the \&{repeat} loop is that a sequence of
2570 decimal digits yet to be printed will yield the original number if and only if
2571 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2572 We can stop if and only if $f=0$ satisfies this condition; the loop will
2573 terminate before $s$ can possibly become zero.
2575 @<Basic printing...@>=
2576 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five digits */
2577 scaled delta; /* amount of allowable inaccuracy */
2579 mp_print_char(mp, xord('-'));
2580 negate(s); /* print the sign, if negative */
2582 mp_print_int(mp, s / unity); /* print the integer part */
2586 mp_print_char(mp, xord('.'));
2589 s=s+0100000-(delta / 2); /* round the final digit */
2590 mp_print_char(mp, xord('0'+(s / unity)));
2597 @ We often want to print two scaled quantities in parentheses,
2598 separated by a comma.
2600 @<Basic printing...@>=
2601 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2602 mp_print_char(mp, xord('('));
2603 mp_print_scaled(mp, x);
2604 mp_print_char(mp, xord(','));
2605 mp_print_scaled(mp, y);
2606 mp_print_char(mp, xord(')'));
2609 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2610 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2611 arithmetic with 28~significant bits of precision. A |fraction| denotes
2612 a scaled integer whose binary point is assumed to be 28 bit positions
2615 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2616 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2617 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2618 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2619 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2622 typedef integer fraction; /* this type is used for scaled fractions */
2624 @ In fact, the two sorts of scaling discussed above aren't quite
2625 sufficient; \MP\ has yet another, used internally to keep track of angles
2626 in units of $2^{-20}$ degrees.
2628 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2629 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2630 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2631 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2634 typedef integer angle; /* this type is used for scaled angles */
2636 @ The |make_fraction| routine produces the |fraction| equivalent of
2637 |p/q|, given integers |p| and~|q|; it computes the integer
2638 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2639 positive. If |p| and |q| are both of the same scaled type |t|,
2640 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2641 and it's also possible to use the subroutine ``backwards,'' using
2642 the relation |make_fraction(t,fraction)=t| between scaled types.
2644 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2645 sets |arith_error:=true|. Most of \MP's internal computations have
2646 been designed to avoid this sort of error.
2648 If this subroutine were programmed in assembly language on a typical
2649 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2650 double-precision product can often be input to a fixed-point division
2651 instruction. But when we are restricted to int-eger arithmetic it
2652 is necessary either to resort to multiple-precision maneuvering
2653 or to use a simple but slow iteration. The multiple-precision technique
2654 would be about three times faster than the code adopted here, but it
2655 would be comparatively long and tricky, involving about sixteen
2656 additional multiplications and divisions.
2658 This operation is part of \MP's ``inner loop''; indeed, it will
2659 consume nearly 10\pct! of the running time (exclusive of input and output)
2660 if the code below is left unchanged. A machine-dependent recoding
2661 will therefore make \MP\ run faster. The present implementation
2662 is highly portable, but slow; it avoids multiplication and division
2663 except in the initial stage. System wizards should be careful to
2664 replace it with a routine that is guaranteed to produce identical
2665 results in all cases.
2666 @^system dependencies@>
2668 As noted below, a few more routines should also be replaced by machine-dependent
2669 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2670 such changes aren't advisable; simplicity and robustness are
2671 preferable to trickery, unless the cost is too high.
2674 @<Internal library declarations@>=
2675 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2678 static fraction mp_make_fraction (MP mp,integer p, integer q);
2680 @ If FIXPT is not defined, we need these preprocessor values
2682 @d TWEXP31 2147483648.0
2683 @d TWEXP28 268435456.0
2685 @d TWEXP_16 (1.0/65536.0)
2686 @d TWEXP_28 (1.0/268435456.0)
2690 fraction mp_make_fraction (MP mp,integer p, integer q) {
2692 if ( q==0 ) mp_confusion(mp, "/");
2693 @:this can't happen /}{\quad \./@>
2696 integer f; /* the fraction bits, with a leading 1 bit */
2697 integer n; /* the integer part of $\vert p/q\vert$ */
2698 boolean negative = false; /* should the result be negated? */
2700 negate(p); negative=true;
2703 negate(q); negative = ! negative;
2707 mp->arith_error=true;
2708 i= ( negative ? -el_gordo : el_gordo);
2710 n=(n-1)*fraction_one;
2711 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2712 i = (negative ? (-(f+n)) : (f+n));
2718 d = TWEXP28 * (double)p /(double)q;
2721 if (d>=TWEXP31) {mp->arith_error=true; return el_gordo;}
2723 if (d==(double)i && ( ((q>0 ? -q : q)&077777)
2724 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2727 if (d<= -TWEXP31) {mp->arith_error=true; return -el_gordo;}
2729 if (d==(double)i && ( ((q>0 ? q : -q)&077777)
2730 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2737 @ The |repeat| loop here preserves the following invariant relations
2738 between |f|, |p|, and~|q|:
2739 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2740 $p_0$ is the original value of~$p$.
2742 Notice that the computation specifies
2743 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2744 Let us hope that optimizing compilers do not miss this point; a
2745 special variable |be_careful| is used to emphasize the necessary
2746 order of computation. Optimizing compilers should keep |be_careful|
2747 in a register, not store it in memory.
2750 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2752 integer be_careful; /* disables certain compiler optimizations */
2755 be_careful=p-q; p=be_careful+p;
2761 } while (f<fraction_one);
2763 if ( be_careful+p>=0 ) incr(f);
2766 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2767 given integer~|q| by a fraction~|f|. When the operands are positive, it
2768 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2771 This routine is even more ``inner loopy'' than |make_fraction|;
2772 the present implementation consumes almost 20\pct! of \MP's computation
2773 time during typical jobs, so a machine-language substitute is advisable.
2774 @^inner loop@> @^system dependencies@>
2776 @<Internal library declarations@>=
2777 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2781 integer mp_take_fraction (MP mp,integer q, fraction f) {
2782 integer p; /* the fraction so far */
2783 boolean negative; /* should the result be negated? */
2784 integer n; /* additional multiple of $q$ */
2785 integer be_careful; /* disables certain compiler optimizations */
2786 @<Reduce to the case that |f>=0| and |q>=0|@>;
2787 if ( f<fraction_one ) {
2790 n=f / fraction_one; f=f % fraction_one;
2791 if ( q<=el_gordo / n ) {
2794 mp->arith_error=true; n=el_gordo;
2798 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2799 be_careful=n-el_gordo;
2800 if ( be_careful+p>0 ){
2801 mp->arith_error=true; n=el_gordo-p;
2808 integer mp_take_fraction (MP mp,integer p, fraction q) {
2811 d = (double)p * (double)q * TWEXP_28;
2815 if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2816 mp->arith_error = true;
2820 if (d==(double)i && (((p&077777)*(q&077777))&040000)!=0) --i;
2824 if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2825 mp->arith_error = true;
2829 if (d==(double)i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2835 @ @<Reduce to the case that |f>=0| and |q>=0|@>=
2839 negate( f); negative=true;
2842 negate(q); negative=! negative;
2845 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2846 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2847 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2850 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2851 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2852 if ( q<fraction_four ) {
2854 if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2859 if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2865 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2866 analogous to |take_fraction| but with a different scaling.
2867 Given positive operands, |take_scaled|
2868 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2870 Once again it is a good idea to use a machine-language replacement if
2871 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2872 when the Computer Modern fonts are being generated.
2877 integer mp_take_scaled (MP mp,integer q, scaled f) {
2878 integer p; /* the fraction so far */
2879 boolean negative; /* should the result be negated? */
2880 integer n; /* additional multiple of $q$ */
2881 integer be_careful; /* disables certain compiler optimizations */
2882 @<Reduce to the case that |f>=0| and |q>=0|@>;
2886 n=f / unity; f=f % unity;
2887 if ( q<=el_gordo / n ) {
2890 mp->arith_error=true; n=el_gordo;
2894 @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2895 be_careful=n-el_gordo;
2896 if ( be_careful+p>0 ) {
2897 mp->arith_error=true; n=el_gordo-p;
2899 return ( negative ?(-(n+p)) :(n+p));
2901 integer mp_take_scaled (MP mp,integer p, scaled q) {
2904 d = (double)p * (double)q * TWEXP_16;
2908 if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2909 mp->arith_error = true;
2913 if (d==(double)i && (((p&077777)*(q&077777))&040000)!=0) --i;
2917 if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2918 mp->arith_error = true;
2922 if (d==(double)i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2928 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2929 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2931 if ( q<fraction_four ) {
2933 p = (odd(f) ? halfp(p+q) : halfp(p));
2938 p = (odd(f) ? p+halfp(q-p) : halfp(p));
2943 @ For completeness, there's also |make_scaled|, which computes a
2944 quotient as a |scaled| number instead of as a |fraction|.
2945 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2946 operands are positive. \ (This procedure is not used especially often,
2947 so it is not part of \MP's inner loop.)
2949 @<Internal library ...@>=
2950 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2953 scaled mp_make_scaled (MP mp,integer p, integer q) {
2955 if ( q==0 ) mp_confusion(mp, "/");
2956 @:this can't happen /}{\quad \./@>
2959 integer f; /* the fraction bits, with a leading 1 bit */
2960 integer n; /* the integer part of $\vert p/q\vert$ */
2961 boolean negative; /* should the result be negated? */
2962 integer be_careful; /* disables certain compiler optimizations */
2963 if ( p>=0 ) negative=false;
2964 else { negate(p); negative=true; };
2966 negate(q); negative=! negative;
2970 mp->arith_error=true;
2971 return (negative ? (-el_gordo) : el_gordo);
2974 @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2975 i = (negative ? (-(f+n)) :(f+n));
2979 d = TWEXP16 * (double)p /(double)q;
2982 if (d>=TWEXP31) {mp->arith_error=true; return el_gordo;}
2984 if (d==(double)i && ( ((q>0 ? -q : q)&077777)
2985 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2988 if (d<= -TWEXP31) {mp->arith_error=true; return -el_gordo;}
2990 if (d==(double)i && ( ((q>0 ? q : -q)&077777)
2991 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2998 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
3001 be_careful=p-q; p=be_careful+p;
3002 if ( p>=0 ) f=f+f+1;
3003 else { f+=f; p=p+q; };
3006 if ( be_careful+p>=0 ) incr(f)
3008 @ Here is a typical example of how the routines above can be used.
3009 It computes the function
3010 $${1\over3\tau}f(\theta,\phi)=
3011 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3012 (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3013 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3014 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3015 fudge factor for placing the first control point of a curve that starts
3016 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3017 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3019 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3020 (It's a sum of eight terms whose absolute values can be bounded using
3021 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3022 is positive; and since the tension $\tau$ is constrained to be at least
3023 $3\over4$, the numerator is less than $16\over3$. The denominator is
3024 nonnegative and at most~6. Hence the fixed-point calculations below
3025 are guaranteed to stay within the bounds of a 32-bit computer word.
3027 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3028 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3029 $\sin\phi$, and $\cos\phi$, respectively.
3032 static fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3033 fraction cf, scaled t) {
3034 integer acc,num,denom; /* registers for intermediate calculations */
3035 acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3036 acc=mp_take_fraction(mp, acc,ct-cf);
3037 num=fraction_two+mp_take_fraction(mp, acc,379625062);
3038 /* $2^{28}\sqrt2\approx379625062.497$ */
3039 denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3040 /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3041 $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3042 if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3043 /* |make_scaled(fraction,scaled)=fraction| */
3044 if ( num / 4>=denom )
3045 return fraction_four;
3047 return mp_make_fraction(mp, num, denom);
3050 @ The following somewhat different subroutine tests rigorously if $ab$ is
3051 greater than, equal to, or less than~$cd$,
3052 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3053 The result is $+1$, 0, or~$-1$ in the three respective cases.
3055 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3058 static integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3059 integer q,r; /* temporary registers */
3060 @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3062 q = a / d; r = c / b;
3064 return ( q>r ? 1 : -1);
3065 q = a % d; r = c % b;
3068 if ( q==0 ) return -1;
3070 } /* now |a>d>0| and |c>b>0| */
3073 @ @<Reduce to the case that |a...@>=
3074 if ( a<0 ) { negate(a); negate(b); };
3075 if ( c<0 ) { negate(c); negate(d); };
3078 if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3082 return ( a==0 ? 0 : -1);
3083 q=a; a=c; c=q; q=-b; b=-d; d=q;
3084 } else if ( b<=0 ) {
3085 if ( b<0 ) if ( a>0 ) return -1;
3086 return (c==0 ? 0 : -1);
3089 @ We conclude this set of elementary routines with some simple rounding
3090 and truncation operations.
3092 @<Internal library declarations@>=
3093 #define mp_floor_scaled(M,i) ((i)&(-65536))
3094 #define mp_round_unscaled(M,i) (((i/32768)+1)/2)
3095 #define mp_round_fraction(M,i) (((i/2048)+1)/2)
3098 @* \[8] Algebraic and transcendental functions.
3099 \MP\ computes all of the necessary special functions from scratch, without
3100 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3102 @ To get the square root of a |scaled| number |x|, we want to calculate
3103 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3104 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3105 determines $s$ by an iterative method that maintains the invariant
3106 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3107 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3108 might, however, be zero at the start of the first iteration.
3111 static scaled mp_square_rt (MP mp,scaled x) ;
3114 scaled mp_square_rt (MP mp,scaled x) {
3115 quarterword k; /* iteration control counter */
3116 integer y; /* register for intermediate calculations */
3117 unsigned q; /* register for intermediate calculations */
3119 @<Handle square root of zero or negative argument@>;
3122 while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3125 if ( x<fraction_four ) y=0;
3126 else { x=x-fraction_four; y=1; };
3128 @<Decrease |k| by 1, maintaining the invariant
3129 relations between |x|, |y|, and~|q|@>;
3131 return (scaled)(halfp(q));
3135 @ @<Handle square root of zero...@>=
3138 print_err("Square root of ");
3139 @.Square root...replaced by 0@>
3140 mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3141 help2("Since I don't take square roots of negative numbers,",
3142 "I'm zeroing this one. Proceed, with fingers crossed.");
3148 @ @<Decrease |k| by 1, maintaining...@>=
3150 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3151 x=x-fraction_four; y++;
3153 x+=x; y=y+y-q; q+=q;
3154 if ( x>=fraction_four ) { x=x-fraction_four; y++; };
3155 if ( y>(int)q ){ y=y-q; q=q+2; }
3156 else if ( y<=0 ) { q=q-2; y=y+q; };
3159 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3160 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3161 @^Moler, Cleve Barry@>
3162 @^Morrison, Donald Ross@>
3163 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3164 in such a way that their Pythagorean sum remains invariant, while the
3165 smaller argument decreases.
3167 @<Internal library ...@>=
3168 integer mp_pyth_add (MP mp,integer a, integer b);
3172 integer mp_pyth_add (MP mp,integer a, integer b) {
3173 fraction r; /* register used to transform |a| and |b| */
3174 boolean big; /* is the result dangerously near $2^{31}$? */
3176 if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3178 if ( a<fraction_two ) {
3181 a=a / 4; b=b / 4; big=true;
3182 }; /* we reduced the precision to avoid arithmetic overflow */
3183 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3185 if ( a<fraction_two ) {
3188 mp->arith_error=true; a=el_gordo;
3195 @ The key idea here is to reflect the vector $(a,b)$ about the
3196 line through $(a,b/2)$.
3198 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3200 r=mp_make_fraction(mp, b,a);
3201 r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3203 r=mp_make_fraction(mp, r,fraction_four+r);
3204 a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3208 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3209 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3212 static integer mp_pyth_sub (MP mp,integer a, integer b) {
3213 fraction r; /* register used to transform |a| and |b| */
3214 boolean big; /* is the input dangerously near $2^{31}$? */
3217 @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3219 if ( a<fraction_four ) {
3222 a=(integer)halfp(a); b=(integer)halfp(b); big=true;
3224 @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3225 if ( big ) double(a);
3230 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3232 r=mp_make_fraction(mp, b,a);
3233 r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3235 r=mp_make_fraction(mp, r,fraction_four-r);
3236 a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3239 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3242 print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3243 mp_print(mp, "+-+"); mp_print_scaled(mp, b);
3244 mp_print(mp, " has been replaced by 0");
3246 help2("Since I don't take square roots of negative numbers,",
3247 "I'm zeroing this one. Proceed, with fingers crossed.");
3253 @ The subroutines for logarithm and exponential involve two tables.
3254 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3255 a bit more calculation, which the author claims to have done correctly:
3256 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3257 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3260 @d two_to_the(A) (1<<(unsigned)(A))
3263 static const integer spec_log[29] = { 0, /* special logarithms */
3264 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3265 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3266 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3268 @ @<Local variables for initialization@>=
3269 integer k; /* all-purpose loop index */
3272 @ Here is the routine that calculates $2^8$ times the natural logarithm
3273 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3274 when |x| is a given positive integer.
3276 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3277 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3278 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3279 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3280 during the calculation, and sixteen auxiliary bits to extend |y| are
3281 kept in~|z| during the initial argument reduction. (We add
3282 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3283 not become negative; also, the actual amount subtracted from~|y| is~96,
3284 not~100, because we want to add~4 for rounding before the final division by~8.)
3287 static scaled mp_m_log (MP mp,scaled x) {
3288 integer y,z; /* auxiliary registers */
3289 integer k; /* iteration counter */
3291 @<Handle non-positive logarithm@>;
3293 y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3294 z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3295 while ( x<fraction_four ) {
3296 double(x); y-=93032639; z-=48782;
3297 } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3298 y=y+(z / unity); k=2;
3299 while ( x>fraction_four+4 ) {
3300 @<Increase |k| until |x| can be multiplied by a
3301 factor of $2^{-k}$, and adjust $y$ accordingly@>;
3307 @ @<Increase |k| until |x| can...@>=
3309 z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3310 while ( x<fraction_four+z ) { z=halfp(z+1); k++; };
3311 y+=spec_log[k]; x-=z;
3314 @ @<Handle non-positive logarithm@>=
3316 print_err("Logarithm of ");
3317 @.Logarithm...replaced by 0@>
3318 mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3319 help2("Since I don't take logs of non-positive numbers,",
3320 "I'm zeroing this one. Proceed, with fingers crossed.");
3325 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3326 when |x| is |scaled|. The result is an integer approximation to
3327 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3330 static scaled mp_m_exp (MP mp,scaled x) {
3331 quarterword k; /* loop control index */
3332 integer y,z; /* auxiliary registers */
3333 if ( x>174436200 ) {
3334 /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3335 mp->arith_error=true;
3337 } else if ( x<-197694359 ) {
3338 /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3342 z=-8*x; y=04000000; /* $y=2^{20}$ */
3344 if ( x<=127919879 ) {
3346 /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3348 z=8*(174436200-x); /* |z| is always nonnegative */
3352 @<Multiply |y| by $\exp(-z/2^{27})$@>;
3354 return ((y+8) / 16);
3360 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3361 to multiplying |y| by $1-2^{-k}$.
3363 A subtle point (which had to be checked) was that if $x=127919879$, the
3364 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3365 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3366 and by~16 when |k=27|.
3368 @<Multiply |y| by...@>=
3371 while ( z>=spec_log[k] ) {
3373 y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3378 @ The trigonometric subroutines use an auxiliary table such that
3379 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3380 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$
3383 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058,
3384 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667,
3385 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3387 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3388 returns the |angle| whose tangent points in the direction $(x,y)$.
3389 This subroutine first determines the correct octant, then solves the
3390 problem for |0<=y<=x|, then converts the result appropriately to
3391 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3392 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3393 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3395 The octants are represented in a ``Gray code,'' since that turns out
3396 to be computationally simplest.
3402 @d second_octant (first_octant+switch_x_and_y)
3403 @d third_octant (first_octant+switch_x_and_y+negate_x)
3404 @d fourth_octant (first_octant+negate_x)
3405 @d fifth_octant (first_octant+negate_x+negate_y)
3406 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3407 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3408 @d eighth_octant (first_octant+negate_y)
3411 static angle mp_n_arg (MP mp,integer x, integer y) {
3412 angle z; /* auxiliary register */
3413 integer t; /* temporary storage */
3414 quarterword k; /* loop counter */
3415 int octant; /* octant code */
3417 octant=first_octant;
3419 negate(x); octant=first_octant+negate_x;
3422 negate(y); octant=octant+negate_y;
3425 t=y; y=x; x=t; octant=octant+switch_x_and_y;
3428 @<Handle undefined arg@>;
3430 @<Set variable |z| to the arg of $(x,y)$@>;
3431 @<Return an appropriate answer based on |z| and |octant|@>;
3435 @ @<Handle undefined arg@>=
3437 print_err("angle(0,0) is taken as zero");
3438 @.angle(0,0)...zero@>
3439 help2("The `angle' between two identical points is undefined.",
3440 "I'm zeroing this one. Proceed, with fingers crossed.");
3445 @ @<Return an appropriate answer...@>=
3447 case first_octant: return z;
3448 case second_octant: return (ninety_deg-z);
3449 case third_octant: return (ninety_deg+z);
3450 case fourth_octant: return (one_eighty_deg-z);
3451 case fifth_octant: return (z-one_eighty_deg);
3452 case sixth_octant: return (-z-ninety_deg);
3453 case seventh_octant: return (z-ninety_deg);
3454 case eighth_octant: return (-z);
3455 }; /* there are no other cases */
3458 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3459 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3462 @<Set variable |z| to the arg...@>=
3463 while ( x>=fraction_two ) {
3464 x=halfp(x); y=halfp(y);
3468 while ( x<fraction_one ) {
3471 @<Increase |z| to the arg of $(x,y)$@>;
3474 @ During the calculations of this section, variables |x| and~|y|
3475 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3476 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3477 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3478 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3479 coordinates whose angle has decreased by~$\phi$; in the special case
3480 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3481 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3482 @^Meggitt, John E.@>
3483 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3485 The initial value of |x| will be multiplied by at most
3486 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3487 there is no chance of integer overflow.
3489 @<Increase |z|...@>=
3494 z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3499 if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3502 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3503 and cosine of that angle. The results of this routine are
3504 stored in global integer variables |n_sin| and |n_cos|.
3507 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3509 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3510 the purpose of |n_sin_cos(z)| is to set
3511 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3512 for some rather large number~|r|. The maximum of |x| and |y|
3513 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3514 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3517 static void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3519 quarterword k; /* loop control variable */
3520 int q; /* specifies the quadrant */
3521 fraction r; /* magnitude of |(x,y)| */
3522 integer x,y,t; /* temporary registers */
3523 while ( z<0 ) z=z+three_sixty_deg;
3524 z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3525 q=z / forty_five_deg; z=z % forty_five_deg;
3526 x=fraction_one; y=x;
3527 if ( ! odd(q) ) z=forty_five_deg-z;
3528 @<Subtract angle |z| from |(x,y)|@>;
3529 @<Convert |(x,y)| to the octant determined by~|q|@>;
3530 r=mp_pyth_add(mp, x,y);
3531 mp->n_cos=mp_make_fraction(mp, x,r);
3532 mp->n_sin=mp_make_fraction(mp, y,r);
3535 @ In this case the octants are numbered sequentially.
3537 @<Convert |(x,...@>=
3540 case 1: t=x; x=y; y=t; break;
3541 case 2: t=x; x=-y; y=t; break;
3542 case 3: negate(x); break;
3543 case 4: negate(x); negate(y); break;
3544 case 5: t=x; x=-y; y=-t; break;
3545 case 6: t=x; x=y; y=-t; break;
3546 case 7: negate(y); break;
3547 } /* there are no other cases */
3549 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3550 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3551 that this loop is guaranteed to terminate before the (nonexistent) value
3552 |spec_atan[27]| would be required.
3554 @<Subtract angle |z|...@>=
3557 if ( z>=spec_atan[k] ) {
3558 z=z-spec_atan[k]; t=x;
3559 x=t+y / two_to_the(k);
3560 y=y-t / two_to_the(k);
3564 if ( y<0 ) y=0 /* this precaution may never be needed */
3566 @ And now let's complete our collection of numeric utility routines
3567 by considering random number generation.
3568 \MP\ generates pseudo-random numbers with the additive scheme recommended
3569 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3570 results are random fractions between 0 and |fraction_one-1|, inclusive.
3572 There's an auxiliary array |randoms| that contains 55 pseudo-random
3573 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3574 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3575 The global variable |j_random| tells which element has most recently
3577 The global variable |random_seed| was introduced in version 0.9,
3578 for the sole reason of stressing the fact that the initial value of the
3579 random seed is system-dependant. The initialization code below will initialize
3580 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this
3581 is not good enough on modern fast machines that are capable of running
3582 multiple MetaPost processes within the same second.
3583 @^system dependencies@>
3586 fraction randoms[55]; /* the last 55 random values generated */
3587 int j_random; /* the number of unused |randoms| */
3589 @ @<Option variables@>=
3590 int random_seed; /* the default random seed */
3592 @ @<Allocate or initialize ...@>=
3593 mp->random_seed = (scaled)opt->random_seed;
3595 @ To consume a random fraction, the program below will say `|next_random|'
3596 and then it will fetch |randoms[j_random]|.
3598 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3599 else decr(mp->j_random); }
3602 static void mp_new_randoms (MP mp) {
3603 int k; /* index into |randoms| */
3604 fraction x; /* accumulator */
3605 for (k=0;k<=23;k++) {
3606 x=mp->randoms[k]-mp->randoms[k+31];
3607 if ( x<0 ) x=x+fraction_one;
3610 for (k=24;k<= 54;k++){
3611 x=mp->randoms[k]-mp->randoms[k-24];
3612 if ( x<0 ) x=x+fraction_one;
3619 static void mp_init_randoms (MP mp,scaled seed);
3621 @ To initialize the |randoms| table, we call the following routine.
3624 void mp_init_randoms (MP mp,scaled seed) {
3625 fraction j,jj,k; /* more or less random integers */
3626 int i; /* index into |randoms| */
3628 while ( j>=fraction_one ) j=halfp(j);
3630 for (i=0;i<=54;i++ ){
3632 if ( k<0 ) k=k+fraction_one;
3633 mp->randoms[(i*21)% 55]=j;
3637 mp_new_randoms(mp); /* ``warm up'' the array */
3640 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3641 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3643 Note that the call of |take_fraction| will produce the values 0 and~|x|
3644 with about half the probability that it will produce any other particular
3645 values between 0 and~|x|, because it rounds its answers.
3648 static scaled mp_unif_rand (MP mp,scaled x) {
3649 scaled y; /* trial value */
3650 next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3651 if ( y==abs(x) ) return 0;
3652 else if ( x>0 ) return y;
3656 @ Finally, a normal deviate with mean zero and unit standard deviation
3657 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3658 {\sl The Art of Computer Programming\/}).
3661 static scaled mp_norm_rand (MP mp) {
3662 integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3666 x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3667 /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3668 next_random; u=mp->randoms[mp->j_random];
3669 } while (abs(x)>=u);
3670 x=mp_make_fraction(mp, x,u);
3671 l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3672 } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3676 @* \[9] Packed data.
3677 In order to make efficient use of storage space, \MP\ bases its major data
3678 structures on a |memory_word|, which contains either a (signed) integer,
3679 possibly scaled, or a small number of fields that are one half or one
3680 quarter of the size used for storing integers.
3682 If |x| is a variable of type |memory_word|, it contains up to four
3683 fields that can be referred to as follows:
3684 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3685 |x|&.|int|&(an |integer|)\cr
3686 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3687 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3688 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3690 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3691 &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3692 This is somewhat cumbersome to write, and not very readable either, but
3693 macros will be used to make the notation shorter and more transparent.
3694 The code below gives a formal definition of |memory_word| and
3695 its subsidiary types, using packed variant records. \MP\ makes no
3696 assumptions about the relative positions of the fields within a word.
3698 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3699 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3701 @ Here are the inequalities that the quarterword and halfword values
3702 must satisfy (or rather, the inequalities that they mustn't satisfy):
3704 @<Check the ``constant''...@>=
3705 if (mp->ini_version) {
3706 if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3708 if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3710 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3711 if ( mp->max_strings>max_halfword ) mp->bad=13;
3713 @ The macros |qi| and |qo| are used for input to and output
3714 from quarterwords. These are legacy macros.
3715 @^system dependencies@>
3717 @d qo(A) (A) /* to read eight bits from a quarterword */
3718 @d qi(A) (quarterword)(A) /* to store eight bits in a quarterword */
3720 @ The reader should study the following definitions closely:
3721 @^system dependencies@>
3723 @d sc cint /* |scaled| data is equivalent to |integer| */
3726 typedef short quarterword; /* 1/4 of a word */
3727 typedef int halfword; /* 1/2 of a word */
3732 struct { /* Make B0,B1 overlap the most significant bytes of LH. */
3739 quarterword B2, B3, B0, B1;
3754 @ When debugging, we may want to print a |memory_word| without knowing
3755 what type it is; so we print it in all modes.
3759 void mp_print_word (MP mp,memory_word w) {
3760 /* prints |w| in all ways */
3761 mp_print_int(mp, w.cint); mp_print_char(mp, xord(' '));
3762 mp_print_scaled(mp, w.sc); mp_print_char(mp, xord(' '));
3763 mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3764 mp_print_int(mp, w.hh.lh); mp_print_char(mp, xord('='));
3765 mp_print_int(mp, w.hh.b0); mp_print_char(mp, xord(':'));
3766 mp_print_int(mp, w.hh.b1); mp_print_char(mp, xord(';'));
3767 mp_print_int(mp, w.hh.rh); mp_print_char(mp, xord(' '));
3768 mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, xord(':'));
3769 mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, xord(':'));
3770 mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, xord(':'));
3771 mp_print_int(mp, w.qqqq.b3);
3775 @* \[10] Dynamic memory allocation.
3777 The \MP\ system does nearly all of its own memory allocation, so that it
3778 can readily be transported into environments that do not have automatic
3779 facilities for strings, garbage collection, etc., and so that it can be in
3780 control of what error messages the user receives. The dynamic storage
3781 requirements of \MP\ are handled by providing a large array |mem| in
3782 which consecutive blocks of words are used as nodes by the \MP\ routines.
3784 Pointer variables are indices into this array, or into another array
3785 called |eqtb| that will be explained later. A pointer variable might
3786 also be a special flag that lies outside the bounds of |mem|, so we
3787 allow pointers to assume any |halfword| value. The minimum memory
3788 index represents a null pointer.
3790 @d null 0 /* the null pointer */
3791 @d mp_void (null+1) /* a null pointer different from |null| */
3795 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3797 @ The |mem| array is divided into two regions that are allocated separately,
3798 but the dividing line between these two regions is not fixed; they grow
3799 together until finding their ``natural'' size in a particular job.
3800 Locations less than or equal to |lo_mem_max| are used for storing
3801 variable-length records consisting of two or more words each. This region
3802 is maintained using an algorithm similar to the one described in exercise
3803 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3804 appears in the allocated nodes; the program is responsible for knowing the
3805 relevant size when a node is freed. Locations greater than or equal to
3806 |hi_mem_min| are used for storing one-word records; a conventional
3807 \.{AVAIL} stack is used for allocation in this region.
3809 Locations of |mem| between |0| and |mem_top| may be dumped as part
3810 of preloaded mem files, by the \.{INIMP} preprocessor.
3812 Production versions of \MP\ may extend the memory at the top end in order to
3813 provide more space; these locations, between |mem_top| and |mem_max|,
3814 are always used for single-word nodes.
3816 The key pointers that govern |mem| allocation have a prescribed order:
3817 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3820 memory_word *mem; /* the big dynamic storage area */
3821 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3822 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3826 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3827 @d xrealloc(P,A,B) mp_xrealloc(mp,P,(size_t)A,B)
3828 @d xmalloc(A,B) mp_xmalloc(mp,(size_t)A,B)
3829 @d xstrdup(A) mp_xstrdup(mp,A)
3830 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3832 @<Declare helpers@>=
3833 extern char *mp_strdup(const char *p) ;
3834 extern void mp_xfree ( @= /*@@only@@*/ /*@@out@@*/ /*@@null@@*/ @> void *x);
3835 extern @= /*@@only@@*/ @> void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3836 extern @= /*@@only@@*/ @> void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3837 extern @= /*@@only@@*/ @> char *mp_xstrdup(MP mp, const char *s);
3838 extern void mp_do_snprintf(char *str, int size, const char *fmt, ...);
3840 @ The |max_size_test| guards against overflow, on the assumption that
3841 |size_t| is at least 31bits wide.
3843 @d max_size_test 0x7FFFFFFF
3846 char *mp_strdup(const char *p) {
3849 if (p==NULL) return NULL;
3851 r = malloc (l*sizeof(char)+1);
3854 return memcpy (r,p,(l+1));
3856 void mp_xfree (void *x) {
3857 if (x!=NULL) free(x);
3859 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3861 if ((max_size_test/size)<nmem) {
3862 do_fprintf(mp->err_out,"Memory size overflow!\n");
3863 mp->history =mp_fatal_error_stop; mp_jump_out(mp);
3865 w = realloc (p,(nmem*size));
3867 do_fprintf(mp->err_out,"Out of memory!\n");
3868 mp->history =mp_system_error_stop; mp_jump_out(mp);
3872 void *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3874 if ((max_size_test/size)<nmem) {
3875 do_fprintf(mp->err_out,"Memory size overflow!\n");
3876 mp->history =mp_fatal_error_stop; mp_jump_out(mp);
3878 w = malloc (nmem*size);
3880 do_fprintf(mp->err_out,"Out of memory!\n");
3881 mp->history =mp_system_error_stop; mp_jump_out(mp);
3885 char *mp_xstrdup(MP mp, const char *s) {
3891 do_fprintf(mp->err_out,"Out of memory!\n");
3892 mp->history =mp_system_error_stop; mp_jump_out(mp);
3897 @ @<Internal library declarations@>=
3898 #ifdef HAVE_SNPRINTF
3899 #define mp_snprintf (void)snprintf
3901 #define mp_snprintf mp_do_snprintf
3904 @ This internal version is rather stupid, but good enough for its purpose.
3907 static char *mp_itoa (int i) {
3910 unsigned v = (unsigned)abs(i);
3911 memset(res,0,32*sizeof(char));
3913 char d = (char)(v % 10);
3917 res[idx--] = (char)v;
3921 return mp_strdup(res+idx);
3923 static char *mp_utoa (unsigned v) {
3926 memset(res,0,32*sizeof(char));
3928 char d = (char)(v % 10);
3932 res[idx--] = (char)v;
3933 return mp_strdup(res+idx);
3935 void mp_do_snprintf (char *str, int size, const char *format, ...) {
3939 va_start(ap, format);
3941 for (fmt=format;*fmt!='\0';fmt++) {
3947 char *s = va_arg(ap, char *);
3950 if (size-->0) res++;
3957 char *s = mp_itoa(va_arg(ap, int));
3961 if (size-->0) res++;
3968 char *s = mp_utoa(va_arg(ap, unsigned));
3972 if (size-->0) res++;
3979 if (size-->0) res++;
3983 if (size-->0) res++;
3985 if (size-->0) res++;
3990 if (size-->0) res++;
3998 @<Allocate or initialize ...@>=
3999 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
4000 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
4002 @ @<Dealloc variables@>=
4005 @ Users who wish to study the memory requirements of particular applications can
4006 can use optional special features that keep track of current and
4007 maximum memory usage. When code between the delimiters |stat| $\ldots$
4008 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
4009 report these statistics when |mp_tracing_stats| is positive.
4012 integer var_used; integer dyn_used; /* how much memory is in use */
4014 @ Let's consider the one-word memory region first, since it's the
4015 simplest. The pointer variable |mem_end| holds the highest-numbered location
4016 of |mem| that has ever been used. The free locations of |mem| that
4017 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
4018 |two_halves|, and we write |info(p)| and |mp_link(p)| for the |lh|
4019 and |rh| fields of |mem[p]| when it is of this type. The single-word
4020 free locations form a linked list
4021 $$|avail|,\;\hbox{|mp_link(avail)|},\;\hbox{|mp_link(mp_link(avail))|},\;\ldots$$
4022 terminated by |null|.
4025 #define mp_link(A) mp->mem[(A)].hh.rh /* the |link| field of a memory word */
4026 #define mp_info(A) mp->mem[(A)].hh.lh /* the |info| field of a memory word */
4029 pointer avail; /* head of the list of available one-word nodes */
4030 pointer mem_end; /* the last one-word node used in |mem| */
4032 @ If one-word memory is exhausted, it might mean that the user has forgotten
4033 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
4034 later that try to help pinpoint the trouble.
4036 @ The function |get_avail| returns a pointer to a new one-word node whose
4037 |link| field is null. However, \MP\ will halt if there is no more room left.
4041 static pointer mp_get_avail (MP mp) { /* single-word node allocation */
4042 pointer p; /* the new node being got */
4043 p=mp->avail; /* get top location in the |avail| stack */
4045 mp->avail=mp_link(mp->avail); /* and pop it off */
4046 } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
4047 incr(mp->mem_end); p=mp->mem_end;
4049 decr(mp->hi_mem_min); p=mp->hi_mem_min;
4050 if ( mp->hi_mem_min<=mp->lo_mem_max ) {
4051 mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
4052 mp_overflow(mp, "main memory size",mp->mem_max);
4053 /* quit; all one-word nodes are busy */
4054 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4057 mp_link(p)=null; /* provide an oft-desired initialization of the new node */
4058 incr(mp->dyn_used);/* maintain statistics */
4062 @ Conversely, a one-word node is recycled by calling |free_avail|.
4064 @d free_avail(A) /* single-word node liberation */
4065 { mp_link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used); }
4067 @ There's also a |fast_get_avail| routine, which saves the procedure-call
4068 overhead at the expense of extra programming. This macro is used in
4069 the places that would otherwise account for the most calls of |get_avail|.
4072 @d fast_get_avail(A) {
4073 (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
4074 if ( (A)==null ) { (A)=mp_get_avail(mp); }
4075 else { mp->avail=mp_link((A)); mp_link((A))=null; incr(mp->dyn_used); }
4078 @ The available-space list that keeps track of the variable-size portion
4079 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
4080 pointed to by the roving pointer |rover|.
4082 Each empty node has size 2 or more; the first word contains the special
4083 value |max_halfword| in its |link| field and the size in its |info| field;
4084 the second word contains the two pointers for double linking.
4086 Each nonempty node also has size 2 or more. Its first word is of type
4087 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
4088 Otherwise there is complete flexibility with respect to the contents
4089 of its other fields and its other words.
4091 (We require |mem_max<max_halfword| because terrible things can happen
4092 when |max_halfword| appears in the |link| field of a nonempty node.)
4094 @d empty_flag max_halfword /* the |link| of an empty variable-size node */
4095 @d is_empty(A) (mp_link((A))==empty_flag) /* tests for empty node */
4098 #define node_size mp_info /* the size field in empty variable-size nodes */
4099 #define lmp_link(A) mp_info((A)+1) /* left link in doubly-linked list of empty nodes */
4100 #define rmp_link(A) mp_link((A)+1) /* right link in doubly-linked list of empty nodes */
4103 pointer rover; /* points to some node in the list of empties */
4105 @ A call to |get_node| with argument |s| returns a pointer to a new node
4106 of size~|s|, which must be 2~or more. The |link| field of the first word
4107 of this new node is set to null. An overflow stop occurs if no suitable
4110 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4111 areas and returns the value |max_halfword|.
4113 @<Internal library declarations@>=
4114 pointer mp_get_node (MP mp,integer s) ;
4117 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4118 pointer p; /* the node currently under inspection */
4119 pointer q; /* the node physically after node |p| */
4120 integer r; /* the newly allocated node, or a candidate for this honor */
4121 integer t,tt; /* temporary registers */
4124 p=mp->rover; /* start at some free node in the ring */
4126 @<Try to allocate within node |p| and its physical successors,
4127 and |goto found| if allocation was possible@>;
4128 if (rmp_link(p)==null || (rmp_link(p)==p && p!=mp->rover)) {
4129 print_err("Free list garbled");
4130 help3("I found an entry in the list of free nodes that links",
4131 "badly. I will try to ignore the broken link, but something",
4132 "is seriously amiss. It is wise to warn the maintainers.")
4134 rmp_link(p)=mp->rover;
4136 p=rmp_link(p); /* move to the next node in the ring */
4137 } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4138 if ( s==010000000000 ) {
4139 return max_halfword;
4141 if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4142 if ( mp->lo_mem_max+2<=max_halfword ) {
4143 @<Grow more variable-size memory and |goto restart|@>;
4146 mp_overflow(mp, "main memory size",mp->mem_max);
4147 /* sorry, nothing satisfactory is left */
4148 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4150 mp_link(r)=null; /* this node is now nonempty */
4151 mp->var_used+=s; /* maintain usage statistics */
4155 @ The lower part of |mem| grows by 1000 words at a time, unless
4156 we are very close to going under. When it grows, we simply link
4157 a new node into the available-space list. This method of controlled
4158 growth helps to keep the |mem| usage consecutive when \MP\ is
4159 implemented on ``virtual memory'' systems.
4162 @<Grow more variable-size memory and |goto restart|@>=
4164 if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4165 t=mp->lo_mem_max+1000;
4167 t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2;
4168 /* |lo_mem_max+2<=t<hi_mem_min| */
4170 if ( t>max_halfword ) t=max_halfword;
4171 p=lmp_link(mp->rover); q=mp->lo_mem_max; rmp_link(p)=q; lmp_link(mp->rover)=q;
4172 rmp_link(q)=mp->rover; lmp_link(q)=p; mp_link(q)=empty_flag;
4173 node_size(q)=t-mp->lo_mem_max;
4174 mp->lo_mem_max=t; mp_link(mp->lo_mem_max)=null; mp_info(mp->lo_mem_max)=null;
4179 @ @<Try to allocate...@>=
4180 q=p+node_size(p); /* find the physical successor */
4181 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4182 t=rmp_link(q); tt=lmp_link(q);
4184 if ( q==mp->rover ) mp->rover=t;
4185 lmp_link(t)=tt; rmp_link(tt)=t;
4190 @<Allocate from the top of node |p| and |goto found|@>;
4193 if ( rmp_link(p)!=p ) {
4194 @<Allocate entire node |p| and |goto found|@>;
4197 node_size(p)=q-p /* reset the size in case it grew */
4199 @ @<Allocate from the top...@>=
4201 node_size(p)=r-p; /* store the remaining size */
4202 mp->rover=p; /* start searching here next time */
4206 @ Here we delete node |p| from the ring, and let |rover| rove around.
4208 @<Allocate entire...@>=
4210 mp->rover=rmp_link(p); t=lmp_link(p);
4211 lmp_link(mp->rover)=t; rmp_link(t)=mp->rover;
4215 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4216 the operation |free_node(p,s)| will make its words available, by inserting
4217 |p| as a new empty node just before where |rover| now points.
4219 @<Internal library declarations@>=
4220 void mp_free_node (MP mp, pointer p, halfword s) ;
4223 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4225 pointer q; /* |lmp_link(rover)| */
4226 node_size(p)=s; mp_link(p)=empty_flag;
4228 q=lmp_link(mp->rover); lmp_link(p)=q; rmp_link(p)=mp->rover; /* set both links */
4229 lmp_link(mp->rover)=p; rmp_link(q)=p; /* insert |p| into the ring */
4230 mp->var_used-=s; /* maintain statistics */
4233 @* \[11] Memory layout.
4234 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4235 more efficient than dynamic allocation when we can get away with it. For
4236 example, locations |0| to |1| are always used to store a
4237 two-word dummy token whose second word is zero.
4238 The following macro definitions accomplish the static allocation by giving
4239 symbolic names to the fixed positions. Static variable-size nodes appear
4240 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4241 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4243 @d sentinel mp->mem_top /* end of sorted lists */
4244 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4245 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4248 #define spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4249 #define null_dash (2) /* the first two words are reserved for a null value */
4250 #define dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4251 #define zero_val (dep_head+2) /* two words for a permanently zero value */
4252 #define temp_val (zero_val+2) /* two words for a temporary value node */
4253 #define end_attr temp_val /* we use |end_attr+2| only */
4254 #define inf_val (end_attr+2) /* and |inf_val+1| only */
4255 #define bad_vardef (inf_val+2) /* two words for \&{vardef} error recovery */
4256 #define lo_mem_stat_max (bad_vardef+1) /* largest statically
4257 allocated word in the variable-size |mem| */
4258 #define hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4259 the one-word |mem| */
4261 @ The following code gets the dynamic part of |mem| off to a good start,
4262 when \MP\ is initializing itself the slow way.
4264 @<Initialize table entries (done by \.{INIMP} only)@>=
4265 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4266 mp_link(mp->rover)=empty_flag;
4267 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4268 lmp_link(mp->rover)=mp->rover; rmp_link(mp->rover)=mp->rover;
4269 mp->lo_mem_max=mp->rover+1000;
4270 mp_link(mp->lo_mem_max)=null; mp_info(mp->lo_mem_max)=null;
4271 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4272 mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4274 mp->avail=null; mp->mem_end=mp->mem_top;
4275 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4276 mp->var_used=lo_mem_stat_max+1;
4277 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min); /* initialize statistics */
4279 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4280 nodes that starts at a given position, until coming to |sentinel| or a
4281 pointer that is not in the one-word region. Another procedure,
4282 |flush_node_list|, frees an entire linked list of one-word and two-word
4283 nodes, until coming to a |null| pointer.
4287 static void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes available */
4288 pointer q,r; /* list traversers */
4289 if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) {
4294 if ( r<mp->hi_mem_min ) break;
4295 } while (r!=sentinel);
4296 /* now |q| is the last node on the list */
4297 mp_link(q)=mp->avail; mp->avail=p;
4301 static void mp_flush_node_list (MP mp,pointer p) {
4302 pointer q; /* the node being recycled */
4305 if ( q<mp->hi_mem_min )
4306 mp_free_node(mp, q,2);
4312 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4313 For example, some pointers might be wrong, or some ``dead'' nodes might not
4314 have been freed when the last reference to them disappeared. Procedures
4315 |check_mem| and |search_mem| are available to help diagnose such
4316 problems. These procedures make use of two arrays called |free| and
4317 |was_free| that are present only if \MP's debugging routines have
4318 been included. (You may want to decrease the size of |mem| while you
4322 Because |boolean|s are typedef-d as ints, it is better to use
4323 unsigned chars here.
4326 unsigned char *free; /* free cells */
4327 unsigned char *was_free; /* previously free cells */
4328 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4329 /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4330 boolean panicking; /* do we want to check memory constantly? */
4332 @ @<Allocate or initialize ...@>=
4333 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4334 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4336 @ @<Dealloc variables@>=
4338 xfree(mp->was_free);
4340 @ @<Allocate or ...@>=
4341 mp->was_hi_min=mp->mem_max;
4342 mp->panicking=false;
4345 static void mp_reallocate_memory(MP mp, int l) ;
4348 static void mp_reallocate_memory(MP mp, int l) {
4349 XREALLOC(mp->free, l, unsigned char);
4350 XREALLOC(mp->was_free, l, unsigned char);
4352 int newarea = l-mp->mem_max;
4353 XREALLOC(mp->mem, l, memory_word);
4354 memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4356 XREALLOC(mp->mem, l, memory_word);
4357 memset(mp->mem,0,sizeof(memory_word)*(l+1));
4360 if (mp->ini_version)
4366 @ Procedure |check_mem| makes sure that the available space lists of
4367 |mem| are well formed, and it optionally prints out all locations
4368 that are reserved now but were free the last time this procedure was called.
4371 void mp_check_mem (MP mp,boolean print_locs ) {
4372 pointer p,q,r; /* current locations of interest in |mem| */
4373 boolean clobbered; /* is something amiss? */
4374 for (p=0;p<=mp->lo_mem_max;p++) {
4375 mp->free[p]=false; /* you can probably do this faster */
4377 for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4378 mp->free[p]=false; /* ditto */
4380 @<Check single-word |avail| list@>;
4381 @<Check variable-size |avail| list@>;
4382 @<Check flags of unavailable nodes@>;
4383 @<Check the list of linear dependencies@>;
4385 @<Print newly busy locations@>;
4387 memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4388 mp->was_mem_end=mp->mem_end;
4389 mp->was_lo_max=mp->lo_mem_max;
4390 mp->was_hi_min=mp->hi_mem_min;
4393 @ @<Check single-word...@>=
4394 p=mp->avail; q=null; clobbered=false;
4396 if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4397 else if ( mp->free[p] ) clobbered=true;
4399 mp_print_nl(mp, "AVAIL list clobbered at ");
4400 @.AVAIL list clobbered...@>
4401 mp_print_int(mp, q); break;
4403 mp->free[p]=true; q=p; p=mp_link(q);
4406 @ @<Check variable-size...@>=
4407 p=mp->rover; q=null; clobbered=false;
4409 if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4410 else if ( (rmp_link(p)>=mp->lo_mem_max)||(rmp_link(p)<0) ) clobbered=true;
4411 else if ( !(is_empty(p))||(node_size(p)<2)||
4412 (p+node_size(p)>mp->lo_mem_max)|| (lmp_link(rmp_link(p))!=p) ) clobbered=true;
4414 mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4415 @.Double-AVAIL list clobbered...@>
4416 mp_print_int(mp, q); break;
4418 for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4419 if ( mp->free[q] ) {
4420 mp_print_nl(mp, "Doubly free location at ");
4421 @.Doubly free location...@>
4422 mp_print_int(mp, q); break;
4427 } while (p!=mp->rover)
4430 @ @<Check flags...@>=
4432 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4433 if ( is_empty(p) ) {
4434 mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4437 while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) p++;
4438 while ( (p<=mp->lo_mem_max) && mp->free[p] ) p++;
4441 @ @<Print newly busy...@>=
4443 @<Do intialization required before printing new busy locations@>;
4444 mp_print_nl(mp, "New busy locs:");
4446 for (p=0;p<= mp->lo_mem_max;p++ ) {
4447 if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4448 @<Indicate that |p| is a new busy location@>;
4451 for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4452 if ( ! mp->free[p] &&
4453 ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4454 @<Indicate that |p| is a new busy location@>;
4457 @<Finish printing new busy locations@>;
4460 @ There might be many new busy locations so we are careful to print contiguous
4461 blocks compactly. During this operation |q| is the last new busy location and
4462 |r| is the start of the block containing |q|.
4464 @<Indicate that |p| is a new busy location@>=
4468 mp_print(mp, ".."); mp_print_int(mp, q);
4470 mp_print_char(mp, xord(' ')); mp_print_int(mp, p);
4476 @ @<Do intialization required before printing new busy locations@>=
4477 q=mp->mem_max; r=mp->mem_max
4479 @ @<Finish printing new busy locations@>=
4481 mp_print(mp, ".."); mp_print_int(mp, q);
4484 @ The |search_mem| procedure attempts to answer the question ``Who points
4485 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4486 that might not be of type |two_halves|. Strictly speaking, this is
4487 undefined, and it can lead to ``false drops'' (words that seem to
4488 point to |p| purely by coincidence). But for debugging purposes, we want
4489 to rule out the places that do {\sl not\/} point to |p|, so a few false
4490 drops are tolerable.
4493 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4494 integer q; /* current position being searched */
4495 for (q=0;q<=mp->lo_mem_max;q++) {
4496 if ( mp_link(q)==p ){
4497 mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4499 if ( mp_info(q)==p ) {
4500 mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4503 for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4504 if ( mp_link(q)==p ) {
4505 mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4507 if ( mp_info(q)==p ) {
4508 mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4511 @<Search |eqtb| for equivalents equal to |p|@>;
4514 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4515 available space list. The list is probably very short at such times, so a
4516 simple insertion sort is used. The smallest available location will be
4517 pointed to by |rover|, the next-smallest by |rmp_link(rover)|, etc.
4519 @<Internal library ...@>=
4520 void mp_sort_avail (MP mp);
4523 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4525 pointer p,q,r; /* indices into |mem| */
4526 pointer old_rover; /* initial |rover| setting */
4527 p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4528 p=rmp_link(mp->rover); rmp_link(mp->rover)=max_halfword; old_rover=mp->rover;
4529 while ( p!=old_rover ) {
4530 @<Sort |p| into the list starting at |rover|
4531 and advance |p| to |rmp_link(p)|@>;
4534 while ( rmp_link(p)!=max_halfword ) {
4535 lmp_link(rmp_link(p))=p; p=rmp_link(p);
4537 rmp_link(p)=mp->rover; lmp_link(mp->rover)=p;
4540 @ The following |while| loop is guaranteed to
4541 terminate, since the list that starts at
4542 |rover| ends with |max_halfword| during the sorting procedure.
4545 if ( p<mp->rover ) {
4546 q=p; p=rmp_link(q); rmp_link(q)=mp->rover; mp->rover=q;
4549 while ( rmp_link(q)<p ) q=rmp_link(q);
4550 r=rmp_link(p); rmp_link(p)=rmp_link(q); rmp_link(q)=p; p=r;
4554 @* \[12] The command codes.
4555 Before we can go much further, we need to define symbolic names for the internal
4556 code numbers that represent the various commands obeyed by \MP. These codes
4557 are somewhat arbitrary, but not completely so. For example,
4558 some codes have been made adjacent so that |case| statements in the
4559 program need not consider cases that are widely spaced, or so that |case|
4560 statements can be replaced by |if| statements. A command can begin an
4561 expression if and only if its code lies between |min_primary_command| and
4562 |max_primary_command|, inclusive. The first token of a statement that doesn't
4563 begin with an expression has a command code between |min_command| and
4564 |max_statement_command|, inclusive. Anything less than |min_command| is
4565 eliminated during macro expansions, and anything no more than |max_pre_command|
4566 is eliminated when expanding \TeX\ material. Ranges such as
4567 |min_secondary_command..max_secondary_command| are used when parsing
4568 expressions, but the relative ordering within such a range is generally not
4571 The ordering of the highest-numbered commands
4572 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4573 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4574 for the smallest two commands. The ordering is also important in the ranges
4575 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4577 At any rate, here is the list, for future reference.
4579 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4580 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4581 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4582 @d max_pre_command mpx_break
4583 @d if_test 4 /* conditional text (\&{if}) */
4584 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi}) */
4585 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4586 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4587 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4588 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4589 @d relax 10 /* do nothing (\.{\char`\\}) */
4590 @d scan_tokens 11 /* put a string into the input buffer */
4591 @d expand_after 12 /* look ahead one token */
4592 @d defined_macro 13 /* a macro defined by the user */
4593 @d min_command (defined_macro+1)
4594 @d save_command 14 /* save a list of tokens (\&{save}) */
4595 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4596 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4597 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4598 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4599 @d ship_out_command 19 /* output a character (\&{shipout}) */
4600 @d add_to_command 20 /* add to edges (\&{addto}) */
4601 @d bounds_command 21 /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4602 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4603 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4604 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4605 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4606 @d mp_random_seed 26 /* initialize random number generator (\&{randomseed}) */
4607 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4608 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4609 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4610 @d special_command 30 /* output special info (\&{special})
4611 or font map info (\&{fontmapfile}, \&{fontmapline}) */
4612 @d write_command 31 /* write text to a file (\&{write}) */
4613 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc.) */
4614 @d max_statement_command type_name
4615 @d min_primary_command type_name
4616 @d left_delimiter 33 /* the left delimiter of a matching pair */
4617 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4618 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4619 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4620 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4621 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4622 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4623 @d capsule_token 40 /* a value that has been put into a token list */
4624 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4625 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4626 @d min_suffix_token internal_quantity
4627 @d tag_token 43 /* a symbolic token without a primitive meaning */
4628 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4629 @d max_suffix_token numeric_token
4630 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4631 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4632 @d min_tertiary_command plus_or_minus
4633 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4634 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4635 @d max_tertiary_command tertiary_binary
4636 @d left_brace 48 /* the operator `\.{\char`\{}' */
4637 @d min_expression_command left_brace
4638 @d path_join 49 /* the operator `\.{..}' */
4639 @d ampersand 50 /* the operator `\.\&' */
4640 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4641 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4642 @d equals 53 /* the operator `\.=' */
4643 @d max_expression_command equals
4644 @d and_command 54 /* the operator `\&{and}' */
4645 @d min_secondary_command and_command
4646 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4647 @d slash 56 /* the operator `\./' */
4648 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4649 @d max_secondary_command secondary_binary
4650 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4651 @d controls 59 /* specify control points explicitly (\&{controls}) */
4652 @d tension 60 /* specify tension between knots (\&{tension}) */
4653 @d at_least 61 /* bounded tension value (\&{atleast}) */
4654 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4655 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4656 @d right_delimiter 64 /* the right delimiter of a matching pair */
4657 @d left_bracket 65 /* the operator `\.[' */
4658 @d right_bracket 66 /* the operator `\.]' */
4659 @d right_brace 67 /* the operator `\.{\char`\}}' */
4660 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4662 /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4663 @d of_token 70 /* the operator `\&{of}' */
4664 @d to_token 71 /* the operator `\&{to}' */
4665 @d step_token 72 /* the operator `\&{step}' */
4666 @d until_token 73 /* the operator `\&{until}' */
4667 @d within_token 74 /* the operator `\&{within}' */
4668 @d lig_kern_token 75
4669 /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}', etc. */
4670 @d assignment 76 /* the operator `\.{:=}' */
4671 @d skip_to 77 /* the operation `\&{skipto}' */
4672 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4673 @d double_colon 79 /* the operator `\.{::}' */
4674 @d colon 80 /* the operator `\.:' */
4676 @d comma 81 /* the operator `\.,', must be |colon+1| */
4677 @d end_of_statement (mp->cur_cmd>comma)
4678 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4679 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4680 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4681 @d max_command_code stop
4682 @d outer_tag (max_command_code+1) /* protection code added to command code */
4685 typedef int command_code;
4687 @ Variables and capsules in \MP\ have a variety of ``types,''
4688 distinguished by the code numbers defined here. These numbers are also
4689 not completely arbitrary. Things that get expanded must have types
4690 |>mp_independent|; a type remaining after expansion is numeric if and only if
4691 its code number is at least |numeric_type|; objects containing numeric
4692 parts must have types between |transform_type| and |pair_type|;
4693 all other types must be smaller than |transform_type|; and among the types
4694 that are not unknown or vacuous, the smallest two must be |boolean_type|
4695 and |string_type| in that order.
4697 @d undefined 0 /* no type has been declared */
4698 @d unknown_tag 1 /* this constant is added to certain type codes below */
4699 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4700 case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4703 enum mp_variable_type {
4704 mp_vacuous=1, /* no expression was present */
4705 mp_boolean_type, /* \&{boolean} with a known value */
4707 mp_string_type, /* \&{string} with a known value */
4709 mp_pen_type, /* \&{pen} with a known value */
4711 mp_path_type, /* \&{path} with a known value */
4713 mp_picture_type, /* \&{picture} with a known value */
4715 mp_transform_type, /* \&{transform} variable or capsule */
4716 mp_color_type, /* \&{color} variable or capsule */
4717 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4718 mp_pair_type, /* \&{pair} variable or capsule */
4719 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4720 mp_known, /* \&{numeric} with a known value */
4721 mp_dependent, /* a linear combination with |fraction| coefficients */
4722 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4723 mp_independent, /* \&{numeric} with unknown value */
4724 mp_token_list, /* variable name or suffix argument or text argument */
4725 mp_structured, /* variable with subscripts and attributes */
4726 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4727 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4731 static void mp_print_type (MP mp,quarterword t) ;
4733 @ @<Basic printing procedures@>=
4734 void mp_print_type (MP mp,quarterword t) {
4736 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4737 case mp_boolean_type:mp_print(mp, "boolean"); break;
4738 case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4739 case mp_string_type:mp_print(mp, "string"); break;
4740 case mp_unknown_string:mp_print(mp, "unknown string"); break;
4741 case mp_pen_type:mp_print(mp, "pen"); break;
4742 case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4743 case mp_path_type:mp_print(mp, "path"); break;
4744 case mp_unknown_path:mp_print(mp, "unknown path"); break;
4745 case mp_picture_type:mp_print(mp, "picture"); break;
4746 case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4747 case mp_transform_type:mp_print(mp, "transform"); break;
4748 case mp_color_type:mp_print(mp, "color"); break;
4749 case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4750 case mp_pair_type:mp_print(mp, "pair"); break;
4751 case mp_known:mp_print(mp, "known numeric"); break;
4752 case mp_dependent:mp_print(mp, "dependent"); break;
4753 case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4754 case mp_numeric_type:mp_print(mp, "numeric"); break;
4755 case mp_independent:mp_print(mp, "independent"); break;
4756 case mp_token_list:mp_print(mp, "token list"); break;
4757 case mp_structured:mp_print(mp, "mp_structured"); break;
4758 case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4759 case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4760 default: mp_print(mp, "undefined"); break;
4764 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4765 as well as a |type|. The possibilities for |name_type| are defined
4766 here; they will be explained in more detail later.
4769 enum mp_name_types {
4770 mp_root=0, /* |name_type| at the top level of a variable */
4771 mp_saved_root, /* same, when the variable has been saved */
4772 mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4773 mp_subscr, /* |name_type| in a subscript node */
4774 mp_attr, /* |name_type| in an attribute node */
4775 mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4776 mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4777 mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4778 mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4779 mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4780 mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4781 mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4782 mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4783 mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4784 mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4785 mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4786 mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4787 mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4788 mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4789 mp_capsule, /* |name_type| in stashed-away subexpressions */
4790 mp_token /* |name_type| in a numeric token or string token */
4793 @ Primitive operations that produce values have a secondary identification
4794 code in addition to their command code; it's something like genera and species.
4795 For example, `\.*' has the command code |primary_binary|, and its
4796 secondary identification is |times|. The secondary codes start at 30 so that
4797 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4798 are used as operators as well as type identifications. The relative values
4799 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4800 and |filled_op..bounded_op|. The restrictions are that
4801 |and_op-false_code=or_op-true_code|, that the ordering of
4802 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4803 and the ordering of |filled_op..bounded_op| must match that of the code
4804 values they test for.
4806 @d true_code 30 /* operation code for \.{true} */
4807 @d false_code 31 /* operation code for \.{false} */
4808 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4809 @d null_pen_code 33 /* operation code for \.{nullpen} */
4810 @d job_name_op 34 /* operation code for \.{jobname} */
4811 @d read_string_op 35 /* operation code for \.{readstring} */
4812 @d pen_circle 36 /* operation code for \.{pencircle} */
4813 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4814 @d read_from_op 38 /* operation code for \.{readfrom} */
4815 @d close_from_op 39 /* operation code for \.{closefrom} */
4816 @d odd_op 40 /* operation code for \.{odd} */
4817 @d known_op 41 /* operation code for \.{known} */
4818 @d unknown_op 42 /* operation code for \.{unknown} */
4819 @d not_op 43 /* operation code for \.{not} */
4820 @d decimal 44 /* operation code for \.{decimal} */
4821 @d reverse 45 /* operation code for \.{reverse} */
4822 @d make_path_op 46 /* operation code for \.{makepath} */
4823 @d make_pen_op 47 /* operation code for \.{makepen} */
4824 @d oct_op 48 /* operation code for \.{oct} */
4825 @d hex_op 49 /* operation code for \.{hex} */
4826 @d ASCII_op 50 /* operation code for \.{ASCII} */
4827 @d char_op 51 /* operation code for \.{char} */
4828 @d length_op 52 /* operation code for \.{length} */
4829 @d turning_op 53 /* operation code for \.{turningnumber} */
4830 @d color_model_part 54 /* operation code for \.{colormodel} */
4831 @d x_part 55 /* operation code for \.{xpart} */
4832 @d y_part 56 /* operation code for \.{ypart} */
4833 @d xx_part 57 /* operation code for \.{xxpart} */
4834 @d xy_part 58 /* operation code for \.{xypart} */
4835 @d yx_part 59 /* operation code for \.{yxpart} */
4836 @d yy_part 60 /* operation code for \.{yypart} */
4837 @d red_part 61 /* operation code for \.{redpart} */
4838 @d green_part 62 /* operation code for \.{greenpart} */
4839 @d blue_part 63 /* operation code for \.{bluepart} */
4840 @d cyan_part 64 /* operation code for \.{cyanpart} */
4841 @d magenta_part 65 /* operation code for \.{magentapart} */
4842 @d yellow_part 66 /* operation code for \.{yellowpart} */
4843 @d black_part 67 /* operation code for \.{blackpart} */
4844 @d grey_part 68 /* operation code for \.{greypart} */
4845 @d font_part 69 /* operation code for \.{fontpart} */
4846 @d text_part 70 /* operation code for \.{textpart} */
4847 @d path_part 71 /* operation code for \.{pathpart} */
4848 @d pen_part 72 /* operation code for \.{penpart} */
4849 @d dash_part 73 /* operation code for \.{dashpart} */
4850 @d sqrt_op 74 /* operation code for \.{sqrt} */
4851 @d mp_m_exp_op 75 /* operation code for \.{mexp} */
4852 @d mp_m_log_op 76 /* operation code for \.{mlog} */
4853 @d sin_d_op 77 /* operation code for \.{sind} */
4854 @d cos_d_op 78 /* operation code for \.{cosd} */
4855 @d floor_op 79 /* operation code for \.{floor} */
4856 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4857 @d char_exists_op 81 /* operation code for \.{charexists} */
4858 @d font_size 82 /* operation code for \.{fontsize} */
4859 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4860 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4861 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4862 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4863 @d arc_length 87 /* operation code for \.{arclength} */
4864 @d angle_op 88 /* operation code for \.{angle} */
4865 @d cycle_op 89 /* operation code for \.{cycle} */
4866 @d filled_op 90 /* operation code for \.{filled} */
4867 @d stroked_op 91 /* operation code for \.{stroked} */
4868 @d textual_op 92 /* operation code for \.{textual} */
4869 @d clipped_op 93 /* operation code for \.{clipped} */
4870 @d bounded_op 94 /* operation code for \.{bounded} */
4871 @d plus 95 /* operation code for \.+ */
4872 @d minus 96 /* operation code for \.- */
4873 @d times 97 /* operation code for \.* */
4874 @d over 98 /* operation code for \./ */
4875 @d pythag_add 99 /* operation code for \.{++} */
4876 @d pythag_sub 100 /* operation code for \.{+-+} */
4877 @d or_op 101 /* operation code for \.{or} */
4878 @d and_op 102 /* operation code for \.{and} */
4879 @d less_than 103 /* operation code for \.< */
4880 @d less_or_equal 104 /* operation code for \.{<=} */
4881 @d greater_than 105 /* operation code for \.> */
4882 @d greater_or_equal 106 /* operation code for \.{>=} */
4883 @d equal_to 107 /* operation code for \.= */
4884 @d unequal_to 108 /* operation code for \.{<>} */
4885 @d concatenate 109 /* operation code for \.\& */
4886 @d rotated_by 110 /* operation code for \.{rotated} */
4887 @d slanted_by 111 /* operation code for \.{slanted} */
4888 @d scaled_by 112 /* operation code for \.{scaled} */
4889 @d shifted_by 113 /* operation code for \.{shifted} */
4890 @d transformed_by 114 /* operation code for \.{transformed} */
4891 @d x_scaled 115 /* operation code for \.{xscaled} */
4892 @d y_scaled 116 /* operation code for \.{yscaled} */
4893 @d z_scaled 117 /* operation code for \.{zscaled} */
4894 @d in_font 118 /* operation code for \.{infont} */
4895 @d intersect 119 /* operation code for \.{intersectiontimes} */
4896 @d double_dot 120 /* operation code for improper \.{..} */
4897 @d substring_of 121 /* operation code for \.{substring} */
4898 @d min_of substring_of
4899 @d subpath_of 122 /* operation code for \.{subpath} */
4900 @d direction_time_of 123 /* operation code for \.{directiontime} */
4901 @d point_of 124 /* operation code for \.{point} */
4902 @d precontrol_of 125 /* operation code for \.{precontrol} */
4903 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4904 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4905 @d arc_time_of 128 /* operation code for \.{arctime} */
4906 @d mp_version 129 /* operation code for \.{mpversion} */
4907 @d envelope_of 130 /* operation code for \.{envelope} */
4909 @c static void mp_print_op (MP mp,quarterword c) {
4910 if (c<=mp_numeric_type ) {
4911 mp_print_type(mp, c);
4914 case true_code:mp_print(mp, "true"); break;
4915 case false_code:mp_print(mp, "false"); break;
4916 case null_picture_code:mp_print(mp, "nullpicture"); break;
4917 case null_pen_code:mp_print(mp, "nullpen"); break;
4918 case job_name_op:mp_print(mp, "jobname"); break;
4919 case read_string_op:mp_print(mp, "readstring"); break;
4920 case pen_circle:mp_print(mp, "pencircle"); break;
4921 case normal_deviate:mp_print(mp, "normaldeviate"); break;
4922 case read_from_op:mp_print(mp, "readfrom"); break;
4923 case close_from_op:mp_print(mp, "closefrom"); break;
4924 case odd_op:mp_print(mp, "odd"); break;
4925 case known_op:mp_print(mp, "known"); break;
4926 case unknown_op:mp_print(mp, "unknown"); break;
4927 case not_op:mp_print(mp, "not"); break;
4928 case decimal:mp_print(mp, "decimal"); break;
4929 case reverse:mp_print(mp, "reverse"); break;
4930 case make_path_op:mp_print(mp, "makepath"); break;
4931 case make_pen_op:mp_print(mp, "makepen"); break;
4932 case oct_op:mp_print(mp, "oct"); break;
4933 case hex_op:mp_print(mp, "hex"); break;
4934 case ASCII_op:mp_print(mp, "ASCII"); break;
4935 case char_op:mp_print(mp, "char"); break;
4936 case length_op:mp_print(mp, "length"); break;
4937 case turning_op:mp_print(mp, "turningnumber"); break;
4938 case x_part:mp_print(mp, "xpart"); break;
4939 case y_part:mp_print(mp, "ypart"); break;
4940 case xx_part:mp_print(mp, "xxpart"); break;
4941 case xy_part:mp_print(mp, "xypart"); break;
4942 case yx_part:mp_print(mp, "yxpart"); break;
4943 case yy_part:mp_print(mp, "yypart"); break;
4944 case red_part:mp_print(mp, "redpart"); break;
4945 case green_part:mp_print(mp, "greenpart"); break;
4946 case blue_part:mp_print(mp, "bluepart"); break;
4947 case cyan_part:mp_print(mp, "cyanpart"); break;
4948 case magenta_part:mp_print(mp, "magentapart"); break;
4949 case yellow_part:mp_print(mp, "yellowpart"); break;
4950 case black_part:mp_print(mp, "blackpart"); break;
4951 case grey_part:mp_print(mp, "greypart"); break;
4952 case color_model_part:mp_print(mp, "colormodel"); break;
4953 case font_part:mp_print(mp, "fontpart"); break;
4954 case text_part:mp_print(mp, "textpart"); break;
4955 case path_part:mp_print(mp, "pathpart"); break;
4956 case pen_part:mp_print(mp, "penpart"); break;
4957 case dash_part:mp_print(mp, "dashpart"); break;
4958 case sqrt_op:mp_print(mp, "sqrt"); break;
4959 case mp_m_exp_op:mp_print(mp, "mexp"); break;
4960 case mp_m_log_op:mp_print(mp, "mlog"); break;
4961 case sin_d_op:mp_print(mp, "sind"); break;
4962 case cos_d_op:mp_print(mp, "cosd"); break;
4963 case floor_op:mp_print(mp, "floor"); break;
4964 case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4965 case char_exists_op:mp_print(mp, "charexists"); break;
4966 case font_size:mp_print(mp, "fontsize"); break;
4967 case ll_corner_op:mp_print(mp, "llcorner"); break;
4968 case lr_corner_op:mp_print(mp, "lrcorner"); break;
4969 case ul_corner_op:mp_print(mp, "ulcorner"); break;
4970 case ur_corner_op:mp_print(mp, "urcorner"); break;
4971 case arc_length:mp_print(mp, "arclength"); break;
4972 case angle_op:mp_print(mp, "angle"); break;
4973 case cycle_op:mp_print(mp, "cycle"); break;
4974 case filled_op:mp_print(mp, "filled"); break;
4975 case stroked_op:mp_print(mp, "stroked"); break;
4976 case textual_op:mp_print(mp, "textual"); break;
4977 case clipped_op:mp_print(mp, "clipped"); break;
4978 case bounded_op:mp_print(mp, "bounded"); break;
4979 case plus:mp_print_char(mp, xord('+')); break;
4980 case minus:mp_print_char(mp, xord('-')); break;
4981 case times:mp_print_char(mp, xord('*')); break;
4982 case over:mp_print_char(mp, xord('/')); break;
4983 case pythag_add:mp_print(mp, "++"); break;
4984 case pythag_sub:mp_print(mp, "+-+"); break;
4985 case or_op:mp_print(mp, "or"); break;
4986 case and_op:mp_print(mp, "and"); break;
4987 case less_than:mp_print_char(mp, xord('<')); break;
4988 case less_or_equal:mp_print(mp, "<="); break;
4989 case greater_than:mp_print_char(mp, xord('>')); break;
4990 case greater_or_equal:mp_print(mp, ">="); break;
4991 case equal_to:mp_print_char(mp, xord('=')); break;
4992 case unequal_to:mp_print(mp, "<>"); break;
4993 case concatenate:mp_print(mp, "&"); break;
4994 case rotated_by:mp_print(mp, "rotated"); break;
4995 case slanted_by:mp_print(mp, "slanted"); break;
4996 case scaled_by:mp_print(mp, "scaled"); break;
4997 case shifted_by:mp_print(mp, "shifted"); break;
4998 case transformed_by:mp_print(mp, "transformed"); break;
4999 case x_scaled:mp_print(mp, "xscaled"); break;
5000 case y_scaled:mp_print(mp, "yscaled"); break;
5001 case z_scaled:mp_print(mp, "zscaled"); break;
5002 case in_font:mp_print(mp, "infont"); break;
5003 case intersect:mp_print(mp, "intersectiontimes"); break;
5004 case substring_of:mp_print(mp, "substring"); break;
5005 case subpath_of:mp_print(mp, "subpath"); break;
5006 case direction_time_of:mp_print(mp, "directiontime"); break;
5007 case point_of:mp_print(mp, "point"); break;
5008 case precontrol_of:mp_print(mp, "precontrol"); break;
5009 case postcontrol_of:mp_print(mp, "postcontrol"); break;
5010 case pen_offset_of:mp_print(mp, "penoffset"); break;
5011 case arc_time_of:mp_print(mp, "arctime"); break;
5012 case mp_version:mp_print(mp, "mpversion"); break;
5013 case envelope_of:mp_print(mp, "envelope"); break;
5014 default: mp_print(mp, ".."); break;
5019 @ \MP\ also has a bunch of internal parameters that a user might want to
5020 fuss with. Every such parameter has an identifying code number, defined here.
5023 enum mp_given_internal {
5024 mp_tracing_titles=1, /* show titles online when they appear */
5025 mp_tracing_equations, /* show each variable when it becomes known */
5026 mp_tracing_capsules, /* show capsules too */
5027 mp_tracing_choices, /* show the control points chosen for paths */
5028 mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
5029 mp_tracing_commands, /* show commands and operations before they are performed */
5030 mp_tracing_restores, /* show when a variable or internal is restored */
5031 mp_tracing_macros, /* show macros before they are expanded */
5032 mp_tracing_output, /* show digitized edges as they are output */
5033 mp_tracing_stats, /* show memory usage at end of job */
5034 mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
5035 mp_tracing_online, /* show long diagnostics on terminal and in the log file */
5036 mp_year, /* the current year (e.g., 1984) */
5037 mp_month, /* the current month (e.g., 3 $\equiv$ March) */
5038 mp_day, /* the current day of the month */
5039 mp_time, /* the number of minutes past midnight when this job started */
5040 mp_char_code, /* the number of the next character to be output */
5041 mp_char_ext, /* the extension code of the next character to be output */
5042 mp_char_wd, /* the width of the next character to be output */
5043 mp_char_ht, /* the height of the next character to be output */
5044 mp_char_dp, /* the depth of the next character to be output */
5045 mp_char_ic, /* the italic correction of the next character to be output */
5046 mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
5047 mp_pausing, /* positive to display lines on the terminal before they are read */
5048 mp_showstopping, /* positive to stop after each \&{show} command */
5049 mp_fontmaking, /* positive if font metric output is to be produced */
5050 mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
5051 mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
5052 mp_miterlimit, /* controls miter length as in \ps */
5053 mp_warning_check, /* controls error message when variable value is large */
5054 mp_boundary_char, /* the right boundary character for ligatures */
5055 mp_prologues, /* positive to output conforming PostScript using built-in fonts */
5056 mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
5057 mp_default_color_model, /* the default color model for unspecified items */
5058 mp_restore_clip_color,
5059 mp_procset, /* wether or not create PostScript command shortcuts */
5060 mp_gtroffmode /* whether the user specified |-troff| on the command line */
5065 @d max_given_internal mp_gtroffmode
5068 scaled *internal; /* the values of internal quantities */
5069 char **int_name; /* their names */
5070 int int_ptr; /* the maximum internal quantity defined so far */
5071 int max_internal; /* current maximum number of internal quantities */
5073 @ @<Option variables@>=
5076 @ @<Allocate or initialize ...@>=
5077 mp->max_internal=2*max_given_internal;
5078 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
5079 memset(mp->internal,0,(mp->max_internal+1)* sizeof(scaled));
5080 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
5081 memset(mp->int_name,0,(mp->max_internal+1) * sizeof(char *));
5082 mp->troff_mode=(opt->troff_mode>0 ? true : false);
5084 @ @<Exported function ...@>=
5085 int mp_troff_mode(MP mp);
5088 int mp_troff_mode(MP mp) { return mp->troff_mode; }
5090 @ @<Set initial ...@>=
5091 mp->int_ptr=max_given_internal;
5093 @ The symbolic names for internal quantities are put into \MP's hash table
5094 by using a routine called |primitive|, which will be defined later. Let us
5095 enter them now, so that we don't have to list all those names again
5098 @<Put each of \MP's primitives into the hash table@>=
5099 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5100 @:tracingtitles_}{\&{tracingtitles} primitive@>
5101 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5102 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5103 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5104 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5105 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5106 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5107 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5108 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5109 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5110 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5111 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5112 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5113 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5114 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5115 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5116 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5117 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5118 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5119 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5120 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5121 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5122 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5123 mp_primitive(mp, "year",internal_quantity,mp_year);
5124 @:mp_year_}{\&{year} primitive@>
5125 mp_primitive(mp, "month",internal_quantity,mp_month);
5126 @:mp_month_}{\&{month} primitive@>
5127 mp_primitive(mp, "day",internal_quantity,mp_day);
5128 @:mp_day_}{\&{day} primitive@>
5129 mp_primitive(mp, "time",internal_quantity,mp_time);
5130 @:time_}{\&{time} primitive@>
5131 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5132 @:mp_char_code_}{\&{charcode} primitive@>
5133 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5134 @:mp_char_ext_}{\&{charext} primitive@>
5135 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5136 @:mp_char_wd_}{\&{charwd} primitive@>
5137 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5138 @:mp_char_ht_}{\&{charht} primitive@>
5139 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5140 @:mp_char_dp_}{\&{chardp} primitive@>
5141 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5142 @:mp_char_ic_}{\&{charic} primitive@>
5143 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5144 @:mp_design_size_}{\&{designsize} primitive@>
5145 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5146 @:mp_pausing_}{\&{pausing} primitive@>
5147 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5148 @:mp_showstopping_}{\&{showstopping} primitive@>
5149 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5150 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5151 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5152 @:mp_linejoin_}{\&{linejoin} primitive@>
5153 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5154 @:mp_linecap_}{\&{linecap} primitive@>
5155 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5156 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5157 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5158 @:mp_warning_check_}{\&{warningcheck} primitive@>
5159 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5160 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5161 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5162 @:mp_prologues_}{\&{prologues} primitive@>
5163 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5164 @:mp_true_corners_}{\&{truecorners} primitive@>
5165 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5166 @:mp_procset_}{\&{mpprocset} primitive@>
5167 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5168 @:troffmode_}{\&{troffmode} primitive@>
5169 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5170 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5171 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5172 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5174 @ Colors can be specified in four color models. In the special
5175 case of |no_model|, MetaPost does not output any color operator to
5176 the postscript output.
5178 Note: these values are passed directly on to |with_option|. This only
5179 works because the other possible values passed to |with_option| are
5180 8 and 10 respectively (from |with_pen| and |with_picture|).
5182 There is a first state, that is only used for |gs_colormodel|. It flags
5183 the fact that there has not been any kind of color specification by
5184 the user so far in the game.
5187 enum mp_color_model {
5192 mp_uninitialized_model=9
5196 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5197 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5198 mp->internal[mp_restore_clip_color]=unity;
5200 @ Well, we do have to list the names one more time, for use in symbolic
5203 @<Initialize table...@>=
5204 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5205 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5206 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5207 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5208 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5209 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5210 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5211 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5212 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5213 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5214 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5215 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5216 mp->int_name[mp_year]=xstrdup("year");
5217 mp->int_name[mp_month]=xstrdup("month");
5218 mp->int_name[mp_day]=xstrdup("day");
5219 mp->int_name[mp_time]=xstrdup("time");
5220 mp->int_name[mp_char_code]=xstrdup("charcode");
5221 mp->int_name[mp_char_ext]=xstrdup("charext");
5222 mp->int_name[mp_char_wd]=xstrdup("charwd");
5223 mp->int_name[mp_char_ht]=xstrdup("charht");
5224 mp->int_name[mp_char_dp]=xstrdup("chardp");
5225 mp->int_name[mp_char_ic]=xstrdup("charic");
5226 mp->int_name[mp_design_size]=xstrdup("designsize");
5227 mp->int_name[mp_pausing]=xstrdup("pausing");
5228 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5229 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5230 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5231 mp->int_name[mp_linecap]=xstrdup("linecap");
5232 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5233 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5234 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5235 mp->int_name[mp_prologues]=xstrdup("prologues");
5236 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5237 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5238 mp->int_name[mp_procset]=xstrdup("mpprocset");
5239 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5240 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5242 @ The following procedure, which is called just before \MP\ initializes its
5243 input and output, establishes the initial values of the date and time.
5244 @^system dependencies@>
5246 Note that the values are |scaled| integers. Hence \MP\ can no longer
5247 be used after the year 32767.
5250 static void mp_fix_date_and_time (MP mp) {
5251 time_t aclock = time ((time_t *) 0);
5252 struct tm *tmptr = localtime (&aclock);
5253 mp->internal[mp_time]=
5254 (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5255 mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5256 mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5257 mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5261 static void mp_fix_date_and_time (MP mp) ;
5263 @ \MP\ is occasionally supposed to print diagnostic information that
5264 goes only into the transcript file, unless |mp_tracing_online| is positive.
5265 Now that we have defined |mp_tracing_online| we can define
5266 two routines that adjust the destination of print commands:
5269 static void mp_begin_diagnostic (MP mp) ;
5270 static void mp_end_diagnostic (MP mp,boolean blank_line);
5271 static void mp_print_diagnostic (MP mp, const char *s, const char *t, boolean nuline) ;
5273 @ @<Basic printing...@>=
5274 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5275 mp->old_setting=mp->selector;
5276 if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){
5278 if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5282 void mp_end_diagnostic (MP mp,boolean blank_line) {
5283 /* restore proper conditions after tracing */
5284 mp_print_nl(mp, "");
5285 if ( blank_line ) mp_print_ln(mp);
5286 mp->selector=mp->old_setting;
5292 unsigned int old_setting;
5294 @ We will occasionally use |begin_diagnostic| in connection with line-number
5295 printing, as follows. (The parameter |s| is typically |"Path"| or
5296 |"Cycle spec"|, etc.)
5298 @<Basic printing...@>=
5299 void mp_print_diagnostic (MP mp, const char *s, const char *t, boolean nuline) {
5300 mp_begin_diagnostic(mp);
5301 if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5302 mp_print(mp, " at line ");
5303 mp_print_int(mp, mp_true_line(mp));
5304 mp_print(mp, t); mp_print_char(mp, xord(':'));
5307 @ The 256 |ASCII_code| characters are grouped into classes by means of
5308 the |char_class| table. Individual class numbers have no semantic
5309 or syntactic significance, except in a few instances defined here.
5310 There's also |max_class|, which can be used as a basis for additional
5311 class numbers in nonstandard extensions of \MP.
5313 @d digit_class 0 /* the class number of \.{0123456789} */
5314 @d period_class 1 /* the class number of `\..' */
5315 @d space_class 2 /* the class number of spaces and nonstandard characters */
5316 @d percent_class 3 /* the class number of `\.\%' */
5317 @d string_class 4 /* the class number of `\."' */
5318 @d right_paren_class 8 /* the class number of `\.)' */
5319 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5320 @d letter_class 9 /* letters and the underline character */
5321 @d left_bracket_class 17 /* `\.[' */
5322 @d right_bracket_class 18 /* `\.]' */
5323 @d invalid_class 20 /* bad character in the input */
5324 @d max_class 20 /* the largest class number */
5327 int char_class[256]; /* the class numbers */
5329 @ If changes are made to accommodate non-ASCII character sets, they should
5330 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5331 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5332 @^system dependencies@>
5334 @<Set initial ...@>=
5335 for (k='0';k<='9';k++)
5336 mp->char_class[k]=digit_class;
5337 mp->char_class['.']=period_class;
5338 mp->char_class[' ']=space_class;
5339 mp->char_class['%']=percent_class;
5340 mp->char_class['"']=string_class;
5341 mp->char_class[',']=5;
5342 mp->char_class[';']=6;
5343 mp->char_class['(']=7;
5344 mp->char_class[')']=right_paren_class;
5345 for (k='A';k<= 'Z';k++ )
5346 mp->char_class[k]=letter_class;
5347 for (k='a';k<='z';k++)
5348 mp->char_class[k]=letter_class;
5349 mp->char_class['_']=letter_class;
5350 mp->char_class['<']=10;
5351 mp->char_class['=']=10;
5352 mp->char_class['>']=10;
5353 mp->char_class[':']=10;
5354 mp->char_class['|']=10;
5355 mp->char_class['`']=11;
5356 mp->char_class['\'']=11;
5357 mp->char_class['+']=12;
5358 mp->char_class['-']=12;
5359 mp->char_class['/']=13;
5360 mp->char_class['*']=13;
5361 mp->char_class['\\']=13;
5362 mp->char_class['!']=14;
5363 mp->char_class['?']=14;
5364 mp->char_class['#']=15;
5365 mp->char_class['&']=15;
5366 mp->char_class['@@']=15;
5367 mp->char_class['$']=15;
5368 mp->char_class['^']=16;
5369 mp->char_class['~']=16;
5370 mp->char_class['[']=left_bracket_class;
5371 mp->char_class[']']=right_bracket_class;
5372 mp->char_class['{']=19;
5373 mp->char_class['}']=19;
5375 mp->char_class[k]=invalid_class;
5376 mp->char_class['\t']=space_class;
5377 mp->char_class['\f']=space_class;
5378 for (k=127;k<=255;k++)
5379 mp->char_class[k]=invalid_class;
5381 @* \[13] The hash table.
5382 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5383 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5384 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5385 table, it is never removed.
5387 The actual sequence of characters forming a symbolic token is
5388 stored in the |str_pool| array together with all the other strings. An
5389 auxiliary array |hash| consists of items with two halfword fields per
5390 word. The first of these, called |mp_next(p)|, points to the next identifier
5391 belonging to the same coalesced list as the identifier corresponding to~|p|;
5392 and the other, called |text(p)|, points to the |str_start| entry for
5393 |p|'s identifier. If position~|p| of the hash table is empty, we have
5394 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5395 hash list, we have |mp_next(p)=0|.
5397 An auxiliary pointer variable called |hash_used| is maintained in such a
5398 way that all locations |p>=hash_used| are nonempty. The global variable
5399 |st_count| tells how many symbolic tokens have been defined, if statistics
5402 The first 256 locations of |hash| are reserved for symbols of length one.
5404 There's a parallel array called |eqtb| that contains the current equivalent
5405 values of each symbolic token. The entries of this array consist of
5406 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5407 piece of information that qualifies the |eq_type|).
5409 @d eq_type(A) mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5410 @d equiv(A) mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5411 @d hash_is_full (mp->hash_used==hash_base) /* are all positions occupied? */
5414 #define mp_next(A) mp->hash[(A)].lh /* link for coalesced lists */
5415 #define text(A) mp->hash[(A)].rh /* string number for symbolic token name */
5416 #define hash_base 257 /* hashing actually starts here */
5419 pointer hash_used; /* allocation pointer for |hash| */
5420 integer st_count; /* total number of known identifiers */
5422 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5423 since they are used in error recovery.
5426 #define hash_top (integer)(hash_base+mp->hash_size) /* the first location of the frozen area */
5427 #define frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5428 #define frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5429 #define frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5430 #define frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5431 #define frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5432 #define frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5433 #define frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5434 #define frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5435 #define frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5436 #define frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5437 #define frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5438 #define frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5439 #define frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5440 #define frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5441 #define frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5442 #define hash_end (integer)(hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5446 two_halves *hash; /* the hash table */
5447 two_halves *eqtb; /* the equivalents */
5449 @ @<Allocate or initialize ...@>=
5450 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5451 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5453 @ @<Dealloc variables@>=
5458 mp_next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5459 for (k=2;k<=hash_end;k++) {
5460 mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5463 @ @<Initialize table entries...@>=
5464 mp->hash_used=frozen_inaccessible; /* nothing is used */
5466 text(frozen_bad_vardef)=intern("a bad variable");
5467 text(frozen_etex)=intern("etex");
5468 text(frozen_mpx_break)=intern("mpxbreak");
5469 text(frozen_fi)=intern("fi");
5470 text(frozen_end_group)=intern("endgroup");
5471 text(frozen_end_def)=intern("enddef");
5472 text(frozen_end_for)=intern("endfor");
5473 text(frozen_semicolon)=intern(";");
5474 text(frozen_colon)=intern(":");
5475 text(frozen_slash)=intern("/");
5476 text(frozen_left_bracket)=intern("[");
5477 text(frozen_right_delimiter)=intern(")");
5478 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5479 eq_type(frozen_right_delimiter)=right_delimiter;
5481 @ @<Check the ``constant'' values...@>=
5482 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5484 @ Here is the subroutine that searches the hash table for an identifier
5485 that matches a given string of length~|l| appearing in |buffer[j..
5486 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5487 will always be found, and the corresponding hash table address
5491 static pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5492 integer h; /* hash code */
5493 pointer p; /* index in |hash| array */
5494 pointer k; /* index in |buffer| array */
5496 @<Treat special case of length 1 and |break|@>;
5498 @<Compute the hash code |h|@>;
5499 p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5501 if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j))
5503 if ( mp_next(p)==0 ) {
5504 @<Insert a new symbolic token after |p|, then
5505 make |p| point to it and |break|@>;
5512 @ @<Treat special case of length 1...@>=
5513 p=mp->buffer[j]+1; text(p)=p-1; return p;
5516 @ @<Insert a new symbolic...@>=
5521 mp_overflow(mp, "hash size",(integer)mp->hash_size);
5522 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5523 decr(mp->hash_used);
5524 } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5525 mp_next(p)=mp->hash_used;
5529 for (k=j;k<=j+l-1;k++) {
5530 append_char(mp->buffer[k]);
5532 text(p)=mp_make_string(mp);
5533 mp->str_ref[text(p)]=max_str_ref;
5539 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5540 should be a prime number. The theory of hashing tells us to expect fewer
5541 than two table probes, on the average, when the search is successful.
5542 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5543 @^Vitter, Jeffrey Scott@>
5545 @<Compute the hash code |h|@>=
5547 for (k=j+1;k<=j+l-1;k++){
5548 h=h+h+mp->buffer[k];
5549 while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5552 @ @<Search |eqtb| for equivalents equal to |p|@>=
5553 for (q=1;q<=hash_end;q++) {
5554 if ( equiv(q)==p ) {
5555 mp_print_nl(mp, "EQUIV(");
5556 mp_print_int(mp, q);
5557 mp_print_char(mp, xord(')'));
5561 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5562 table, together with their command code (which will be the |eq_type|)
5563 and an operand (which will be the |equiv|). The |primitive| procedure
5564 does this, in a way that no \MP\ user can. The global value |cur_sym|
5565 contains the new |eqtb| pointer after |primitive| has acted.
5568 static void mp_primitive (MP mp, const char *ss, halfword c, halfword o) {
5569 pool_pointer k; /* index into |str_pool| */
5570 quarterword j; /* index into |buffer| */
5571 quarterword l; /* length of the string */
5574 k=mp->str_start[s]; l=str_stop(s)-k;
5575 /* we will move |s| into the (empty) |buffer| */
5576 for (j=0;j<=l-1;j++) {
5577 mp->buffer[j]=mp->str_pool[k+j];
5579 mp->cur_sym=mp_id_lookup(mp, 0,l);
5580 if ( s>=256 ) { /* we don't want to have the string twice */
5581 mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5583 eq_type(mp->cur_sym)=c;
5584 equiv(mp->cur_sym)=o;
5588 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5589 by their |eq_type| alone. These primitives are loaded into the hash table
5592 @<Put each of \MP's primitives into the hash table@>=
5593 mp_primitive(mp, "..",path_join,0);
5594 @:.._}{\.{..} primitive@>
5595 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5596 @:[ }{\.{[} primitive@>
5597 mp_primitive(mp, "]",right_bracket,0);
5598 @:] }{\.{]} primitive@>
5599 mp_primitive(mp, "}",right_brace,0);
5600 @:]]}{\.{\char`\}} primitive@>
5601 mp_primitive(mp, "{",left_brace,0);
5602 @:][}{\.{\char`\{} primitive@>
5603 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5604 @:: }{\.{:} primitive@>
5605 mp_primitive(mp, "::",double_colon,0);
5606 @::: }{\.{::} primitive@>
5607 mp_primitive(mp, "||:",bchar_label,0);
5608 @:::: }{\.{\char'174\char'174:} primitive@>
5609 mp_primitive(mp, ":=",assignment,0);
5610 @::=_}{\.{:=} primitive@>
5611 mp_primitive(mp, ",",comma,0);
5612 @:, }{\., primitive@>
5613 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5614 @:; }{\.; primitive@>
5615 mp_primitive(mp, "\\",relax,0);
5616 @:]]\\}{\.{\char`\\} primitive@>
5618 mp_primitive(mp, "addto",add_to_command,0);
5619 @:add_to_}{\&{addto} primitive@>
5620 mp_primitive(mp, "atleast",at_least,0);
5621 @:at_least_}{\&{atleast} primitive@>
5622 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5623 @:begin_group_}{\&{begingroup} primitive@>
5624 mp_primitive(mp, "controls",controls,0);
5625 @:controls_}{\&{controls} primitive@>
5626 mp_primitive(mp, "curl",curl_command,0);
5627 @:curl_}{\&{curl} primitive@>
5628 mp_primitive(mp, "delimiters",delimiters,0);
5629 @:delimiters_}{\&{delimiters} primitive@>
5630 mp_primitive(mp, "endgroup",end_group,0);
5631 mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5632 @:endgroup_}{\&{endgroup} primitive@>
5633 mp_primitive(mp, "everyjob",every_job_command,0);
5634 @:every_job_}{\&{everyjob} primitive@>
5635 mp_primitive(mp, "exitif",exit_test,0);
5636 @:exit_if_}{\&{exitif} primitive@>
5637 mp_primitive(mp, "expandafter",expand_after,0);
5638 @:expand_after_}{\&{expandafter} primitive@>
5639 mp_primitive(mp, "interim",interim_command,0);
5640 @:interim_}{\&{interim} primitive@>
5641 mp_primitive(mp, "let",let_command,0);
5642 @:let_}{\&{let} primitive@>
5643 mp_primitive(mp, "newinternal",new_internal,0);
5644 @:new_internal_}{\&{newinternal} primitive@>
5645 mp_primitive(mp, "of",of_token,0);
5646 @:of_}{\&{of} primitive@>
5647 mp_primitive(mp, "randomseed",mp_random_seed,0);
5648 @:mp_random_seed_}{\&{randomseed} primitive@>
5649 mp_primitive(mp, "save",save_command,0);
5650 @:save_}{\&{save} primitive@>
5651 mp_primitive(mp, "scantokens",scan_tokens,0);
5652 @:scan_tokens_}{\&{scantokens} primitive@>
5653 mp_primitive(mp, "shipout",ship_out_command,0);
5654 @:ship_out_}{\&{shipout} primitive@>
5655 mp_primitive(mp, "skipto",skip_to,0);
5656 @:skip_to_}{\&{skipto} primitive@>
5657 mp_primitive(mp, "special",special_command,0);
5658 @:special}{\&{special} primitive@>
5659 mp_primitive(mp, "fontmapfile",special_command,1);
5660 @:fontmapfile}{\&{fontmapfile} primitive@>
5661 mp_primitive(mp, "fontmapline",special_command,2);
5662 @:fontmapline}{\&{fontmapline} primitive@>
5663 mp_primitive(mp, "step",step_token,0);
5664 @:step_}{\&{step} primitive@>
5665 mp_primitive(mp, "str",str_op,0);
5666 @:str_}{\&{str} primitive@>
5667 mp_primitive(mp, "tension",tension,0);
5668 @:tension_}{\&{tension} primitive@>
5669 mp_primitive(mp, "to",to_token,0);
5670 @:to_}{\&{to} primitive@>
5671 mp_primitive(mp, "until",until_token,0);
5672 @:until_}{\&{until} primitive@>
5673 mp_primitive(mp, "within",within_token,0);
5674 @:within_}{\&{within} primitive@>
5675 mp_primitive(mp, "write",write_command,0);
5676 @:write_}{\&{write} primitive@>
5678 @ Each primitive has a corresponding inverse, so that it is possible to
5679 display the cryptic numeric contents of |eqtb| in symbolic form.
5680 Every call of |primitive| in this program is therefore accompanied by some
5681 straightforward code that forms part of the |print_cmd_mod| routine
5684 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5685 case add_to_command:mp_print(mp, "addto"); break;
5686 case assignment:mp_print(mp, ":="); break;
5687 case at_least:mp_print(mp, "atleast"); break;
5688 case bchar_label:mp_print(mp, "||:"); break;
5689 case begin_group:mp_print(mp, "begingroup"); break;
5690 case colon:mp_print(mp, ":"); break;
5691 case comma:mp_print(mp, ","); break;
5692 case controls:mp_print(mp, "controls"); break;
5693 case curl_command:mp_print(mp, "curl"); break;
5694 case delimiters:mp_print(mp, "delimiters"); break;
5695 case double_colon:mp_print(mp, "::"); break;
5696 case end_group:mp_print(mp, "endgroup"); break;
5697 case every_job_command:mp_print(mp, "everyjob"); break;
5698 case exit_test:mp_print(mp, "exitif"); break;
5699 case expand_after:mp_print(mp, "expandafter"); break;
5700 case interim_command:mp_print(mp, "interim"); break;
5701 case left_brace:mp_print(mp, "{"); break;
5702 case left_bracket:mp_print(mp, "["); break;
5703 case let_command:mp_print(mp, "let"); break;
5704 case new_internal:mp_print(mp, "newinternal"); break;
5705 case of_token:mp_print(mp, "of"); break;
5706 case path_join:mp_print(mp, ".."); break;
5707 case mp_random_seed:mp_print(mp, "randomseed"); break;
5708 case relax:mp_print_char(mp, xord('\\')); break;
5709 case right_brace:mp_print_char(mp, xord('}')); break;
5710 case right_bracket:mp_print_char(mp, xord(']')); break;
5711 case save_command:mp_print(mp, "save"); break;
5712 case scan_tokens:mp_print(mp, "scantokens"); break;
5713 case semicolon:mp_print_char(mp, xord(';')); break;
5714 case ship_out_command:mp_print(mp, "shipout"); break;
5715 case skip_to:mp_print(mp, "skipto"); break;
5716 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5717 if ( m==1 ) mp_print(mp, "fontmapfile"); else
5718 mp_print(mp, "special"); break;
5719 case step_token:mp_print(mp, "step"); break;
5720 case str_op:mp_print(mp, "str"); break;
5721 case tension:mp_print(mp, "tension"); break;
5722 case to_token:mp_print(mp, "to"); break;
5723 case until_token:mp_print(mp, "until"); break;
5724 case within_token:mp_print(mp, "within"); break;
5725 case write_command:mp_print(mp, "write"); break;
5727 @ We will deal with the other primitives later, at some point in the program
5728 where their |eq_type| and |equiv| values are more meaningful. For example,
5729 the primitives for macro definitions will be loaded when we consider the
5730 routines that define macros.
5731 It is easy to find where each particular
5732 primitive was treated by looking in the index at the end; for example, the
5733 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5735 @* \[14] Token lists.
5736 A \MP\ token is either symbolic or numeric or a string, or it denotes
5737 a macro parameter or capsule; so there are five corresponding ways to encode it
5739 internally: (1)~A symbolic token whose hash code is~|p|
5740 is represented by the number |p|, in the |info| field of a single-word
5741 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5742 represented in a two-word node of~|mem|; the |type| field is |known|,
5743 the |name_type| field is |token|, and the |value| field holds~|v|.
5744 The fact that this token appears in a two-word node rather than a
5745 one-word node is, of course, clear from the node address.
5746 (3)~A string token is also represented in a two-word node; the |type|
5747 field is |mp_string_type|, the |name_type| field is |token|, and the
5748 |value| field holds the corresponding |str_number|. (4)~Capsules have
5749 |name_type=capsule|, and their |type| and |value| fields represent
5750 arbitrary values (in ways to be explained later). (5)~Macro parameters
5751 are like symbolic tokens in that they appear in |info| fields of
5752 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5753 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5754 by |text_base+k| if it is of type \&{text}. (Here |0<=k<param_size|.)
5755 Actual values of these parameters are kept in a separate stack, as we will
5756 see later. The constants |expr_base|, |suffix_base|, and |text_base| are,
5757 of course, chosen so that there will be no confusion between symbolic
5758 tokens and parameters of various types.
5761 the `\\{type}' field of a node has nothing to do with ``type'' in a
5762 printer's sense. It's curious that the same word is used in such different ways.
5764 @d mp_type(A) mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5765 @d mp_name_type(A) mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5766 @d token_node_size 2 /* the number of words in a large token node */
5767 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5768 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5769 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5770 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5771 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5773 @<Check the ``constant''...@>=
5774 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5776 @ We have set aside a two word node beginning at |null| so that we can have
5777 |value(null)=0|. We will make use of this coincidence later.
5779 @<Initialize table entries...@>=
5780 mp_link(null)=null; value(null)=0;
5782 @ A numeric token is created by the following trivial routine.
5785 static pointer mp_new_num_tok (MP mp,scaled v) {
5786 pointer p; /* the new node */
5787 p=mp_get_node(mp, token_node_size); value(p)=v;
5788 mp_type(p)=mp_known; mp_name_type(p)=mp_token;
5792 @ A token list is a singly linked list of nodes in |mem|, where
5793 each node contains a token and a link. Here's a subroutine that gets rid
5794 of a token list when it is no longer needed.
5796 @c static void mp_flush_token_list (MP mp,pointer p) {
5797 pointer q; /* the node being recycled */
5800 if ( q>=mp->hi_mem_min ) {
5803 switch (mp_type(q)) {
5804 case mp_vacuous: case mp_boolean_type: case mp_known:
5806 case mp_string_type:
5807 delete_str_ref(value(q));
5809 case unknown_types: case mp_pen_type: case mp_path_type:
5810 case mp_picture_type: case mp_pair_type: case mp_color_type:
5811 case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5812 case mp_proto_dependent: case mp_independent:
5813 mp_recycle_value(mp,q);
5815 default: mp_confusion(mp, "token");
5816 @:this can't happen token}{\quad token@>
5818 mp_free_node(mp, q,token_node_size);
5823 @ The procedure |show_token_list|, which prints a symbolic form of
5824 the token list that starts at a given node |p|, illustrates these
5825 conventions. The token list being displayed should not begin with a reference
5826 count. However, the procedure is intended to be fairly robust, so that if the
5827 memory links are awry or if |p| is not really a pointer to a token list,
5828 almost nothing catastrophic can happen.
5830 An additional parameter |q| is also given; this parameter is either null
5831 or it points to a node in the token list where a certain magic computation
5832 takes place that will be explained later. (Basically, |q| is non-null when
5833 we are printing the two-line context information at the time of an error
5834 message; |q| marks the place corresponding to where the second line
5837 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5838 of printing exceeds a given limit~|l|; the length of printing upon entry is
5839 assumed to be a given amount called |null_tally|. (Note that
5840 |show_token_list| sometimes uses itself recursively to print
5841 variable names within a capsule.)
5844 Unusual entries are printed in the form of all-caps tokens
5845 preceded by a space, e.g., `\.{\char`\ BAD}'.
5848 static void mp_show_token_list (MP mp, integer p, integer q, integer l,
5849 integer null_tally) ;
5852 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5853 integer null_tally) {
5854 quarterword class,c; /* the |char_class| of previous and new tokens */
5855 integer r,v; /* temporary registers */
5856 class=percent_class;
5857 mp->tally=null_tally;
5858 while ( (p!=null) && (mp->tally<l) ) {
5860 @<Do magic computation@>;
5861 @<Display token |p| and set |c| to its class;
5862 but |return| if there are problems@>;
5863 class=c; p=mp_link(p);
5866 mp_print(mp, " ETC.");
5871 @ @<Display token |p| and set |c| to its class...@>=
5872 c=letter_class; /* the default */
5873 if ( (p<0)||(p>mp->mem_end) ) {
5874 mp_print(mp, " CLOBBERED"); return;
5877 if ( p<mp->hi_mem_min ) {
5878 @<Display two-word token@>;
5881 if ( r>=expr_base ) {
5882 @<Display a parameter token@>;
5886 @<Display a collective subscript@>
5888 mp_print(mp, " IMPOSSIBLE");
5893 if ( (r<0)||(r>mp->max_str_ptr) ) {
5894 mp_print(mp, " NONEXISTENT");
5897 @<Print string |r| as a symbolic token
5898 and set |c| to its class@>;
5904 @ @<Display two-word token@>=
5905 if ( mp_name_type(p)==mp_token ) {
5906 if ( mp_type(p)==mp_known ) {
5907 @<Display a numeric token@>;
5908 } else if ( mp_type(p)!=mp_string_type ) {
5909 mp_print(mp, " BAD");
5912 mp_print_char(mp, xord('"')); mp_print_str(mp, value(p)); mp_print_char(mp, xord('"'));
5915 } else if ((mp_name_type(p)!=mp_capsule)||(mp_type(p)<mp_vacuous)||(mp_type(p)>mp_independent) ) {
5916 mp_print(mp, " BAD");
5918 mp_print_capsule(mp,p); c=right_paren_class;
5921 @ @<Display a numeric token@>=
5922 if ( class==digit_class )
5923 mp_print_char(mp, xord(' '));
5926 if ( class==left_bracket_class )
5927 mp_print_char(mp, xord(' '));
5928 mp_print_char(mp, xord('[')); mp_print_scaled(mp, v); mp_print_char(mp, xord(']'));
5929 c=right_bracket_class;
5931 mp_print_scaled(mp, v); c=digit_class;
5935 @ Strictly speaking, a genuine token will never have |mp_info(p)=0|.
5936 But we will see later (in the |print_variable_name| routine) that
5937 it is convenient to let |mp_info(p)=0| stand for `\.{[]}'.
5939 @<Display a collective subscript@>=
5941 if ( class==left_bracket_class )
5942 mp_print_char(mp, xord(' '));
5943 mp_print(mp, "[]"); c=right_bracket_class;
5946 @ @<Display a parameter token@>=
5948 if ( r<suffix_base ) {
5949 mp_print(mp, "(EXPR"); r=r-(expr_base);
5951 } else if ( r<text_base ) {
5952 mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5955 mp_print(mp, "(TEXT"); r=r-(text_base);
5958 mp_print_int(mp, r); mp_print_char(mp, xord(')')); c=right_paren_class;
5962 @ @<Print string |r| as a symbolic token...@>=
5964 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5967 case letter_class:mp_print_char(mp, xord('.')); break;
5968 case isolated_classes: break;
5969 default: mp_print_char(mp, xord(' ')); break;
5972 mp_print_str(mp, r);
5976 static void mp_print_capsule (MP mp, pointer p);
5978 @ @<Declare miscellaneous procedures that were declared |forward|@>=
5979 void mp_print_capsule (MP mp, pointer p) {
5980 mp_print_char(mp, xord('(')); mp_print_exp(mp,p,0); mp_print_char(mp, xord(')'));
5983 @ Macro definitions are kept in \MP's memory in the form of token lists
5984 that have a few extra one-word nodes at the beginning.
5986 The first node contains a reference count that is used to tell when the
5987 list is no longer needed. To emphasize the fact that a reference count is
5988 present, we shall refer to the |info| field of this special node as the
5990 @^reference counts@>
5992 The next node or nodes after the reference count serve to describe the
5993 formal parameters. They consist of zero or more parameter tokens followed
5994 by a code for the type of macro.
5996 @d ref_count mp_info
5997 /* reference count preceding a macro definition or picture header */
5998 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5999 @d general_macro 0 /* preface to a macro defined with a parameter list */
6000 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
6001 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
6002 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
6003 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
6004 @d of_macro 5 /* preface to a macro with
6005 undelimited `\&{expr} |x| \&{of}~|y|' parameters */
6006 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
6007 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
6010 static void mp_delete_mac_ref (MP mp,pointer p) {
6011 /* |p| points to the reference count of a macro list that is
6012 losing one reference */
6013 if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
6014 else decr(ref_count(p));
6017 @ The following subroutine displays a macro, given a pointer to its
6021 static void mp_show_macro (MP mp, pointer p, integer q, integer l) {
6022 pointer r; /* temporary storage */
6023 p=mp_link(p); /* bypass the reference count */
6024 while ( mp_info(p)>text_macro ){
6025 r=mp_link(p); mp_link(p)=null;
6026 mp_show_token_list(mp, p,null,l,0); mp_link(p)=r; p=r;
6027 if ( l>0 ) l=l-mp->tally; else return;
6028 } /* control printing of `\.{ETC.}' */
6031 switch(mp_info(p)) {
6032 case general_macro:mp_print(mp, "->"); break;
6034 case primary_macro: case secondary_macro: case tertiary_macro:
6035 mp_print_char(mp, xord('<'));
6036 mp_print_cmd_mod(mp, param_type,mp_info(p));
6037 mp_print(mp, ">->");
6039 case expr_macro:mp_print(mp, "<expr>->"); break;
6040 case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
6041 case suffix_macro:mp_print(mp, "<suffix>->"); break;
6042 case text_macro:mp_print(mp, "<text>->"); break;
6043 } /* there are no other cases */
6044 mp_show_token_list(mp, mp_link(p),q,l-mp->tally,0);
6047 @* \[15] Data structures for variables.
6048 The variables of \MP\ programs can be simple, like `\.x', or they can
6049 combine the structural properties of arrays and records, like `\.{x20a.b}'.
6050 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
6051 example, `\.{boolean} \.{x[]a.b}'. It's time for us to study how such
6052 things are represented inside of the computer.
6054 Each variable value occupies two consecutive words, either in a two-word
6055 node called a value node, or as a two-word subfield of a larger node. One
6056 of those two words is called the |value| field; it is an integer,
6057 containing either a |scaled| numeric value or the representation of some
6058 other type of quantity. (It might also be subdivided into halfwords, in
6059 which case it is referred to by other names instead of |value|.) The other
6060 word is broken into subfields called |type|, |name_type|, and |link|. The
6061 |type| field is a quarterword that specifies the variable's type, and
6062 |name_type| is a quarterword from which \MP\ can reconstruct the
6063 variable's name (sometimes by using the |link| field as well). Thus, only
6064 1.25 words are actually devoted to the value itself; the other
6065 three-quarters of a word are overhead, but they aren't wasted because they
6066 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
6068 In this section we shall be concerned only with the structural aspects of
6069 variables, not their values. Later parts of the program will change the
6070 |type| and |value| fields, but we shall treat those fields as black boxes
6071 whose contents should not be touched.
6073 However, if the |type| field is |mp_structured|, there is no |value| field,
6074 and the second word is broken into two pointer fields called |attr_head|
6075 and |subscr_head|. Those fields point to additional nodes that
6076 contain structural information, as we shall see.
6078 @d subscr_head_loc(A) (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
6079 @d attr_head(A) mp_info(subscr_head_loc((A))) /* pointer to attribute info */
6080 @d subscr_head(A) mp_link(subscr_head_loc((A))) /* pointer to subscript info */
6081 @d value_node_size 2 /* the number of words in a value node */
6083 @ An attribute node is three words long. Two of these words contain |type|
6084 and |value| fields as described above, and the third word contains
6085 additional information: There is an |attr_loc| field, which contains the
6086 hash address of the token that names this attribute; and there's also a
6087 |parent| field, which points to the value node of |mp_structured| type at the
6088 next higher level (i.e., at the level to which this attribute is
6089 subsidiary). The |name_type| in an attribute node is `|attr|'. The
6090 |link| field points to the next attribute with the same parent; these are
6091 arranged in increasing order, so that |attr_loc(mp_link(p))>attr_loc(p)|. The
6092 final attribute node links to the constant |end_attr|, whose |attr_loc|
6093 field is greater than any legal hash address. The |attr_head| in the
6094 parent points to a node whose |name_type| is |mp_structured_root|; this
6095 node represents the null attribute, i.e., the variable that is relevant
6096 when no attributes are attached to the parent. The |attr_head| node
6097 has the fields of either
6098 a value node, a subscript node, or an attribute node, depending on what
6099 the parent would be if it were not structured; but the subscript and
6100 attribute fields are ignored, so it effectively contains only the data of
6101 a value node. The |link| field in this special node points to an attribute
6102 node whose |attr_loc| field is zero; the latter node represents a collective
6103 subscript `\.{[]}' attached to the parent, and its |link| field points to
6104 the first non-special attribute node (or to |end_attr| if there are none).
6106 A subscript node likewise occupies three words, with |type| and |value| fields
6107 plus extra information; its |name_type| is |subscr|. In this case the
6108 third word is called the |subscript| field, which is a |scaled| integer.
6109 The |link| field points to the subscript node with the next larger
6110 subscript, if any; otherwise the |link| points to the attribute node
6111 for collective subscripts at this level. We have seen that the latter node
6112 contains an upward pointer, so that the parent can be deduced.
6114 The |name_type| in a parent-less value node is |root|, and the |link|
6115 is the hash address of the token that names this value.
6117 In other words, variables have a hierarchical structure that includes
6118 enough threads running around so that the program is able to move easily
6119 between siblings, parents, and children. An example should be helpful:
6120 (The reader is advised to draw a picture while reading the following
6121 description, since that will help to firm up the ideas.)
6122 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6123 and `\.{x20b}' have been mentioned in a user's program, where
6124 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6125 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6126 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6127 node with |mp_name_type(p)=root| and |mp_link(p)=h(x)|. We have |type(p)=mp_structured|,
6128 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6129 node and |r| to a subscript node. (Are you still following this? Use
6130 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6131 |type(q)| and |value(q)|; furthermore
6132 |mp_name_type(q)=mp_structured_root| and |mp_link(q)=q1|, where |q1| points
6133 to an attribute node representing `\.{x[]}'. Thus |mp_name_type(q1)=attr|,
6134 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6135 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6136 |qq| is a three-word ``attribute-as-value'' node with |type(qq)=numeric_type|
6137 (assuming that \.{x5} is numeric, because |qq| represents `\.{x[]}'
6138 with no further attributes), |mp_name_type(qq)=structured_root|,
6139 |attr_loc(qq)=0|, |parent(qq)=p|, and
6140 |mp_link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6141 an attribute node representing `\.{x[][]}', which has never yet
6142 occurred; its |type| field is |undefined|, and its |value| field is
6143 undefined. We have |mp_name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6144 |parent(qq1)=q1|, and |mp_link(qq1)=qq2|. Since |qq2| represents
6145 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6146 |parent(qq2)=q1|, |mp_name_type(qq2)=attr|, |mp_link(qq2)=end_attr|.
6147 (Maybe colored lines will help untangle your picture.)
6148 Node |r| is a subscript node with |type| and |value|
6149 representing `\.{x5}'; |mp_name_type(r)=subscr|, |subscript(r)=5.0|,
6150 and |mp_link(r)=r1| is another subscript node. To complete the picture,
6151 see if you can guess what |mp_link(r1)| is; give up? It's~|q1|.
6152 Furthermore |subscript(r1)=20.0|, |mp_name_type(r1)=subscr|,
6153 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6154 and we finish things off with three more nodes
6155 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6156 with a larger sheet of paper.) The value of variable \.{x20b}
6157 appears in node~|qqq2|, as you can well imagine.
6159 If the example in the previous paragraph doesn't make things crystal
6160 clear, a glance at some of the simpler subroutines below will reveal how
6161 things work out in practice.
6163 The only really unusual thing about these conventions is the use of
6164 collective subscript attributes. The idea is to avoid repeating a lot of
6165 type information when many elements of an array are identical macros
6166 (for which distinct values need not be stored) or when they don't have
6167 all of the possible attributes. Branches of the structure below collective
6168 subscript attributes do not carry actual values except for macro identifiers;
6169 branches of the structure below subscript nodes do not carry significant
6170 information in their collective subscript attributes.
6172 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6173 @d attr_loc(A) mp_info(attr_loc_loc((A))) /* hash address of this attribute */
6174 @d parent(A) mp_link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6175 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6176 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6177 @d attr_node_size 3 /* the number of words in an attribute node */
6178 @d subscr_node_size 3 /* the number of words in a subscript node */
6179 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6181 @<Initialize table...@>=
6182 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6184 @ Variables of type \&{pair} will have values that point to four-word
6185 nodes containing two numeric values. The first of these values has
6186 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6187 the |link| in the first points back to the node whose |value| points
6188 to this four-word node.
6190 Variables of type \&{transform} are similar, but in this case their
6191 |value| points to a 12-word node containing six values, identified by
6192 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6193 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6194 Finally, variables of type \&{color} have 3~values in 6~words
6195 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6197 When an entire structured variable is saved, the |root| indication
6198 is temporarily replaced by |saved_root|.
6200 Some variables have no name; they just are used for temporary storage
6201 while expressions are being evaluated. We call them {\sl capsules}.
6203 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6204 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6205 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6206 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6207 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6208 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6209 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6210 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6211 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6212 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6213 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6214 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6215 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6216 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6218 @d pair_node_size 4 /* the number of words in a pair node */
6219 @d transform_node_size 12 /* the number of words in a transform node */
6220 @d color_node_size 6 /* the number of words in a color node */
6221 @d cmykcolor_node_size 8 /* the number of words in a color node */
6224 quarterword big_node_size[mp_pair_type+1];
6225 quarterword sector0[mp_pair_type+1];
6226 quarterword sector_offset[mp_black_part_sector+1];
6228 @ The |sector0| array gives for each big node type, |name_type| values
6229 for its first subfield; the |sector_offset| array gives for each
6230 |name_type| value, the offset from the first subfield in words;
6231 and the |big_node_size| array gives the size in words for each type of
6235 mp->big_node_size[mp_transform_type]=transform_node_size;
6236 mp->big_node_size[mp_pair_type]=pair_node_size;
6237 mp->big_node_size[mp_color_type]=color_node_size;
6238 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6239 mp->sector0[mp_transform_type]=mp_x_part_sector;
6240 mp->sector0[mp_pair_type]=mp_x_part_sector;
6241 mp->sector0[mp_color_type]=mp_red_part_sector;
6242 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6243 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6244 mp->sector_offset[k]=2*(k-mp_x_part_sector);
6246 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6247 mp->sector_offset[k]=2*(k-mp_red_part_sector);
6249 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6250 mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6253 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6254 procedure call |init_big_node(p)| will allocate a pair or transform node
6255 for~|p|. The individual parts of such nodes are initially of type
6259 static void mp_init_big_node (MP mp,pointer p) {
6260 pointer q; /* the new node */
6261 quarterword s; /* its size */
6262 s=mp->big_node_size[mp_type(p)]; q=mp_get_node(mp, s);
6265 @<Make variable |q+s| newly independent@>;
6266 mp_name_type(q+s)=halfp(s)+mp->sector0[mp_type(p)];
6269 mp_link(q)=p; value(p)=q;
6272 @ The |id_transform| function creates a capsule for the
6273 identity transformation.
6276 static pointer mp_id_transform (MP mp) {
6277 pointer p,q,r; /* list manipulation registers */
6278 p=mp_get_node(mp, value_node_size); mp_type(p)=mp_transform_type;
6279 mp_name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6280 r=q+transform_node_size;
6283 mp_type(r)=mp_known; value(r)=0;
6285 value(xx_part_loc(q))=unity;
6286 value(yy_part_loc(q))=unity;
6290 @ Tokens are of type |tag_token| when they first appear, but they point
6291 to |null| until they are first used as the root of a variable.
6292 The following subroutine establishes the root node on such grand occasions.
6295 static void mp_new_root (MP mp,pointer x) {
6296 pointer p; /* the new node */
6297 p=mp_get_node(mp, value_node_size); mp_type(p)=undefined; mp_name_type(p)=mp_root;
6298 mp_link(p)=x; equiv(x)=p;
6301 @ These conventions for variable representation are illustrated by the
6302 |print_variable_name| routine, which displays the full name of a
6303 variable given only a pointer to its two-word value packet.
6306 static void mp_print_variable_name (MP mp, pointer p);
6309 void mp_print_variable_name (MP mp, pointer p) {
6310 pointer q; /* a token list that will name the variable's suffix */
6311 pointer r; /* temporary for token list creation */
6312 while ( mp_name_type(p)>=mp_x_part_sector ) {
6313 @<Preface the output with a part specifier; |return| in the
6314 case of a capsule@>;
6317 while ( mp_name_type(p)>mp_saved_root ) {
6318 @<Ascend one level, pushing a token onto list |q|
6319 and replacing |p| by its parent@>;
6321 r=mp_get_avail(mp); mp_info(r)=mp_link(p); mp_link(r)=q;
6322 if ( mp_name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6324 mp_show_token_list(mp, r,null,el_gordo,mp->tally);
6325 mp_flush_token_list(mp, r);
6328 @ @<Ascend one level, pushing a token onto list |q|...@>=
6330 if ( mp_name_type(p)==mp_subscr ) {
6331 r=mp_new_num_tok(mp, subscript(p));
6334 } while (mp_name_type(p)!=mp_attr);
6335 } else if ( mp_name_type(p)==mp_structured_root ) {
6336 p=mp_link(p); goto FOUND;
6338 if ( mp_name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6339 @:this can't happen var}{\quad var@>
6340 r=mp_get_avail(mp); mp_info(r)=attr_loc(p);
6347 @ @<Preface the output with a part specifier...@>=
6348 { switch (mp_name_type(p)) {
6349 case mp_x_part_sector: mp_print_char(mp, xord('x')); break;
6350 case mp_y_part_sector: mp_print_char(mp, xord('y')); break;
6351 case mp_xx_part_sector: mp_print(mp, "xx"); break;
6352 case mp_xy_part_sector: mp_print(mp, "xy"); break;
6353 case mp_yx_part_sector: mp_print(mp, "yx"); break;
6354 case mp_yy_part_sector: mp_print(mp, "yy"); break;
6355 case mp_red_part_sector: mp_print(mp, "red"); break;
6356 case mp_green_part_sector: mp_print(mp, "green"); break;
6357 case mp_blue_part_sector: mp_print(mp, "blue"); break;
6358 case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6359 case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6360 case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6361 case mp_black_part_sector: mp_print(mp, "black"); break;
6362 case mp_grey_part_sector: mp_print(mp, "grey"); break;
6364 mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6367 } /* there are no other cases */
6368 mp_print(mp, "part ");
6369 p=mp_link(p-mp->sector_offset[mp_name_type(p)]);
6372 @ The |interesting| function returns |true| if a given variable is not
6373 in a capsule, or if the user wants to trace capsules.
6376 static boolean mp_interesting (MP mp,pointer p) {
6377 quarterword t; /* a |name_type| */
6378 if ( mp->internal[mp_tracing_capsules]>0 ) {
6382 if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6383 t=mp_name_type(mp_link(p-mp->sector_offset[t]));
6384 return (t!=mp_capsule);
6388 @ Now here is a subroutine that converts an unstructured type into an
6389 equivalent structured type, by inserting a |mp_structured| node that is
6390 capable of growing. This operation is done only when |mp_name_type(p)=root|,
6391 |subscr|, or |attr|.
6393 The procedure returns a pointer to the new node that has taken node~|p|'s
6394 place in the structure. Node~|p| itself does not move, nor are its
6395 |value| or |type| fields changed in any way.
6398 static pointer mp_new_structure (MP mp,pointer p) {
6399 pointer q,r=0; /* list manipulation registers */
6400 switch (mp_name_type(p)) {
6402 q=mp_link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6405 @<Link a new subscript node |r| in place of node |p|@>;
6408 @<Link a new attribute node |r| in place of node |p|@>;
6411 mp_confusion(mp, "struct");
6412 @:this can't happen struct}{\quad struct@>
6415 mp_link(r)=mp_link(p); mp_type(r)=mp_structured; mp_name_type(r)=mp_name_type(p);
6416 attr_head(r)=p; mp_name_type(p)=mp_structured_root;
6417 q=mp_get_node(mp, attr_node_size); mp_link(p)=q; subscr_head(r)=q;
6418 parent(q)=r; mp_type(q)=undefined; mp_name_type(q)=mp_attr; mp_link(q)=end_attr;
6419 attr_loc(q)=collective_subscript;
6423 @ @<Link a new subscript node |r| in place of node |p|@>=
6428 } while (mp_name_type(q)!=mp_attr);
6429 q=parent(q); r=subscr_head_loc(q); /* |mp_link(r)=subscr_head(q)| */
6433 r=mp_get_node(mp, subscr_node_size);
6434 mp_link(q)=r; subscript(r)=subscript(p);
6437 @ If the attribute is |collective_subscript|, there are two pointers to
6438 node~|p|, so we must change both of them.
6440 @<Link a new attribute node |r| in place of node |p|@>=
6442 q=parent(p); r=attr_head(q);
6446 r=mp_get_node(mp, attr_node_size); mp_link(q)=r;
6447 mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6448 if ( attr_loc(p)==collective_subscript ) {
6449 q=subscr_head_loc(parent(p));
6450 while ( mp_link(q)!=p ) q=mp_link(q);
6455 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6456 list of suffixes; it returns a pointer to the corresponding two-word
6457 value. For example, if |t| points to token \.x followed by a numeric
6458 token containing the value~7, |find_variable| finds where the value of
6459 \.{x7} is stored in memory. This may seem a simple task, and it
6460 usually is, except when \.{x7} has never been referenced before.
6461 Indeed, \.x may never have even been subscripted before; complexities
6462 arise with respect to updating the collective subscript information.
6464 If a macro type is detected anywhere along path~|t|, or if the first
6465 item on |t| isn't a |tag_token|, the value |null| is returned.
6466 Otherwise |p| will be a non-null pointer to a node such that
6467 |undefined<type(p)<mp_structured|.
6469 @d abort_find { return null; }
6472 static pointer mp_find_variable (MP mp,pointer t) {
6473 pointer p,q,r,s; /* nodes in the ``value'' line */
6474 pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6475 integer n; /* subscript or attribute */
6476 memory_word save_word; /* temporary storage for a word of |mem| */
6478 p=mp_info(t); t=mp_link(t);
6479 if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6480 if ( equiv(p)==null ) mp_new_root(mp, p);
6483 @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6484 if ( t<mp->hi_mem_min ) {
6485 @<Descend one level for the subscript |value(t)|@>
6487 @<Descend one level for the attribute |mp_info(t)|@>;
6491 if ( mp_type(pp)>=mp_structured ) {
6492 if ( mp_type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6494 if ( mp_type(p)==mp_structured ) p=attr_head(p);
6495 if ( mp_type(p)==undefined ) {
6496 if ( mp_type(pp)==undefined ) { mp_type(pp)=mp_numeric_type; value(pp)=null; };
6497 mp_type(p)=mp_type(pp); value(p)=null;
6502 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6503 |pp|~stays in the collective line while |p|~goes through actual subscript
6506 @<Make sure that both nodes |p| and |pp|...@>=
6507 if ( mp_type(pp)!=mp_structured ) {
6508 if ( mp_type(pp)>mp_structured ) abort_find;
6509 ss=mp_new_structure(mp, pp);
6512 }; /* now |type(pp)=mp_structured| */
6513 if ( mp_type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6514 p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6516 @ We want this part of the program to be reasonably fast, in case there are
6518 lots of subscripts at the same level of the data structure. Therefore
6519 we store an ``infinite'' value in the word that appears at the end of the
6520 subscript list, even though that word isn't part of a subscript node.
6522 @<Descend one level for the subscript |value(t)|@>=
6525 pp=mp_link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6526 q=mp_link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6527 subscript(q)=el_gordo; s=subscr_head_loc(p); /* |mp_link(s)=subscr_head(p)| */
6530 } while (n>subscript(s));
6531 if ( n==subscript(s) ) {
6534 p=mp_get_node(mp, subscr_node_size); mp_link(r)=p; mp_link(p)=s;
6535 subscript(p)=n; mp_name_type(p)=mp_subscr; mp_type(p)=undefined;
6537 mp->mem[subscript_loc(q)]=save_word;
6540 @ @<Descend one level for the attribute |mp_info(t)|@>=
6545 rr=ss; ss=mp_link(ss);
6546 } while (n>attr_loc(ss));
6547 if ( n<attr_loc(ss) ) {
6548 qq=mp_get_node(mp, attr_node_size); mp_link(rr)=qq; mp_link(qq)=ss;
6549 attr_loc(qq)=n; mp_name_type(qq)=mp_attr; mp_type(qq)=undefined;
6550 parent(qq)=pp; ss=qq;
6555 pp=ss; s=attr_head(p);
6558 } while (n>attr_loc(s));
6559 if ( n==attr_loc(s) ) {
6562 q=mp_get_node(mp, attr_node_size); mp_link(r)=q; mp_link(q)=s;
6563 attr_loc(q)=n; mp_name_type(q)=mp_attr; mp_type(q)=undefined;
6569 @ Variables lose their former values when they appear in a type declaration,
6570 or when they are defined to be macros or \&{let} equal to something else.
6571 A subroutine will be defined later that recycles the storage associated
6572 with any particular |type| or |value|; our goal now is to study a higher
6573 level process called |flush_variable|, which selectively frees parts of a
6576 This routine has some complexity because of examples such as
6577 `\hbox{\tt numeric x[]a[]b}'
6578 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6579 `\hbox{\tt vardef x[]a[]=...}'
6580 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6581 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6582 to handle such examples is to use recursion; so that's what we~do.
6585 Parameter |p| points to the root information of the variable;
6586 parameter |t| points to a list of one-word nodes that represent
6587 suffixes, with |info=collective_subscript| for subscripts.
6590 static void mp_flush_cur_exp (MP mp,scaled v) ;
6593 static void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6594 pointer q,r; /* list manipulation */
6595 halfword n; /* attribute to match */
6597 if ( mp_type(p)!=mp_structured ) return;
6598 n=mp_info(t); t=mp_link(t);
6599 if ( n==collective_subscript ) {
6600 r=subscr_head_loc(p); q=mp_link(r); /* |q=subscr_head(p)| */
6601 while ( mp_name_type(q)==mp_subscr ){
6602 mp_flush_variable(mp, q,t,discard_suffixes);
6604 if ( mp_type(q)==mp_structured ) r=q;
6605 else { mp_link(r)=mp_link(q); mp_free_node(mp, q,subscr_node_size); }
6615 } while (attr_loc(p)<n);
6616 if ( attr_loc(p)!=n ) return;
6618 if ( discard_suffixes ) {
6619 mp_flush_below_variable(mp, p);
6621 if ( mp_type(p)==mp_structured ) p=attr_head(p);
6622 mp_recycle_value(mp, p);
6626 @ The next procedure is simpler; it wipes out everything but |p| itself,
6627 which becomes undefined.
6630 static void mp_flush_below_variable (MP mp, pointer p);
6633 void mp_flush_below_variable (MP mp,pointer p) {
6634 pointer q,r; /* list manipulation registers */
6635 if ( mp_type(p)!=mp_structured ) {
6636 mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6639 while ( mp_name_type(q)==mp_subscr ) {
6640 mp_flush_below_variable(mp, q); r=q; q=mp_link(q);
6641 mp_free_node(mp, r,subscr_node_size);
6643 r=attr_head(p); q=mp_link(r); mp_recycle_value(mp, r);
6644 if ( mp_name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6645 else mp_free_node(mp, r,subscr_node_size);
6646 /* we assume that |subscr_node_size=attr_node_size| */
6648 mp_flush_below_variable(mp, q); r=q; q=mp_link(q); mp_free_node(mp, r,attr_node_size);
6649 } while (q!=end_attr);
6650 mp_type(p)=undefined;
6654 @ Just before assigning a new value to a variable, we will recycle the
6655 old value and make the old value undefined. The |und_type| routine
6656 determines what type of undefined value should be given, based on
6657 the current type before recycling.
6660 static quarterword mp_und_type (MP mp,pointer p) {
6661 switch (mp_type(p)) {
6662 case undefined: case mp_vacuous:
6664 case mp_boolean_type: case mp_unknown_boolean:
6665 return mp_unknown_boolean;
6666 case mp_string_type: case mp_unknown_string:
6667 return mp_unknown_string;
6668 case mp_pen_type: case mp_unknown_pen:
6669 return mp_unknown_pen;
6670 case mp_path_type: case mp_unknown_path:
6671 return mp_unknown_path;
6672 case mp_picture_type: case mp_unknown_picture:
6673 return mp_unknown_picture;
6674 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6675 case mp_pair_type: case mp_numeric_type:
6677 case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6678 return mp_numeric_type;
6679 } /* there are no other cases */
6683 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6684 of a symbolic token. It must remove any variable structure or macro
6685 definition that is currently attached to that symbol. If the |saving|
6686 parameter is true, a subsidiary structure is saved instead of destroyed.
6689 static void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6690 pointer q; /* |equiv(p)| */
6692 switch (eq_type(p) % outer_tag) {
6694 case secondary_primary_macro:
6695 case tertiary_secondary_macro:
6696 case expression_tertiary_macro:
6697 if ( ! saving ) mp_delete_mac_ref(mp, q);
6702 mp_name_type(q)=mp_saved_root;
6704 mp_flush_below_variable(mp, q);
6705 mp_free_node(mp,q,value_node_size);
6712 mp->eqtb[p]=mp->eqtb[frozen_undefined];
6715 @* \[16] Saving and restoring equivalents.
6716 The nested structure given by \&{begingroup} and \&{endgroup}
6717 allows |eqtb| entries to be saved and restored, so that temporary changes
6718 can be made without difficulty. When the user requests a current value to
6719 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6720 \&{endgroup} ultimately causes the old values to be removed from the save
6721 stack and put back in their former places.
6723 The save stack is a linked list containing three kinds of entries,
6724 distinguished by their |info| fields. If |p| points to a saved item,
6728 |mp_info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6729 such an item to the save stack and each \&{endgroup} cuts back the stack
6730 until the most recent such entry has been removed.
6733 |mp_info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6734 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6738 |mp_info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6739 integer to be restored to internal parameter number~|q|. Such entries
6740 are generated by \&{interim} commands.
6743 The global variable |save_ptr| points to the top item on the save stack.
6745 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6746 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6747 @d save_boundary_item(A) { (A)=mp_get_avail(mp); mp_info((A))=0;
6748 mp_link((A))=mp->save_ptr; mp->save_ptr=(A);
6752 pointer save_ptr; /* the most recently saved item */
6754 @ @<Set init...@>=mp->save_ptr=null;
6756 @ The |save_variable| routine is given a hash address |q|; it salts this
6757 address in the save stack, together with its current equivalent,
6758 then makes token~|q| behave as though it were brand new.
6760 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6761 things from the stack when the program is not inside a group, so there's
6762 no point in wasting the space.
6765 static void mp_save_variable (MP mp,pointer q) {
6766 pointer p; /* temporary register */
6767 if ( mp->save_ptr!=null ){
6768 p=mp_get_node(mp, save_node_size); mp_info(p)=q; mp_link(p)=mp->save_ptr;
6769 saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6771 mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6774 @ Similarly, |save_internal| is given the location |q| of an internal
6775 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6779 static void mp_save_internal (MP mp,halfword q) {
6780 pointer p; /* new item for the save stack */
6781 if ( mp->save_ptr!=null ){
6782 p=mp_get_node(mp, save_node_size); mp_info(p)=hash_end+q;
6783 mp_link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6787 @ At the end of a group, the |unsave| routine restores all of the saved
6788 equivalents in reverse order. This routine will be called only when there
6789 is at least one boundary item on the save stack.
6792 static void mp_unsave (MP mp) {
6793 pointer q; /* index to saved item */
6794 pointer p; /* temporary register */
6795 while ( mp_info(mp->save_ptr)!=0 ) {
6796 q=mp_info(mp->save_ptr);
6798 if ( mp->internal[mp_tracing_restores]>0 ) {
6799 mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6800 mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, xord('='));
6801 mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, xord('}'));
6802 mp_end_diagnostic(mp, false);
6804 mp->internal[q-(hash_end)]=value(mp->save_ptr);
6806 if ( mp->internal[mp_tracing_restores]>0 ) {
6807 mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6808 mp_print_text(q); mp_print_char(mp, xord('}'));
6809 mp_end_diagnostic(mp, false);
6811 mp_clear_symbol(mp, q,false);
6812 mp->eqtb[q]=saved_equiv(mp->save_ptr);
6813 if ( eq_type(q) % outer_tag==tag_token ) {
6815 if ( p!=null ) mp_name_type(p)=mp_root;
6818 p=mp_link(mp->save_ptr);
6819 mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6821 p=mp_link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6824 @* \[17] Data structures for paths.
6825 When a \MP\ user specifies a path, \MP\ will create a list of knots
6826 and control points for the associated cubic spline curves. If the
6827 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6828 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6829 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6830 @:Bezier}{B\'ezier, Pierre Etienne@>
6831 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6832 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6835 There is a 8-word node for each knot $z_k$, containing one word of
6836 control information and six words for the |x| and |y| coordinates of
6837 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6838 |mp_left_type| and |mp_right_type| fields, which each occupy a quarter of
6839 the first word in the node; they specify properties of the curve as it
6840 enters and leaves the knot. There's also a halfword |link| field,
6841 which points to the following knot, and a final supplementary word (of
6842 which only a quarter is used).
6844 If the path is a closed contour, knots 0 and |n| are identical;
6845 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6846 is not closed, the |mp_left_type| of knot~0 and the |mp_right_type| of knot~|n|
6847 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6848 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6850 @d mp_left_type(A) mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6851 @d mp_right_type(A) mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6852 @d mp_x_coord(A) mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6853 @d mp_y_coord(A) mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6854 @d mp_left_x(A) mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6855 @d mp_left_y(A) mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6856 @d mp_right_x(A) mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6857 @d mp_right_y(A) mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6858 @d x_loc(A) ((A)+1) /* where the |x| coordinate is stored in a knot */
6859 @d y_loc(A) ((A)+2) /* where the |y| coordinate is stored in a knot */
6860 @d knot_coord(A) mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6861 @d left_coord(A) mp->mem[(A)+2].sc
6862 /* coordinate of previous control point given |x_loc| or |y_loc| */
6863 @d right_coord(A) mp->mem[(A)+4].sc
6864 /* coordinate of next control point given |x_loc| or |y_loc| */
6865 @d knot_node_size 8 /* number of words in a knot node */
6869 mp_endpoint=0, /* |mp_left_type| at path beginning and |mp_right_type| at path end */
6870 mp_explicit, /* |mp_left_type| or |mp_right_type| when control points are known */
6871 mp_given, /* |mp_left_type| or |mp_right_type| when a direction is given */
6872 mp_curl, /* |mp_left_type| or |mp_right_type| when a curl is desired */
6873 mp_open, /* |mp_left_type| or |mp_right_type| when \MP\ should choose the direction */
6877 @ Before the B\'ezier control points have been calculated, the memory
6878 space they will ultimately occupy is taken up by information that can be
6879 used to compute them. There are four cases:
6882 \textindent{$\bullet$} If |mp_right_type=mp_open|, the curve should leave
6883 the knot in the same direction it entered; \MP\ will figure out a
6887 \textindent{$\bullet$} If |mp_right_type=mp_curl|, the curve should leave the
6888 knot in a direction depending on the angle at which it enters the next
6889 knot and on the curl parameter stored in |right_curl|.
6892 \textindent{$\bullet$} If |mp_right_type=mp_given|, the curve should leave the
6893 knot in a nonzero direction stored as an |angle| in |right_given|.
6896 \textindent{$\bullet$} If |mp_right_type=mp_explicit|, the B\'ezier control
6897 point for leaving this knot has already been computed; it is in the
6898 |mp_right_x| and |mp_right_y| fields.
6901 The rules for |mp_left_type| are similar, but they refer to the curve entering
6902 the knot, and to \\{left} fields instead of \\{right} fields.
6904 Non-|explicit| control points will be chosen based on ``tension'' parameters
6905 in the |left_tension| and |right_tension| fields. The
6906 `\&{atleast}' option is represented by negative tension values.
6907 @:at_least_}{\&{atleast} primitive@>
6909 For example, the \MP\ path specification
6910 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6912 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6914 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6915 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6916 |mp_left_type|&\\{left} info&|mp_x_coord,mp_y_coord|&|mp_right_type|&\\{right} info\cr
6918 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6919 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6920 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6921 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6922 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6923 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6924 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6925 Of course, this example is more complicated than anything a normal user
6928 These types must satisfy certain restrictions because of the form of \MP's
6930 (i)~|open| type never appears in the same node together with |endpoint|,
6932 (ii)~The |mp_right_type| of a node is |explicit| if and only if the
6933 |mp_left_type| of the following node is |explicit|.
6934 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6936 @d left_curl mp_left_x /* curl information when entering this knot */
6937 @d left_given mp_left_x /* given direction when entering this knot */
6938 @d left_tension mp_left_y /* tension information when entering this knot */
6939 @d right_curl mp_right_x /* curl information when leaving this knot */
6940 @d right_given mp_right_x /* given direction when leaving this knot */
6941 @d right_tension mp_right_y /* tension information when leaving this knot */
6943 @ Knots can be user-supplied, or they can be created by program code,
6944 like the |split_cubic| function, or |copy_path|. The distinction is
6945 needed for the cleanup routine that runs after |split_cubic|, because
6946 it should only delete knots it has previously inserted, and never
6947 anything that was user-supplied. In order to be able to differentiate
6948 one knot from another, we will set |originator(p):=mp_metapost_user| when
6949 it appeared in the actual metapost program, and
6950 |originator(p):=mp_program_code| in all other cases.
6952 @d mp_originator(A) mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6955 enum mp_knot_originator {
6956 mp_program_code=0, /* not created by a user */
6957 mp_metapost_user /* created by a user */
6960 @ Here is a routine that prints a given knot list
6961 in symbolic form. It illustrates the conventions discussed above,
6962 and checks for anomalies that might arise while \MP\ is being debugged.
6965 static void mp_pr_path (MP mp,pointer h);
6968 void mp_pr_path (MP mp,pointer h) {
6969 pointer p,q; /* for list traversal */
6973 if ( (p==null)||(q==null) ) {
6974 mp_print_nl(mp, "???"); return; /* this won't happen */
6977 @<Print information for adjacent knots |p| and |q|@>;
6980 if ( (p!=h)||(mp_left_type(h)!=mp_endpoint) ) {
6981 @<Print two dots, followed by |given| or |curl| if present@>;
6984 if ( mp_left_type(h)!=mp_endpoint )
6985 mp_print(mp, "cycle");
6988 @ @<Print information for adjacent knots...@>=
6989 mp_print_two(mp, mp_x_coord(p),mp_y_coord(p));
6990 switch (mp_right_type(p)) {
6992 if ( mp_left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6994 if ( (mp_left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6998 @<Print control points between |p| and |q|, then |goto done1|@>;
7001 @<Print information for a curve that begins |open|@>;
7005 @<Print information for a curve that begins |curl| or |given|@>;
7008 mp_print(mp, "???"); /* can't happen */
7012 if ( mp_left_type(q)<=mp_explicit ) {
7013 mp_print(mp, "..control?"); /* can't happen */
7015 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
7016 @<Print tension between |p| and |q|@>;
7019 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
7020 were |scaled|, the magnitude of a |given| direction vector will be~4096.
7022 @<Print two dots...@>=
7024 mp_print_nl(mp, " ..");
7025 if ( mp_left_type(p)==mp_given ) {
7026 mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, xord('{'));
7027 mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, xord(','));
7028 mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, xord('}'));
7029 } else if ( mp_left_type(p)==mp_curl ){
7030 mp_print(mp, "{curl ");
7031 mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, xord('}'));
7035 @ @<Print tension between |p| and |q|@>=
7037 mp_print(mp, "..tension ");
7038 if ( right_tension(p)<0 ) mp_print(mp, "atleast");
7039 mp_print_scaled(mp, abs(right_tension(p)));
7040 if ( right_tension(p)!=left_tension(q) ){
7041 mp_print(mp, " and ");
7042 if ( left_tension(q)<0 ) mp_print(mp, "atleast");
7043 mp_print_scaled(mp, abs(left_tension(q)));
7047 @ @<Print control points between |p| and |q|, then |goto done1|@>=
7049 mp_print(mp, "..controls ");
7050 mp_print_two(mp, mp_right_x(p),mp_right_y(p));
7051 mp_print(mp, " and ");
7052 if ( mp_left_type(q)!=mp_explicit ) {
7053 mp_print(mp, "??"); /* can't happen */
7056 mp_print_two(mp, mp_left_x(q),mp_left_y(q));
7061 @ @<Print information for a curve that begins |open|@>=
7062 if ( (mp_left_type(p)!=mp_explicit)&&(mp_left_type(p)!=mp_open) ) {
7063 mp_print(mp, "{open?}"); /* can't happen */
7067 @ A curl of 1 is shown explicitly, so that the user sees clearly that
7068 \MP's default curl is present.
7070 @<Print information for a curve that begins |curl|...@>=
7072 if ( mp_left_type(p)==mp_open )
7073 mp_print(mp, "??"); /* can't happen */
7075 if ( mp_right_type(p)==mp_curl ) {
7076 mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
7078 mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, xord('{'));
7079 mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, xord(','));
7080 mp_print_scaled(mp, mp->n_sin);
7082 mp_print_char(mp, xord('}'));
7085 @ It is convenient to have another version of |pr_path| that prints the path
7086 as a diagnostic message.
7089 static void mp_print_path (MP mp,pointer h, const char *s, boolean nuline) ;
7092 void mp_print_path (MP mp,pointer h, const char *s, boolean nuline) {
7093 mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
7096 mp_end_diagnostic(mp, true);
7099 @ If we want to duplicate a knot node, we can say |copy_knot|:
7102 static pointer mp_copy_knot (MP mp,pointer p) {
7103 pointer q; /* the copy */
7104 int k; /* runs through the words of a knot node */
7105 q=mp_get_node(mp, knot_node_size);
7106 for (k=0;k<knot_node_size;k++) {
7107 mp->mem[q+k]=mp->mem[p+k];
7109 mp_originator(q)=mp_originator(p);
7113 @ The |copy_path| routine makes a clone of a given path.
7116 static pointer mp_copy_path (MP mp, pointer p) {
7117 pointer q,pp,qq; /* for list manipulation */
7118 q=mp_copy_knot(mp, p);
7119 qq=q; pp=mp_link(p);
7121 mp_link(qq)=mp_copy_knot(mp, pp);
7130 @ Just before |ship_out|, knot lists are exported for printing.
7132 The |gr_XXXX| macros are defined in |mppsout.h|.
7135 static mp_knot *mp_export_knot (MP mp,pointer p) {
7136 mp_knot *q; /* the copy */
7139 q = xmalloc(1, sizeof (mp_knot));
7140 memset(q,0,sizeof (mp_knot));
7141 gr_left_type(q) = (unsigned short)mp_left_type(p);
7142 gr_right_type(q) = (unsigned short)mp_right_type(p);
7143 gr_x_coord(q) = mp_x_coord(p);
7144 gr_y_coord(q) = mp_y_coord(p);
7145 gr_left_x(q) = mp_left_x(p);
7146 gr_left_y(q) = mp_left_y(p);
7147 gr_right_x(q) = mp_right_x(p);
7148 gr_right_y(q) = mp_right_y(p);
7149 gr_originator(q) = (unsigned char)mp_originator(p);
7153 @ The |export_knot_list| routine therefore also makes a clone
7157 static mp_knot *mp_export_knot_list (MP mp, pointer p) {
7158 mp_knot *q, *qq; /* for list manipulation */
7159 pointer pp; /* for list manipulation */
7162 q=mp_export_knot(mp, p);
7163 qq=q; pp=mp_link(p);
7165 gr_next_knot(qq)=mp_export_knot(mp, pp);
7166 qq=gr_next_knot(qq);
7174 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7175 returns a pointer to the first node of the copy, if the path is a cycle,
7176 but to the final node of a non-cyclic copy. The global
7177 variable |path_tail| will point to the final node of the original path;
7178 this trick makes it easier to implement `\&{doublepath}'.
7180 All node types are assumed to be |endpoint| or |explicit| only.
7183 static pointer mp_htap_ypoc (MP mp,pointer p) {
7184 pointer q,pp,qq,rr; /* for list manipulation */
7185 q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7188 mp_right_type(qq)=mp_left_type(pp); mp_left_type(qq)=mp_right_type(pp);
7189 mp_x_coord(qq)=mp_x_coord(pp); mp_y_coord(qq)=mp_y_coord(pp);
7190 mp_right_x(qq)=mp_left_x(pp); mp_right_y(qq)=mp_left_y(pp);
7191 mp_left_x(qq)=mp_right_x(pp); mp_left_y(qq)=mp_right_y(pp);
7192 mp_originator(qq)=mp_originator(pp);
7193 if ( mp_link(pp)==p ) {
7194 mp_link(q)=qq; mp->path_tail=pp; return q;
7196 rr=mp_get_node(mp, knot_node_size); mp_link(rr)=qq; qq=rr; pp=mp_link(pp);
7201 pointer path_tail; /* the node that links to the beginning of a path */
7203 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7204 calling the following subroutine.
7207 static void mp_toss_knot_list (MP mp,pointer p) ;
7210 void mp_toss_knot_list (MP mp,pointer p) {
7211 pointer q; /* the node being freed */
7212 pointer r; /* the next node */
7216 mp_free_node(mp, q,knot_node_size); q=r;
7220 @* \[18] Choosing control points.
7221 Now we must actually delve into one of \MP's more difficult routines,
7222 the |make_choices| procedure that chooses angles and control points for
7223 the splines of a curve when the user has not specified them explicitly.
7224 The parameter to |make_choices| points to a list of knots and
7225 path information, as described above.
7227 A path decomposes into independent segments at ``breakpoint'' knots,
7228 which are knots whose left and right angles are both prespecified in
7229 some way (i.e., their |mp_left_type| and |mp_right_type| aren't both open).
7232 static void mp_make_choices (MP mp,pointer knots) {
7233 pointer h; /* the first breakpoint */
7234 pointer p,q; /* consecutive breakpoints being processed */
7235 @<Other local variables for |make_choices|@>;
7236 check_arith; /* make sure that |arith_error=false| */
7237 if ( mp->internal[mp_tracing_choices]>0 )
7238 mp_print_path(mp, knots,", before choices",true);
7239 @<If consecutive knots are equal, join them explicitly@>;
7240 @<Find the first breakpoint, |h|, on the path;
7241 insert an artificial breakpoint if the path is an unbroken cycle@>;
7244 @<Fill in the control points between |p| and the next breakpoint,
7245 then advance |p| to that breakpoint@>;
7247 if ( mp->internal[mp_tracing_choices]>0 )
7248 mp_print_path(mp, knots,", after choices",true);
7249 if ( mp->arith_error ) {
7250 @<Report an unexpected problem during the choice-making@>;
7254 @ @<Report an unexpected problem during the choice...@>=
7256 print_err("Some number got too big");
7257 @.Some number got too big@>
7258 help2("The path that I just computed is out of range.",
7259 "So it will probably look funny. Proceed, for a laugh.");
7260 mp_put_get_error(mp); mp->arith_error=false;
7263 @ Two knots in a row with the same coordinates will always be joined
7264 by an explicit ``curve'' whose control points are identical with the
7267 @<If consecutive knots are equal, join them explicitly@>=
7271 if ( mp_x_coord(p)==mp_x_coord(q) &&
7272 mp_y_coord(p)==mp_y_coord(q) && mp_right_type(p)>mp_explicit ) {
7273 mp_right_type(p)=mp_explicit;
7274 if ( mp_left_type(p)==mp_open ) {
7275 mp_left_type(p)=mp_curl; left_curl(p)=unity;
7277 mp_left_type(q)=mp_explicit;
7278 if ( mp_right_type(q)==mp_open ) {
7279 mp_right_type(q)=mp_curl; right_curl(q)=unity;
7281 mp_right_x(p)=mp_x_coord(p); mp_left_x(q)=mp_x_coord(p);
7282 mp_right_y(p)=mp_y_coord(p); mp_left_y(q)=mp_y_coord(p);
7287 @ If there are no breakpoints, it is necessary to compute the direction
7288 angles around an entire cycle. In this case the |mp_left_type| of the first
7289 node is temporarily changed to |end_cycle|.
7291 @<Find the first breakpoint, |h|, on the path...@>=
7294 if ( mp_left_type(h)!=mp_open ) break;
7295 if ( mp_right_type(h)!=mp_open ) break;
7298 mp_left_type(h)=mp_end_cycle; break;
7302 @ If |mp_right_type(p)<given| and |q=mp_link(p)|, we must have
7303 |mp_right_type(p)=mp_left_type(q)=mp_explicit| or |endpoint|.
7305 @<Fill in the control points between |p| and the next breakpoint...@>=
7307 if ( mp_right_type(p)>=mp_given ) {
7308 while ( (mp_left_type(q)==mp_open)&&(mp_right_type(q)==mp_open) ) q=mp_link(q);
7309 @<Fill in the control information between
7310 consecutive breakpoints |p| and |q|@>;
7311 } else if ( mp_right_type(p)==mp_endpoint ) {
7312 @<Give reasonable values for the unused control points between |p| and~|q|@>;
7316 @ This step makes it possible to transform an explicitly computed path without
7317 checking the |mp_left_type| and |mp_right_type| fields.
7319 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7321 mp_right_x(p)=mp_x_coord(p); mp_right_y(p)=mp_y_coord(p);
7322 mp_left_x(q)=mp_x_coord(q); mp_left_y(q)=mp_y_coord(q);
7325 @ Before we can go further into the way choices are made, we need to
7326 consider the underlying theory. The basic ideas implemented in |make_choices|
7327 are due to John Hobby, who introduced the notion of ``mock curvature''
7328 @^Hobby, John Douglas@>
7329 at a knot. Angles are chosen so that they preserve mock curvature when
7330 a knot is passed, and this has been found to produce excellent results.
7332 It is convenient to introduce some notations that simplify the necessary
7333 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7334 between knots |k| and |k+1|; and let
7335 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7336 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7337 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7338 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7339 $$\eqalign{z_k^+&=z_k+
7340 \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7342 \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7343 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7344 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7345 corresponding ``offset angles.'' These angles satisfy the condition
7346 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7347 whenever the curve leaves an intermediate knot~|k| in the direction that
7350 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7351 the curve at its beginning and ending points. This means that
7352 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7353 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7354 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7355 z\k^-,z\k^{\phantom+};t)$
7358 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7359 \qquad{\rm and}\qquad
7360 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7361 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7363 approximation to this true curvature that arises in the limit for
7364 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7365 The standard velocity function satisfies
7366 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7367 hence the mock curvatures are respectively
7368 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7369 \qquad{\rm and}\qquad
7370 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7372 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7373 determines $\phi_k$ when $\theta_k$ is known, so the task of
7374 angle selection is essentially to choose appropriate values for each
7375 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7376 from $(**)$, we obtain a system of linear equations of the form
7377 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7379 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7380 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7381 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7382 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7383 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7384 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7385 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7386 hence they have a unique solution. Moreover, in most cases the tensions
7387 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7388 solution numerically stable, and there is an exponential damping
7389 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7390 a factor of~$O(2^{-j})$.
7392 @ However, we still must consider the angles at the starting and ending
7393 knots of a non-cyclic path. These angles might be given explicitly, or
7394 they might be specified implicitly in terms of an amount of ``curl.''
7396 Let's assume that angles need to be determined for a non-cyclic path
7397 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7398 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7399 have been given for $0<k<n$, and it will be convenient to introduce
7400 equations of the same form for $k=0$ and $k=n$, where
7401 $$A_0=B_0=C_n=D_n=0.$$
7402 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7403 define $C_0=1$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7404 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7405 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7406 mock curvature at $z_1$; i.e.,
7407 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7408 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7409 This equation simplifies to
7410 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7411 \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7412 -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7413 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7414 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7415 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7416 hence the linear equations remain nonsingular.
7418 Similar considerations apply at the right end, when the final angle $\phi_n$
7419 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7420 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7422 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7423 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7424 \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7426 When |make_choices| chooses angles, it must compute the coefficients of
7427 these linear equations, then solve the equations. To compute the coefficients,
7428 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7429 When the equations are solved, the chosen directions $\theta_k$ are put
7430 back into the form of control points by essentially computing sines and
7433 @ OK, we are ready to make the hard choices of |make_choices|.
7434 Most of the work is relegated to an auxiliary procedure
7435 called |solve_choices|, which has been introduced to keep
7436 |make_choices| from being extremely long.
7438 @<Fill in the control information between...@>=
7439 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7440 set $n$ to the length of the path@>;
7441 @<Remove |open| types at the breakpoints@>;
7442 mp_solve_choices(mp, p,q,n)
7444 @ It's convenient to precompute quantities that will be needed several
7445 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7446 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7447 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7448 and $z\k-z_k$ will be stored in |psi[k]|.
7451 int path_size; /* maximum number of knots between breakpoints of a path */
7454 scaled *delta; /* knot differences */
7455 angle *psi; /* turning angles */
7457 @ @<Dealloc variables@>=
7463 @ @<Other local variables for |make_choices|@>=
7464 int k,n; /* current and final knot numbers */
7465 pointer s,t; /* registers for list traversal */
7466 scaled delx,dely; /* directions where |open| meets |explicit| */
7467 fraction sine,cosine; /* trig functions of various angles */
7469 @ @<Calculate the turning angles...@>=
7472 k=0; s=p; n=mp->path_size;
7475 mp->delta_x[k]=mp_x_coord(t)-mp_x_coord(s);
7476 mp->delta_y[k]=mp_y_coord(t)-mp_y_coord(s);
7477 mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7479 sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7480 cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7481 mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7482 mp_take_fraction(mp, mp->delta_y[k],sine),
7483 mp_take_fraction(mp, mp->delta_y[k],cosine)-
7484 mp_take_fraction(mp, mp->delta_x[k],sine));
7487 if ( k==mp->path_size ) {
7488 mp_reallocate_paths(mp, mp->path_size+(mp->path_size/4));
7489 goto RESTART; /* retry, loop size has changed */
7492 } while (!((k>=n)&&(mp_left_type(s)!=mp_end_cycle)));
7493 if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7496 @ When we get to this point of the code, |mp_right_type(p)| is either
7497 |given| or |curl| or |open|. If it is |open|, we must have
7498 |mp_left_type(p)=mp_end_cycle| or |mp_left_type(p)=mp_explicit|. In the latter
7499 case, the |open| type is converted to |given|; however, if the
7500 velocity coming into this knot is zero, the |open| type is
7501 converted to a |curl|, since we don't know the incoming direction.
7503 Similarly, |mp_left_type(q)| is either |given| or |curl| or |open| or
7504 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7506 @<Remove |open| types at the breakpoints@>=
7507 if ( mp_left_type(q)==mp_open ) {
7508 delx=mp_right_x(q)-mp_x_coord(q); dely=mp_right_y(q)-mp_y_coord(q);
7509 if ( (delx==0)&&(dely==0) ) {
7510 mp_left_type(q)=mp_curl; left_curl(q)=unity;
7512 mp_left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7515 if ( (mp_right_type(p)==mp_open)&&(mp_left_type(p)==mp_explicit) ) {
7516 delx=mp_x_coord(p)-mp_left_x(p); dely=mp_y_coord(p)-mp_left_y(p);
7517 if ( (delx==0)&&(dely==0) ) {
7518 mp_right_type(p)=mp_curl; right_curl(p)=unity;
7520 mp_right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7524 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7525 and exactly one of the breakpoints involves a curl. The simplest case occurs
7526 when |n=1| and there is a curl at both breakpoints; then we simply draw
7529 But before coding up the simple cases, we might as well face the general case,
7530 since we must deal with it sooner or later, and since the general case
7531 is likely to give some insight into the way simple cases can be handled best.
7533 When there is no cycle, the linear equations to be solved form a tridiagonal
7534 system, and we can apply the standard technique of Gaussian elimination
7535 to convert that system to a sequence of equations of the form
7536 $$\theta_0+u_0\theta_1=v_0,\quad
7537 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7538 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7540 It is possible to do this diagonalization while generating the equations.
7541 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7542 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7544 The procedure is slightly more complex when there is a cycle, but the
7545 basic idea will be nearly the same. In the cyclic case the right-hand
7546 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7547 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7548 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7549 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7550 eliminate the $w$'s from the system, after which the solution can be
7553 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7554 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7555 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7556 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7559 angle *theta; /* values of $\theta_k$ */
7560 fraction *uu; /* values of $u_k$ */
7561 angle *vv; /* values of $v_k$ */
7562 fraction *ww; /* values of $w_k$ */
7564 @ @<Dealloc variables@>=
7571 static void mp_reallocate_paths (MP mp, int l);
7574 void mp_reallocate_paths (MP mp, int l) {
7575 XREALLOC (mp->delta_x, l, scaled);
7576 XREALLOC (mp->delta_y, l, scaled);
7577 XREALLOC (mp->delta, l, scaled);
7578 XREALLOC (mp->psi, l, angle);
7579 XREALLOC (mp->theta, l, angle);
7580 XREALLOC (mp->uu, l, fraction);
7581 XREALLOC (mp->vv, l, angle);
7582 XREALLOC (mp->ww, l, fraction);
7586 @ Our immediate problem is to get the ball rolling by setting up the
7587 first equation or by realizing that no equations are needed, and to fit
7588 this initialization into a framework suitable for the overall computation.
7591 static void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) ;
7594 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7595 int k; /* current knot number */
7596 pointer r,s,t; /* registers for list traversal */
7597 @<Other local variables for |solve_choices|@>;
7602 @<Get the linear equations started; or |return|
7603 with the control points in place, if linear equations
7606 switch (mp_left_type(s)) {
7607 case mp_end_cycle: case mp_open:
7608 @<Set up equation to match mock curvatures
7609 at $z_k$; then |goto found| with $\theta_n$
7610 adjusted to equal $\theta_0$, if a cycle has ended@>;
7613 @<Set up equation for a curl at $\theta_n$
7617 @<Calculate the given value of $\theta_n$
7620 } /* there are no other cases */
7625 @<Finish choosing angles and assigning control points@>;
7628 @ On the first time through the loop, we have |k=0| and |r| is not yet
7629 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7631 @<Get the linear equations started...@>=
7632 switch (mp_right_type(s)) {
7634 if ( mp_left_type(t)==mp_given ) {
7635 @<Reduce to simple case of two givens and |return|@>
7637 @<Set up the equation for a given value of $\theta_0$@>;
7641 if ( mp_left_type(t)==mp_curl ) {
7642 @<Reduce to simple case of straight line and |return|@>
7644 @<Set up the equation for a curl at $\theta_0$@>;
7648 mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7649 /* this begins a cycle */
7651 } /* there are no other cases */
7653 @ The general equation that specifies equality of mock curvature at $z_k$ is
7654 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7655 as derived above. We want to combine this with the already-derived equation
7656 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7658 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7660 $$(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}
7661 -A_kw_{k-1}\theta_0$$
7662 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7663 fixed-point arithmetic, avoiding the chance of overflow while retaining
7666 The calculations will be performed in several registers that
7667 provide temporary storage for intermediate quantities.
7669 @<Other local variables for |solve_choices|@>=
7670 fraction aa,bb,cc,ff,acc; /* temporary registers */
7671 scaled dd,ee; /* likewise, but |scaled| */
7672 scaled lt,rt; /* tension values */
7674 @ @<Set up equation to match mock curvatures...@>=
7675 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7676 $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7677 and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7678 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7679 mp->uu[k]=mp_take_fraction(mp, ff,bb);
7680 @<Calculate the values of $v_k$ and $w_k$@>;
7681 if ( mp_left_type(s)==mp_end_cycle ) {
7682 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7686 @ Since tension values are never less than 3/4, the values |aa| and
7687 |bb| computed here are never more than 4/5.
7689 @<Calculate the values $\\{aa}=...@>=
7690 if ( abs(right_tension(r))==unity) {
7691 aa=fraction_half; dd=2*mp->delta[k];
7693 aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7694 dd=mp_take_fraction(mp, mp->delta[k],
7695 fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7697 if ( abs(left_tension(t))==unity ){
7698 bb=fraction_half; ee=2*mp->delta[k-1];
7700 bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7701 ee=mp_take_fraction(mp, mp->delta[k-1],
7702 fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7704 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7706 @ The ratio to be calculated in this step can be written in the form
7707 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7708 \\{cc}\cdot\\{dd},$$
7709 because of the quantities just calculated. The values of |dd| and |ee|
7710 will not be needed after this step has been performed.
7712 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7713 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7714 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7716 ff=mp_make_fraction(mp, lt,rt);
7717 ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7718 dd=mp_take_fraction(mp, dd,ff);
7720 ff=mp_make_fraction(mp, rt,lt);
7721 ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7722 ee=mp_take_fraction(mp, ee,ff);
7725 ff=mp_make_fraction(mp, ee,ee+dd)
7727 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7728 equation was specified by a curl. In that case we must use a special
7729 method of computation to prevent overflow.
7731 Fortunately, the calculations turn out to be even simpler in this ``hard''
7732 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7733 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7735 @<Calculate the values of $v_k$ and $w_k$@>=
7736 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7737 if ( mp_right_type(r)==mp_curl ) {
7739 mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7741 ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7742 $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7743 acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7744 ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7745 mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7746 if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7747 else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7750 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7751 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7752 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7753 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7756 The idea in the following code is to observe that
7757 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7758 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7759 -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7760 so we can solve for $\theta_n=\theta_0$.
7762 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7764 aa=0; bb=fraction_one; /* we have |k=n| */
7767 aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7768 bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7769 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7770 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7771 mp->theta[n]=aa; mp->vv[0]=aa;
7772 for (k=1;k<=n-1;k++) {
7773 mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7778 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7779 if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7781 @<Calculate the given value of $\theta_n$...@>=
7783 mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7784 reduce_angle(mp->theta[n]);
7788 @ @<Set up the equation for a given value of $\theta_0$@>=
7790 mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7791 reduce_angle(mp->vv[0]);
7792 mp->uu[0]=0; mp->ww[0]=0;
7795 @ @<Set up the equation for a curl at $\theta_0$@>=
7796 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7797 if ( (rt==unity)&&(lt==unity) )
7798 mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7800 mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7801 mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7804 @ @<Set up equation for a curl at $\theta_n$...@>=
7805 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7806 if ( (rt==unity)&&(lt==unity) )
7807 ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7809 ff=mp_curl_ratio(mp, cc,lt,rt);
7810 mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7811 fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7815 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7816 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7817 a somewhat tedious program to calculate
7818 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7819 \alpha^3\gamma+(3-\beta)\beta^2},$$
7820 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7821 is necessary only if the curl and tension are both large.)
7822 The values of $\alpha$ and $\beta$ will be at most~4/3.
7825 static fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension,
7829 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension,
7831 fraction alpha,beta,num,denom,ff; /* registers */
7832 alpha=mp_make_fraction(mp, unity,a_tension);
7833 beta=mp_make_fraction(mp, unity,b_tension);
7834 if ( alpha<=beta ) {
7835 ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7836 gamma=mp_take_fraction(mp, gamma,ff);
7837 beta=beta / 010000; /* convert |fraction| to |scaled| */
7838 denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7839 num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7841 ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7842 beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7843 denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7844 /* $1365\approx 2^{12}/3$ */
7845 num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7847 if ( num>=denom+denom+denom+denom ) return fraction_four;
7848 else return mp_make_fraction(mp, num,denom);
7851 @ We're in the home stretch now.
7853 @<Finish choosing angles and assigning control points@>=
7854 for (k=n-1;k>=0;k--) {
7855 mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7860 mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7861 mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7862 mp_set_controls(mp, s,t,k);
7866 @ The |set_controls| routine actually puts the control points into
7867 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7868 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7869 $\cos\phi$ needed in this calculation.
7875 fraction cf; /* sines and cosines */
7878 static void mp_set_controls (MP mp,pointer p, pointer q, integer k);
7881 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7882 fraction rr,ss; /* velocities, divided by thrice the tension */
7883 scaled lt,rt; /* tensions */
7884 fraction sine; /* $\sin(\theta+\phi)$ */
7885 lt=abs(left_tension(q)); rt=abs(right_tension(p));
7886 rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7887 ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7888 if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7889 @<Decrease the velocities,
7890 if necessary, to stay inside the bounding triangle@>;
7892 mp_right_x(p)=mp_x_coord(p)+mp_take_fraction(mp,
7893 mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7894 mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7895 mp_right_y(p)=mp_y_coord(p)+mp_take_fraction(mp,
7896 mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7897 mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7898 mp_left_x(q)=mp_x_coord(q)-mp_take_fraction(mp,
7899 mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7900 mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7901 mp_left_y(q)=mp_y_coord(q)-mp_take_fraction(mp,
7902 mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7903 mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7904 mp_right_type(p)=mp_explicit; mp_left_type(q)=mp_explicit;
7907 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7908 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7909 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7910 there is no ``bounding triangle.''
7912 @<Decrease the velocities, if necessary...@>=
7913 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7914 sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7915 mp_take_fraction(mp, abs(mp->sf),mp->ct);
7917 sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7918 if ( right_tension(p)<0 )
7919 if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7920 rr=mp_make_fraction(mp, abs(mp->sf),sine);
7921 if ( left_tension(q)<0 )
7922 if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7923 ss=mp_make_fraction(mp, abs(mp->st),sine);
7927 @ Only the simple cases remain to be handled.
7929 @<Reduce to simple case of two givens and |return|@>=
7931 aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7932 mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7933 mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7934 mp_set_controls(mp, p,q,0); return;
7937 @ @<Reduce to simple case of straight line and |return|@>=
7939 mp_right_type(p)=mp_explicit; mp_left_type(q)=mp_explicit;
7940 lt=abs(left_tension(q)); rt=abs(right_tension(p));
7942 if ( mp->delta_x[0]>=0 ) mp_right_x(p)=mp_x_coord(p)+((mp->delta_x[0]+1) / 3);
7943 else mp_right_x(p)=mp_x_coord(p)+((mp->delta_x[0]-1) / 3);
7944 if ( mp->delta_y[0]>=0 ) mp_right_y(p)=mp_y_coord(p)+((mp->delta_y[0]+1) / 3);
7945 else mp_right_y(p)=mp_y_coord(p)+((mp->delta_y[0]-1) / 3);
7947 ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7948 mp_right_x(p)=mp_x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7949 mp_right_y(p)=mp_y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7952 if ( mp->delta_x[0]>=0 ) mp_left_x(q)=mp_x_coord(q)-((mp->delta_x[0]+1) / 3);
7953 else mp_left_x(q)=mp_x_coord(q)-((mp->delta_x[0]-1) / 3);
7954 if ( mp->delta_y[0]>=0 ) mp_left_y(q)=mp_y_coord(q)-((mp->delta_y[0]+1) / 3);
7955 else mp_left_y(q)=mp_y_coord(q)-((mp->delta_y[0]-1) / 3);
7957 ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7958 mp_left_x(q)=mp_x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7959 mp_left_y(q)=mp_y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7964 @* \[19] Measuring paths.
7965 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7966 allow the user to measure the bounding box of anything that can go into a
7967 picture. It's easy to get rough bounds on the $x$ and $y$ extent of a path
7968 by just finding the bounding box of the knots and the control points. We
7969 need a more accurate version of the bounding box, but we can still use the
7970 easy estimate to save time by focusing on the interesting parts of the path.
7972 @ Computing an accurate bounding box involves a theme that will come up again
7973 and again. Given a Bernshte{\u\i}n polynomial
7974 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7975 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7976 we can conveniently bisect its range as follows:
7979 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7982 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7983 |0<=k<n-j|, for |0<=j<n|.
7987 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7988 =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7989 This formula gives us the coefficients of polynomials to use over the ranges
7990 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7992 @ Now here's a subroutine that's handy for all sorts of path computations:
7993 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7994 returns the unique |fraction| value |t| between 0 and~1 at which
7995 $B(a,b,c;t)$ changes from positive to negative, or returns
7996 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7997 is already negative at |t=0|), |crossing_point| returns the value zero.
7999 @d no_crossing { return (fraction_one+1); }
8000 @d one_crossing { return fraction_one; }
8001 @d zero_crossing { return 0; }
8002 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
8004 @c static fraction mp_do_crossing_point (integer a, integer b, integer c) {
8005 integer d; /* recursive counter */
8006 integer x,xx,x0,x1,x2; /* temporary registers for bisection */
8007 if ( a<0 ) zero_crossing;
8010 if ( c>0 ) { no_crossing; }
8011 else if ( (a==0)&&(b==0) ) { no_crossing;}
8012 else { one_crossing; }
8014 if ( a==0 ) zero_crossing;
8015 } else if ( a==0 ) {
8016 if ( b<=0 ) zero_crossing;
8018 @<Use bisection to find the crossing point, if one exists@>;
8021 @ The general bisection method is quite simple when $n=2$, hence
8022 |crossing_point| does not take much time. At each stage in the
8023 recursion we have a subinterval defined by |l| and~|j| such that
8024 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
8025 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
8027 It is convenient for purposes of calculation to combine the values
8028 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
8029 of bisection then corresponds simply to doubling $d$ and possibly
8030 adding~1. Furthermore it proves to be convenient to modify
8031 our previous conventions for bisection slightly, maintaining the
8032 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
8033 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
8034 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
8036 The following code maintains the invariant relations
8037 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
8038 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
8039 it has been constructed in such a way that no arithmetic overflow
8040 will occur if the inputs satisfy
8041 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
8043 @<Use bisection to find the crossing point...@>=
8044 d=1; x0=a; x1=a-b; x2=b-c;
8055 if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
8059 } while (d<fraction_one);
8060 return (d-fraction_one)
8062 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
8063 a cubic corresponding to the |fraction| value~|t|.
8065 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
8066 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
8068 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
8070 @c static scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
8071 scaled x1,x2,x3; /* intermediate values */
8072 x1=t_of_the_way(knot_coord(p),right_coord(p));
8073 x2=t_of_the_way(right_coord(p),left_coord(q));
8074 x3=t_of_the_way(left_coord(q),knot_coord(q));
8075 x1=t_of_the_way(x1,x2);
8076 x2=t_of_the_way(x2,x3);
8077 return t_of_the_way(x1,x2);
8080 @ The actual bounding box information is stored in global variables.
8081 Since it is convenient to address the $x$ and $y$ information
8082 separately, we define arrays indexed by |x_code..y_code| and use
8083 macros to give them more convenient names.
8087 mp_x_code=0, /* index for |minx| and |maxx| */
8088 mp_y_code /* index for |miny| and |maxy| */
8092 @d mp_minx mp->bbmin[mp_x_code]
8093 @d mp_maxx mp->bbmax[mp_x_code]
8094 @d mp_miny mp->bbmin[mp_y_code]
8095 @d mp_maxy mp->bbmax[mp_y_code]
8098 scaled bbmin[mp_y_code+1];
8099 scaled bbmax[mp_y_code+1];
8100 /* the result of procedures that compute bounding box information */
8102 @ Now we're ready for the key part of the bounding box computation.
8103 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
8104 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
8105 \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
8107 for $0<t\le1$. In other words, the procedure adjusts the bounds to
8108 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8109 The |c| parameter is |x_code| or |y_code|.
8111 @c static void mp_bound_cubic (MP mp,pointer p, pointer q, quarterword c) {
8112 boolean wavy; /* whether we need to look for extremes */
8113 scaled del1,del2,del3,del,dmax; /* proportional to the control
8114 points of a quadratic derived from a cubic */
8115 fraction t,tt; /* where a quadratic crosses zero */
8116 scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8118 @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8119 @<Check the control points against the bounding box and set |wavy:=true|
8120 if any of them lie outside@>;
8122 del1=right_coord(p)-knot_coord(p);
8123 del2=left_coord(q)-right_coord(p);
8124 del3=knot_coord(q)-left_coord(q);
8125 @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8126 also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8128 negate(del1); negate(del2); negate(del3);
8130 t=mp_crossing_point(mp, del1,del2,del3);
8131 if ( t<fraction_one ) {
8132 @<Test the extremes of the cubic against the bounding box@>;
8137 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8138 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8139 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8141 @ @<Check the control points against the bounding box and set...@>=
8143 if ( mp->bbmin[c]<=right_coord(p) )
8144 if ( right_coord(p)<=mp->bbmax[c] )
8145 if ( mp->bbmin[c]<=left_coord(q) )
8146 if ( left_coord(q)<=mp->bbmax[c] )
8149 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8150 section. We just set |del=0| in that case.
8152 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8153 if ( del1!=0 ) del=del1;
8154 else if ( del2!=0 ) del=del2;
8158 if ( abs(del2)>dmax ) dmax=abs(del2);
8159 if ( abs(del3)>dmax ) dmax=abs(del3);
8160 while ( dmax<fraction_half ) {
8161 dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8165 @ Since |crossing_point| has tried to choose |t| so that
8166 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8167 slope, the value of |del2| computed below should not be positive.
8168 But rounding error could make it slightly positive in which case we
8169 must cut it to zero to avoid confusion.
8171 @<Test the extremes of the cubic against the bounding box@>=
8173 x=mp_eval_cubic(mp, p,q,t);
8174 @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8175 del2=t_of_the_way(del2,del3);
8176 /* now |0,del2,del3| represent the derivative on the remaining interval */
8177 if ( del2>0 ) del2=0;
8178 tt=mp_crossing_point(mp, 0,-del2,-del3);
8179 if ( tt<fraction_one ) {
8180 @<Test the second extreme against the bounding box@>;
8184 @ @<Test the second extreme against the bounding box@>=
8186 x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8187 @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8190 @ Finding the bounding box of a path is basically a matter of applying
8191 |bound_cubic| twice for each pair of adjacent knots.
8193 @c static void mp_path_bbox (MP mp,pointer h) {
8194 pointer p,q; /* a pair of adjacent knots */
8195 mp_minx=mp_x_coord(h); mp_miny=mp_y_coord(h);
8196 mp_maxx=mp_minx; mp_maxy=mp_miny;
8199 if ( mp_right_type(p)==mp_endpoint ) return;
8201 mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8202 mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8207 @ Another important way to measure a path is to find its arc length. This
8208 is best done by using the general bisection algorithm to subdivide the path
8209 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8212 Since the arc length is the integral with respect to time of the magnitude of
8213 the velocity, it is natural to use Simpson's rule for the approximation.
8215 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8216 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8217 for the arc length of a path of length~1. For a cubic spline
8218 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8219 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$. Hence the arc length
8221 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8223 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8224 is the result of the bisection algorithm.
8226 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8227 This could be done via the theoretical error bound for Simpson's rule,
8229 but this is impractical because it requires an estimate of the fourth
8230 derivative of the quantity being integrated. It is much easier to just perform
8231 a bisection step and see how much the arc length estimate changes. Since the
8232 error for Simpson's rule is proportional to the fourth power of the sample
8233 spacing, the remaining error is typically about $1\over16$ of the amount of
8234 the change. We say ``typically'' because the error has a pseudo-random behavior
8235 that could cause the two estimates to agree when each contain large errors.
8237 To protect against disasters such as undetected cusps, the bisection process
8238 should always continue until all the $dz_i$ vectors belong to a single
8239 $90^\circ$ sector. This ensures that no point on the spline can have velocity
8240 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8241 If such a spline happens to produce an erroneous arc length estimate that
8242 is little changed by bisection, the amount of the error is likely to be fairly
8243 small. We will try to arrange things so that freak accidents of this type do
8244 not destroy the inverse relationship between the \&{arclength} and
8245 \&{arctime} operations.
8246 @:arclength_}{\&{arclength} primitive@>
8247 @:arctime_}{\&{arctime} primitive@>
8249 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8251 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8252 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8253 returns the time when the arc length reaches |a_goal| if there is such a time.
8254 Thus the return value is either an arc length less than |a_goal| or, if the
8255 arc length would be at least |a_goal|, it returns a time value decreased by
8256 |two|. This allows the caller to use the sign of the result to distinguish
8257 between arc lengths and time values. On certain types of overflow, it is
8258 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8259 Otherwise, the result is always less than |a_goal|.
8261 Rather than halving the control point coordinates on each recursive call to
8262 |arc_test|, it is better to keep them proportional to velocity on the original
8263 curve and halve the results instead. This means that recursive calls can
8264 potentially use larger error tolerances in their arc length estimates. How
8265 much larger depends on to what extent the errors behave as though they are
8266 independent of each other. To save computing time, we use optimistic assumptions
8267 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8270 In addition to the tolerance parameter, |arc_test| should also have parameters
8271 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8272 ${1\over3}\vb\dot B(1)\vb$. These quantities are relatively expensive to compute
8273 and they are needed in different instances of |arc_test|.
8276 static scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1,
8277 scaled dx2, scaled dy2, scaled v0, scaled v02,
8278 scaled v2, scaled a_goal, scaled tol) {
8279 boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8280 scaled dx01, dy01, dx12, dy12, dx02, dy02; /* bisection results */
8282 /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8283 scaled arc; /* best arc length estimate before recursion */
8284 @<Other local variables in |arc_test|@>;
8285 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8287 @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8288 set |arc_test| and |return|@>;
8289 @<Test if the control points are confined to one quadrant or rotating them
8290 $45^\circ$ would put them in one quadrant. Then set |simple| appropriately@>;
8291 if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8292 if ( arc < a_goal ) {
8295 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8296 that time minus |two|@>;
8299 @<Use one or two recursive calls to compute the |arc_test| function@>;
8303 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8304 calls, but $1.5$ is an adequate approximation. It is best to avoid using
8305 |make_fraction| in this inner loop.
8308 @<Use one or two recursive calls to compute the |arc_test| function@>=
8310 @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8311 large as possible@>;
8312 tol = tol + halfp(tol);
8313 a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002,
8314 halfp(v02), a_new, tol);
8316 return (-halfp(two-a));
8318 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8319 b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8320 halfp(v02), v022, v2, a_new, tol);
8322 return (-halfp(-b) - half_unit);
8324 return (a + half(b-a));
8328 @ @<Other local variables in |arc_test|@>=
8329 scaled a,b; /* results of recursive calls */
8330 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8332 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8333 a_aux = el_gordo - a_goal;
8334 if ( a_goal > a_aux ) {
8335 a_aux = a_goal - a_aux;
8338 a_new = a_goal + a_goal;
8342 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8343 to force the additions and subtractions to be done in an order that avoids
8346 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8349 a_new = a_new + a_aux;
8352 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8353 |fraction_four|. To simplify the rest of the |arc_test| routine, we strengthen
8354 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8355 this bound. Note that recursive calls will maintain this invariant.
8357 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8358 dx01 = half(dx0 + dx1);
8359 dx12 = half(dx1 + dx2);
8360 dx02 = half(dx01 + dx12);
8361 dy01 = half(dy0 + dy1);
8362 dy12 = half(dy1 + dy2);
8363 dy02 = half(dy01 + dy12)
8365 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8366 |a_goal=el_gordo| is guaranteed to yield the arc length.
8368 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8369 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8370 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8372 arc1 = v002 + half(halfp(v0+tmp) - v002);
8373 arc = v022 + half(halfp(v2+tmp) - v022);
8374 if ( (arc < el_gordo-arc1) ) {
8377 mp->arith_error = true;
8378 if ( a_goal==el_gordo ) return (el_gordo);
8382 @ @<Other local variables in |arc_test|@>=
8383 scaled tmp, tmp2; /* all purpose temporary registers */
8384 scaled arc1; /* arc length estimate for the first half */
8386 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8387 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8388 ((dx0<=0) && (dx1<=0) && (dx2<=0));
8390 simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8391 ((dy0<=0) && (dy1<=0) && (dy2<=0));
8393 simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8394 ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8396 simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8397 ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8400 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8402 it is appropriate to use the same approximation to decide when the integral
8403 reaches the intermediate value |a_goal|. At this point
8405 {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8406 {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8407 {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8408 {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8409 {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8413 $$ {\vb\dot B(t)\vb\over 3} \approx
8414 \cases{B\left(\hbox{|v0|},
8415 \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8416 {1\over 2}\hbox{|v02|}; 2t \right)&
8417 if $t\le{1\over 2}$\cr
8418 B\left({1\over 2}\hbox{|v02|},
8419 \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8420 \hbox{|v2|}; 2t-1 \right)&
8421 if $t\ge{1\over 2}$.\cr}
8424 We can integrate $\vb\dot B(t)\vb$ by using
8425 $$\int 3B(a,b,c;\tau)\,dt =
8426 {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8429 This construction allows us to find the time when the arc length reaches
8430 |a_goal| by solving a cubic equation of the form
8431 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8432 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8433 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8434 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8435 $d\tau\over dt$. We shall define a function |solve_rising_cubic| that finds
8436 $\tau$ given $a$, $b$, $c$, and $x$.
8438 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8440 tmp = (v02 + 2) / 4;
8441 if ( a_goal<=arc1 ) {
8444 (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8447 return ((half_unit - two) +
8448 halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8452 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8453 $$ B(0, a, a+b, a+b+c; t) = x. $$
8454 This routine is based on |crossing_point| but is simplified by the
8455 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8456 If rounding error causes this condition to be violated slightly, we just ignore
8457 it and proceed with binary search. This finds a time when the function value
8458 reaches |x| and the slope is positive.
8461 static scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b, scaled c, scaled x) ;
8464 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b, scaled c, scaled x) {
8465 scaled ab, bc, ac; /* bisection results */
8466 integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8467 integer xx; /* temporary for updating |x| */
8468 if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8469 @:this can't happen rising?}{\quad rising?@>
8472 } else if ( x >= a+b+c ) {
8476 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8480 @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8481 xx = x - a - ab - ac;
8482 if ( xx < -x ) { x+=x; b=ab; c=ac; }
8483 else { x = x + xx; a=ac; b=bc; t = t+1; };
8484 } while (t < unity);
8489 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8494 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8496 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8497 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) {
8504 @ It is convenient to have a simpler interface to |arc_test| that requires no
8505 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8506 length less than |fraction_four|.
8508 @d arc_tol 16 /* quit when change in arc length estimate reaches this */
8510 @c static scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1,
8511 scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8512 scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8513 scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8514 v0 = mp_pyth_add(mp, dx0,dy0);
8515 v1 = mp_pyth_add(mp, dx1,dy1);
8516 v2 = mp_pyth_add(mp, dx2,dy2);
8517 if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) {
8518 mp->arith_error = true;
8519 if ( a_goal==el_gordo ) return el_gordo;
8522 v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8523 return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8524 v0, v02, v2, a_goal, arc_tol));
8528 @ Now it is easy to find the arc length of an entire path.
8530 @c static scaled mp_get_arc_length (MP mp,pointer h) {
8531 pointer p,q; /* for traversing the path */
8532 scaled a,a_tot; /* current and total arc lengths */
8535 while ( mp_right_type(p)!=mp_endpoint ){
8537 a = mp_do_arc_test(mp, mp_right_x(p)-mp_x_coord(p), mp_right_y(p)-mp_y_coord(p),
8538 mp_left_x(q)-mp_right_x(p), mp_left_y(q)-mp_right_y(p),
8539 mp_x_coord(q)-mp_left_x(q), mp_y_coord(q)-mp_left_y(q), el_gordo);
8540 a_tot = mp_slow_add(mp, a, a_tot);
8541 if ( q==h ) break; else p=q;
8547 @ The inverse operation of finding the time on a path~|h| when the arc length
8548 reaches some value |arc0| can also be accomplished via |do_arc_test|. Some care
8549 is required to handle very large times or negative times on cyclic paths. For
8550 non-cyclic paths, |arc0| values that are negative or too large cause
8551 |get_arc_time| to return 0 or the length of path~|h|.
8553 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8554 time value greater than the length of the path. Since it could be much greater,
8555 we must be prepared to compute the arc length of path~|h| and divide this into
8556 |arc0| to find how many multiples of the length of path~|h| to add.
8558 @c static scaled mp_get_arc_time (MP mp,pointer h, scaled arc0) {
8559 pointer p,q; /* for traversing the path */
8560 scaled t_tot; /* accumulator for the result */
8561 scaled t; /* the result of |do_arc_test| */
8562 scaled arc; /* portion of |arc0| not used up so far */
8563 integer n; /* number of extra times to go around the cycle */
8565 @<Deal with a negative |arc0| value and |return|@>;
8567 if ( arc0==el_gordo ) decr(arc0);
8571 while ( (mp_right_type(p)!=mp_endpoint) && (arc>0) ) {
8573 t = mp_do_arc_test(mp, mp_right_x(p)-mp_x_coord(p), mp_right_y(p)-mp_y_coord(p),
8574 mp_left_x(q)-mp_right_x(p), mp_left_y(q)-mp_right_y(p),
8575 mp_x_coord(q)-mp_left_x(q), mp_y_coord(q)-mp_left_y(q), arc);
8576 @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8578 @<Update |t_tot| and |arc| to avoid going around the cyclic
8579 path too many times but set |arith_error:=true| and |goto done| on
8588 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8589 if ( t<0 ) { t_tot = t_tot + t + two; arc = 0; }
8590 else { t_tot = t_tot + unity; arc = arc - t; }
8592 @ @<Deal with a negative |arc0| value and |return|@>=
8594 if ( mp_left_type(h)==mp_endpoint ) {
8597 p = mp_htap_ypoc(mp, h);
8598 t_tot = -mp_get_arc_time(mp, p, -arc0);
8599 mp_toss_knot_list(mp, p);
8605 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8607 n = arc / (arc0 - arc);
8608 arc = arc - n*(arc0 - arc);
8609 if ( t_tot > (el_gordo / (n+1)) ) {
8612 t_tot = (n + 1)*t_tot;
8615 @* \[20] Data structures for pens.
8616 A Pen in \MP\ can be either elliptical or polygonal. Elliptical pens result
8617 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8618 @:stroke}{\&{stroke} command@>
8619 converted into an area fill as described in the next part of this program.
8620 The mathematics behind this process is based on simple aspects of the theory
8621 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8622 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8623 Foundations of Computer Science {\bf 24} (1983), 100--111].
8625 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8626 @:makepen_}{\&{makepen} primitive@>
8627 This path representation is almost sufficient for our purposes except that
8628 a pen path should always be a convex polygon with the vertices in
8629 counter-clockwise order.
8630 Since we will need to scan pen polygons both forward and backward, a pen
8631 should be represented as a doubly linked ring of knot nodes. There is
8632 room for the extra back pointer because we do not need the
8633 |mp_left_type| or |mp_right_type| fields. In fact, we don't need the |mp_left_x|,
8634 |mp_left_y|, |mp_right_x|, or |mp_right_y| fields either but we leave these alone
8635 so that certain procedures can operate on both pens and paths. In particular,
8636 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8639 /* this replaces the |mp_left_type| and |mp_right_type| fields in a pen knot */
8641 @ The |make_pen| procedure turns a path into a pen by initializing
8642 the |knil| pointers and making sure the knots form a convex polygon.
8643 Thus each cubic in the given path becomes a straight line and the control
8644 points are ignored. If the path is not cyclic, the ends are connected by a
8647 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8650 static pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8651 pointer p,q; /* two consecutive knots */
8658 h=mp_convex_hull(mp, h);
8659 @<Make sure |h| isn't confused with an elliptical pen@>;
8664 @ The only information required about an elliptical pen is the overall
8665 transformation that has been applied to the original \&{pencircle}.
8666 @:pencircle_}{\&{pencircle} primitive@>
8667 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8668 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8669 knot node and transformed as if it were a path.
8671 @d pen_is_elliptical(A) ((A)==mp_link((A)))
8674 static pointer mp_get_pen_circle (MP mp,scaled diam) {
8675 pointer h; /* the knot node to return */
8676 h=mp_get_node(mp, knot_node_size);
8677 mp_link(h)=h; knil(h)=h;
8678 mp_originator(h)=mp_program_code;
8679 mp_x_coord(h)=0; mp_y_coord(h)=0;
8680 mp_left_x(h)=diam; mp_left_y(h)=0;
8681 mp_right_x(h)=0; mp_right_y(h)=diam;
8685 @ If the polygon being returned by |make_pen| has only one vertex, it will
8686 be interpreted as an elliptical pen. This is no problem since a degenerate
8687 polygon can equally well be thought of as a degenerate ellipse. We need only
8688 initialize the |mp_left_x|, |mp_left_y|, |mp_right_x|, and |mp_right_y| fields.
8690 @<Make sure |h| isn't confused with an elliptical pen@>=
8691 if ( pen_is_elliptical( h) ){
8692 mp_left_x(h)=mp_x_coord(h); mp_left_y(h)=mp_y_coord(h);
8693 mp_right_x(h)=mp_x_coord(h); mp_right_y(h)=mp_y_coord(h);
8696 @ Printing a polygonal pen is very much like printing a path
8699 static void mp_pr_pen (MP mp,pointer h) ;
8702 void mp_pr_pen (MP mp,pointer h) {
8703 pointer p,q; /* for list traversal */
8704 if ( pen_is_elliptical(h) ) {
8705 @<Print the elliptical pen |h|@>;
8709 mp_print_two(mp, mp_x_coord(p),mp_y_coord(p));
8710 mp_print_nl(mp, " .. ");
8711 @<Advance |p| making sure the links are OK and |return| if there is
8714 mp_print(mp, "cycle");
8718 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8720 if ( (q==null) || (knil(q)!=p) ) {
8721 mp_print_nl(mp, "???"); return; /* this won't happen */
8726 @ @<Print the elliptical pen |h|@>=
8728 mp_print(mp, "pencircle transformed (");
8729 mp_print_scaled(mp, mp_x_coord(h));
8730 mp_print_char(mp, xord(','));
8731 mp_print_scaled(mp, mp_y_coord(h));
8732 mp_print_char(mp, xord(','));
8733 mp_print_scaled(mp, mp_left_x(h)-mp_x_coord(h));
8734 mp_print_char(mp, xord(','));
8735 mp_print_scaled(mp, mp_right_x(h)-mp_x_coord(h));
8736 mp_print_char(mp, xord(','));
8737 mp_print_scaled(mp, mp_left_y(h)-mp_y_coord(h));
8738 mp_print_char(mp, xord(','));
8739 mp_print_scaled(mp, mp_right_y(h)-mp_y_coord(h));
8740 mp_print_char(mp, xord(')'));
8743 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8747 static void mp_print_pen (MP mp,pointer h, const char *s, boolean nuline) ;
8750 void mp_print_pen (MP mp,pointer h, const char *s, boolean nuline) {
8751 mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8754 mp_end_diagnostic(mp, true);
8757 @ Making a polygonal pen into a path involves restoring the |mp_left_type| and
8758 |mp_right_type| fields and setting the control points so as to make a polygonal
8762 static void mp_make_path (MP mp,pointer h) {
8763 pointer p; /* for traversing the knot list */
8764 quarterword k; /* a loop counter */
8765 @<Other local variables in |make_path|@>;
8766 if ( pen_is_elliptical(h) ) {
8767 @<Make the elliptical pen |h| into a path@>;
8771 mp_left_type(p)=mp_explicit;
8772 mp_right_type(p)=mp_explicit;
8773 @<copy the coordinates of knot |p| into its control points@>;
8779 @ @<copy the coordinates of knot |p| into its control points@>=
8780 mp_left_x(p)=mp_x_coord(p);
8781 mp_left_y(p)=mp_y_coord(p);
8782 mp_right_x(p)=mp_x_coord(p);
8783 mp_right_y(p)=mp_y_coord(p)
8785 @ We need an eight knot path to get a good approximation to an ellipse.
8787 @<Make the elliptical pen |h| into a path@>=
8789 @<Extract the transformation parameters from the elliptical pen~|h|@>;
8791 for (k=0;k<=7;k++ ) {
8792 @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8793 transforming it appropriately@>;
8794 if ( k==7 ) mp_link(p)=h; else mp_link(p)=mp_get_node(mp, knot_node_size);
8799 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8800 center_x=mp_x_coord(h);
8801 center_y=mp_y_coord(h);
8802 width_x=mp_left_x(h)-center_x;
8803 width_y=mp_left_y(h)-center_y;
8804 height_x=mp_right_x(h)-center_x;
8805 height_y=mp_right_y(h)-center_y
8807 @ @<Other local variables in |make_path|@>=
8808 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8809 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8810 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8811 scaled dx,dy; /* the vector from knot |p| to its right control point */
8813 /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8815 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8816 find the point $k/8$ of the way around the circle and the direction vector
8819 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8821 mp_x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8822 +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8823 mp_y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8824 +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8825 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8826 +mp_take_fraction(mp, mp->d_cos[k],height_x);
8827 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8828 +mp_take_fraction(mp, mp->d_cos[k],height_y);
8829 mp_right_x(p)=mp_x_coord(p)+dx;
8830 mp_right_y(p)=mp_y_coord(p)+dy;
8831 mp_left_x(p)=mp_x_coord(p)-dx;
8832 mp_left_y(p)=mp_y_coord(p)-dy;
8833 mp_left_type(p)=mp_explicit;
8834 mp_right_type(p)=mp_explicit;
8835 mp_originator(p)=mp_program_code
8838 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8839 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8841 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8842 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8843 function for $\theta=\phi=22.5^\circ$. This comes out to be
8844 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8845 \approx 0.132608244919772.
8849 mp->half_cos[0]=fraction_half;
8850 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8852 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8853 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8855 for (k=3;k<= 4;k++ ) {
8856 mp->half_cos[k]=-mp->half_cos[4-k];
8857 mp->d_cos[k]=-mp->d_cos[4-k];
8859 for (k=5;k<= 7;k++ ) {
8860 mp->half_cos[k]=mp->half_cos[8-k];
8861 mp->d_cos[k]=mp->d_cos[8-k];
8864 @ The |convex_hull| function forces a pen polygon to be convex when it is
8865 returned by |make_pen| and after any subsequent transformation where rounding
8866 error might allow the convexity to be lost.
8867 The convex hull algorithm used here is described by F.~P. Preparata and
8868 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8871 static pointer mp_convex_hull (MP mp,pointer h);
8874 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8875 pointer l,r; /* the leftmost and rightmost knots */
8876 pointer p,q; /* knots being scanned */
8877 pointer s; /* the starting point for an upcoming scan */
8878 scaled dx,dy; /* a temporary pointer */
8879 if ( pen_is_elliptical(h) ) {
8882 @<Set |l| to the leftmost knot in polygon~|h|@>;
8883 @<Set |r| to the rightmost knot in polygon~|h|@>;
8886 @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8887 move them past~|r|@>;
8888 @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8889 move them past~|l|@>;
8890 @<Sort the path from |l| to |r| by increasing $x$@>;
8891 @<Sort the path from |r| to |l| by decreasing $x$@>;
8893 if ( l!=mp_link(l) ) {
8894 @<Do a Gramm scan and remove vertices where there is no left turn@>;
8900 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8902 @<Set |l| to the leftmost knot in polygon~|h|@>=
8906 if ( mp_x_coord(p)<=mp_x_coord(l) )
8907 if ( (mp_x_coord(p)<mp_x_coord(l)) || (mp_y_coord(p)<mp_y_coord(l)) )
8912 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8916 if ( mp_x_coord(p)>=mp_x_coord(r) )
8917 if ( (mp_x_coord(p)>mp_x_coord(r)) || (mp_y_coord(p)>mp_y_coord(r)) )
8922 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8923 dx=mp_x_coord(r)-mp_x_coord(l);
8924 dy=mp_y_coord(r)-mp_y_coord(l);
8928 if ( mp_ab_vs_cd(mp, dx,mp_y_coord(p)-mp_y_coord(l),dy,mp_x_coord(p)-mp_x_coord(l))>0 )
8929 mp_move_knot(mp, p, r);
8933 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8937 static void mp_move_knot (MP mp,pointer p, pointer q) ;
8940 void mp_move_knot (MP mp,pointer p, pointer q) {
8941 mp_link(knil(p))=mp_link(p);
8942 knil(mp_link(p))=knil(p);
8944 mp_link(p)=mp_link(q);
8949 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8953 if ( mp_ab_vs_cd(mp, dx,mp_y_coord(p)-mp_y_coord(l),dy,mp_x_coord(p)-mp_x_coord(l))<0 )
8954 mp_move_knot(mp, p,l);
8958 @ The list is likely to be in order already so we just do linear insertions.
8959 Secondary comparisons on $y$ ensure that the sort is consistent with the
8960 choice of |l| and |r|.
8962 @<Sort the path from |l| to |r| by increasing $x$@>=
8966 while ( mp_x_coord(q)>mp_x_coord(p) ) q=knil(q);
8967 while ( mp_x_coord(q)==mp_x_coord(p) ) {
8968 if ( mp_y_coord(q)>mp_y_coord(p) ) q=knil(q); else break;
8970 if ( q==knil(p) ) p=mp_link(p);
8971 else { p=mp_link(p); mp_move_knot(mp, knil(p),q); };
8974 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8978 while ( mp_x_coord(q)<mp_x_coord(p) ) q=knil(q);
8979 while ( mp_x_coord(q)==mp_x_coord(p) ) {
8980 if ( mp_y_coord(q)<mp_y_coord(p) ) q=knil(q); else break;
8982 if ( q==knil(p) ) p=mp_link(p);
8983 else { p=mp_link(p); mp_move_knot(mp, knil(p),q); };
8986 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8987 at knot |q|. There usually will be a left turn so we streamline the case
8988 where the |then| clause is not executed.
8990 @<Do a Gramm scan and remove vertices where there...@>=
8994 dx=mp_x_coord(q)-mp_x_coord(p);
8995 dy=mp_y_coord(q)-mp_y_coord(p);
8999 if ( mp_ab_vs_cd(mp, dx,mp_y_coord(q)-mp_y_coord(p),dy,mp_x_coord(q)-mp_x_coord(p))<=0 ) {
9000 @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
9005 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
9008 mp_free_node(mp, p,knot_node_size);
9009 mp_link(s)=q; knil(q)=s;
9011 else { p=knil(s); q=s; };
9014 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
9015 offset associated with the given direction |(x,y)|. If two different offsets
9016 apply, it chooses one of them.
9019 static void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
9020 pointer p,q; /* consecutive knots */
9022 /* the transformation matrix for an elliptical pen */
9023 fraction xx,yy; /* untransformed offset for an elliptical pen */
9024 fraction d; /* a temporary register */
9025 if ( pen_is_elliptical(h) ) {
9026 @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
9031 } while (!(mp_ab_vs_cd(mp, mp_x_coord(q)-mp_x_coord(p),y, mp_y_coord(q)-mp_y_coord(p),x)>=0));
9034 } while (!(mp_ab_vs_cd(mp, mp_x_coord(q)-mp_x_coord(p),y, mp_y_coord(q)-mp_y_coord(p),x)<=0));
9035 mp->cur_x=mp_x_coord(p);
9036 mp->cur_y=mp_y_coord(p);
9042 scaled cur_y; /* all-purpose return value registers */
9044 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
9045 if ( (x==0) && (y==0) ) {
9046 mp->cur_x=mp_x_coord(h); mp->cur_y=mp_y_coord(h);
9048 @<Find the non-constant part of the transformation for |h|@>;
9049 while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){
9052 @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
9053 untransformed version of |(x,y)|@>;
9054 mp->cur_x=mp_x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
9055 mp->cur_y=mp_y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
9058 @ @<Find the non-constant part of the transformation for |h|@>=
9059 wx=mp_left_x(h)-mp_x_coord(h);
9060 wy=mp_left_y(h)-mp_y_coord(h);
9061 hx=mp_right_x(h)-mp_x_coord(h);
9062 hy=mp_right_y(h)-mp_y_coord(h)
9064 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
9065 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
9066 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
9067 d=mp_pyth_add(mp, xx,yy);
9069 xx=half(mp_make_fraction(mp, xx,d));
9070 yy=half(mp_make_fraction(mp, yy,d));
9073 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
9074 But we can handle that case by just calling |find_offset| twice. The answer
9075 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
9078 static void mp_pen_bbox (MP mp,pointer h) {
9079 pointer p; /* for scanning the knot list */
9080 if ( pen_is_elliptical(h) ) {
9081 @<Find the bounding box of an elliptical pen@>;
9083 mp_minx=mp_x_coord(h); mp_maxx=mp_minx;
9084 mp_miny=mp_y_coord(h); mp_maxy=mp_miny;
9087 if ( mp_x_coord(p)<mp_minx ) mp_minx=mp_x_coord(p);
9088 if ( mp_y_coord(p)<mp_miny ) mp_miny=mp_y_coord(p);
9089 if ( mp_x_coord(p)>mp_maxx ) mp_maxx=mp_x_coord(p);
9090 if ( mp_y_coord(p)>mp_maxy ) mp_maxy=mp_y_coord(p);
9096 @ @<Find the bounding box of an elliptical pen@>=
9098 mp_find_offset(mp, 0,fraction_one,h);
9100 mp_minx=2*mp_x_coord(h)-mp->cur_x;
9101 mp_find_offset(mp, -fraction_one,0,h);
9103 mp_miny=2*mp_y_coord(h)-mp->cur_y;
9106 @* \[21] Edge structures.
9107 Now we come to \MP's internal scheme for representing pictures.
9108 The representation is very different from \MF's edge structures
9109 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9110 images. However, the basic idea is somewhat similar in that shapes
9111 are represented via their boundaries.
9113 The main purpose of edge structures is to keep track of graphical objects
9114 until it is time to translate them into \ps. Since \MP\ does not need to
9115 know anything about an edge structure other than how to translate it into
9116 \ps\ and how to find its bounding box, edge structures can be just linked
9117 lists of graphical objects. \MP\ has no easy way to determine whether
9118 two such objects overlap, but it suffices to draw the first one first and
9119 let the second one overwrite it if necessary.
9122 enum mp_graphical_object_code {
9123 @<Graphical object codes@>
9127 @ Let's consider the types of graphical objects one at a time.
9128 First of all, a filled contour is represented by a eight-word node. The first
9129 word contains |type| and |link| fields, and the next six words contain a
9130 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9131 parameter. If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9132 give the relevant information.
9134 @d mp_path_p(A) mp_link((A)+1)
9135 /* a pointer to the path that needs filling */
9136 @d mp_pen_p(A) mp_info((A)+1)
9137 /* a pointer to the pen to fill or stroke with */
9138 @d mp_color_model(A) mp_type((A)+2) /* the color model */
9139 @d obj_red_loc(A) ((A)+3) /* the first of three locations for the color */
9140 @d obj_cyan_loc obj_red_loc /* the first of four locations for the color */
9141 @d obj_grey_loc obj_red_loc /* the location for the color */
9142 @d red_val(A) mp->mem[(A)+3].sc
9143 /* the red component of the color in the range $0\ldots1$ */
9146 @d green_val(A) mp->mem[(A)+4].sc
9147 /* the green component of the color in the range $0\ldots1$ */
9148 @d magenta_val green_val
9149 @d blue_val(A) mp->mem[(A)+5].sc
9150 /* the blue component of the color in the range $0\ldots1$ */
9151 @d yellow_val blue_val
9152 @d black_val(A) mp->mem[(A)+6].sc
9153 /* the blue component of the color in the range $0\ldots1$ */
9154 @d ljoin_val(A) mp_name_type((A)) /* the value of \&{linejoin} */
9155 @:mp_linejoin_}{\&{linejoin} primitive@>
9156 @d miterlim_val(A) mp->mem[(A)+7].sc /* the value of \&{miterlimit} */
9157 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9158 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9159 /* interpret an object pointer that has been offset by |red_part..blue_part| */
9160 @d mp_pre_script(A) mp->mem[(A)+8].hh.lh
9161 @d mp_post_script(A) mp->mem[(A)+8].hh.rh
9164 @ @<Graphical object codes@>=
9168 static pointer mp_new_fill_node (MP mp,pointer p) {
9169 /* make a fill node for cyclic path |p| and color black */
9170 pointer t; /* the new node */
9171 t=mp_get_node(mp, fill_node_size);
9172 mp_type(t)=mp_fill_code;
9174 mp_pen_p(t)=null; /* |null| means don't use a pen */
9179 mp_color_model(t)=mp_uninitialized_model;
9180 mp_pre_script(t)=null;
9181 mp_post_script(t)=null;
9182 @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9186 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9187 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9188 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9189 else ljoin_val(t)=0;
9190 if ( mp->internal[mp_miterlimit]<unity )
9191 miterlim_val(t)=unity;
9193 miterlim_val(t)=mp->internal[mp_miterlimit]
9195 @ A stroked path is represented by an eight-word node that is like a filled
9196 contour node except that it contains the current \&{linecap} value, a scale
9197 factor for the dash pattern, and a pointer that is non-null if the stroke
9198 is to be dashed. The purpose of the scale factor is to allow a picture to
9199 be transformed without touching the picture that |dash_p| points to.
9201 @d mp_dash_p(A) mp_link((A)+9)
9202 /* a pointer to the edge structure that gives the dash pattern */
9203 @d lcap_val(A) mp_type((A)+9)
9204 /* the value of \&{linecap} */
9205 @:mp_linecap_}{\&{linecap} primitive@>
9206 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9207 @d stroked_node_size 11
9209 @ @<Graphical object codes@>=
9213 static pointer mp_new_stroked_node (MP mp,pointer p) {
9214 /* make a stroked node for path |p| with |mp_pen_p(p)| temporarily |null| */
9215 pointer t; /* the new node */
9216 t=mp_get_node(mp, stroked_node_size);
9217 mp_type(t)=mp_stroked_code;
9218 mp_path_p(t)=p; mp_pen_p(t)=null;
9220 dash_scale(t)=unity;
9225 mp_color_model(t)=mp_uninitialized_model;
9226 mp_pre_script(t)=null;
9227 mp_post_script(t)=null;
9228 @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9229 if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9230 else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9235 @ When a dashed line is computed in a transformed coordinate system, the dash
9236 lengths get scaled like the pen shape and we need to compensate for this. Since
9237 there is no unique scale factor for an arbitrary transformation, we use the
9238 the square root of the determinant. The properties of the determinant make it
9239 easier to maintain the |dash_scale|. The computation is fairly straight-forward
9240 except for the initialization of the scale factor |s|. The factor of 64 is
9241 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9242 to counteract the effect of |take_fraction|.
9245 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9246 scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9247 unsigned s; /* amount by which the result of |square_rt| needs to be scaled */
9248 @<Initialize |maxabs|@>;
9250 while ( (maxabs<fraction_one) && (s>1) ){
9251 a+=a; b+=b; c+=c; d+=d;
9252 maxabs+=maxabs; s=(unsigned)(halfp(s));
9254 return (scaled)(s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c))));
9257 static scaled mp_get_pen_scale (MP mp,pointer p) {
9258 return mp_sqrt_det(mp,
9259 mp_left_x(p)-mp_x_coord(p), mp_right_x(p)-mp_x_coord(p),
9260 mp_left_y(p)-mp_y_coord(p), mp_right_y(p)-mp_y_coord(p));
9264 static scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9267 @ @<Initialize |maxabs|@>=
9269 if ( abs(b)>maxabs ) maxabs=abs(b);
9270 if ( abs(c)>maxabs ) maxabs=abs(c);
9271 if ( abs(d)>maxabs ) maxabs=abs(d)
9273 @ When a picture contains text, this is represented by a fourteen-word node
9274 where the color information and |type| and |link| fields are augmented by
9275 additional fields that describe the text and how it is transformed.
9276 The |path_p| and |mp_pen_p| pointers are replaced by a number that identifies
9277 the font and a string number that gives the text to be displayed.
9278 The |width|, |height|, and |depth| fields
9279 give the dimensions of the text at its design size, and the remaining six
9280 words give a transformation to be applied to the text. The |new_text_node|
9281 function initializes everything to default values so that the text comes out
9282 black with its reference point at the origin.
9284 @d mp_text_p(A) mp_link((A)+1) /* a string pointer for the text to display */
9285 @d mp_font_n(A) mp_info((A)+1) /* the font number */
9286 @d width_val(A) mp->mem[(A)+7].sc /* unscaled width of the text */
9287 @d height_val(A) mp->mem[(A)+9].sc /* unscaled height of the text */
9288 @d depth_val(A) mp->mem[(A)+10].sc /* unscaled depth of the text */
9289 @d text_tx_loc(A) ((A)+11)
9290 /* the first of six locations for transformation parameters */
9291 @d tx_val(A) mp->mem[(A)+11].sc /* $x$ shift amount */
9292 @d ty_val(A) mp->mem[(A)+12].sc /* $y$ shift amount */
9293 @d txx_val(A) mp->mem[(A)+13].sc /* |txx| transformation parameter */
9294 @d txy_val(A) mp->mem[(A)+14].sc /* |txy| transformation parameter */
9295 @d tyx_val(A) mp->mem[(A)+15].sc /* |tyx| transformation parameter */
9296 @d tyy_val(A) mp->mem[(A)+16].sc /* |tyy| transformation parameter */
9297 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9298 /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9299 @d text_node_size 17
9301 @ @<Graphical object codes@>=
9305 static pointer mp_new_text_node (MP mp,char *f,str_number s) {
9306 /* make a text node for font |f| and text string |s| */
9307 pointer t; /* the new node */
9308 t=mp_get_node(mp, text_node_size);
9309 mp_type(t)=mp_text_code;
9311 mp_font_n(t)=(halfword)mp_find_font(mp, f); /* this identifies the font */
9316 mp_color_model(t)=mp_uninitialized_model;
9317 mp_pre_script(t)=null;
9318 mp_post_script(t)=null;
9319 tx_val(t)=0; ty_val(t)=0;
9320 txx_val(t)=unity; txy_val(t)=0;
9321 tyx_val(t)=0; tyy_val(t)=unity;
9322 mp_set_text_box(mp, t); /* this finds the bounding box */
9326 @ The last two types of graphical objects that can occur in an edge structure
9327 are clipping paths and \&{setbounds} paths. These are slightly more difficult
9328 @:set_bounds_}{\&{setbounds} primitive@>
9329 to implement because we must keep track of exactly what is being clipped or
9330 bounded when pictures get merged together. For this reason, each clipping or
9331 \&{setbounds} operation is represented by a pair of nodes: first comes a
9332 two-word node whose |path_p| gives the relevant path, then there is the list
9333 of objects to clip or bound followed by a two-word node whose second word is
9336 Using at least two words for each graphical object node allows them all to be
9337 allocated and deallocated similarly with a global array |gr_object_size| to
9338 give the size in words for each object type.
9340 @d start_clip_size 2
9341 @d start_bounds_size 2
9342 @d stop_clip_size 2 /* the second word is not used here */
9343 @d stop_bounds_size 2 /* the second word is not used here */
9345 @d stop_type(A) ((A)+2)
9346 /* matching |type| for |start_clip_code| or |start_bounds_code| */
9347 @d has_color(A) (mp_type((A))<mp_start_clip_code)
9348 /* does a graphical object have color fields? */
9349 @d has_pen(A) (mp_type((A))<mp_text_code)
9350 /* does a graphical object have a |mp_pen_p| field? */
9351 @d is_start_or_stop(A) (mp_type((A))>=mp_start_clip_code)
9352 @d is_stop(A) (mp_type((A))>=mp_stop_clip_code)
9354 @ @<Graphical object codes@>=
9355 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9356 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9357 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9358 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9361 static pointer mp_new_bounds_node (MP mp,pointer p, quarterword c) {
9362 /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9363 pointer t; /* the new node */
9364 t=mp_get_node(mp, mp->gr_object_size[c]);
9370 @ We need an array to keep track of the sizes of graphical objects.
9373 quarterword gr_object_size[mp_stop_bounds_code+1];
9376 mp->gr_object_size[mp_fill_code]=fill_node_size;
9377 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9378 mp->gr_object_size[mp_text_code]=text_node_size;
9379 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9380 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9381 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9382 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9384 @ All the essential information in an edge structure is encoded as a linked list
9385 of graphical objects as we have just seen, but it is helpful to add some
9386 redundant information. A single edge structure might be used as a dash pattern
9387 many times, and it would be nice to avoid scanning the same structure
9388 repeatedly. Thus, an edge structure known to be a suitable dash pattern
9389 has a header that gives a list of dashes in a sorted order designed for rapid
9390 translation into \ps.
9392 Each dash is represented by a three-word node containing the initial and final
9393 $x$~coordinates as well as the usual |link| field. The |link| fields points to
9394 the dash node with the next higher $x$-coordinates and the final link points
9395 to a special location called |null_dash|. (There should be no overlap between
9396 dashes). Since the $y$~coordinate of the dash pattern is needed to determine
9397 the period of repetition, this needs to be stored in the edge header along
9398 with a pointer to the list of dash nodes.
9400 @d start_x(A) mp->mem[(A)+1].sc /* the starting $x$~coordinate in a dash node */
9401 @d stop_x(A) mp->mem[(A)+2].sc /* the ending $x$~coordinate in a dash node */
9403 @d dash_list mp_link
9404 /* in an edge header this points to the first dash node */
9405 @d dash_y(A) mp->mem[(A)+1].sc /* $y$ value for the dash list in an edge header */
9407 @ It is also convenient for an edge header to contain the bounding
9408 box information needed by the \&{llcorner} and \&{urcorner} operators
9409 so that this does not have to be recomputed unnecessarily. This is done by
9410 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9411 how far the bounding box computation has gotten. Thus if the user asks for
9412 the bounding box and then adds some more text to the picture before asking
9413 for more bounding box information, the second computation need only look at
9414 the additional text.
9416 When the bounding box has not been computed, the |bblast| pointer points
9417 to a dummy link at the head of the graphical object list while the |minx_val|
9418 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9419 fields contain |-el_gordo|.
9421 Since the bounding box of pictures containing objects of type
9422 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9423 @:mp_true_corners_}{\&{truecorners} primitive@>
9424 data might not be valid for all values of this parameter. Hence, the |bbtype|
9425 field is needed to keep track of this.
9427 @d minx_val(A) mp->mem[(A)+2].sc
9428 @d miny_val(A) mp->mem[(A)+3].sc
9429 @d maxx_val(A) mp->mem[(A)+4].sc
9430 @d maxy_val(A) mp->mem[(A)+5].sc
9431 @d bblast(A) mp_link((A)+6) /* last item considered in bounding box computation */
9432 @d bbtype(A) mp_info((A)+6) /* tells how bounding box data depends on \&{truecorners} */
9433 @d dummy_loc(A) ((A)+7) /* where the object list begins in an edge header */
9435 /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9437 /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9439 /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9442 static void mp_init_bbox (MP mp,pointer h) {
9443 /* Initialize the bounding box information in edge structure |h| */
9444 bblast(h)=dummy_loc(h);
9445 bbtype(h)=no_bounds;
9446 minx_val(h)=el_gordo;
9447 miny_val(h)=el_gordo;
9448 maxx_val(h)=-el_gordo;
9449 maxy_val(h)=-el_gordo;
9452 @ The only other entries in an edge header are a reference count in the first
9453 word and a pointer to the tail of the object list in the last word.
9455 @d obj_tail(A) mp_info((A)+7) /* points to the last entry in the object list */
9456 @d edge_header_size 8
9459 static void mp_init_edges (MP mp,pointer h) {
9460 /* initialize an edge header to null values */
9461 dash_list(h)=null_dash;
9462 obj_tail(h)=dummy_loc(h);
9463 mp_link(dummy_loc(h))=null;
9465 mp_init_bbox(mp, h);
9468 @ Here is how edge structures are deleted. The process can be recursive because
9469 of the need to dereference edge structures that are used as dash patterns.
9472 @d add_edge_ref(A) incr(ref_count(A))
9473 @d delete_edge_ref(A) {
9474 if ( ref_count((A))==null )
9475 mp_toss_edges(mp, A);
9481 static void mp_flush_dash_list (MP mp,pointer h);
9482 static pointer mp_toss_gr_object (MP mp,pointer p) ;
9483 static void mp_toss_edges (MP mp,pointer h) ;
9485 @ @c void mp_toss_edges (MP mp,pointer h) {
9486 pointer p,q; /* pointers that scan the list being recycled */
9487 pointer r; /* an edge structure that object |p| refers to */
9488 mp_flush_dash_list(mp, h);
9489 q=mp_link(dummy_loc(h));
9490 while ( (q!=null) ) {
9492 r=mp_toss_gr_object(mp, p);
9493 if ( r!=null ) delete_edge_ref(r);
9495 mp_free_node(mp, h,edge_header_size);
9497 void mp_flush_dash_list (MP mp,pointer h) {
9498 pointer p,q; /* pointers that scan the list being recycled */
9500 while ( q!=null_dash ) {
9502 mp_free_node(mp, p,dash_node_size);
9504 dash_list(h)=null_dash;
9506 pointer mp_toss_gr_object (MP mp,pointer p) {
9507 /* returns an edge structure that needs to be dereferenced */
9508 pointer e; /* the edge structure to return */
9510 @<Prepare to recycle graphical object |p|@>;
9511 mp_free_node(mp, p,mp->gr_object_size[mp_type(p)]);
9515 @ @<Prepare to recycle graphical object |p|@>=
9516 switch (mp_type(p)) {
9518 mp_toss_knot_list(mp, mp_path_p(p));
9519 if ( mp_pen_p(p)!=null ) mp_toss_knot_list(mp, mp_pen_p(p));
9520 if ( mp_pre_script(p)!=null ) delete_str_ref(mp_pre_script(p));
9521 if ( mp_post_script(p)!=null ) delete_str_ref(mp_post_script(p));
9523 case mp_stroked_code:
9524 mp_toss_knot_list(mp, mp_path_p(p));
9525 if ( mp_pen_p(p)!=null ) mp_toss_knot_list(mp, mp_pen_p(p));
9526 if ( mp_pre_script(p)!=null ) delete_str_ref(mp_pre_script(p));
9527 if ( mp_post_script(p)!=null ) delete_str_ref(mp_post_script(p));
9531 delete_str_ref(mp_text_p(p));
9532 if ( mp_pre_script(p)!=null ) delete_str_ref(mp_pre_script(p));
9533 if ( mp_post_script(p)!=null ) delete_str_ref(mp_post_script(p));
9535 case mp_start_clip_code:
9536 case mp_start_bounds_code:
9537 mp_toss_knot_list(mp, mp_path_p(p));
9539 case mp_stop_clip_code:
9540 case mp_stop_bounds_code:
9542 } /* there are no other cases */
9544 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9545 to be done before making a significant change to an edge structure. Much of
9546 the work is done in a separate routine |copy_objects| that copies a list of
9547 graphical objects into a new edge header.
9550 static pointer mp_private_edges (MP mp,pointer h) {
9551 /* make a private copy of the edge structure headed by |h| */
9552 pointer hh; /* the edge header for the new copy */
9553 pointer p,pp; /* pointers for copying the dash list */
9554 if ( ref_count(h)==null ) {
9558 hh=mp_copy_objects(mp, mp_link(dummy_loc(h)),null);
9559 @<Copy the dash list from |h| to |hh|@>;
9560 @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9561 point into the new object list@>;
9566 @ Here we use the fact that |dash_list(hh)=mp_link(hh)|.
9567 @^data structure assumptions@>
9569 @<Copy the dash list from |h| to |hh|@>=
9570 pp=hh; p=dash_list(h);
9571 while ( (p!=null_dash) ) {
9572 mp_link(pp)=mp_get_node(mp, dash_node_size);
9574 start_x(pp)=start_x(p);
9575 stop_x(pp)=stop_x(p);
9578 mp_link(pp)=null_dash;
9579 dash_y(hh)=dash_y(h)
9582 @ |h| is an edge structure
9585 static mp_dash_object *mp_export_dashes (MP mp, pointer q, scaled *w) {
9588 scaled scf; /* scale factor */
9592 if (h==null || dash_list(h)==null_dash)
9595 scf=mp_get_pen_scale(mp, mp_pen_p(q));
9597 if (*w==0) scf = dash_scale(q); else return NULL;
9599 scf=mp_make_scaled(mp, *w,scf);
9600 scf=mp_take_scaled(mp, scf,dash_scale(q));
9603 d = xmalloc(1,sizeof(mp_dash_object));
9604 start_x(null_dash)=start_x(p)+dash_y(h);
9605 while (p != null_dash) {
9606 dashes = xrealloc(dashes, (num_dashes+2), sizeof(scaled));
9607 dashes[(num_dashes-1)] =
9608 mp_take_scaled(mp,(stop_x(p)-start_x(p)),scf);
9609 dashes[(num_dashes)] =
9610 mp_take_scaled(mp,(start_x(mp_link(p))-stop_x(p)),scf);
9611 dashes[(num_dashes+1)] = -1; /* terminus */
9616 d->offset = mp_take_scaled(mp,mp_dash_offset(mp, h),scf);
9622 @ @<Copy the bounding box information from |h| to |hh|...@>=
9623 minx_val(hh)=minx_val(h);
9624 miny_val(hh)=miny_val(h);
9625 maxx_val(hh)=maxx_val(h);
9626 maxy_val(hh)=maxy_val(h);
9627 bbtype(hh)=bbtype(h);
9628 p=dummy_loc(h); pp=dummy_loc(hh);
9629 while ((p!=bblast(h)) ) {
9630 if ( p==null ) mp_confusion(mp, "bblast");
9631 @:this can't happen bblast}{\quad bblast@>
9632 p=mp_link(p); pp=mp_link(pp);
9636 @ Here is the promised routine for copying graphical objects into a new edge
9637 structure. It starts copying at object~|p| and stops just before object~|q|.
9638 If |q| is null, it copies the entire sublist headed at |p|. The resulting edge
9639 structure requires further initialization by |init_bbox|.
9642 static pointer mp_copy_objects (MP mp, pointer p, pointer q);
9645 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9646 pointer hh; /* the new edge header */
9647 pointer pp; /* the last newly copied object */
9648 quarterword k; /* temporary register */
9649 hh=mp_get_node(mp, edge_header_size);
9650 dash_list(hh)=null_dash;
9654 @<Make |mp_link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9661 @ @<Make |mp_link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9662 { k=mp->gr_object_size[mp_type(p)];
9663 mp_link(pp)=mp_get_node(mp, k);
9665 while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k]; };
9666 @<Fix anything in graphical object |pp| that should differ from the
9667 corresponding field in |p|@>;
9671 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9672 switch (mp_type(p)) {
9673 case mp_start_clip_code:
9674 case mp_start_bounds_code:
9675 mp_path_p(pp)=mp_copy_path(mp, mp_path_p(p));
9678 mp_path_p(pp)=mp_copy_path(mp, mp_path_p(p));
9679 if ( mp_pre_script(p)!=null ) add_str_ref(mp_pre_script(p));
9680 if ( mp_post_script(p)!=null ) add_str_ref(mp_post_script(p));
9681 if ( mp_pen_p(p)!=null ) mp_pen_p(pp)=copy_pen(mp_pen_p(p));
9683 case mp_stroked_code:
9684 if ( mp_pre_script(p)!=null ) add_str_ref(mp_pre_script(p));
9685 if ( mp_post_script(p)!=null ) add_str_ref(mp_post_script(p));
9686 mp_path_p(pp)=mp_copy_path(mp, mp_path_p(p));
9687 mp_pen_p(pp)=copy_pen(mp_pen_p(p));
9688 if ( mp_dash_p(p)!=null ) add_edge_ref(mp_dash_p(pp));
9691 if ( mp_pre_script(p)!=null ) add_str_ref(mp_pre_script(p));
9692 if ( mp_post_script(p)!=null ) add_str_ref(mp_post_script(p));
9693 add_str_ref(mp_text_p(pp));
9695 case mp_stop_clip_code:
9696 case mp_stop_bounds_code:
9698 } /* there are no other cases */
9700 @ Here is one way to find an acceptable value for the second argument to
9701 |copy_objects|. Given a non-null graphical object list, |skip_1component|
9702 skips past one picture component, where a ``picture component'' is a single
9703 graphical object, or a start bounds or start clip object and everything up
9704 through the matching stop bounds or stop clip object. The macro version avoids
9705 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9706 unless |p| points to a stop bounds or stop clip node, in which case it executes
9709 @d skip_component(A)
9710 if ( ! is_start_or_stop((A)) ) (A)=mp_link((A));
9711 else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9715 static pointer mp_skip_1component (MP mp,pointer p) {
9716 integer lev; /* current nesting level */
9719 if ( is_start_or_stop(p) ) {
9720 if ( is_stop(p) ) decr(lev); else incr(lev);
9727 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9730 static void mp_print_edges (MP mp,pointer h, const char *s, boolean nuline) ;
9733 void mp_print_edges (MP mp,pointer h, const char *s, boolean nuline) {
9734 pointer p; /* a graphical object to be printed */
9735 pointer hh,pp; /* temporary pointers */
9736 scaled scf; /* a scale factor for the dash pattern */
9737 boolean ok_to_dash; /* |false| for polygonal pen strokes */
9738 mp_print_diagnostic(mp, "Edge structure",s,nuline);
9740 while ( mp_link(p)!=null ) {
9743 switch (mp_type(p)) {
9744 @<Cases for printing graphical object node |p|@>;
9746 mp_print(mp, "[unknown object type!]");
9750 mp_print_nl(mp, "End edges");
9751 if ( p!=obj_tail(h) ) mp_print(mp, "?");
9753 mp_end_diagnostic(mp, true);
9756 @ @<Cases for printing graphical object node |p|@>=
9758 mp_print(mp, "Filled contour ");
9759 mp_print_obj_color(mp, p);
9760 mp_print_char(mp, xord(':')); mp_print_ln(mp);
9761 mp_pr_path(mp, mp_path_p(p)); mp_print_ln(mp);
9762 if ( (mp_pen_p(p)!=null) ) {
9763 @<Print join type for graphical object |p|@>;
9764 mp_print(mp, " with pen"); mp_print_ln(mp);
9765 mp_pr_pen(mp, mp_pen_p(p));
9769 @ @<Print join type for graphical object |p|@>=
9770 switch (ljoin_val(p)) {
9772 mp_print(mp, "mitered joins limited ");
9773 mp_print_scaled(mp, miterlim_val(p));
9776 mp_print(mp, "round joins");
9779 mp_print(mp, "beveled joins");
9782 mp_print(mp, "?? joins");
9787 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9789 @<Print join and cap types for stroked node |p|@>=
9790 switch (lcap_val(p)) {
9791 case 0:mp_print(mp, "butt"); break;
9792 case 1:mp_print(mp, "round"); break;
9793 case 2:mp_print(mp, "square"); break;
9794 default: mp_print(mp, "??"); break;
9797 mp_print(mp, " ends, ");
9798 @<Print join type for graphical object |p|@>
9800 @ Here is a routine that prints the color of a graphical object if it isn't
9801 black (the default color).
9804 static void mp_print_obj_color (MP mp,pointer p) ;
9807 void mp_print_obj_color (MP mp,pointer p) {
9808 if ( mp_color_model(p)==mp_grey_model ) {
9809 if ( grey_val(p)>0 ) {
9810 mp_print(mp, "greyed ");
9811 mp_print_compact_node(mp, obj_grey_loc(p),1);
9813 } else if ( mp_color_model(p)==mp_cmyk_model ) {
9814 if ( (cyan_val(p)>0) || (magenta_val(p)>0) ||
9815 (yellow_val(p)>0) || (black_val(p)>0) ) {
9816 mp_print(mp, "processcolored ");
9817 mp_print_compact_node(mp, obj_cyan_loc(p),4);
9819 } else if ( mp_color_model(p)==mp_rgb_model ) {
9820 if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) {
9821 mp_print(mp, "colored ");
9822 mp_print_compact_node(mp, obj_red_loc(p),3);
9827 @ We also need a procedure for printing consecutive scaled values as if they
9828 were a known big node.
9831 static void mp_print_compact_node (MP mp,pointer p, quarterword k) ;
9834 void mp_print_compact_node (MP mp,pointer p, quarterword k) {
9835 pointer q; /* last location to print */
9837 mp_print_char(mp, xord('('));
9839 mp_print_scaled(mp, mp->mem[p].sc);
9840 if ( p<q ) mp_print_char(mp, xord(','));
9843 mp_print_char(mp, xord(')'));
9846 @ @<Cases for printing graphical object node |p|@>=
9847 case mp_stroked_code:
9848 mp_print(mp, "Filled pen stroke ");
9849 mp_print_obj_color(mp, p);
9850 mp_print_char(mp, xord(':')); mp_print_ln(mp);
9851 mp_pr_path(mp, mp_path_p(p));
9852 if ( mp_dash_p(p)!=null ) {
9853 mp_print_nl(mp, "dashed (");
9854 @<Finish printing the dash pattern that |p| refers to@>;
9857 @<Print join and cap types for stroked node |p|@>;
9858 mp_print(mp, " with pen"); mp_print_ln(mp);
9859 if ( mp_pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9861 else mp_pr_pen(mp, mp_pen_p(p));
9864 @ Normally, the |dash_list| field in an edge header is set to |null_dash|
9865 when it is not known to define a suitable dash pattern. This is disallowed
9866 here because the |mp_dash_p| field should never point to such an edge header.
9867 Note that memory is allocated for |start_x(null_dash)| and we are free to
9868 give it any convenient value.
9870 @<Finish printing the dash pattern that |p| refers to@>=
9871 ok_to_dash=pen_is_elliptical(mp_pen_p(p));
9872 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9875 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9876 mp_print(mp, " ??");
9877 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9878 while ( pp!=null_dash ) {
9879 mp_print(mp, "on ");
9880 mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9881 mp_print(mp, " off ");
9882 mp_print_scaled(mp, mp_take_scaled(mp, start_x(mp_link(pp))-stop_x(pp),scf));
9884 if ( pp!=null_dash ) mp_print_char(mp, xord(' '));
9886 mp_print(mp, ") shifted ");
9887 mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9888 if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9892 static scaled mp_dash_offset (MP mp,pointer h) ;
9895 scaled mp_dash_offset (MP mp,pointer h) {
9896 scaled x; /* the answer */
9897 if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9898 @:this can't happen dash0}{\quad dash0@>
9899 if ( dash_y(h)==0 ) {
9902 x=-(start_x(dash_list(h)) % dash_y(h));
9903 if ( x<0 ) x=x+dash_y(h);
9908 @ @<Cases for printing graphical object node |p|@>=
9910 mp_print_char(mp, xord('"')); mp_print_str(mp,mp_text_p(p));
9911 mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[mp_font_n(p)]);
9912 mp_print_char(mp, xord('"')); mp_print_ln(mp);
9913 mp_print_obj_color(mp, p);
9914 mp_print(mp, "transformed ");
9915 mp_print_compact_node(mp, text_tx_loc(p),6);
9918 @ @<Cases for printing graphical object node |p|@>=
9919 case mp_start_clip_code:
9920 mp_print(mp, "clipping path:");
9922 mp_pr_path(mp, mp_path_p(p));
9924 case mp_stop_clip_code:
9925 mp_print(mp, "stop clipping");
9928 @ @<Cases for printing graphical object node |p|@>=
9929 case mp_start_bounds_code:
9930 mp_print(mp, "setbounds path:");
9932 mp_pr_path(mp, mp_path_p(p));
9934 case mp_stop_bounds_code:
9935 mp_print(mp, "end of setbounds");
9938 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9939 subroutine that scans an edge structure and tries to interpret it as a dash
9940 pattern. This can only be done when there are no filled regions or clipping
9941 paths and all the pen strokes have the same color. The first step is to let
9942 $y_0$ be the initial $y$~coordinate of the first pen stroke. Then we implicitly
9943 project all the pen stroke paths onto the line $y=y_0$ and require that there
9944 be no retracing. If the resulting paths cover a range of $x$~coordinates of
9945 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9946 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9949 static pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9950 pointer p; /* this scans the stroked nodes in the object list */
9951 pointer p0; /* if not |null| this points to the first stroked node */
9952 pointer pp,qq,rr; /* pointers into |mp_path_p(p)| */
9953 pointer d,dd; /* pointers used to create the dash list */
9955 @<Other local variables in |make_dashes|@>;
9956 y0=0; /* the initial $y$ coordinate */
9957 if ( dash_list(h)!=null_dash )
9960 p=mp_link(dummy_loc(h));
9962 if ( mp_type(p)!=mp_stroked_code ) {
9963 @<Compain that the edge structure contains a node of the wrong type
9964 and |goto not_found|@>;
9967 if ( p0==null ){ p0=p; y0=mp_y_coord(pp); };
9968 @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9969 or |goto not_found| if there is an error@>;
9970 @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9973 if ( dash_list(h)==null_dash )
9974 goto NOT_FOUND; /* No error message */
9975 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9976 @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9979 @<Flush the dash list, recycle |h| and return |null|@>;
9982 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9984 print_err("Picture is too complicated to use as a dash pattern");
9985 help3("When you say `dashed p', picture p should not contain any",
9986 "text, filled regions, or clipping paths. This time it did",
9987 "so I'll just make it a solid line instead.");
9988 mp_put_get_error(mp);
9992 @ A similar error occurs when monotonicity fails.
9995 static void mp_x_retrace_error (MP mp) ;
9998 void mp_x_retrace_error (MP mp) {
9999 print_err("Picture is too complicated to use as a dash pattern");
10000 help3("When you say `dashed p', every path in p should be monotone",
10001 "in x and there must be no overlapping. This failed",
10002 "so I'll just make it a solid line instead.");
10003 mp_put_get_error(mp);
10006 @ We stash |p| in |mp_info(d)| if |mp_dash_p(p)<>0| so that subsequent processing can
10007 handle the case where the pen stroke |p| is itself dashed.
10009 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
10010 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
10013 if ( mp_link(pp)!=pp ) {
10015 qq=rr; rr=mp_link(rr);
10016 @<Check for retracing between knots |qq| and |rr| and |goto not_found|
10017 if there is a problem@>;
10018 } while (mp_right_type(rr)!=mp_endpoint);
10020 d=mp_get_node(mp, dash_node_size);
10021 if ( mp_dash_p(p)==0 ) mp_info(d)=0; else mp_info(d)=p;
10022 if ( mp_x_coord(pp)<mp_x_coord(rr) ) {
10023 start_x(d)=mp_x_coord(pp);
10024 stop_x(d)=mp_x_coord(rr);
10026 start_x(d)=mp_x_coord(rr);
10027 stop_x(d)=mp_x_coord(pp);
10030 @ We also need to check for the case where the segment from |qq| to |rr| is
10031 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
10033 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
10038 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
10039 if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
10040 if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
10041 mp_x_retrace_error(mp); goto NOT_FOUND;
10045 if ( (mp_x_coord(pp)>x0) || (x0>x3) ) {
10046 if ( (mp_x_coord(pp)<x0) || (x0<x3) ) {
10047 mp_x_retrace_error(mp); goto NOT_FOUND;
10051 @ @<Other local variables in |make_dashes|@>=
10052 scaled x0,x1,x2,x3; /* $x$ coordinates of the segment from |qq| to |rr| */
10054 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
10055 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
10056 (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
10057 print_err("Picture is too complicated to use as a dash pattern");
10058 help3("When you say `dashed p', everything in picture p should",
10059 "be the same color. I can\'t handle your color changes",
10060 "so I'll just make it a solid line instead.");
10061 mp_put_get_error(mp);
10065 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
10066 start_x(null_dash)=stop_x(d);
10067 dd=h; /* this makes |mp_link(dd)=dash_list(h)| */
10068 while ( start_x(mp_link(dd))<stop_x(d) )
10071 if ( (stop_x(dd)>start_x(d)) )
10072 { mp_x_retrace_error(mp); goto NOT_FOUND; };
10074 mp_link(d)=mp_link(dd);
10077 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
10079 while ( (mp_link(d)!=null_dash) )
10082 dash_y(h)=stop_x(d)-start_x(dd);
10083 if ( abs(y0)>dash_y(h) ) {
10085 } else if ( d!=dd ) {
10086 dash_list(h)=mp_link(dd);
10087 stop_x(d)=stop_x(dd)+dash_y(h);
10088 mp_free_node(mp, dd,dash_node_size);
10091 @ We get here when the argument is a null picture or when there is an error.
10092 Recovering from an error involves making |dash_list(h)| empty to indicate
10093 that |h| is not known to be a valid dash pattern. We also dereference |h|
10094 since it is not being used for the return value.
10096 @<Flush the dash list, recycle |h| and return |null|@>=
10097 mp_flush_dash_list(mp, h);
10098 delete_edge_ref(h);
10101 @ Having carefully saved the dashed stroked nodes in the
10102 corresponding dash nodes, we must be prepared to break up these dashes into
10105 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
10106 d=h; /* now |mp_link(d)=dash_list(h)| */
10107 while ( mp_link(d)!=null_dash ) {
10108 ds=mp_info(mp_link(d));
10113 hsf=dash_scale(ds);
10114 if ( (hh==null) ) mp_confusion(mp, "dash1");
10115 @:this can't happen dash0}{\quad dash1@>
10116 if ( dash_y(hh)==0 ) {
10119 if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
10120 @:this can't happen dash0}{\quad dash1@>
10121 @<Replace |mp_link(d)| by a dashed version as determined by edge header
10122 |hh| and scale factor |ds|@>;
10127 @ @<Other local variables in |make_dashes|@>=
10128 pointer dln; /* |mp_link(d)| */
10129 pointer hh; /* an edge header that tells how to break up |dln| */
10130 scaled hsf; /* the dash pattern from |hh| gets scaled by this */
10131 pointer ds; /* the stroked node from which |hh| and |hsf| are derived */
10132 scaled xoff; /* added to $x$ values in |dash_list(hh)| to match |dln| */
10134 @ @<Replace |mp_link(d)| by a dashed version as determined by edge header...@>=
10137 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10138 mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10139 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10140 +mp_take_scaled(mp, hsf,dash_y(hh));
10141 stop_x(null_dash)=start_x(null_dash);
10142 @<Advance |dd| until finding the first dash that overlaps |dln| when
10143 offset by |xoff|@>;
10144 while ( start_x(dln)<=stop_x(dln) ) {
10145 @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10146 @<Insert a dash between |d| and |dln| for the overlap with the offset version
10149 start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10151 mp_link(d)=mp_link(dln);
10152 mp_free_node(mp, dln,dash_node_size)
10154 @ The name of this module is a bit of a lie because we just find the
10155 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10156 overlap possible. It could be that the unoffset version of dash |dln| falls
10157 in the gap between |dd| and its predecessor.
10159 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10160 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10164 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10165 if ( dd==null_dash ) {
10167 xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10170 @ At this point we already know that
10171 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10173 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10174 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10175 mp_link(d)=mp_get_node(mp, dash_node_size);
10178 if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10179 start_x(d)=start_x(dln);
10181 start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10182 if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd))))
10183 stop_x(d)=stop_x(dln);
10185 stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10188 @ The next major task is to update the bounding box information in an edge
10189 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10190 header's bounding box to accommodate the box computed by |path_bbox| or
10191 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10194 @c static void mp_adjust_bbox (MP mp,pointer h) {
10195 if ( mp_minx<minx_val(h) ) minx_val(h)=mp_minx;
10196 if ( mp_miny<miny_val(h) ) miny_val(h)=mp_miny;
10197 if ( mp_maxx>maxx_val(h) ) maxx_val(h)=mp_maxx;
10198 if ( mp_maxy>maxy_val(h) ) maxy_val(h)=mp_maxy;
10201 @ Here is a special routine for updating the bounding box information in
10202 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10203 that is to be stroked with the pen~|pp|.
10205 @c static void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10206 pointer q; /* a knot node adjacent to knot |p| */
10207 fraction dx,dy; /* a unit vector in the direction out of the path at~|p| */
10208 scaled d; /* a factor for adjusting the length of |(dx,dy)| */
10209 scaled z; /* a coordinate being tested against the bounding box */
10210 scaled xx,yy; /* the extreme pen vertex in the |(dx,dy)| direction */
10211 integer i; /* a loop counter */
10212 if ( mp_right_type(p)!=mp_endpoint ) {
10215 @<Make |(dx,dy)| the final direction for the path segment from
10216 |q| to~|p|; set~|d|@>;
10217 d=mp_pyth_add(mp, dx,dy);
10219 @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10220 for (i=1;i<= 2;i++) {
10221 @<Use |(dx,dy)| to generate a vertex of the square end cap and
10222 update the bounding box to accommodate it@>;
10226 if ( mp_right_type(p)==mp_endpoint ) {
10229 @<Advance |p| to the end of the path and make |q| the previous knot@>;
10235 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10236 if ( q==mp_link(p) ) {
10237 dx=mp_x_coord(p)-mp_right_x(p);
10238 dy=mp_y_coord(p)-mp_right_y(p);
10239 if ( (dx==0)&&(dy==0) ) {
10240 dx=mp_x_coord(p)-mp_left_x(q);
10241 dy=mp_y_coord(p)-mp_left_y(q);
10244 dx=mp_x_coord(p)-mp_left_x(p);
10245 dy=mp_y_coord(p)-mp_left_y(p);
10246 if ( (dx==0)&&(dy==0) ) {
10247 dx=mp_x_coord(p)-mp_right_x(q);
10248 dy=mp_y_coord(p)-mp_right_y(q);
10251 dx=mp_x_coord(p)-mp_x_coord(q);
10252 dy=mp_y_coord(p)-mp_y_coord(q)
10254 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10255 dx=mp_make_fraction(mp, dx,d);
10256 dy=mp_make_fraction(mp, dy,d);
10257 mp_find_offset(mp, -dy,dx,pp);
10258 xx=mp->cur_x; yy=mp->cur_y
10260 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10261 mp_find_offset(mp, dx,dy,pp);
10262 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10263 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2)))
10264 mp_confusion(mp, "box_ends");
10265 @:this can't happen box ends}{\quad\\{box\_ends}@>
10266 z=mp_x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10267 if ( z<minx_val(h) ) minx_val(h)=z;
10268 if ( z>maxx_val(h) ) maxx_val(h)=z;
10269 z=mp_y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10270 if ( z<miny_val(h) ) miny_val(h)=z;
10271 if ( z>maxy_val(h) ) maxy_val(h)=z
10273 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10277 } while (mp_right_type(p)!=mp_endpoint)
10279 @ The major difficulty in finding the bounding box of an edge structure is the
10280 effect of clipping paths. We treat them conservatively by only clipping to the
10281 clipping path's bounding box, but this still
10282 requires recursive calls to |set_bbox| in order to find the bounding box of
10284 the objects to be clipped. Such calls are distinguished by the fact that the
10285 boolean parameter |top_level| is false.
10288 void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10289 pointer p; /* a graphical object being considered */
10290 scaled sminx,sminy,smaxx,smaxy;
10291 /* for saving the bounding box during recursive calls */
10292 scaled x0,x1,y0,y1; /* temporary registers */
10293 integer lev; /* nesting level for |mp_start_bounds_code| nodes */
10294 @<Wipe out any existing bounding box information if |bbtype(h)| is
10295 incompatible with |internal[mp_true_corners]|@>;
10296 while ( mp_link(bblast(h))!=null ) {
10297 p=mp_link(bblast(h));
10299 switch (mp_type(p)) {
10300 case mp_stop_clip_code:
10301 if ( top_level ) mp_confusion(mp, "bbox"); else return;
10302 @:this can't happen bbox}{\quad bbox@>
10304 @<Other cases for updating the bounding box based on the type of object |p|@>;
10305 } /* all cases are enumerated above */
10307 if ( ! top_level ) mp_confusion(mp, "bbox");
10310 @ @<Declarations@>=
10311 static void mp_set_bbox (MP mp,pointer h, boolean top_level);
10313 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10314 switch (bbtype(h)) {
10318 if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10321 if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10323 } /* there are no other cases */
10325 @ @<Other cases for updating the bounding box...@>=
10327 mp_path_bbox(mp, mp_path_p(p));
10328 if ( mp_pen_p(p)!=null ) {
10329 x0=mp_minx; y0=mp_miny;
10330 x1=mp_maxx; y1=mp_maxy;
10331 mp_pen_bbox(mp, mp_pen_p(p));
10332 mp_minx=mp_minx+x0;
10333 mp_miny=mp_miny+y0;
10334 mp_maxx=mp_maxx+x1;
10335 mp_maxy=mp_maxy+y1;
10337 mp_adjust_bbox(mp, h);
10340 @ @<Other cases for updating the bounding box...@>=
10341 case mp_start_bounds_code:
10342 if ( mp->internal[mp_true_corners]>0 ) {
10343 bbtype(h)=bounds_unset;
10345 bbtype(h)=bounds_set;
10346 mp_path_bbox(mp, mp_path_p(p));
10347 mp_adjust_bbox(mp, h);
10348 @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10352 case mp_stop_bounds_code:
10353 if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10354 @:this can't happen bbox2}{\quad bbox2@>
10357 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10360 if ( mp_link(p)==null ) mp_confusion(mp, "bbox2");
10361 @:this can't happen bbox2}{\quad bbox2@>
10363 if ( mp_type(p)==mp_start_bounds_code ) incr(lev);
10364 else if ( mp_type(p)==mp_stop_bounds_code ) decr(lev);
10368 @ It saves a lot of grief here to be slightly conservative and not account for
10369 omitted parts of dashed lines. We also don't worry about the material omitted
10370 when using butt end caps. The basic computation is for round end caps and
10371 |box_ends| augments it for square end caps.
10373 @<Other cases for updating the bounding box...@>=
10374 case mp_stroked_code:
10375 mp_path_bbox(mp, mp_path_p(p));
10376 x0=mp_minx; y0=mp_miny;
10377 x1=mp_maxx; y1=mp_maxy;
10378 mp_pen_bbox(mp, mp_pen_p(p));
10379 mp_minx=mp_minx+x0;
10380 mp_miny=mp_miny+y0;
10381 mp_maxx=mp_maxx+x1;
10382 mp_maxy=mp_maxy+y1;
10383 mp_adjust_bbox(mp, h);
10384 if ( (mp_left_type(mp_path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10385 mp_box_ends(mp, mp_path_p(p), mp_pen_p(p), h);
10388 @ The height width and depth information stored in a text node determines a
10389 rectangle that needs to be transformed according to the transformation
10390 parameters stored in the text node.
10392 @<Other cases for updating the bounding box...@>=
10394 x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10395 y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10396 y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10399 if ( y0<y1 ) { mp_minx=mp_minx+y0; mp_maxx=mp_maxx+y1; }
10400 else { mp_minx=mp_minx+y1; mp_maxx=mp_maxx+y0; }
10401 if ( x1<0 ) mp_minx=mp_minx+x1; else mp_maxx=mp_maxx+x1;
10402 x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10403 y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10404 y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10407 if ( y0<y1 ) { mp_miny=mp_miny+y0; mp_maxy=mp_maxy+y1; }
10408 else { mp_miny=mp_miny+y1; mp_maxy=mp_maxy+y0; }
10409 if ( x1<0 ) mp_miny=mp_miny+x1; else mp_maxy=mp_maxy+x1;
10410 mp_adjust_bbox(mp, h);
10413 @ This case involves a recursive call that advances |bblast(h)| to the node of
10414 type |mp_stop_clip_code| that matches |p|.
10416 @<Other cases for updating the bounding box...@>=
10417 case mp_start_clip_code:
10418 mp_path_bbox(mp, mp_path_p(p));
10419 x0=mp_minx; y0=mp_miny;
10420 x1=mp_maxx; y1=mp_maxy;
10421 sminx=minx_val(h); sminy=miny_val(h);
10422 smaxx=maxx_val(h); smaxy=maxy_val(h);
10423 @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10424 starting at |mp_link(p)|@>;
10425 @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10427 mp_minx=sminx; mp_miny=sminy;
10428 mp_maxx=smaxx; mp_maxy=smaxy;
10429 mp_adjust_bbox(mp, h);
10432 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10433 minx_val(h)=el_gordo;
10434 miny_val(h)=el_gordo;
10435 maxx_val(h)=-el_gordo;
10436 maxy_val(h)=-el_gordo;
10437 mp_set_bbox(mp, h,false)
10439 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10440 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10441 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10442 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10443 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10445 @* \[22] Finding an envelope.
10446 When \MP\ has a path and a polygonal pen, it needs to express the desired
10447 shape in terms of things \ps\ can understand. The present task is to compute
10448 a new path that describes the region to be filled. It is convenient to
10449 define this as a two step process where the first step is determining what
10450 offset to use for each segment of the path.
10452 @ Given a pointer |c| to a cyclic path,
10453 and a pointer~|h| to the first knot of a pen polygon,
10454 the |offset_prep| routine changes the path into cubics that are
10455 associated with particular pen offsets. Thus if the cubic between |p|
10456 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10457 has offset |l| then |mp_info(q)=zero_off+l-k|. (The constant |zero_off| is added
10458 to because |l-k| could be negative.)
10460 After overwriting the type information with offset differences, we no longer
10461 have a true path so we refer to the knot list returned by |offset_prep| as an
10464 Since an envelope spec only determines relative changes in pen offsets,
10465 |offset_prep| sets a global variable |spec_offset| to the relative change from
10466 |h| to the first offset.
10468 @d zero_off 16384 /* added to offset changes to make them positive */
10471 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10474 static pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10475 halfword n; /* the number of vertices in the pen polygon */
10476 pointer c0,p,q,q0,r,w, ww; /* for list manipulation */
10477 integer k_needed; /* amount to be added to |mp_info(p)| when it is computed */
10478 pointer w0; /* a pointer to pen offset to use just before |p| */
10479 scaled dxin,dyin; /* the direction into knot |p| */
10480 integer turn_amt; /* change in pen offsets for the current cubic */
10481 @<Other local variables for |offset_prep|@>;
10483 @<Initialize the pen size~|n|@>;
10484 @<Initialize the incoming direction and pen offset at |c|@>;
10485 p=c; c0=c; k_needed=0;
10488 @<Split the cubic between |p| and |q|, if necessary, into cubics
10489 associated with single offsets, after which |q| should
10490 point to the end of the final such cubic@>;
10492 @<Advance |p| to node |q|, removing any ``dead'' cubics that
10493 might have been introduced by the splitting process@>;
10495 @<Fix the offset change in |mp_info(c)| and set |c| to the return value of
10500 @ We shall want to keep track of where certain knots on the cyclic path
10501 wind up in the envelope spec. It doesn't suffice just to keep pointers to
10502 knot nodes because some nodes are deleted while removing dead cubics. Thus
10503 |offset_prep| updates the following pointers
10507 pointer spec_p2; /* pointers to distinguished knots */
10510 mp->spec_p1=null; mp->spec_p2=null;
10512 @ @<Initialize the pen size~|n|@>=
10519 @ Since the true incoming direction isn't known yet, we just pick a direction
10520 consistent with the pen offset~|h|. If this is wrong, it can be corrected
10523 @<Initialize the incoming direction and pen offset at |c|@>=
10524 dxin=mp_x_coord(mp_link(h))-mp_x_coord(knil(h));
10525 dyin=mp_y_coord(mp_link(h))-mp_y_coord(knil(h));
10526 if ( (dxin==0)&&(dyin==0) ) {
10527 dxin=mp_y_coord(knil(h))-mp_y_coord(h);
10528 dyin=mp_x_coord(h)-mp_x_coord(knil(h));
10532 @ We must be careful not to remove the only cubic in a cycle.
10534 But we must also be careful for another reason. If the user-supplied
10535 path starts with a set of degenerate cubics, the target node |q| can
10536 be collapsed to the initial node |p| which might be the same as the
10537 initial node |c| of the curve. This would cause the |offset_prep| routine
10538 to bail out too early, causing distress later on. (See for example
10539 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10542 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10546 if ( mp_x_coord(p)==mp_right_x(p) && mp_y_coord(p)==mp_right_y(p) &&
10547 mp_x_coord(p)==mp_left_x(r) && mp_y_coord(p)==mp_left_y(r) &&
10548 mp_x_coord(p)==mp_x_coord(r) && mp_y_coord(p)==mp_y_coord(r) &&
10550 @<Remove the cubic following |p| and update the data structures
10551 to merge |r| into |p|@>;
10555 /* Check if we removed too much */
10556 if ((q!=q0)&&(q!=c||c==c0))
10559 @ @<Remove the cubic following |p| and update the data structures...@>=
10560 { k_needed=mp_info(p)-zero_off;
10564 mp_info(p)=k_needed+mp_info(r);
10567 if ( r==c ) { mp_info(p)=mp_info(c); c=p; };
10568 if ( r==mp->spec_p1 ) mp->spec_p1=p;
10569 if ( r==mp->spec_p2 ) mp->spec_p2=p;
10570 r=p; mp_remove_cubic(mp, p);
10573 @ Not setting the |info| field of the newly created knot allows the splitting
10574 routine to work for paths.
10577 static void mp_split_cubic (MP mp,pointer p, fraction t) ;
10580 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10581 scaled v; /* an intermediate value */
10582 pointer q,r; /* for list manipulation */
10583 q=mp_link(p); r=mp_get_node(mp, knot_node_size); mp_link(p)=r; mp_link(r)=q;
10584 mp_originator(r)=mp_program_code;
10585 mp_left_type(r)=mp_explicit; mp_right_type(r)=mp_explicit;
10586 v=t_of_the_way(mp_right_x(p),mp_left_x(q));
10587 mp_right_x(p)=t_of_the_way(mp_x_coord(p),mp_right_x(p));
10588 mp_left_x(q)=t_of_the_way(mp_left_x(q),mp_x_coord(q));
10589 mp_left_x(r)=t_of_the_way(mp_right_x(p),v);
10590 mp_right_x(r)=t_of_the_way(v,mp_left_x(q));
10591 mp_x_coord(r)=t_of_the_way(mp_left_x(r),mp_right_x(r));
10592 v=t_of_the_way(mp_right_y(p),mp_left_y(q));
10593 mp_right_y(p)=t_of_the_way(mp_y_coord(p),mp_right_y(p));
10594 mp_left_y(q)=t_of_the_way(mp_left_y(q),mp_y_coord(q));
10595 mp_left_y(r)=t_of_the_way(mp_right_y(p),v);
10596 mp_right_y(r)=t_of_the_way(v,mp_left_y(q));
10597 mp_y_coord(r)=t_of_the_way(mp_left_y(r),mp_right_y(r));
10600 @ This does not set |mp_info(p)| or |mp_right_type(p)|.
10603 static void mp_remove_cubic (MP mp,pointer p) ;
10606 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10607 pointer q; /* the node that disappears */
10608 q=mp_link(p); mp_link(p)=mp_link(q);
10609 mp_right_x(p)=mp_right_x(q); mp_right_y(p)=mp_right_y(q);
10610 mp_free_node(mp, q,knot_node_size);
10613 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10614 strictly between zero and $180^\circ$. Then we can define $d\preceq d'$ to
10615 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10616 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10617 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10618 When listed by increasing $k$, these directions occur in counter-clockwise
10619 order so that $d_k\preceq d\k$ for all~$k$.
10620 The goal of |offset_prep| is to find an offset index~|k| to associate with
10621 each cubic, such that the direction $d(t)$ of the cubic satisfies
10622 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10623 We may have to split a cubic into many pieces before each
10624 piece corresponds to a unique offset.
10626 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10627 mp_info(p)=zero_off+k_needed;
10629 @<Prepare for derivative computations;
10630 |goto not_found| if the current cubic is dead@>;
10631 @<Find the initial direction |(dx,dy)|@>;
10632 @<Update |mp_info(p)| and find the offset $w_k$ such that
10633 $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10634 the direction change at |p|@>;
10635 @<Find the final direction |(dxin,dyin)|@>;
10636 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10637 @<Complete the offset splitting process@>;
10638 w0=mp_pen_walk(mp, w0,turn_amt)
10640 @ @<Declarations@>=
10641 static pointer mp_pen_walk (MP mp,pointer w, integer k) ;
10644 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10645 /* walk |k| steps around a pen from |w| */
10646 while ( k>0 ) { w=mp_link(w); decr(k); };
10647 while ( k<0 ) { w=knil(w); incr(k); };
10651 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10652 calculated from the quadratic polynomials
10653 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10654 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10655 Since we may be calculating directions from several cubics
10656 split from the current one, it is desirable to do these calculations
10657 without losing too much precision. ``Scaled up'' values of the
10658 derivatives, which will be less tainted by accumulated errors than
10659 derivatives found from the cubics themselves, are maintained in
10660 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10661 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10662 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)$.
10664 @<Other local variables for |offset_prep|@>=
10665 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10666 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10667 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10668 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10669 integer max_coef; /* used while scaling */
10670 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10671 fraction t; /* where the derivative passes through zero */
10672 fraction s; /* a temporary value */
10674 @ @<Prepare for derivative computations...@>=
10675 x0=mp_right_x(p)-mp_x_coord(p);
10676 x2=mp_x_coord(q)-mp_left_x(q);
10677 x1=mp_left_x(q)-mp_right_x(p);
10678 y0=mp_right_y(p)-mp_y_coord(p); y2=mp_y_coord(q)-mp_left_y(q);
10679 y1=mp_left_y(q)-mp_right_y(p);
10681 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10682 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10683 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10684 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10685 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10686 if ( max_coef==0 ) goto NOT_FOUND;
10687 while ( max_coef<fraction_half ) {
10689 double(x0); double(x1); double(x2);
10690 double(y0); double(y1); double(y2);
10693 @ Let us first solve a special case of the problem: Suppose we
10694 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10695 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10696 $d(0)\succ d_{k-1}$.
10697 Then, in a sense, we're halfway done, since one of the two relations
10698 in $(*)$ is satisfied, and the other couldn't be satisfied for
10699 any other value of~|k|.
10701 Actually, the conditions can be relaxed somewhat since a relation such as
10702 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10703 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10704 the origin. The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10705 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10706 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10707 counterclockwise direction.
10709 The |fin_offset_prep| subroutine solves the stated subproblem.
10710 It has a parameter called |rise| that is |1| in
10711 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10712 the derivative of the cubic following |p|.
10713 The |w| parameter should point to offset~$w_k$ and |mp_info(p)| should already
10714 be set properly. The |turn_amt| parameter gives the absolute value of the
10715 overall net change in pen offsets.
10718 static void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer
10719 x0,integer x1, integer x2, integer y0, integer y1, integer y2,
10720 integer rise, integer turn_amt) ;
10723 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer
10724 x0,integer x1, integer x2, integer y0, integer y1, integer y2,
10725 integer rise, integer turn_amt) {
10726 pointer ww; /* for list manipulation */
10727 scaled du,dv; /* for slope calculation */
10728 integer t0,t1,t2; /* test coefficients */
10729 fraction t; /* place where the derivative passes a critical slope */
10730 fraction s; /* slope or reciprocal slope */
10731 integer v; /* intermediate value for updating |x0..y2| */
10732 pointer q; /* original |mp_link(p)| */
10735 if ( rise>0 ) ww=mp_link(w); /* a pointer to $w\k$ */
10736 else ww=knil(w); /* a pointer to $w_{k-1}$ */
10737 @<Compute test coefficients |(t0,t1,t2)|
10738 for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10739 t=mp_crossing_point(mp, t0,t1,t2);
10740 if ( t>=fraction_one ) {
10741 if ( turn_amt>0 ) t=fraction_one; else return;
10743 @<Split the cubic at $t$,
10744 and split off another cubic if the derivative crosses back@>;
10749 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10750 $-90^\circ$ rotation of the vector from |w| to |ww|. This makes the resulting
10751 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10754 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10755 du=mp_x_coord(ww)-mp_x_coord(w); dv=mp_y_coord(ww)-mp_y_coord(w);
10756 if ( abs(du)>=abs(dv) ) {
10757 s=mp_make_fraction(mp, dv,du);
10758 t0=mp_take_fraction(mp, x0,s)-y0;
10759 t1=mp_take_fraction(mp, x1,s)-y1;
10760 t2=mp_take_fraction(mp, x2,s)-y2;
10761 if ( du<0 ) { negate(t0); negate(t1); negate(t2); }
10763 s=mp_make_fraction(mp, du,dv);
10764 t0=x0-mp_take_fraction(mp, y0,s);
10765 t1=x1-mp_take_fraction(mp, y1,s);
10766 t2=x2-mp_take_fraction(mp, y2,s);
10767 if ( dv<0 ) { negate(t0); negate(t1); negate(t2); }
10769 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10771 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10772 $(*)$, and it might cross again and return towards $s_{k-1}$ or $s_k$,
10773 respectively, yielding another solution of $(*)$.
10775 @<Split the cubic at $t$, and split off another...@>=
10777 mp_split_cubic(mp, p,t); p=mp_link(p); mp_info(p)=zero_off+rise;
10779 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10780 x0=t_of_the_way(v,x1);
10781 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10782 y0=t_of_the_way(v,y1);
10783 if ( turn_amt<0 ) {
10784 t1=t_of_the_way(t1,t2);
10785 if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10786 t=mp_crossing_point(mp, 0,-t1,-t2);
10787 if ( t>fraction_one ) t=fraction_one;
10789 if ( (t==fraction_one)&&(mp_link(p)!=q) ) {
10790 mp_info(mp_link(p))=mp_info(mp_link(p))-rise;
10792 mp_split_cubic(mp, p,t); mp_info(mp_link(p))=zero_off-rise;
10793 v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10794 x2=t_of_the_way(x1,v);
10795 v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10796 y2=t_of_the_way(y1,v);
10801 @ Now we must consider the general problem of |offset_prep|, when
10802 nothing is known about a given cubic. We start by finding its
10803 direction in the vicinity of |t=0|.
10805 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10806 has not yet introduced any more numerical errors. Thus we can compute
10807 the true initial direction for the given cubic, even if it is almost
10810 @<Find the initial direction |(dx,dy)|@>=
10812 if ( dx==0 && dy==0 ) {
10814 if ( dx==0 && dy==0 ) {
10818 if ( p==c ) { dx0=dx; dy0=dy; }
10820 @ @<Find the final direction |(dxin,dyin)|@>=
10822 if ( dxin==0 && dyin==0 ) {
10824 if ( dxin==0 && dyin==0 ) {
10829 @ The next step is to bracket the initial direction between consecutive
10830 edges of the pen polygon. We must be careful to turn clockwise only if
10831 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10832 counter-clockwise in order to make \&{doublepath} envelopes come out
10833 @:double_path_}{\&{doublepath} primitive@>
10834 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10836 @<Update |mp_info(p)| and find the offset $w_k$ such that...@>=
10837 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10838 w=mp_pen_walk(mp, w0, turn_amt);
10840 mp_info(p)=mp_info(p)+turn_amt
10842 @ Decide how many pen offsets to go away from |w| in order to find the offset
10843 for |(dx,dy)|, going counterclockwise if |ccw| is |true|. This assumes that
10844 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10845 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10847 If the pen polygon has only two edges, they could both be parallel
10848 to |(dx,dy)|. In this case, we must be careful to stop after crossing the first
10849 such edge in order to avoid an infinite loop.
10852 static integer mp_get_turn_amt (MP mp,pointer w, scaled dx,
10853 scaled dy, boolean ccw);
10856 integer mp_get_turn_amt (MP mp,pointer w, scaled dx,
10857 scaled dy, boolean ccw) {
10858 pointer ww; /* a neighbor of knot~|w| */
10859 integer s; /* turn amount so far */
10860 integer t; /* |ab_vs_cd| result */
10865 t=mp_ab_vs_cd(mp, dy,(mp_x_coord(ww)-mp_x_coord(w)),
10866 dx,(mp_y_coord(ww)-mp_y_coord(w)));
10869 w=ww; ww=mp_link(ww);
10873 while ( mp_ab_vs_cd(mp, dy,(mp_x_coord(w)-mp_x_coord(ww)),
10874 dx,(mp_y_coord(w)-mp_y_coord(ww))) < 0) {
10882 @ When we're all done, the final offset is |w0| and the final curve direction
10883 is |(dxin,dyin)|. With this knowledge of the incoming direction at |c|, we
10884 can correct |mp_info(c)| which was erroneously based on an incoming offset
10887 @d fix_by(A) mp_info(c)=mp_info(c)+(A)
10889 @<Fix the offset change in |mp_info(c)| and set |c| to the return value of...@>=
10890 mp->spec_offset=mp_info(c)-zero_off;
10891 if ( mp_link(c)==c ) {
10892 mp_info(c)=zero_off+n;
10895 while ( w0!=h ) { fix_by(1); w0=mp_link(w0); };
10896 while ( mp_info(c)<=zero_off-n ) fix_by(n);
10897 while ( mp_info(c)>zero_off ) fix_by(-n);
10898 if ( (mp_info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10901 @ Finally we want to reduce the general problem to situations that
10902 |fin_offset_prep| can handle. We split the cubic into at most three parts
10903 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10905 @<Complete the offset splitting process@>=
10907 @<Compute test coeff...@>;
10908 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10909 |t:=fraction_one+1|@>;
10910 if ( t>fraction_one ) {
10911 mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10913 mp_split_cubic(mp, p,t); r=mp_link(p);
10914 x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10915 x2a=t_of_the_way(x1a,x1);
10916 y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10917 y2a=t_of_the_way(y1a,y1);
10918 mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10919 mp_info(r)=zero_off-1;
10920 if ( turn_amt>=0 ) {
10921 t1=t_of_the_way(t1,t2);
10923 t=mp_crossing_point(mp, 0,-t1,-t2);
10924 if ( t>fraction_one ) t=fraction_one;
10925 @<Split off another rising cubic for |fin_offset_prep|@>;
10926 mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10928 mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10932 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10933 mp_split_cubic(mp, r,t); mp_info(mp_link(r))=zero_off+1;
10934 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10935 x0a=t_of_the_way(x1,x1a);
10936 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10937 y0a=t_of_the_way(y1,y1a);
10938 mp_fin_offset_prep(mp, mp_link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10941 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10942 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10943 need to decide whether the directions are parallel or antiparallel. We
10944 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10945 should be avoided when the value of |turn_amt| already determines the
10946 answer. If |t2<0|, there is one crossing and it is antiparallel only if
10947 |turn_amt>=0|. If |turn_amt<0|, there should always be at least one
10948 crossing and the first crossing cannot be antiparallel.
10950 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10951 t=mp_crossing_point(mp, t0,t1,t2);
10952 if ( turn_amt>=0 ) {
10956 u0=t_of_the_way(x0,x1);
10957 u1=t_of_the_way(x1,x2);
10958 ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10959 v0=t_of_the_way(y0,y1);
10960 v1=t_of_the_way(y1,y2);
10961 ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10962 if ( ss<0 ) t=fraction_one+1;
10964 } else if ( t>fraction_one ) {
10968 @ @<Other local variables for |offset_prep|@>=
10969 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10970 integer ss = 0; /* the part of the dot product computed so far */
10971 int d_sign; /* sign of overall change in direction for this cubic */
10973 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10974 problem to decide which way it loops around but that's OK as long we're
10975 consistent. To make \&{doublepath} envelopes work properly, reversing
10976 the path should always change the sign of |turn_amt|.
10978 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10979 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10981 @<Check rotation direction based on node position@>
10985 if ( dy>0 ) d_sign=1; else d_sign=-1;
10987 if ( dx>0 ) d_sign=1; else d_sign=-1;
10990 @<Make |ss| negative if and only if the total change in direction is
10991 more than $180^\circ$@>;
10992 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
10993 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10995 @ We check rotation direction by looking at the vector connecting the current
10996 node with the next. If its angle with incoming and outgoing tangents has the
10997 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
10998 Otherwise we proceed to the cusp code.
11000 @<Check rotation direction based on node position@>=
11001 u0=mp_x_coord(q)-mp_x_coord(p);
11002 u1=mp_y_coord(q)-mp_y_coord(p);
11003 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
11004 mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
11006 @ In order to be invariant under path reversal, the result of this computation
11007 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
11008 then swapped with |(x2,y2)|. We make use of the identities
11009 |take_fraction(-a,-b)=take_fraction(a,b)| and
11010 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
11012 @<Make |ss| negative if and only if the total change in direction is...@>=
11013 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
11014 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
11015 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
11017 t=mp_crossing_point(mp, t0,t1,-t0);
11018 u0=t_of_the_way(x0,x1);
11019 u1=t_of_the_way(x1,x2);
11020 v0=t_of_the_way(y0,y1);
11021 v1=t_of_the_way(y1,y2);
11023 t=mp_crossing_point(mp, -t0,t1,t0);
11024 u0=t_of_the_way(x2,x1);
11025 u1=t_of_the_way(x1,x0);
11026 v0=t_of_the_way(y2,y1);
11027 v1=t_of_the_way(y1,y0);
11029 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
11030 mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
11032 @ Here's a routine that prints an envelope spec in symbolic form. It assumes
11033 that the |cur_pen| has not been walked around to the first offset.
11036 static void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, const char *s) {
11037 pointer p,q; /* list traversal */
11038 pointer w; /* the current pen offset */
11039 mp_print_diagnostic(mp, "Envelope spec",s,true);
11040 p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
11042 mp_print_two(mp, mp_x_coord(cur_spec),mp_y_coord(cur_spec));
11043 mp_print(mp, " % beginning with offset ");
11044 mp_print_two(mp, mp_x_coord(w),mp_y_coord(w));
11048 @<Print the cubic between |p| and |q|@>;
11050 if ((p==cur_spec) || (mp_info(p)!=zero_off))
11053 if ( mp_info(p)!=zero_off ) {
11054 @<Update |w| as indicated by |mp_info(p)| and print an explanation@>;
11056 } while (p!=cur_spec);
11057 mp_print_nl(mp, " & cycle");
11058 mp_end_diagnostic(mp, true);
11061 @ @<Update |w| as indicated by |mp_info(p)| and print an explanation@>=
11063 w=mp_pen_walk(mp, w, (mp_info(p)-zero_off));
11064 mp_print(mp, " % ");
11065 if ( mp_info(p)>zero_off ) mp_print(mp, "counter");
11066 mp_print(mp, "clockwise to offset ");
11067 mp_print_two(mp, mp_x_coord(w),mp_y_coord(w));
11070 @ @<Print the cubic between |p| and |q|@>=
11072 mp_print_nl(mp, " ..controls ");
11073 mp_print_two(mp, mp_right_x(p),mp_right_y(p));
11074 mp_print(mp, " and ");
11075 mp_print_two(mp, mp_left_x(q),mp_left_y(q));
11076 mp_print_nl(mp, " ..");
11077 mp_print_two(mp, mp_x_coord(q),mp_y_coord(q));
11080 @ Once we have an envelope spec, the remaining task to construct the actual
11081 envelope by offsetting each cubic as determined by the |info| fields in
11082 the knots. First we use |offset_prep| to convert the |c| into an envelope
11083 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
11086 The |ljoin| and |miterlim| parameters control the treatment of points where the
11087 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
11088 The endpoints are easily located because |c| is given in undoubled form
11089 and then doubled in this procedure. We use |spec_p1| and |spec_p2| to keep
11090 track of the endpoints and treat them like very sharp corners.
11091 Butt end caps are treated like beveled joins; round end caps are treated like
11092 round joins; and square end caps are achieved by setting |join_type:=3|.
11094 None of these parameters apply to inside joins where the convolution tracing
11095 has retrograde lines. In such cases we use a simple connect-the-endpoints
11096 approach that is achieved by setting |join_type:=2|.
11099 static pointer mp_make_envelope (MP mp,pointer c, pointer h, quarterword ljoin,
11100 quarterword lcap, scaled miterlim) {
11101 pointer p,q,r,q0; /* for manipulating the path */
11102 int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
11103 pointer w,w0; /* the pen knot for the current offset */
11104 scaled qx,qy; /* unshifted coordinates of |q| */
11105 halfword k,k0; /* controls pen edge insertion */
11106 @<Other local variables for |make_envelope|@>;
11107 dxin=0; dyin=0; dxout=0; dyout=0;
11108 mp->spec_p1=null; mp->spec_p2=null;
11109 @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
11110 @<Use |offset_prep| to compute the envelope spec then walk |h| around to
11111 the initial offset@>;
11115 q=mp_link(p); q0=q;
11116 qx=mp_x_coord(q); qy=mp_y_coord(q);
11119 if ( k!=zero_off ) {
11120 @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
11122 @<Add offset |w| to the cubic from |p| to |q|@>;
11123 while ( k!=zero_off ) {
11124 @<Step |w| and move |k| one step closer to |zero_off|@>;
11125 if ( (join_type==1)||(k==zero_off) )
11126 q=mp_insert_knot(mp, q,qx+mp_x_coord(w),qy+mp_y_coord(w));
11128 if ( q!=mp_link(p) ) {
11129 @<Set |p=mp_link(p)| and add knots between |p| and |q| as
11130 required by |join_type|@>;
11137 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
11138 c=mp_offset_prep(mp, c,h);
11139 if ( mp->internal[mp_tracing_specs]>0 )
11140 mp_print_spec(mp, c,h,"");
11141 h=mp_pen_walk(mp, h,mp->spec_offset)
11143 @ Mitered and squared-off joins depend on path directions that are difficult to
11144 compute for degenerate cubics. The envelope spec computed by |offset_prep| can
11145 have degenerate cubics only if the entire cycle collapses to a single
11146 degenerate cubic. Setting |join_type:=2| in this case makes the computed
11147 envelope degenerate as well.
11149 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
11150 if ( k<zero_off ) {
11153 if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
11154 else if ( lcap==2 ) join_type=3;
11155 else join_type=2-lcap;
11156 if ( (join_type==0)||(join_type==3) ) {
11157 @<Set the incoming and outgoing directions at |q|; in case of
11158 degeneracy set |join_type:=2|@>;
11159 if ( join_type==0 ) {
11160 @<If |miterlim| is less than the secant of half the angle at |q|
11161 then set |join_type:=2|@>;
11166 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11168 tmp=mp_take_fraction(mp, miterlim,fraction_half+
11169 half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11171 if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11174 @ @<Other local variables for |make_envelope|@>=
11175 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11176 scaled tmp; /* a temporary value */
11178 @ The coordinates of |p| have already been shifted unless |p| is the first
11179 knot in which case they get shifted at the very end.
11181 @<Add offset |w| to the cubic from |p| to |q|@>=
11182 mp_right_x(p)=mp_right_x(p)+mp_x_coord(w);
11183 mp_right_y(p)=mp_right_y(p)+mp_y_coord(w);
11184 mp_left_x(q)=mp_left_x(q)+mp_x_coord(w);
11185 mp_left_y(q)=mp_left_y(q)+mp_y_coord(w);
11186 mp_x_coord(q)=mp_x_coord(q)+mp_x_coord(w);
11187 mp_y_coord(q)=mp_y_coord(q)+mp_y_coord(w);
11188 mp_left_type(q)=mp_explicit;
11189 mp_right_type(q)=mp_explicit
11191 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11192 if ( k>zero_off ){ w=mp_link(w); decr(k); }
11193 else { w=knil(w); incr(k); }
11195 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11196 the |mp_right_x| and |mp_right_y| fields of |r| are set from |q|. This is done in
11197 case the cubic containing these control points is ``yet to be examined.''
11200 static pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y);
11203 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11204 /* returns the inserted knot */
11205 pointer r; /* the new knot */
11206 r=mp_get_node(mp, knot_node_size);
11207 mp_link(r)=mp_link(q); mp_link(q)=r;
11208 mp_right_x(r)=mp_right_x(q);
11209 mp_right_y(r)=mp_right_y(q);
11212 mp_right_x(q)=mp_x_coord(q);
11213 mp_right_y(q)=mp_y_coord(q);
11214 mp_left_x(r)=mp_x_coord(r);
11215 mp_left_y(r)=mp_y_coord(r);
11216 mp_left_type(r)=mp_explicit;
11217 mp_right_type(r)=mp_explicit;
11218 mp_originator(r)=mp_program_code;
11222 @ After setting |p:=mp_link(p)|, either |join_type=1| or |q=mp_link(p)|.
11224 @<Set |p=mp_link(p)| and add knots between |p| and |q| as...@>=
11227 if ( (join_type==0)||(join_type==3) ) {
11228 if ( join_type==0 ) {
11229 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11231 @<Make |r| the last of two knots inserted between |p| and |q| to form a
11235 mp_right_x(r)=mp_x_coord(r);
11236 mp_right_y(r)=mp_y_coord(r);
11241 @ For very small angles, adding a knot is unnecessary and would cause numerical
11242 problems, so we just set |r:=null| in that case.
11244 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11246 det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11247 if ( abs(det)<26844 ) {
11248 r=null; /* sine $<10^{-4}$ */
11250 tmp=mp_take_fraction(mp, mp_x_coord(q)-mp_x_coord(p),dyout)-
11251 mp_take_fraction(mp, mp_y_coord(q)-mp_y_coord(p),dxout);
11252 tmp=mp_make_fraction(mp, tmp,det);
11253 r=mp_insert_knot(mp, p,mp_x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11254 mp_y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11258 @ @<Other local variables for |make_envelope|@>=
11259 fraction det; /* a determinant used for mitered join calculations */
11261 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11263 ht_x=mp_y_coord(w)-mp_y_coord(w0);
11264 ht_y=mp_x_coord(w0)-mp_x_coord(w);
11265 while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) {
11266 ht_x+=ht_x; ht_y+=ht_y;
11268 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11269 product with |(ht_x,ht_y)|@>;
11270 tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11271 mp_take_fraction(mp, dyin,ht_y));
11272 r=mp_insert_knot(mp, p,mp_x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11273 mp_y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11274 tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11275 mp_take_fraction(mp, dyout,ht_y));
11276 r=mp_insert_knot(mp, r,mp_x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11277 mp_y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11280 @ @<Other local variables for |make_envelope|@>=
11281 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11282 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11283 halfword kk; /* keeps track of the pen vertices being scanned */
11284 pointer ww; /* the pen vertex being tested */
11286 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11287 from zero to |max_ht|.
11289 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11294 @<Step |ww| and move |kk| one step closer to |k0|@>;
11295 if ( kk==k0 ) break;
11296 tmp=mp_take_fraction(mp, (mp_x_coord(ww)-mp_x_coord(w0)),ht_x)+
11297 mp_take_fraction(mp, (mp_y_coord(ww)-mp_y_coord(w0)),ht_y);
11298 if ( tmp>max_ht ) max_ht=tmp;
11302 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11303 if ( kk>k0 ) { ww=mp_link(ww); decr(kk); }
11304 else { ww=knil(ww); incr(kk); }
11306 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11307 if ( mp_left_type(c)==mp_endpoint ) {
11308 mp->spec_p1=mp_htap_ypoc(mp, c);
11309 mp->spec_p2=mp->path_tail;
11310 mp_originator(mp->spec_p1)=mp_program_code;
11311 mp_link(mp->spec_p2)=mp_link(mp->spec_p1);
11312 mp_link(mp->spec_p1)=c;
11313 mp_remove_cubic(mp, mp->spec_p1);
11315 if ( c!=mp_link(c) ) {
11316 mp_originator(mp->spec_p2)=mp_program_code;
11317 mp_remove_cubic(mp, mp->spec_p2);
11319 @<Make |c| look like a cycle of length one@>;
11323 @ @<Make |c| look like a cycle of length one@>=
11325 mp_left_type(c)=mp_explicit; mp_right_type(c)=mp_explicit;
11326 mp_left_x(c)=mp_x_coord(c); mp_left_y(c)=mp_y_coord(c);
11327 mp_right_x(c)=mp_x_coord(c); mp_right_y(c)=mp_y_coord(c);
11330 @ In degenerate situations we might have to look at the knot preceding~|q|.
11331 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11333 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11334 dxin=mp_x_coord(q)-mp_left_x(q);
11335 dyin=mp_y_coord(q)-mp_left_y(q);
11336 if ( (dxin==0)&&(dyin==0) ) {
11337 dxin=mp_x_coord(q)-mp_right_x(p);
11338 dyin=mp_y_coord(q)-mp_right_y(p);
11339 if ( (dxin==0)&&(dyin==0) ) {
11340 dxin=mp_x_coord(q)-mp_x_coord(p);
11341 dyin=mp_y_coord(q)-mp_y_coord(p);
11342 if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11343 dxin=dxin+mp_x_coord(w);
11344 dyin=dyin+mp_y_coord(w);
11348 tmp=mp_pyth_add(mp, dxin,dyin);
11352 dxin=mp_make_fraction(mp, dxin,tmp);
11353 dyin=mp_make_fraction(mp, dyin,tmp);
11354 @<Set the outgoing direction at |q|@>;
11357 @ If |q=c| then the coordinates of |r| and the control points between |q|
11358 and~|r| have already been offset by |h|.
11360 @<Set the outgoing direction at |q|@>=
11361 dxout=mp_right_x(q)-mp_x_coord(q);
11362 dyout=mp_right_y(q)-mp_y_coord(q);
11363 if ( (dxout==0)&&(dyout==0) ) {
11365 dxout=mp_left_x(r)-mp_x_coord(q);
11366 dyout=mp_left_y(r)-mp_y_coord(q);
11367 if ( (dxout==0)&&(dyout==0) ) {
11368 dxout=mp_x_coord(r)-mp_x_coord(q);
11369 dyout=mp_y_coord(r)-mp_y_coord(q);
11373 dxout=dxout-mp_x_coord(h);
11374 dyout=dyout-mp_y_coord(h);
11376 tmp=mp_pyth_add(mp, dxout,dyout);
11377 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11378 @:this can't happen degerate spec}{\quad degenerate spec@>
11379 dxout=mp_make_fraction(mp, dxout,tmp);
11380 dyout=mp_make_fraction(mp, dyout,tmp)
11382 @* \[23] Direction and intersection times.
11383 A path of length $n$ is defined parametrically by functions $x(t)$ and
11384 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11385 reaches the point $\bigl(x(t),y(t)\bigr)$. In this section of the program
11386 we shall consider operations that determine special times associated with
11387 given paths: the first time that a path travels in a given direction, and
11388 a pair of times at which two paths cross each other.
11390 @ Let's start with the easier task. The function |find_direction_time| is
11391 given a direction |(x,y)| and a path starting at~|h|. If the path never
11392 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11393 it will be nonnegative.
11395 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11396 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11397 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11398 assumed to match any given direction at time~|t|.
11400 The routine solves this problem in nondegenerate cases by rotating the path
11401 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11402 to find when a given path first travels ``due east.''
11405 static scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11406 scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11407 pointer p,q; /* for list traversal */
11408 scaled n; /* the direction time at knot |p| */
11409 scaled tt; /* the direction time within a cubic */
11410 @<Other local variables for |find_direction_time|@>;
11411 @<Normalize the given direction for better accuracy;
11412 but |return| with zero result if it's zero@>;
11415 if ( mp_right_type(p)==mp_endpoint ) break;
11417 @<Rotate the cubic between |p| and |q|; then
11418 |goto found| if the rotated cubic travels due east at some time |tt|;
11419 but |break| if an entire cyclic path has been traversed@>;
11427 @ @<Normalize the given direction for better accuracy...@>=
11428 if ( abs(x)<abs(y) ) {
11429 x=mp_make_fraction(mp, x,abs(y));
11430 if ( y>0 ) y=fraction_one; else y=-fraction_one;
11431 } else if ( x==0 ) {
11434 y=mp_make_fraction(mp, y,abs(x));
11435 if ( x>0 ) x=fraction_one; else x=-fraction_one;
11438 @ Since we're interested in the tangent directions, we work with the
11439 derivative $${1\over3}B'(x_0,x_1,x_2,x_3;t)=
11440 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11441 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11442 in order to achieve better accuracy.
11444 The given path may turn abruptly at a knot, and it might pass the critical
11445 tangent direction at such a time. Therefore we remember the direction |phi|
11446 in which the previous rotated cubic was traveling. (The value of |phi| will be
11447 undefined on the first cubic, i.e., when |n=0|.)
11449 @<Rotate the cubic between |p| and |q|; then...@>=
11451 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11452 points of the rotated derivatives@>;
11453 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11455 @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11458 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11459 @<Exit to |found| if the curve whose derivatives are specified by
11460 |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11462 @ @<Other local variables for |find_direction_time|@>=
11463 scaled x1,x2,x3,y1,y2,y3; /* multiples of rotated derivatives */
11464 angle theta,phi; /* angles of exit and entry at a knot */
11465 fraction t; /* temp storage */
11467 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11468 x1=mp_right_x(p)-mp_x_coord(p); x2=mp_left_x(q)-mp_right_x(p);
11469 x3=mp_x_coord(q)-mp_left_x(q);
11470 y1=mp_right_y(p)-mp_y_coord(p); y2=mp_left_y(q)-mp_right_y(p);
11471 y3=mp_y_coord(q)-mp_left_y(q);
11473 if ( abs(x2)>max ) max=abs(x2);
11474 if ( abs(x3)>max ) max=abs(x3);
11475 if ( abs(y1)>max ) max=abs(y1);
11476 if ( abs(y2)>max ) max=abs(y2);
11477 if ( abs(y3)>max ) max=abs(y3);
11478 if ( max==0 ) goto FOUND;
11479 while ( max<fraction_half ){
11480 max+=max; x1+=x1; x2+=x2; x3+=x3;
11481 y1+=y1; y2+=y2; y3+=y3;
11483 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11484 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11485 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11486 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11487 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11488 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11490 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11491 theta=mp_n_arg(mp, x1,y1);
11492 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11493 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11495 @ In this step we want to use the |crossing_point| routine to find the
11496 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11497 Several complications arise: If the quadratic equation has a double root,
11498 the curve never crosses zero, and |crossing_point| will find nothing;
11499 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11500 equation has simple roots, or only one root, we may have to negate it
11501 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11502 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11505 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11506 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11507 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11508 @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11509 either |goto found| or |goto done|@>;
11512 if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11513 else if ( y2>0 ){ y2=-y2; y3=-y3; };
11515 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11516 $B(x_1,x_2,x_3;t)\ge0$@>;
11519 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11520 two roots, because we know that it isn't identically zero.
11522 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11523 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11524 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11525 subject to rounding errors. Yet this code optimistically tries to
11526 do the right thing.
11528 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11530 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11531 t=mp_crossing_point(mp, y1,y2,y3);
11532 if ( t>fraction_one ) goto DONE;
11533 y2=t_of_the_way(y2,y3);
11534 x1=t_of_the_way(x1,x2);
11535 x2=t_of_the_way(x2,x3);
11536 x1=t_of_the_way(x1,x2);
11537 if ( x1>=0 ) we_found_it;
11539 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11540 if ( t>fraction_one ) goto DONE;
11541 x1=t_of_the_way(x1,x2);
11542 x2=t_of_the_way(x2,x3);
11543 if ( t_of_the_way(x1,x2)>=0 ) {
11544 t=t_of_the_way(tt,fraction_one); we_found_it;
11547 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11548 either |goto found| or |goto done|@>=
11550 if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11551 t=mp_make_fraction(mp, y1,y1-y2);
11552 x1=t_of_the_way(x1,x2);
11553 x2=t_of_the_way(x2,x3);
11554 if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11555 } else if ( y3==0 ) {
11557 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11558 } else if ( x3>=0 ) {
11559 tt=unity; goto FOUND;
11565 @ At this point we know that the derivative of |y(t)| is identically zero,
11566 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11569 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11571 t=mp_crossing_point(mp, -x1,-x2,-x3);
11572 if ( t<=fraction_one ) we_found_it;
11573 if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) {
11574 t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11578 @ The intersection of two cubics can be found by an interesting variant
11579 of the general bisection scheme described in the introduction to
11581 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)$,
11582 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11583 if an intersection exists. First we find the smallest rectangle that
11584 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11585 the smallest rectangle that encloses
11586 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11587 But if the rectangles do overlap, we bisect the intervals, getting
11588 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11589 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11590 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11591 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11592 levels of bisection we will have determined the intersection times $t_1$
11593 and~$t_2$ to $l$~bits of accuracy.
11595 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11596 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11597 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11598 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11599 to determine when the enclosing rectangles overlap. Here's why:
11600 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11601 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11602 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11603 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11604 overlap if and only if $u\submin\L x\submax$ and
11605 $x\submin\L u\submax$. Letting
11606 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11607 U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11608 we have $2^lu\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11610 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11611 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11612 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11613 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11614 because of the overlap condition; i.e., we know that $X\submin$,
11615 $X\submax$, and their relatives are bounded, hence $X\submax-
11616 U\submin$ and $X\submin-U\submax$ are bounded.
11618 @ Incidentally, if the given cubics intersect more than once, the process
11619 just sketched will not necessarily find the lexicographically smallest pair
11620 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11621 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11622 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11623 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11624 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11625 Shuffled order agrees with lexicographic order if all pairs of solutions
11626 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11627 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11628 and the bisection algorithm would be substantially less efficient if it were
11629 constrained by lexicographic order.
11631 For example, suppose that an overlap has been found for $l=3$ and
11632 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11633 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11634 Then there is probably an intersection in one of the subintervals
11635 $(.1011,.011x)$; but lexicographic order would require us to explore
11636 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11637 want to store all of the subdivision data for the second path, so the
11638 subdivisions would have to be regenerated many times. Such inefficiencies
11639 would be associated with every `1' in the binary representation of~$t_1$.
11641 @ The subdivision process introduces rounding errors, hence we need to
11642 make a more liberal test for overlap. It is not hard to show that the
11643 computed values of $U_i$ differ from the truth by at most~$l$, on
11644 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11645 If $\beta$ is an upper bound on the absolute error in the computed
11646 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11647 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11648 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11650 More accuracy is obtained if we try the algorithm first with |tol=0|;
11651 the more liberal tolerance is used only if an exact approach fails.
11652 It is convenient to do this double-take by letting `3' in the preceding
11653 paragraph be a parameter, which is first 0, then 3.
11656 unsigned int tol_step; /* either 0 or 3, usually */
11658 @ We shall use an explicit stack to implement the recursive bisection
11659 method described above. The |bisect_stack| array will contain numerous 5-word
11660 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11661 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11663 The following macros define the allocation of stack positions to
11664 the quantities needed for bisection-intersection.
11666 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11667 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11668 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11669 @d stack_min(A) mp->bisect_stack[(A)+3]
11670 /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11671 @d stack_max(A) mp->bisect_stack[(A)+4]
11672 /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11673 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11675 @d u_packet(A) ((A)-5)
11676 @d v_packet(A) ((A)-10)
11677 @d x_packet(A) ((A)-15)
11678 @d y_packet(A) ((A)-20)
11679 @d l_packets (mp->bisect_ptr-int_packets)
11680 @d r_packets mp->bisect_ptr
11681 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11682 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11683 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11684 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11685 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11686 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11687 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11688 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11690 @d u1l stack_1(ul_packet) /* $U'_1$ */
11691 @d u2l stack_2(ul_packet) /* $U'_2$ */
11692 @d u3l stack_3(ul_packet) /* $U'_3$ */
11693 @d v1l stack_1(vl_packet) /* $V'_1$ */
11694 @d v2l stack_2(vl_packet) /* $V'_2$ */
11695 @d v3l stack_3(vl_packet) /* $V'_3$ */
11696 @d x1l stack_1(xl_packet) /* $X'_1$ */
11697 @d x2l stack_2(xl_packet) /* $X'_2$ */
11698 @d x3l stack_3(xl_packet) /* $X'_3$ */
11699 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11700 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11701 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11702 @d u1r stack_1(ur_packet) /* $U''_1$ */
11703 @d u2r stack_2(ur_packet) /* $U''_2$ */
11704 @d u3r stack_3(ur_packet) /* $U''_3$ */
11705 @d v1r stack_1(vr_packet) /* $V''_1$ */
11706 @d v2r stack_2(vr_packet) /* $V''_2$ */
11707 @d v3r stack_3(vr_packet) /* $V''_3$ */
11708 @d x1r stack_1(xr_packet) /* $X''_1$ */
11709 @d x2r stack_2(xr_packet) /* $X''_2$ */
11710 @d x3r stack_3(xr_packet) /* $X''_3$ */
11711 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11712 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11713 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11715 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11716 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11717 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11718 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11719 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11720 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11723 integer *bisect_stack;
11724 integer bisect_ptr;
11726 @ @<Allocate or initialize ...@>=
11727 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11729 @ @<Dealloc variables@>=
11730 xfree(mp->bisect_stack);
11732 @ @<Check the ``constant''...@>=
11733 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11735 @ Computation of the min and max is a tedious but fairly fast sequence of
11736 instructions; exactly four comparisons are made in each branch.
11739 if ( stack_1((A))<0 ) {
11740 if ( stack_3((A))>=0 ) {
11741 if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11742 else stack_min((A))=stack_1((A));
11743 stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11744 if ( stack_max((A))<0 ) stack_max((A))=0;
11746 stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11747 if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11748 stack_max((A))=stack_1((A))+stack_2((A));
11749 if ( stack_max((A))<0 ) stack_max((A))=0;
11751 } else if ( stack_3((A))<=0 ) {
11752 if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11753 else stack_max((A))=stack_1((A));
11754 stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11755 if ( stack_min((A))>0 ) stack_min((A))=0;
11757 stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11758 if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11759 stack_min((A))=stack_1((A))+stack_2((A));
11760 if ( stack_min((A))>0 ) stack_min((A))=0;
11763 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11764 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11765 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11766 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11767 plus the |scaled| values of $t_1$ and~$t_2$.
11769 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11770 finds no intersection. The routine gives up and gives an approximate answer
11771 if it has backtracked
11772 more than 5000 times (otherwise there are cases where several minutes
11773 of fruitless computation would be possible).
11775 @d max_patience 5000
11778 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11779 integer time_to_go; /* this many backtracks before giving up */
11780 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11782 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11783 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,mp_link(p))|
11784 and |(pp,mp_link(pp))|, respectively.
11787 static void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11788 pointer q,qq; /* |mp_link(p)|, |mp_link(pp)| */
11789 mp->time_to_go=max_patience; mp->max_t=2;
11790 @<Initialize for intersections at level zero@>;
11793 if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11794 if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11795 if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11796 if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv)))
11798 if ( mp->cur_t>=mp->max_t ){
11799 if ( mp->max_t==two ) { /* we've done 17 bisections */
11800 mp->cur_t=halfp(mp->cur_t+1);
11801 mp->cur_tt=halfp(mp->cur_tt+1);
11804 mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11806 @<Subdivide for a new level of intersection@>;
11809 if ( mp->time_to_go>0 ) {
11810 decr(mp->time_to_go);
11812 while ( mp->appr_t<unity ) {
11813 mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11815 mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11817 @<Advance to the next pair |(cur_t,cur_tt)|@>;
11821 @ The following variables are global, although they are used only by
11822 |cubic_intersection|, because it is necessary on some machines to
11823 split |cubic_intersection| up into two procedures.
11826 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11827 integer tol; /* bound on the uncertainty in the overlap test */
11829 integer xy; /* pointers to the current packets of interest */
11830 integer three_l; /* |tol_step| times the bisection level */
11831 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11833 @ We shall assume that the coordinates are sufficiently non-extreme that
11834 integer overflow will not occur.
11835 @^overflow in arithmetic@>
11837 @<Initialize for intersections at level zero@>=
11838 q=mp_link(p); qq=mp_link(pp); mp->bisect_ptr=int_packets;
11839 u1r=mp_right_x(p)-mp_x_coord(p); u2r=mp_left_x(q)-mp_right_x(p);
11840 u3r=mp_x_coord(q)-mp_left_x(q); set_min_max(ur_packet);
11841 v1r=mp_right_y(p)-mp_y_coord(p); v2r=mp_left_y(q)-mp_right_y(p);
11842 v3r=mp_y_coord(q)-mp_left_y(q); set_min_max(vr_packet);
11843 x1r=mp_right_x(pp)-mp_x_coord(pp); x2r=mp_left_x(qq)-mp_right_x(pp);
11844 x3r=mp_x_coord(qq)-mp_left_x(qq); set_min_max(xr_packet);
11845 y1r=mp_right_y(pp)-mp_y_coord(pp); y2r=mp_left_y(qq)-mp_right_y(pp);
11846 y3r=mp_y_coord(qq)-mp_left_y(qq); set_min_max(yr_packet);
11847 mp->delx=mp_x_coord(p)-mp_x_coord(pp); mp->dely=mp_y_coord(p)-mp_y_coord(pp);
11848 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets;
11849 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11851 @ @<Subdivide for a new level of intersection@>=
11852 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol;
11853 stack_uv=mp->uv; stack_xy=mp->xy;
11854 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11855 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11856 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11857 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11858 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11859 u3l=half(u2l+u2r); u1r=u3l;
11860 set_min_max(ul_packet); set_min_max(ur_packet);
11861 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11862 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11863 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11864 v3l=half(v2l+v2r); v1r=v3l;
11865 set_min_max(vl_packet); set_min_max(vr_packet);
11866 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11867 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11868 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11869 x3l=half(x2l+x2r); x1r=x3l;
11870 set_min_max(xl_packet); set_min_max(xr_packet);
11871 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11872 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11873 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11874 y3l=half(y2l+y2r); y1r=y3l;
11875 set_min_max(yl_packet); set_min_max(yr_packet);
11876 mp->uv=l_packets; mp->xy=l_packets;
11877 mp->delx+=mp->delx; mp->dely+=mp->dely;
11878 mp->tol=mp->tol-mp->three_l+mp->tol_step;
11879 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11881 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11883 if ( odd(mp->cur_tt) ) {
11884 if ( odd(mp->cur_t) ) {
11885 @<Descend to the previous level and |goto not_found|@>;
11888 mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11889 +stack_3(u_packet(mp->uv));
11890 mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11891 +stack_3(v_packet(mp->uv));
11892 mp->uv=mp->uv+int_packets; /* switch from |l_packets| to |r_packets| */
11893 decr(mp->cur_tt); mp->xy=mp->xy-int_packets;
11894 /* switch from |r_packets| to |l_packets| */
11895 mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11896 +stack_3(x_packet(mp->xy));
11897 mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11898 +stack_3(y_packet(mp->xy));
11901 incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11902 mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11903 -stack_3(x_packet(mp->xy));
11904 mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11905 -stack_3(y_packet(mp->xy));
11906 mp->xy=mp->xy+int_packets; /* switch from |l_packets| to |r_packets| */
11909 @ @<Descend to the previous level...@>=
11911 mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11912 if ( mp->cur_t==0 ) return;
11913 mp->bisect_ptr=mp->bisect_ptr-int_increment;
11914 mp->three_l=mp->three_l-mp->tol_step;
11915 mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol;
11916 mp->uv=stack_uv; mp->xy=stack_xy;
11920 @ The |path_intersection| procedure is much simpler.
11921 It invokes |cubic_intersection| in lexicographic order until finding a
11922 pair of cubics that intersect. The final intersection times are placed in
11923 |cur_t| and~|cur_tt|.
11926 static void mp_path_intersection (MP mp,pointer h, pointer hh) {
11927 pointer p,pp; /* link registers that traverse the given paths */
11928 integer n,nn; /* integer parts of intersection times, minus |unity| */
11929 @<Change one-point paths into dead cycles@>;
11934 if ( mp_right_type(p)!=mp_endpoint ) {
11937 if ( mp_right_type(pp)!=mp_endpoint ) {
11938 mp_cubic_intersection(mp, p,pp);
11939 if ( mp->cur_t>0 ) {
11940 mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn;
11944 nn=nn+unity; pp=mp_link(pp);
11947 n=n+unity; p=mp_link(p);
11949 mp->tol_step=mp->tol_step+3;
11950 } while (mp->tol_step<=3);
11951 mp->cur_t=-unity; mp->cur_tt=-unity;
11954 @ @<Change one-point paths...@>=
11955 if ( mp_right_type(h)==mp_endpoint ) {
11956 mp_right_x(h)=mp_x_coord(h); mp_left_x(h)=mp_x_coord(h);
11957 mp_right_y(h)=mp_y_coord(h); mp_left_y(h)=mp_y_coord(h); mp_right_type(h)=mp_explicit;
11959 if ( mp_right_type(hh)==mp_endpoint ) {
11960 mp_right_x(hh)=mp_x_coord(hh); mp_left_x(hh)=mp_x_coord(hh);
11961 mp_right_y(hh)=mp_y_coord(hh); mp_left_y(hh)=mp_y_coord(hh); mp_right_type(hh)=mp_explicit;
11964 @* \[24] Dynamic linear equations.
11965 \MP\ users define variables implicitly by stating equations that should be
11966 satisfied; the computer is supposed to be smart enough to solve those equations.
11967 And indeed, the computer tries valiantly to do so, by distinguishing five
11968 different types of numeric values:
11971 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11972 of the variable whose address is~|p|.
11975 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11976 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11977 as a |scaled| number plus a sum of independent variables with |fraction|
11981 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11982 number'' reflecting the time this variable was first used in an equation;
11983 also |0<=m<64|, and each dependent variable
11984 that refers to this one is actually referring to the future value of
11985 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11986 scaling are sometimes needed to keep the coefficients in dependency lists
11987 from getting too large. The value of~|m| will always be even.)
11990 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11991 equation before, but it has been explicitly declared to be numeric.
11994 |type(p)=undefined| means that variable |p| hasn't appeared before.
11996 \smallskip\noindent
11997 We have actually discussed these five types in the reverse order of their
11998 history during a computation: Once |known|, a variable never again
11999 becomes |dependent|; once |dependent|, it almost never again becomes
12000 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
12001 and once |mp_numeric_type|, it never again becomes |undefined| (except
12002 of course when the user specifically decides to scrap the old value
12003 and start again). A backward step may, however, take place: Sometimes
12004 a |dependent| variable becomes |mp_independent| again, when one of the
12005 independent variables it depends on is reverting to |undefined|.
12008 The next patch detects overflow of independent-variable serial
12009 numbers. Diagnosed and patched by Thorsten Dahlheimer.
12011 @d s_scale 64 /* the serial numbers are multiplied by this factor */
12012 @d new_indep(A) /* create a new independent variable */
12013 { if ( mp->serial_no>el_gordo-s_scale )
12014 mp_fatal_error(mp, "variable instance identifiers exhausted");
12015 mp_type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
12016 value((A))=mp->serial_no;
12020 integer serial_no; /* the most recent serial number, times |s_scale| */
12022 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
12024 @ But how are dependency lists represented? It's simple: The linear combination
12025 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
12026 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
12027 @t$\alpha_1$@>| (which is a |fraction|); |mp_info(q)| points to the location
12028 of $\alpha_1$; and |mp_link(p)| points to the dependency list
12029 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
12030 then |value(q)=@t$\beta$@>| (which is |scaled|) and |mp_info(q)=null|.
12031 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
12032 they appear in decreasing order of their |value| fields (i.e., of
12033 their serial numbers). \ (It is convenient to use decreasing order,
12034 since |value(null)=0|. If the independent variables were not sorted by
12035 serial number but by some other criterion, such as their location in |mem|,
12036 the equation-solving mechanism would be too system-dependent, because
12037 the ordering can affect the computed results.)
12039 The |link| field in the node that contains the constant term $\beta$ is
12040 called the {\sl final link\/} of the dependency list. \MP\ maintains
12041 a doubly-linked master list of all dependency lists, in terms of a permanently
12043 in |mem| called |dep_head|. If there are no dependencies, we have
12044 |mp_link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
12045 otherwise |mp_link(dep_head)| points to the first dependent variable, say~|p|,
12046 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
12047 points to its dependency list. If the final link of that dependency list
12048 occurs in location~|q|, then |mp_link(q)| points to the next dependent
12049 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
12051 @d dep_list(A) mp_link(value_loc((A)))
12052 /* half of the |value| field in a |dependent| variable */
12053 @d prev_dep(A) mp_info(value_loc((A)))
12054 /* the other half; makes a doubly linked list */
12055 @d dep_node_size 2 /* the number of words per dependency node */
12057 @<Initialize table entries...@>= mp->serial_no=0;
12058 mp_link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
12059 mp_info(dep_head)=null; dep_list(dep_head)=null;
12061 @ Actually the description above contains a little white lie. There's
12062 another kind of variable called |mp_proto_dependent|, which is
12063 just like a |dependent| one except that the $\alpha$ coefficients
12064 in its dependency list are |scaled| instead of being fractions.
12065 Proto-dependency lists are mixed with dependency lists in the
12066 nodes reachable from |dep_head|.
12068 @ Here is a procedure that prints a dependency list in symbolic form.
12069 The second parameter should be either |dependent| or |mp_proto_dependent|,
12070 to indicate the scaling of the coefficients.
12073 static void mp_print_dependency (MP mp,pointer p, quarterword t);
12076 void mp_print_dependency (MP mp,pointer p, quarterword t) {
12077 integer v; /* a coefficient */
12078 pointer pp,q; /* for list manipulation */
12081 v=abs(value(p)); q=mp_info(p);
12082 if ( q==null ) { /* the constant term */
12083 if ( (v!=0)||(p==pp) ) {
12084 if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, xord('+'));
12085 mp_print_scaled(mp, value(p));
12089 @<Print the coefficient, unless it's $\pm1.0$@>;
12090 if ( mp_type(q)!=mp_independent ) mp_confusion(mp, "dep");
12091 @:this can't happen dep}{\quad dep@>
12092 mp_print_variable_name(mp, q); v=value(q) % s_scale;
12093 while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
12098 @ @<Print the coefficient, unless it's $\pm1.0$@>=
12099 if ( value(p)<0 ) mp_print_char(mp, xord('-'));
12100 else if ( p!=pp ) mp_print_char(mp, xord('+'));
12101 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
12102 if ( v!=unity ) mp_print_scaled(mp, v)
12104 @ The maximum absolute value of a coefficient in a given dependency list
12105 is returned by the following simple function.
12108 static fraction mp_max_coef (MP mp,pointer p) {
12109 fraction x; /* the maximum so far */
12111 while ( mp_info(p)!=null ) {
12112 if ( abs(value(p))>x ) x=abs(value(p));
12118 @ One of the main operations needed on dependency lists is to add a multiple
12119 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
12120 to dependency lists and |f| is a fraction.
12122 If the coefficient of any independent variable becomes |coef_bound| or
12123 more, in absolute value, this procedure changes the type of that variable
12124 to `|independent_needing_fix|', and sets the global variable |fix_needed|
12125 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
12126 $\mu^2+\mu<8$; this means that the numbers we deal with won't
12127 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
12128 2.3723$, the safer value 7/3 is taken as the threshold.)
12130 The changes mentioned in the preceding paragraph are actually done only if
12131 the global variable |watch_coefs| is |true|. But it usually is; in fact,
12132 it is |false| only when \MP\ is making a dependency list that will soon
12133 be equated to zero.
12135 Several procedures that act on dependency lists, including |p_plus_fq|,
12136 set the global variable |dep_final| to the final (constant term) node of
12137 the dependency list that they produce.
12139 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
12140 @d independent_needing_fix 0
12143 boolean fix_needed; /* does at least one |independent| variable need scaling? */
12144 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
12145 pointer dep_final; /* location of the constant term and final link */
12148 mp->fix_needed=false; mp->watch_coefs=true;
12150 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
12151 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
12152 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
12153 should be |mp_proto_dependent| if |q| is a proto-dependency list.
12155 List |q| is unchanged by the operation; but list |p| is totally destroyed.
12157 The final link of the dependency list or proto-dependency list returned
12158 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
12159 constant term of the result will be located in the same |mem| location
12160 as the original constant term of~|p|.
12162 Coefficients of the result are assumed to be zero if they are less than
12163 a certain threshold. This compensates for inevitable rounding errors,
12164 and tends to make more variables `|known|'. The threshold is approximately
12165 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12166 proto-dependencies.
12168 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12169 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12170 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12171 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12174 static pointer mp_p_plus_fq ( MP mp, pointer p, integer f,
12175 pointer q, quarterword t, quarterword tt) ;
12178 pointer mp_p_plus_fq ( MP mp, pointer p, integer f,
12179 pointer q, quarterword t, quarterword tt) {
12180 pointer pp,qq; /* |mp_info(p)| and |mp_info(q)|, respectively */
12181 pointer r,s; /* for list manipulation */
12182 integer threshold; /* defines a neighborhood of zero */
12183 integer v; /* temporary register */
12184 if ( t==mp_dependent ) threshold=fraction_threshold;
12185 else threshold=scaled_threshold;
12186 r=temp_head; pp=mp_info(p); qq=mp_info(q);
12192 @<Contribute a term from |p|, plus |f| times the
12193 corresponding term from |q|@>
12195 } else if ( value(pp)<value(qq) ) {
12196 @<Contribute a term from |q|, multiplied by~|f|@>
12198 mp_link(r)=p; r=p; p=mp_link(p); pp=mp_info(p);
12201 if ( t==mp_dependent )
12202 value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12204 value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12205 mp_link(r)=p; mp->dep_final=p;
12206 return mp_link(temp_head);
12209 @ @<Contribute a term from |p|, plus |f|...@>=
12211 if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12212 else v=value(p)+mp_take_scaled(mp, f,value(q));
12213 value(p)=v; s=p; p=mp_link(p);
12214 if ( abs(v)<threshold ) {
12215 mp_free_node(mp, s,dep_node_size);
12217 if ( (abs(v)>=coef_bound) && mp->watch_coefs ) {
12218 mp_type(qq)=independent_needing_fix; mp->fix_needed=true;
12222 pp=mp_info(p); q=mp_link(q); qq=mp_info(q);
12225 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12227 if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12228 else v=mp_take_scaled(mp, f,value(q));
12229 if ( abs(v)>halfp(threshold) ) {
12230 s=mp_get_node(mp, dep_node_size); mp_info(s)=qq; value(s)=v;
12231 if ( (abs(v)>=coef_bound) && mp->watch_coefs ) {
12232 mp_type(qq)=independent_needing_fix; mp->fix_needed=true;
12236 q=mp_link(q); qq=mp_info(q);
12239 @ It is convenient to have another subroutine for the special case
12240 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12241 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12244 static pointer mp_p_plus_q (MP mp,pointer p, pointer q, quarterword t) {
12245 pointer pp,qq; /* |mp_info(p)| and |mp_info(q)|, respectively */
12246 pointer r,s; /* for list manipulation */
12247 integer threshold; /* defines a neighborhood of zero */
12248 integer v; /* temporary register */
12249 if ( t==mp_dependent ) threshold=fraction_threshold;
12250 else threshold=scaled_threshold;
12251 r=temp_head; pp=mp_info(p); qq=mp_info(q);
12257 @<Contribute a term from |p|, plus the
12258 corresponding term from |q|@>
12261 if ( value(pp)<value(qq) ) {
12262 s=mp_get_node(mp, dep_node_size); mp_info(s)=qq; value(s)=value(q);
12263 q=mp_link(q); qq=mp_info(q); mp_link(r)=s; r=s;
12265 mp_link(r)=p; r=p; p=mp_link(p); pp=mp_info(p);
12269 value(p)=mp_slow_add(mp, value(p),value(q));
12270 mp_link(r)=p; mp->dep_final=p;
12271 return mp_link(temp_head);
12274 @ @<Contribute a term from |p|, plus the...@>=
12276 v=value(p)+value(q);
12277 value(p)=v; s=p; p=mp_link(p); pp=mp_info(p);
12278 if ( abs(v)<threshold ) {
12279 mp_free_node(mp, s,dep_node_size);
12281 if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12282 mp_type(qq)=independent_needing_fix; mp->fix_needed=true;
12286 q=mp_link(q); qq=mp_info(q);
12289 @ A somewhat simpler routine will multiply a dependency list
12290 by a given constant~|v|. The constant is either a |fraction| less than
12291 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12292 convert a dependency list to a proto-dependency list.
12293 Parameters |t0| and |t1| are the list types before and after;
12294 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12295 and |v_is_scaled=true|.
12298 static pointer mp_p_times_v (MP mp,pointer p, integer v, quarterword t0,
12299 quarterword t1, boolean v_is_scaled) {
12300 pointer r,s; /* for list manipulation */
12301 integer w; /* tentative coefficient */
12303 boolean scaling_down;
12304 if ( t0!=t1 ) scaling_down=true; else scaling_down=(!v_is_scaled);
12305 if ( t1==mp_dependent ) threshold=half_fraction_threshold;
12306 else threshold=half_scaled_threshold;
12308 while ( mp_info(p)!=null ) {
12309 if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12310 else w=mp_take_scaled(mp, v,value(p));
12311 if ( abs(w)<=threshold ) {
12312 s=mp_link(p); mp_free_node(mp, p,dep_node_size); p=s;
12314 if ( abs(w)>=coef_bound ) {
12315 mp->fix_needed=true; mp_type(mp_info(p))=independent_needing_fix;
12317 mp_link(r)=p; r=p; value(p)=w; p=mp_link(p);
12321 if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12322 else value(p)=mp_take_fraction(mp, value(p),v);
12323 return mp_link(temp_head);
12326 @ Similarly, we sometimes need to divide a dependency list
12327 by a given |scaled| constant.
12330 static pointer mp_p_over_v (MP mp,pointer p, scaled v, quarterword
12331 t0, quarterword t1) ;
12334 pointer mp_p_over_v (MP mp,pointer p, scaled v, quarterword
12335 t0, quarterword t1) {
12336 pointer r,s; /* for list manipulation */
12337 integer w; /* tentative coefficient */
12339 boolean scaling_down;
12340 if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12341 if ( t1==mp_dependent ) threshold=half_fraction_threshold;
12342 else threshold=half_scaled_threshold;
12344 while ( mp_info( p)!=null ) {
12345 if ( scaling_down ) {
12346 if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12347 else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12349 w=mp_make_scaled(mp, value(p),v);
12351 if ( abs(w)<=threshold ) {
12352 s=mp_link(p); mp_free_node(mp, p,dep_node_size); p=s;
12354 if ( abs(w)>=coef_bound ) {
12355 mp->fix_needed=true; mp_type(mp_info(p))=independent_needing_fix;
12357 mp_link(r)=p; r=p; value(p)=w; p=mp_link(p);
12360 mp_link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12361 return mp_link(temp_head);
12364 @ Here's another utility routine for dependency lists. When an independent
12365 variable becomes dependent, we want to remove it from all existing
12366 dependencies. The |p_with_x_becoming_q| function computes the
12367 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12369 This procedure has basically the same calling conventions as |p_plus_fq|:
12370 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12371 final link are inherited from~|p|; and the fourth parameter tells whether
12372 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12373 is not altered if |x| does not occur in list~|p|.
12376 static pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12377 pointer x, pointer q, quarterword t) {
12378 pointer r,s; /* for list manipulation */
12379 integer v; /* coefficient of |x| */
12380 integer sx; /* serial number of |x| */
12381 s=p; r=temp_head; sx=value(x);
12382 while ( value(mp_info(s))>sx ) { r=s; s=mp_link(s); };
12383 if ( mp_info(s)!=x ) {
12386 mp_link(temp_head)=p; mp_link(r)=mp_link(s); v=value(s);
12387 mp_free_node(mp, s,dep_node_size);
12388 return mp_p_plus_fq(mp, mp_link(temp_head),v,q,t,mp_dependent);
12392 @ Here's a simple procedure that reports an error when a variable
12393 has just received a known value that's out of the required range.
12396 static void mp_val_too_big (MP mp,scaled x) ;
12398 @ @c void mp_val_too_big (MP mp,scaled x) {
12399 if ( mp->internal[mp_warning_check]>0 ) {
12400 print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, xord(')'));
12401 @.Value is too large@>
12402 help4("The equation I just processed has given some variable",
12403 "a value of 4096 or more. Continue and I'll try to cope",
12404 "with that big value; but it might be dangerous.",
12405 "(Set warningcheck:=0 to suppress this message.)");
12410 @ When a dependent variable becomes known, the following routine
12411 removes its dependency list. Here |p| points to the variable, and
12412 |q| points to the dependency list (which is one node long).
12415 static void mp_make_known (MP mp,pointer p, pointer q) ;
12417 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12418 int t; /* the previous type */
12419 prev_dep(mp_link(q))=prev_dep(p);
12420 mp_link(prev_dep(p))=mp_link(q); t=mp_type(p);
12421 mp_type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12422 if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12423 if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12424 mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12425 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12426 mp_print_variable_name(mp, p);
12427 mp_print_char(mp, xord('=')); mp_print_scaled(mp, value(p));
12428 mp_end_diagnostic(mp, false);
12430 if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12431 mp->cur_type=mp_known; mp->cur_exp=value(p);
12432 mp_free_node(mp, p,value_node_size);
12436 @ The |fix_dependencies| routine is called into action when |fix_needed|
12437 has been triggered. The program keeps a list~|s| of independent variables
12438 whose coefficients must be divided by~4.
12440 In unusual cases, this fixup process might reduce one or more coefficients
12441 to zero, so that a variable will become known more or less by default.
12444 static void mp_fix_dependencies (MP mp);
12447 static void mp_fix_dependencies (MP mp) {
12448 pointer p,q,r,s,t; /* list manipulation registers */
12449 pointer x; /* an independent variable */
12450 r=mp_link(dep_head); s=null;
12451 while ( r!=dep_head ){
12453 @<Run through the dependency list for variable |t|, fixing
12454 all nodes, and ending with final link~|q|@>;
12456 if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12458 while ( s!=null ) {
12459 p=mp_link(s); x=mp_info(s); free_avail(s); s=p;
12460 mp_type(x)=mp_independent; value(x)=value(x)+2;
12462 mp->fix_needed=false;
12465 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12467 @<Run through the dependency list for variable |t|...@>=
12468 r=value_loc(t); /* |mp_link(r)=dep_list(t)| */
12470 q=mp_link(r); x=mp_info(q);
12471 if ( x==null ) break;
12472 if ( mp_type(x)<=independent_being_fixed ) {
12473 if ( mp_type(x)<independent_being_fixed ) {
12474 p=mp_get_avail(mp); mp_link(p)=s; s=p;
12475 mp_info(s)=x; mp_type(x)=independent_being_fixed;
12477 value(q)=value(q) / 4;
12478 if ( value(q)==0 ) {
12479 mp_link(r)=mp_link(q); mp_free_node(mp, q,dep_node_size); q=r;
12486 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12487 linking it into the list of all known dependencies. We assume that
12488 |dep_final| points to the final node of list~|p|.
12491 static void mp_new_dep (MP mp,pointer q, pointer p) {
12492 pointer r; /* what used to be the first dependency */
12493 dep_list(q)=p; prev_dep(q)=dep_head;
12494 r=mp_link(dep_head); mp_link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12495 mp_link(dep_head)=q;
12498 @ Here is one of the ways a dependency list gets started.
12499 The |const_dependency| routine produces a list that has nothing but
12502 @c static pointer mp_const_dependency (MP mp, scaled v) {
12503 mp->dep_final=mp_get_node(mp, dep_node_size);
12504 value(mp->dep_final)=v; mp_info(mp->dep_final)=null;
12505 return mp->dep_final;
12508 @ And here's a more interesting way to start a dependency list from scratch:
12509 The parameter to |single_dependency| is the location of an
12510 independent variable~|x|, and the result is the simple dependency list
12513 In the unlikely event that the given independent variable has been doubled so
12514 often that we can't refer to it with a nonzero coefficient,
12515 |single_dependency| returns the simple list `0'. This case can be
12516 recognized by testing that the returned list pointer is equal to
12520 static pointer mp_single_dependency (MP mp,pointer p) {
12521 pointer q; /* the new dependency list */
12522 integer m; /* the number of doublings */
12523 m=value(p) % s_scale;
12525 return mp_const_dependency(mp, 0);
12527 q=mp_get_node(mp, dep_node_size);
12528 value(q)=(integer)two_to_the(28-m); mp_info(q)=p;
12529 mp_link(q)=mp_const_dependency(mp, 0);
12534 @ We sometimes need to make an exact copy of a dependency list.
12537 static pointer mp_copy_dep_list (MP mp,pointer p) {
12538 pointer q; /* the new dependency list */
12539 q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12541 mp_info(mp->dep_final)=mp_info(p); value(mp->dep_final)=value(p);
12542 if ( mp_info(mp->dep_final)==null ) break;
12543 mp_link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12544 mp->dep_final=mp_link(mp->dep_final); p=mp_link(p);
12549 @ But how do variables normally become known? Ah, now we get to the heart of the
12550 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12551 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12552 appears. It equates this list to zero, by choosing an independent variable
12553 with the largest coefficient and making it dependent on the others. The
12554 newly dependent variable is eliminated from all current dependencies,
12555 thereby possibly making other dependent variables known.
12557 The given list |p| is, of course, totally destroyed by all this processing.
12560 static void mp_linear_eq (MP mp, pointer p, quarterword t) {
12561 pointer q,r,s; /* for link manipulation */
12562 pointer x; /* the variable that loses its independence */
12563 integer n; /* the number of times |x| had been halved */
12564 integer v; /* the coefficient of |x| in list |p| */
12565 pointer prev_r; /* lags one step behind |r| */
12566 pointer final_node; /* the constant term of the new dependency list */
12567 integer w; /* a tentative coefficient */
12568 @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12569 x=mp_info(q); n=value(x) % s_scale;
12570 @<Divide list |p| by |-v|, removing node |q|@>;
12571 if ( mp->internal[mp_tracing_equations]>0 ) {
12572 @<Display the new dependency@>;
12574 @<Simplify all existing dependencies by substituting for |x|@>;
12575 @<Change variable |x| from |independent| to |dependent| or |known|@>;
12576 if ( mp->fix_needed ) mp_fix_dependencies(mp);
12579 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12580 q=p; r=mp_link(p); v=value(q);
12581 while ( mp_info(r)!=null ) {
12582 if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12586 @ Here we want to change the coefficients from |scaled| to |fraction|,
12587 except in the constant term. In the common case of a trivial equation
12588 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12590 @<Divide list |p| by |-v|, removing node |q|@>=
12591 s=temp_head; mp_link(s)=p; r=p;
12594 mp_link(s)=mp_link(r); mp_free_node(mp, r,dep_node_size);
12596 w=mp_make_fraction(mp, value(r),v);
12597 if ( abs(w)<=half_fraction_threshold ) {
12598 mp_link(s)=mp_link(r); mp_free_node(mp, r,dep_node_size);
12604 } while (mp_info(r)!=null);
12605 if ( t==mp_proto_dependent ) {
12606 value(r)=-mp_make_scaled(mp, value(r),v);
12607 } else if ( v!=-fraction_one ) {
12608 value(r)=-mp_make_fraction(mp, value(r),v);
12610 final_node=r; p=mp_link(temp_head)
12612 @ @<Display the new dependency@>=
12613 if ( mp_interesting(mp, x) ) {
12614 mp_begin_diagnostic(mp); mp_print_nl(mp, "## ");
12615 mp_print_variable_name(mp, x);
12616 @:]]]\#\#_}{\.{\#\#}@>
12618 while ( w>0 ) { mp_print(mp, "*4"); w=w-2; };
12619 mp_print_char(mp, xord('=')); mp_print_dependency(mp, p,mp_dependent);
12620 mp_end_diagnostic(mp, false);
12623 @ @<Simplify all existing dependencies by substituting for |x|@>=
12624 prev_r=dep_head; r=mp_link(dep_head);
12625 while ( r!=dep_head ) {
12626 s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,mp_type(r));
12627 if ( mp_info(q)==null ) {
12628 mp_make_known(mp, r,q);
12631 do { q=mp_link(q); } while (mp_info(q)!=null);
12637 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12638 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12639 if ( mp_info(p)==null ) {
12640 mp_type(x)=mp_known;
12642 if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12643 mp_free_node(mp, p,dep_node_size);
12644 if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12645 mp->cur_exp=value(x); mp->cur_type=mp_known;
12646 mp_free_node(mp, x,value_node_size);
12649 mp_type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12650 if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12653 @ @<Divide list |p| by $2^n$@>=
12655 s=temp_head; mp_link(temp_head)=p; r=p;
12658 else w=value(r) / two_to_the(n);
12659 if ( (abs(w)<=half_fraction_threshold)&&(mp_info(r)!=null) ) {
12660 mp_link(s)=mp_link(r);
12661 mp_free_node(mp, r,dep_node_size);
12666 } while (mp_info(s)!=null);
12667 p=mp_link(temp_head);
12670 @ The |check_mem| procedure, which is used only when \MP\ is being
12671 debugged, makes sure that the current dependency lists are well formed.
12673 @<Check the list of linear dependencies@>=
12674 q=dep_head; p=mp_link(q);
12675 while ( p!=dep_head ) {
12676 if ( prev_dep(p)!=q ) {
12677 mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12682 r=mp_info(p); q=p; p=mp_link(q);
12683 if ( r==null ) break;
12684 if ( value(mp_info(p))>=value(r) ) {
12685 mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12686 @.Out of order...@>
12691 @* \[25] Dynamic nonlinear equations.
12692 Variables of numeric type are maintained by the general scheme of
12693 independent, dependent, and known values that we have just studied;
12694 and the components of pair and transform variables are handled in the
12695 same way. But \MP\ also has five other types of values: \&{boolean},
12696 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12698 Equations are allowed between nonlinear quantities, but only in a
12699 simple form. Two variables that haven't yet been assigned values are
12700 either equal to each other, or they're not.
12702 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12703 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12704 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12705 |null| (which means that no other variables are equivalent to this one), or
12706 it points to another variable of the same undefined type. The pointers in the
12707 latter case form a cycle of nodes, which we shall call a ``ring.''
12708 Rings of undefined variables may include capsules, which arise as
12709 intermediate results within expressions or as \&{expr} parameters to macros.
12711 When one member of a ring receives a value, the same value is given to
12712 all the other members. In the case of paths and pictures, this implies
12713 making separate copies of a potentially large data structure; users should
12714 restrain their enthusiasm for such generality, unless they have lots and
12715 lots of memory space.
12717 @ The following procedure is called when a capsule node is being
12718 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12721 static pointer mp_new_ring_entry (MP mp,pointer p) {
12722 pointer q; /* the new capsule node */
12723 q=mp_get_node(mp, value_node_size); mp_name_type(q)=mp_capsule;
12724 mp_type(q)=mp_type(p);
12725 if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12730 @ Conversely, we might delete a capsule or a variable before it becomes known.
12731 The following procedure simply detaches a quantity from its ring,
12732 without recycling the storage.
12735 static void mp_ring_delete (MP mp,pointer p);
12738 void mp_ring_delete (MP mp,pointer p) {
12741 if ( q!=null ) if ( q!=p ){
12742 while ( value(q)!=p ) q=value(q);
12747 @ Eventually there might be an equation that assigns values to all of the
12748 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12749 propagation of values.
12751 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12752 value, it will soon be recycled.
12755 static void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12756 quarterword t; /* the type of ring |p| */
12757 pointer q,r; /* link manipulation registers */
12758 t=mp_type(p)-unknown_tag; q=value(p);
12759 if ( flush_p ) mp_type(p)=mp_vacuous; else p=q;
12761 r=value(q); mp_type(q)=t;
12763 case mp_boolean_type: value(q)=v; break;
12764 case mp_string_type: value(q)=v; add_str_ref(v); break;
12765 case mp_pen_type: value(q)=copy_pen(v); break;
12766 case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12767 case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12768 } /* there ain't no more cases */
12773 @ If two members of rings are equated, and if they have the same type,
12774 the |ring_merge| procedure is called on to make them equivalent.
12777 static void mp_ring_merge (MP mp,pointer p, pointer q) {
12778 pointer r; /* traverses one list */
12782 @<Exclaim about a redundant equation@>;
12787 r=value(p); value(p)=value(q); value(q)=r;
12790 @ @<Exclaim about a redundant equation@>=
12792 print_err("Redundant equation");
12793 @.Redundant equation@>
12794 help2("I already knew that this equation was true.",
12795 "But perhaps no harm has been done; let's continue.");
12796 mp_put_get_error(mp);
12799 @* \[26] Introduction to the syntactic routines.
12800 Let's pause a moment now and try to look at the Big Picture.
12801 The \MP\ program consists of three main parts: syntactic routines,
12802 semantic routines, and output routines. The chief purpose of the
12803 syntactic routines is to deliver the user's input to the semantic routines,
12804 while parsing expressions and locating operators and operands. The
12805 semantic routines act as an interpreter responding to these operators,
12806 which may be regarded as commands. And the output routines are
12807 periodically called on to produce compact font descriptions that can be
12808 used for typesetting or for making interim proof drawings. We have
12809 discussed the basic data structures and many of the details of semantic
12810 operations, so we are good and ready to plunge into the part of \MP\ that
12811 actually controls the activities.
12813 Our current goal is to come to grips with the |get_next| procedure,
12814 which is the keystone of \MP's input mechanism. Each call of |get_next|
12815 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12816 representing the next input token.
12817 $$\vbox{\halign{#\hfil\cr
12818 \hbox{|cur_cmd| denotes a command code from the long list of codes
12820 \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12821 \hbox{|cur_sym| is the hash address of the symbolic token that was
12823 \hbox{\qquad or zero in the case of a numeric or string
12824 or capsule token.}\cr}}$$
12825 Underlying this external behavior of |get_next| is all the machinery
12826 necessary to convert from character files to tokens. At a given time we
12827 may be only partially finished with the reading of several files (for
12828 which \&{input} was specified), and partially finished with the expansion
12829 of some user-defined macros and/or some macro parameters, and partially
12830 finished reading some text that the user has inserted online,
12831 and so on. When reading a character file, the characters must be
12832 converted to tokens; comments and blank spaces must
12833 be removed, numeric and string tokens must be evaluated.
12835 To handle these situations, which might all be present simultaneously,
12836 \MP\ uses various stacks that hold information about the incomplete
12837 activities, and there is a finite state control for each level of the
12838 input mechanism. These stacks record the current state of an implicitly
12839 recursive process, but the |get_next| procedure is not recursive.
12842 integer cur_cmd; /* current command set by |get_next| */
12843 integer cur_mod; /* operand of current command */
12844 halfword cur_sym; /* hash address of current symbol */
12846 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12847 command code and its modifier.
12848 It consists of a rather tedious sequence of print
12849 commands, and most of it is essentially an inverse to the |primitive|
12850 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12851 all of this procedure appears elsewhere in the program, together with the
12852 corresponding |primitive| calls.
12855 static void mp_print_cmd_mod (MP mp,integer c, integer m) ;
12858 void mp_print_cmd_mod (MP mp,integer c, integer m) {
12860 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12861 default: mp_print(mp, "[unknown command code!]"); break;
12865 @ Here is a procedure that displays a given command in braces, in the
12866 user's transcript file.
12868 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12871 static void mp_show_cmd_mod (MP mp,integer c, integer m) {
12872 mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12873 mp_print_cmd_mod(mp, c,m); mp_print_char(mp, xord('}'));
12874 mp_end_diagnostic(mp, false);
12877 @* \[27] Input stacks and states.
12878 The state of \MP's input mechanism appears in the input stack, whose
12879 entries are records with five fields, called |index|, |start|, |loc|,
12880 |limit|, and |name|. The top element of this stack is maintained in a
12881 global variable for which no subscripting needs to be done; the other
12882 elements of the stack appear in an array. Hence the stack is declared thus:
12886 quarterword index_field;
12887 halfword start_field, loc_field, limit_field, name_field;
12891 in_state_record *input_stack;
12892 integer input_ptr; /* first unused location of |input_stack| */
12893 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12894 in_state_record cur_input; /* the ``top'' input state */
12895 int stack_size; /* maximum number of simultaneous input sources */
12897 @ @<Allocate or initialize ...@>=
12898 mp->stack_size = 300;
12899 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12901 @ @<Dealloc variables@>=
12902 xfree(mp->input_stack);
12904 @ We've already defined the special variable |loc==cur_input.loc_field|
12905 in our discussion of basic input-output routines. The other components of
12906 |cur_input| are defined in the same way:
12908 @d iindex mp->cur_input.index_field /* reference for buffer information */
12909 @d start mp->cur_input.start_field /* starting position in |buffer| */
12910 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12911 @d name mp->cur_input.name_field /* name of the current file */
12913 @ Let's look more closely now at the five control variables
12914 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12915 assuming that \MP\ is reading a line of characters that have been input
12916 from some file or from the user's terminal. There is an array called
12917 |buffer| that acts as a stack of all lines of characters that are
12918 currently being read from files, including all lines on subsidiary
12919 levels of the input stack that are not yet completed. \MP\ will return to
12920 the other lines when it is finished with the present input file.
12922 (Incidentally, on a machine with byte-oriented addressing, it would be
12923 appropriate to combine |buffer| with the |str_pool| array,
12924 letting the buffer entries grow downward from the top of the string pool
12925 and checking that these two tables don't bump into each other.)
12927 The line we are currently working on begins in position |start| of the
12928 buffer; the next character we are about to read is |buffer[loc]|; and
12929 |limit| is the location of the last character present. We always have
12930 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12931 that the end of a line is easily sensed.
12933 The |name| variable is a string number that designates the name of
12934 the current file, if we are reading an ordinary text file. Special codes
12935 |is_term..max_spec_src| indicate other sources of input text.
12937 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12938 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12939 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12940 @d max_spec_src is_scantok
12942 @ Additional information about the current line is available via the
12943 |index| variable, which counts how many lines of characters are present
12944 in the buffer below the current level. We have |index=0| when reading
12945 from the terminal and prompting the user for each line; then if the user types,
12946 e.g., `\.{input figs}', we will have |index=1| while reading
12947 the file \.{figs.mp}. However, it does not follow that |index| is the
12948 same as the input stack pointer, since many of the levels on the input
12949 stack may come from token lists and some |index| values may correspond
12950 to \.{MPX} files that are not currently on the stack.
12952 The global variable |in_open| is equal to the highest |index| value counting
12953 \.{MPX} files but excluding token-list input levels. Thus, the number of
12954 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12955 when we are not reading a token list.
12957 If we are not currently reading from the terminal,
12958 we are reading from the file variable |input_file[index]|. We use
12959 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12960 and |cur_file| as an abbreviation for |input_file[index]|.
12962 When \MP\ is not reading from the terminal, the global variable |line| contains
12963 the line number in the current file, for use in error messages. More precisely,
12964 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12965 the line number for each file in the |input_file| array.
12967 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12968 array so that the name doesn't get lost when the file is temporarily removed
12969 from the input stack.
12970 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12971 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12972 Since this is not an \.{MPX} file, we have
12973 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12974 This |name| field is set to |finished| when |input_file[k]| is completely
12977 If more information about the input state is needed, it can be
12978 included in small arrays like those shown here. For example,
12979 the current page or segment number in the input file might be put
12980 into a variable |page|, that is really a macro for the current entry
12981 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12982 by analogy with |line_stack|.
12983 @^system dependencies@>
12985 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12986 @d cur_file mp->input_file[iindex] /* the current |void *| variable */
12987 @d line mp->line_stack[iindex] /* current line number in the current source file */
12988 @d in_name mp->iname_stack[iindex] /* a string used to construct \.{MPX} file names */
12989 @d in_area mp->iarea_stack[iindex] /* another string for naming \.{MPX} files */
12990 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12991 @d mpx_reading (mp->mpx_name[iindex]>absent)
12992 /* when reading a file, is it an \.{MPX} file? */
12994 /* |name_field| value when the corresponding \.{MPX} file is finished */
12997 integer in_open; /* the number of lines in the buffer, less one */
12998 unsigned int open_parens; /* the number of open text files */
12999 void * *input_file ;
13000 integer *line_stack ; /* the line number for each file */
13001 char * *iname_stack; /* used for naming \.{MPX} files */
13002 char * *iarea_stack; /* used for naming \.{MPX} files */
13003 halfword*mpx_name ;
13005 @ @<Allocate or ...@>=
13006 mp->input_file = xmalloc((mp->max_in_open+1),sizeof(void *));
13007 mp->line_stack = xmalloc((mp->max_in_open+1),sizeof(integer));
13008 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
13009 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
13010 mp->mpx_name = xmalloc((mp->max_in_open+1),sizeof(halfword));
13013 for (k=0;k<=mp->max_in_open;k++) {
13014 mp->iname_stack[k] =NULL;
13015 mp->iarea_stack[k] =NULL;
13019 @ @<Dealloc variables@>=
13022 for (l=0;l<=mp->max_in_open;l++) {
13023 xfree(mp->iname_stack[l]);
13024 xfree(mp->iarea_stack[l]);
13027 xfree(mp->input_file);
13028 xfree(mp->line_stack);
13029 xfree(mp->iname_stack);
13030 xfree(mp->iarea_stack);
13031 xfree(mp->mpx_name);
13034 @ However, all this discussion about input state really applies only to the
13035 case that we are inputting from a file. There is another important case,
13036 namely when we are currently getting input from a token list. In this case
13037 |iindex>max_in_open|, and the conventions about the other state variables
13040 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
13041 the node that will be read next. If |loc=null|, the token list has been
13044 \yskip\hang|start| points to the first node of the token list; this node
13045 may or may not contain a reference count, depending on the type of token
13048 \yskip\hang|token_type|, which takes the place of |iindex| in the
13049 discussion above, is a code number that explains what kind of token list
13052 \yskip\hang|name| points to the |eqtb| address of the control sequence
13053 being expanded, if the current token list is a macro not defined by
13054 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
13055 can be deduced by looking at their first two parameters.
13057 \yskip\hang|param_start|, which takes the place of |limit|, tells where
13058 the parameters of the current macro or loop text begin in the |param_stack|.
13060 \yskip\noindent The |token_type| can take several values, depending on
13061 where the current token list came from:
13064 \indent|forever_text|, if the token list being scanned is the body of
13065 a \&{forever} loop;
13067 \indent|loop_text|, if the token list being scanned is the body of
13068 a \&{for} or \&{forsuffixes} loop;
13070 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
13072 \indent|backed_up|, if the token list being scanned has been inserted as
13073 `to be read again'.
13075 \indent|inserted|, if the token list being scanned has been inserted as
13076 part of error recovery;
13078 \indent|macro|, if the expansion of a user-defined symbolic token is being
13082 The token list begins with a reference count if and only if |token_type=
13084 @^reference counts@>
13086 @d token_type iindex /* type of current token list */
13087 @d token_state (iindex>(int)mp->max_in_open) /* are we scanning a token list? */
13088 @d file_state (iindex<=(int)mp->max_in_open) /* are we scanning a file line? */
13089 @d param_start limit /* base of macro parameters in |param_stack| */
13090 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
13091 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
13092 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
13093 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
13094 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
13095 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
13097 @ The |param_stack| is an auxiliary array used to hold pointers to the token
13098 lists for parameters at the current level and subsidiary levels of input.
13099 This stack grows at a different rate from the others.
13102 pointer *param_stack; /* token list pointers for parameters */
13103 integer param_ptr; /* first unused entry in |param_stack| */
13104 integer max_param_stack; /* largest value of |param_ptr| */
13106 @ @<Allocate or initialize ...@>=
13107 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
13109 @ @<Dealloc variables@>=
13110 xfree(mp->param_stack);
13112 @ Notice that the |line| isn't valid when |token_state| is true because it
13113 depends on |iindex|. If we really need to know the line number for the
13114 topmost file in the iindex stack we use the following function. If a page
13115 number or other information is needed, this routine should be modified to
13116 compute it as well.
13117 @^system dependencies@>
13120 static integer mp_true_line (MP mp) ;
13123 integer mp_true_line (MP mp) {
13124 int k; /* an index into the input stack */
13125 if ( file_state && (name>max_spec_src) ) {
13130 ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
13131 (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
13134 return (k>0 ? mp->line_stack[(k-1)] : 0 );
13138 @ Thus, the ``current input state'' can be very complicated indeed; there
13139 can be many levels and each level can arise in a variety of ways. The
13140 |show_context| procedure, which is used by \MP's error-reporting routine to
13141 print out the current input state on all levels down to the most recent
13142 line of characters from an input file, illustrates most of these conventions.
13143 The global variable |file_ptr| contains the lowest level that was
13144 displayed by this procedure.
13147 integer file_ptr; /* shallowest level shown by |show_context| */
13149 @ The status at each level is indicated by printing two lines, where the first
13150 line indicates what was read so far and the second line shows what remains
13151 to be read. The context is cropped, if necessary, so that the first line
13152 contains at most |half_error_line| characters, and the second contains
13153 at most |error_line|. Non-current input levels whose |token_type| is
13154 `|backed_up|' are shown only if they have not been fully read.
13156 @c void mp_show_context (MP mp) { /* prints where the scanner is */
13157 unsigned old_setting; /* saved |selector| setting */
13158 @<Local variables for formatting calculations@>
13159 mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
13160 /* store current state */
13162 mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
13163 @<Display the current context@>;
13165 if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
13166 decr(mp->file_ptr);
13168 mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
13171 @ @<Display the current context@>=
13172 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
13173 (token_type!=backed_up) || (loc!=null) ) {
13174 /* we omit backed-up token lists that have already been read */
13175 mp->tally=0; /* get ready to count characters */
13176 old_setting=mp->selector;
13177 if ( file_state ) {
13178 @<Print location of current line@>;
13179 @<Pseudoprint the line@>;
13181 @<Print type of token list@>;
13182 @<Pseudoprint the token list@>;
13184 mp->selector=old_setting; /* stop pseudoprinting */
13185 @<Print two lines using the tricky pseudoprinted information@>;
13188 @ This routine should be changed, if necessary, to give the best possible
13189 indication of where the current line resides in the input file.
13190 For example, on some systems it is best to print both a page and line number.
13191 @^system dependencies@>
13193 @<Print location of current line@>=
13194 if ( name>max_spec_src ) {
13195 mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13196 } else if ( terminal_input ) {
13197 if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13198 else mp_print_nl(mp, "<insert>");
13199 } else if ( name==is_scantok ) {
13200 mp_print_nl(mp, "<scantokens>");
13202 mp_print_nl(mp, "<read>");
13204 mp_print_char(mp, xord(' '))
13206 @ Can't use case statement here because the |token_type| is not
13207 a constant expression.
13209 @<Print type of token list@>=
13211 if(token_type==forever_text) {
13212 mp_print_nl(mp, "<forever> ");
13213 } else if (token_type==loop_text) {
13214 @<Print the current loop value@>;
13215 } else if (token_type==parameter) {
13216 mp_print_nl(mp, "<argument> ");
13217 } else if (token_type==backed_up) {
13218 if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13219 else mp_print_nl(mp, "<to be read again> ");
13220 } else if (token_type==inserted) {
13221 mp_print_nl(mp, "<inserted text> ");
13222 } else if (token_type==macro) {
13224 if ( name!=null ) mp_print_text(name);
13225 else @<Print the name of a \&{vardef}'d macro@>;
13226 mp_print(mp, "->");
13228 mp_print_nl(mp, "?");/* this should never happen */
13233 @ The parameter that corresponds to a loop text is either a token list
13234 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13235 We'll discuss capsules later; for now, all we need to know is that
13236 the |link| field in a capsule parameter is |void| and that
13237 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13239 @<Print the current loop value@>=
13240 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13242 if ( mp_link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13243 else mp_show_token_list(mp, p,null,20,mp->tally);
13245 mp_print(mp, ")> ");
13248 @ The first two parameters of a macro defined by \&{vardef} will be token
13249 lists representing the macro's prefix and ``at point.'' By putting these
13250 together, we get the macro's full name.
13252 @<Print the name of a \&{vardef}'d macro@>=
13253 { p=mp->param_stack[param_start];
13255 mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13258 while ( mp_link(q)!=null ) q=mp_link(q);
13259 mp_link(q)=mp->param_stack[param_start+1];
13260 mp_show_token_list(mp, p,null,20,mp->tally);
13265 @ Now it is necessary to explain a little trick. We don't want to store a long
13266 string that corresponds to a token list, because that string might take up
13267 lots of memory; and we are printing during a time when an error message is
13268 being given, so we dare not do anything that might overflow one of \MP's
13269 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13270 that stores characters into a buffer of length |error_line|, where character
13271 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13272 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13273 |tally:=0| and |trick_count:=1000000|; then when we reach the
13274 point where transition from line 1 to line 2 should occur, we
13275 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13276 tally+1+error_line-half_error_line)|. At the end of the
13277 pseudoprinting, the values of |first_count|, |tally|, and
13278 |trick_count| give us all the information we need to print the two lines,
13279 and all of the necessary text is in |trick_buf|.
13281 Namely, let |l| be the length of the descriptive information that appears
13282 on the first line. The length of the context information gathered for that
13283 line is |k=first_count|, and the length of the context information
13284 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13285 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13286 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13287 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13288 and print `\.{...}' followed by
13289 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13290 where subscripts of |trick_buf| are circular modulo |error_line|. The
13291 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13292 unless |n+m>error_line|; in the latter case, further cropping is done.
13293 This is easier to program than to explain.
13295 @<Local variables for formatting...@>=
13296 int i; /* index into |buffer| */
13297 integer l; /* length of descriptive information on line 1 */
13298 integer m; /* context information gathered for line 2 */
13299 int n; /* length of line 1 */
13300 integer p; /* starting or ending place in |trick_buf| */
13301 integer q; /* temporary index */
13303 @ The following code tells the print routines to gather
13304 the desired information.
13306 @d begin_pseudoprint {
13307 l=mp->tally; mp->tally=0; mp->selector=pseudo;
13308 mp->trick_count=1000000;
13310 @d set_trick_count {
13311 mp->first_count=mp->tally;
13312 mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13313 if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13316 @ And the following code uses the information after it has been gathered.
13318 @<Print two lines using the tricky pseudoprinted information@>=
13319 if ( mp->trick_count==1000000 ) set_trick_count;
13320 /* |set_trick_count| must be performed */
13321 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13322 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13323 if ( l+mp->first_count<=mp->half_error_line ) {
13324 p=0; n=l+mp->first_count;
13326 mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13327 n=mp->half_error_line;
13329 for (q=p;q<=mp->first_count-1;q++) {
13330 mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13333 for (q=1;q<=n;q++) {
13334 mp_print_char(mp, xord(' ')); /* print |n| spaces to begin line~2 */
13336 if ( m+n<=mp->error_line ) p=mp->first_count+m;
13337 else p=mp->first_count+(mp->error_line-n-3);
13338 for (q=mp->first_count;q<=p-1;q++) {
13339 mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13341 if ( m+n>mp->error_line ) mp_print(mp, "...")
13343 @ But the trick is distracting us from our current goal, which is to
13344 understand the input state. So let's concentrate on the data structures that
13345 are being pseudoprinted as we finish up the |show_context| procedure.
13347 @<Pseudoprint the line@>=
13350 for (i=start;i<=limit-1;i++) {
13351 if ( i==loc ) set_trick_count;
13352 mp_print_str(mp, mp->buffer[i]);
13356 @ @<Pseudoprint the token list@>=
13358 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13359 else mp_show_macro(mp, start,loc,100000)
13361 @ Here is the missing piece of |show_token_list| that is activated when the
13362 token beginning line~2 is about to be shown:
13364 @<Do magic computation@>=set_trick_count
13366 @* \[28] Maintaining the input stacks.
13367 The following subroutines change the input status in commonly needed ways.
13369 First comes |push_input|, which stores the current state and creates a
13370 new level (having, initially, the same properties as the old).
13372 @d push_input { /* enter a new input level, save the old */
13373 if ( mp->input_ptr>mp->max_in_stack ) {
13374 mp->max_in_stack=mp->input_ptr;
13375 if ( mp->input_ptr==mp->stack_size ) {
13376 int l = (mp->stack_size+(mp->stack_size/4));
13377 XREALLOC(mp->input_stack, l, in_state_record);
13378 mp->stack_size = l;
13381 mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13382 incr(mp->input_ptr);
13385 @ And of course what goes up must come down.
13387 @d pop_input { /* leave an input level, re-enter the old */
13388 decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13391 @ Here is a procedure that starts a new level of token-list input, given
13392 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13393 set |name|, reset~|loc|, and increase the macro's reference count.
13395 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13398 static void mp_begin_token_list (MP mp,pointer p, quarterword t) {
13399 push_input; start=p; token_type=t;
13400 param_start=mp->param_ptr; loc=p;
13403 @ When a token list has been fully scanned, the following computations
13404 should be done as we leave that level of input.
13408 static void mp_end_token_list (MP mp) { /* leave a token-list input level */
13409 pointer p; /* temporary register */
13410 if ( token_type>=backed_up ) { /* token list to be deleted */
13411 if ( token_type<=inserted ) {
13412 mp_flush_token_list(mp, start); goto DONE;
13414 mp_delete_mac_ref(mp, start); /* update reference count */
13417 while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13418 decr(mp->param_ptr);
13419 p=mp->param_stack[mp->param_ptr];
13421 if ( mp_link(p)==mp_void ) { /* it's an \&{expr} parameter */
13422 mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13424 mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13429 pop_input; check_interrupt;
13432 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13433 token by the |cur_tok| routine.
13436 @c @<Declare the procedure called |make_exp_copy|@>
13437 static pointer mp_cur_tok (MP mp) {
13438 pointer p; /* a new token node */
13439 quarterword save_type; /* |cur_type| to be restored */
13440 integer save_exp; /* |cur_exp| to be restored */
13441 if ( mp->cur_sym==0 ) {
13442 if ( mp->cur_cmd==capsule_token ) {
13443 save_type=mp->cur_type; save_exp=mp->cur_exp;
13444 mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); mp_link(p)=null;
13445 mp->cur_type=save_type; mp->cur_exp=save_exp;
13447 p=mp_get_node(mp, token_node_size);
13448 value(p)=mp->cur_mod; mp_name_type(p)=mp_token;
13449 if ( mp->cur_cmd==numeric_token ) mp_type(p)=mp_known;
13450 else mp_type(p)=mp_string_type;
13453 fast_get_avail(p); mp_info(p)=mp->cur_sym;
13458 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13459 seen. The |back_input| procedure takes care of this by putting the token
13460 just scanned back into the input stream, ready to be read again.
13461 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13464 static void mp_back_input (MP mp);
13466 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13467 pointer p; /* a token list of length one */
13469 while ( token_state &&(loc==null) )
13470 mp_end_token_list(mp); /* conserve stack space */
13474 @ The |back_error| routine is used when we want to restore or replace an
13475 offending token just before issuing an error message. We disable interrupts
13476 during the call of |back_input| so that the help message won't be lost.
13478 @ @c static void mp_back_error (MP mp) { /* back up one token and call |error| */
13479 mp->OK_to_interrupt=false;
13481 mp->OK_to_interrupt=true; mp_error(mp);
13483 static void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13484 mp->OK_to_interrupt=false;
13485 mp_back_input(mp); token_type=inserted;
13486 mp->OK_to_interrupt=true; mp_error(mp);
13489 @ The |begin_file_reading| procedure starts a new level of input for lines
13490 of characters to be read from a file, or as an insertion from the
13491 terminal. It does not take care of opening the file, nor does it set |loc|
13492 or |limit| or |line|.
13493 @^system dependencies@>
13495 @c void mp_begin_file_reading (MP mp) {
13496 if ( mp->in_open==mp->max_in_open )
13497 mp_overflow(mp, "text input levels",mp->max_in_open);
13498 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13499 if ( mp->first==mp->buf_size )
13500 mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size/4)));
13501 incr(mp->in_open); push_input; iindex=mp->in_open;
13502 mp->mpx_name[iindex]=absent;
13503 start=(halfword)mp->first;
13504 name=is_term; /* |terminal_input| is now |true| */
13507 @ Conversely, the variables must be downdated when such a level of input
13508 is finished. Any associated \.{MPX} file must also be closed and popped
13509 off the file stack.
13511 @c static void mp_end_file_reading (MP mp) {
13512 if ( mp->in_open>iindex ) {
13513 if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13514 mp_confusion(mp, "endinput");
13515 @:this can't happen endinput}{\quad endinput@>
13517 (mp->close_file)(mp,mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13518 delete_str_ref(mp->mpx_name[mp->in_open]);
13522 mp->first=(size_t)start;
13523 if ( iindex!=mp->in_open ) mp_confusion(mp, "endinput");
13524 if ( name>max_spec_src ) {
13525 (mp->close_file)(mp,cur_file);
13526 delete_str_ref(name);
13530 pop_input; decr(mp->in_open);
13533 @ Here is a function that tries to resume input from an \.{MPX} file already
13534 associated with the current input file. It returns |false| if this doesn't
13537 @c static boolean mp_begin_mpx_reading (MP mp) {
13538 if ( mp->in_open!=iindex+1 ) {
13541 if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13542 @:this can't happen mpx}{\quad mpx@>
13543 if ( mp->first==mp->buf_size )
13544 mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size/4)));
13545 push_input; iindex=mp->in_open;
13546 start=(halfword)mp->first;
13547 name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13548 @<Put an empty line in the input buffer@>;
13553 @ This procedure temporarily stops reading an \.{MPX} file.
13555 @c static void mp_end_mpx_reading (MP mp) {
13556 if ( mp->in_open!=iindex ) mp_confusion(mp, "mpx");
13557 @:this can't happen mpx}{\quad mpx@>
13559 @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13561 mp->first=(size_t)start;
13565 @ Here we enforce a restriction that simplifies the input stacks considerably.
13566 This should not inconvenience the user because \.{MPX} files are generated
13567 by an auxiliary program called \.{DVItoMP}.
13569 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13571 print_err("`mpxbreak' must be at the end of a line");
13572 help4("This file contains picture expressions for btex...etex",
13573 "blocks. Such files are normally generated automatically",
13574 "but this one seems to be messed up. I'm going to ignore",
13575 "the rest of this line.");
13579 @ In order to keep the stack from overflowing during a long sequence of
13580 inserted `\.{show}' commands, the following routine removes completed
13581 error-inserted lines from memory.
13583 @c void mp_clear_for_error_prompt (MP mp) {
13584 while ( file_state && terminal_input &&
13585 (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13586 mp_print_ln(mp); clear_terminal;
13589 @ To get \MP's whole input mechanism going, we perform the following
13592 @<Initialize the input routines@>=
13593 { mp->input_ptr=0; mp->max_in_stack=0;
13594 mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13595 mp->param_ptr=0; mp->max_param_stack=0;
13597 start=1; iindex=0; line=0; name=is_term;
13598 mp->mpx_name[0]=absent;
13599 mp->force_eof=false;
13600 if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13601 limit=(halfword)mp->last; mp->first=mp->last+1;
13602 /* |init_terminal| has set |loc| and |last| */
13605 @* \[29] Getting the next token.
13606 The heart of \MP's input mechanism is the |get_next| procedure, which
13607 we shall develop in the next few sections of the program. Perhaps we
13608 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13609 eyes and mouth, reading the source files and gobbling them up. And it also
13610 helps \MP\ to regurgitate stored token lists that are to be processed again.
13612 The main duty of |get_next| is to input one token and to set |cur_cmd|
13613 and |cur_mod| to that token's command code and modifier. Furthermore, if
13614 the input token is a symbolic token, that token's |hash| address
13615 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13617 Underlying this simple description is a certain amount of complexity
13618 because of all the cases that need to be handled.
13619 However, the inner loop of |get_next| is reasonably short and fast.
13621 @ Before getting into |get_next|, we need to consider a mechanism by which
13622 \MP\ helps keep errors from propagating too far. Whenever the program goes
13623 into a mode where it keeps calling |get_next| repeatedly until a certain
13624 condition is met, it sets |scanner_status| to some value other than |normal|.
13625 Then if an input file ends, or if an `\&{outer}' symbol appears,
13626 an appropriate error recovery will be possible.
13628 The global variable |warning_info| helps in this error recovery by providing
13629 additional information. For example, |warning_info| might indicate the
13630 name of a macro whose replacement text is being scanned.
13632 @d normal 0 /* |scanner_status| at ``quiet times'' */
13633 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13634 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13635 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13636 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13637 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13638 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13639 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13642 integer scanner_status; /* are we scanning at high speed? */
13643 integer warning_info; /* if so, what else do we need to know,
13644 in case an error occurs? */
13646 @ @<Initialize the input routines@>=
13647 mp->scanner_status=normal;
13649 @ The following subroutine
13650 is called when an `\&{outer}' symbolic token has been scanned or
13651 when the end of a file has been reached. These two cases are distinguished
13652 by |cur_sym|, which is zero at the end of a file.
13655 static boolean mp_check_outer_validity (MP mp) {
13656 pointer p; /* points to inserted token list */
13657 if ( mp->scanner_status==normal ) {
13659 } else if ( mp->scanner_status==tex_flushing ) {
13660 @<Check if the file has ended while flushing \TeX\ material and set the
13661 result value for |check_outer_validity|@>;
13663 mp->deletions_allowed=false;
13664 @<Back up an outer symbolic token so that it can be reread@>;
13665 if ( mp->scanner_status>skipping ) {
13666 @<Tell the user what has run away and try to recover@>;
13668 print_err("Incomplete if; all text was ignored after line ");
13669 @.Incomplete if...@>
13670 mp_print_int(mp, mp->warning_info);
13671 help3("A forbidden `outer' token occurred in skipped text.",
13672 "This kind of error happens when you say `if...' and forget",
13673 "the matching `fi'. I've inserted a `fi'; this might work.");
13674 if ( mp->cur_sym==0 )
13675 mp->help_line[2]="The file ended while I was skipping conditional text.";
13676 mp->cur_sym=frozen_fi; mp_ins_error(mp);
13678 mp->deletions_allowed=true;
13683 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13684 if ( mp->cur_sym!=0 ) {
13687 mp->deletions_allowed=false;
13688 print_err("TeX mode didn't end; all text was ignored after line ");
13689 mp_print_int(mp, mp->warning_info);
13690 help2("The file ended while I was looking for the `etex' to",
13691 "finish this TeX material. I've inserted `etex' now.");
13692 mp->cur_sym = frozen_etex;
13694 mp->deletions_allowed=true;
13698 @ @<Back up an outer symbolic token so that it can be reread@>=
13699 if ( mp->cur_sym!=0 ) {
13700 p=mp_get_avail(mp); mp_info(p)=mp->cur_sym;
13701 back_list(p); /* prepare to read the symbolic token again */
13704 @ @<Tell the user what has run away...@>=
13706 mp_runaway(mp); /* print the definition-so-far */
13707 if ( mp->cur_sym==0 ) {
13708 print_err("File ended");
13709 @.File ended while scanning...@>
13711 print_err("Forbidden token found");
13712 @.Forbidden token found...@>
13714 mp_print(mp, " while scanning ");
13715 help4("I suspect you have forgotten an `enddef',",
13716 "causing me to read past where you wanted me to stop.",
13717 "I'll try to recover; but if the error is serious,",
13718 "you'd better type `E' or `X' now and fix your file.");
13719 switch (mp->scanner_status) {
13720 @<Complete the error message,
13721 and set |cur_sym| to a token that might help recover from the error@>
13722 } /* there are no other cases */
13726 @ As we consider various kinds of errors, it is also appropriate to
13727 change the first line of the help message just given; |help_line[3]|
13728 points to the string that might be changed.
13730 @<Complete the error message,...@>=
13732 mp_print(mp, "to the end of the statement");
13733 mp->help_line[3]="A previous error seems to have propagated,";
13734 mp->cur_sym=frozen_semicolon;
13737 mp_print(mp, "a text argument");
13738 mp->help_line[3]="It seems that a right delimiter was left out,";
13739 if ( mp->warning_info==0 ) {
13740 mp->cur_sym=frozen_end_group;
13742 mp->cur_sym=frozen_right_delimiter;
13743 equiv(frozen_right_delimiter)=mp->warning_info;
13748 mp_print(mp, "the definition of ");
13749 if ( mp->scanner_status==op_defining )
13750 mp_print_text(mp->warning_info);
13752 mp_print_variable_name(mp, mp->warning_info);
13753 mp->cur_sym=frozen_end_def;
13755 case loop_defining:
13756 mp_print(mp, "the text of a ");
13757 mp_print_text(mp->warning_info);
13758 mp_print(mp, " loop");
13759 mp->help_line[3]="I suspect you have forgotten an `endfor',";
13760 mp->cur_sym=frozen_end_for;
13763 @ The |runaway| procedure displays the first part of the text that occurred
13764 when \MP\ began its special |scanner_status|, if that text has been saved.
13767 static void mp_runaway (MP mp) ;
13770 void mp_runaway (MP mp) {
13771 if ( mp->scanner_status>flushing ) {
13772 mp_print_nl(mp, "Runaway ");
13773 switch (mp->scanner_status) {
13774 case absorbing: mp_print(mp, "text?"); break;
13776 case op_defining: mp_print(mp,"definition?"); break;
13777 case loop_defining: mp_print(mp, "loop?"); break;
13778 } /* there are no other cases */
13780 mp_show_token_list(mp, mp_link(hold_head),null,mp->error_line-10,0);
13784 @ We need to mention a procedure that may be called by |get_next|.
13787 static void mp_firm_up_the_line (MP mp);
13789 @ And now we're ready to take the plunge into |get_next| itself.
13790 Note that the behavior depends on the |scanner_status| because percent signs
13791 and double quotes need to be passed over when skipping TeX material.
13794 void mp_get_next (MP mp) {
13795 /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13797 /*restart*/ /* go here to get the next input token */
13798 /*exit*/ /* go here when the next input token has been got */
13799 /*|common_ending|*/ /* go here to finish getting a symbolic token */
13800 /*found*/ /* go here when the end of a symbolic token has been found */
13801 /*switch*/ /* go here to branch on the class of an input character */
13802 /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13803 /* go here at crucial stages when scanning a number */
13804 int k; /* an index into |buffer| */
13805 ASCII_code c; /* the current character in the buffer */
13806 int class; /* its class number */
13807 integer n,f; /* registers for decimal-to-binary conversion */
13810 if ( file_state ) {
13811 @<Input from external file; |goto restart| if no input found,
13812 or |return| if a non-symbolic token is found@>;
13814 @<Input from token list; |goto restart| if end of list or
13815 if a parameter needs to be expanded,
13816 or |return| if a non-symbolic token is found@>;
13819 @<Finish getting the symbolic token in |cur_sym|;
13820 |goto restart| if it is illegal@>;
13823 @ When a symbolic token is declared to be `\&{outer}', its command code
13824 is increased by |outer_tag|.
13827 @<Finish getting the symbolic token in |cur_sym|...@>=
13828 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13829 if ( mp->cur_cmd>=outer_tag ) {
13830 if ( mp_check_outer_validity(mp) )
13831 mp->cur_cmd=mp->cur_cmd-outer_tag;
13836 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13837 to have a special test for end-of-line.
13840 @<Input from external file;...@>=
13843 c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13845 case digit_class: goto START_NUMERIC_TOKEN; break;
13847 class=mp->char_class[mp->buffer[loc]];
13848 if ( class>period_class ) {
13850 } else if ( class<period_class ) { /* |class=digit_class| */
13851 n=0; goto START_DECIMAL_TOKEN;
13855 case space_class: goto SWITCH; break;
13856 case percent_class:
13857 if ( mp->scanner_status==tex_flushing ) {
13858 if ( loc<limit ) goto SWITCH;
13860 @<Move to next line of file, or |goto restart| if there is no next line@>;
13865 if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13866 else @<Get a string token and |return|@>;
13868 case isolated_classes:
13869 k=loc-1; goto FOUND; break;
13870 case invalid_class:
13871 if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13872 else @<Decry the invalid character and |goto restart|@>;
13874 default: break; /* letters, etc. */
13877 while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13879 START_NUMERIC_TOKEN:
13880 @<Get the integer part |n| of a numeric token;
13881 set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13882 START_DECIMAL_TOKEN:
13883 @<Get the fraction part |f| of a numeric token@>;
13885 @<Pack the numeric and fraction parts of a numeric token
13888 mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13891 @ We go to |restart| instead of to |SWITCH|, because we might enter
13892 |token_state| after the error has been dealt with
13893 (cf.\ |clear_for_error_prompt|).
13895 @<Decry the invalid...@>=
13897 print_err("Text line contains an invalid character");
13898 @.Text line contains...@>
13899 help2("A funny symbol that I can\'t read has just been input.",
13900 "Continue, and I'll forget that it ever happened.");
13901 mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13905 @ @<Get a string token and |return|@>=
13907 if ( mp->buffer[loc]=='"' ) {
13908 mp->cur_mod=null_str;
13910 k=loc; mp->buffer[limit+1]=xord('"');
13913 } while (mp->buffer[loc]!='"');
13915 @<Decry the missing string delimiter and |goto restart|@>;
13918 mp->cur_mod=mp->buffer[k];
13922 append_char(mp->buffer[k]); incr(k);
13924 mp->cur_mod=mp_make_string(mp);
13927 incr(loc); mp->cur_cmd=string_token;
13931 @ We go to |restart| after this error message, not to |SWITCH|,
13932 because the |clear_for_error_prompt| routine might have reinstated
13933 |token_state| after |error| has finished.
13935 @<Decry the missing string delimiter and |goto restart|@>=
13937 loc=limit; /* the next character to be read on this line will be |"%"| */
13938 print_err("Incomplete string token has been flushed");
13939 @.Incomplete string token...@>
13940 help3("Strings should finish on the same line as they began.",
13941 "I've deleted the partial string; you might want to",
13942 "insert another by typing, e.g., `I\"new string\"'.");
13943 mp->deletions_allowed=false; mp_error(mp);
13944 mp->deletions_allowed=true;
13948 @ @<Get the integer part |n| of a numeric token...@>=
13950 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13951 if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13954 if ( mp->buffer[loc]=='.' )
13955 if ( mp->char_class[mp->buffer[loc+1]]==digit_class )
13958 goto FIN_NUMERIC_TOKEN;
13961 @ @<Get the fraction part |f| of a numeric token@>=
13964 if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13965 mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13968 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13969 f=mp_round_decimals(mp, k);
13974 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13976 @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13977 } else if ( mp->scanner_status!=tex_flushing ) {
13978 print_err("Enormous number has been reduced");
13979 @.Enormous number...@>
13980 help2("I can\'t handle numbers bigger than 32767.99998;",
13981 "so I've changed your constant to that maximum amount.");
13982 mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13983 mp->cur_mod=el_gordo;
13985 mp->cur_cmd=numeric_token; return
13987 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13989 mp->cur_mod=n*unity+f;
13990 if ( mp->cur_mod>=fraction_one ) {
13991 if ( (mp->internal[mp_warning_check]>0) &&
13992 (mp->scanner_status!=tex_flushing) ) {
13993 print_err("Number is too large (");
13994 mp_print_scaled(mp, mp->cur_mod);
13995 mp_print_char(mp, xord(')'));
13996 help3("It is at least 4096. Continue and I'll try to cope",
13997 "with that big value; but it might be dangerous.",
13998 "(Set warningcheck:=0 to suppress this message.)");
14004 @ Let's consider now what happens when |get_next| is looking at a token list.
14007 @<Input from token list;...@>=
14008 if ( loc>=mp->hi_mem_min ) { /* one-word token */
14009 mp->cur_sym=mp_info(loc); loc=mp_link(loc); /* move to next */
14010 if ( mp->cur_sym>=expr_base ) {
14011 if ( mp->cur_sym>=suffix_base ) {
14012 @<Insert a suffix or text parameter and |goto restart|@>;
14014 mp->cur_cmd=capsule_token;
14015 mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
14016 mp->cur_sym=0; return;
14019 } else if ( loc>null ) {
14020 @<Get a stored numeric or string or capsule token and |return|@>
14021 } else { /* we are done with this token list */
14022 mp_end_token_list(mp); goto RESTART; /* resume previous level */
14025 @ @<Insert a suffix or text parameter...@>=
14027 if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
14028 /* |param_size=text_base-suffix_base| */
14029 mp_begin_token_list(mp,
14030 mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
14035 @ @<Get a stored numeric or string or capsule token...@>=
14037 if ( mp_name_type(loc)==mp_token ) {
14038 mp->cur_mod=value(loc);
14039 if ( mp_type(loc)==mp_known ) {
14040 mp->cur_cmd=numeric_token;
14042 mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
14045 mp->cur_mod=loc; mp->cur_cmd=capsule_token;
14047 loc=mp_link(loc); return;
14050 @ All of the easy branches of |get_next| have now been taken care of.
14051 There is one more branch.
14053 @<Move to next line of file, or |goto restart|...@>=
14054 if ( name>max_spec_src) {
14055 @<Read next line of file into |buffer|, or
14056 |goto restart| if the file has ended@>;
14058 if ( mp->input_ptr>0 ) {
14059 /* text was inserted during error recovery or by \&{scantokens} */
14060 mp_end_file_reading(mp); goto RESTART; /* resume previous level */
14062 if (mp->job_name == NULL && ( mp->selector<log_only || mp->selector>=write_file))
14063 mp_open_log_file(mp);
14064 if ( mp->interaction>mp_nonstop_mode ) {
14065 if ( limit==start ) /* previous line was empty */
14066 mp_print_nl(mp, "(Please type a command or say `end')");
14068 mp_print_ln(mp); mp->first=(size_t)start;
14069 prompt_input("*"); /* input on-line into |buffer| */
14071 limit=(halfword)mp->last; mp->buffer[limit]=xord('%');
14072 mp->first=(size_t)(limit+1); loc=start;
14074 mp_fatal_error(mp, "*** (job aborted, no legal end found)");
14076 /* nonstop mode, which is intended for overnight batch processing,
14077 never waits for on-line input */
14081 @ The global variable |force_eof| is normally |false|; it is set |true|
14082 by an \&{endinput} command.
14085 boolean force_eof; /* should the next \&{input} be aborted early? */
14087 @ We must decrement |loc| in order to leave the buffer in a valid state
14088 when an error condition causes us to |goto restart| without calling
14089 |end_file_reading|.
14091 @<Read next line of file into |buffer|, or
14092 |goto restart| if the file has ended@>=
14094 incr(line); mp->first=(size_t)start;
14095 if ( ! mp->force_eof ) {
14096 if ( mp_input_ln(mp, cur_file ) ) /* not end of file */
14097 mp_firm_up_the_line(mp); /* this sets |limit| */
14099 mp->force_eof=true;
14101 if ( mp->force_eof ) {
14102 mp->force_eof=false;
14104 if ( mpx_reading ) {
14105 @<Complain that the \.{MPX} file ended unexpectly; then set
14106 |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
14108 mp_print_char(mp, xord(')')); decr(mp->open_parens);
14109 update_terminal; /* show user that file has been read */
14110 mp_end_file_reading(mp); /* resume previous level */
14111 if ( mp_check_outer_validity(mp) ) goto RESTART;
14115 mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start; /* ready to read */
14118 @ We should never actually come to the end of an \.{MPX} file because such
14119 files should have an \&{mpxbreak} after the translation of the last
14120 \&{btex}$\,\ldots\,$\&{etex} block.
14122 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
14124 mp->mpx_name[iindex]=mpx_finished;
14125 print_err("mpx file ended unexpectedly");
14126 help4("The file had too few picture expressions for btex...etex",
14127 "blocks. Such files are normally generated automatically",
14128 "but this one got messed up. You might want to insert a",
14129 "picture expression now.");
14130 mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
14131 mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
14134 @ Sometimes we want to make it look as though we have just read a blank line
14135 without really doing so.
14137 @<Put an empty line in the input buffer@>=
14138 mp->last=mp->first; limit=(halfword)mp->last;
14139 /* simulate |input_ln| and |firm_up_the_line| */
14140 mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start
14142 @ If the user has set the |mp_pausing| parameter to some positive value,
14143 and if nonstop mode has not been selected, each line of input is displayed
14144 on the terminal and the transcript file, followed by `\.{=>}'.
14145 \MP\ waits for a response. If the response is null (i.e., if nothing is
14146 typed except perhaps a few blank spaces), the original
14147 line is accepted as it stands; otherwise the line typed is
14148 used instead of the line in the file.
14150 @c void mp_firm_up_the_line (MP mp) {
14151 size_t k; /* an index into |buffer| */
14152 limit=(halfword)mp->last;
14153 if ((!mp->noninteractive)
14154 && (mp->internal[mp_pausing]>0 )
14155 && (mp->interaction>mp_nonstop_mode )) {
14156 wake_up_terminal; mp_print_ln(mp);
14157 if ( start<limit ) {
14158 for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
14159 mp_print_str(mp, mp->buffer[k]);
14162 mp->first=(size_t)limit; prompt_input("=>"); /* wait for user response */
14164 if ( mp->last>mp->first ) {
14165 for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
14166 mp->buffer[k+start-mp->first]=mp->buffer[k];
14168 limit=(halfword)(start+mp->last-mp->first);
14173 @* \[30] Dealing with \TeX\ material.
14174 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
14175 features need to be implemented at a low level in the scanning process
14176 so that \MP\ can stay in synch with the a preprocessor that treats
14177 blocks of \TeX\ material as they occur in the input file without trying
14178 to expand \MP\ macros. Thus we need a special version of |get_next|
14179 that does not expand macros and such but does handle \&{btex},
14180 \&{verbatimtex}, etc.
14182 The special version of |get_next| is called |get_t_next|. It works by flushing
14183 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
14184 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
14185 \&{btex}, and switching back when it sees \&{mpxbreak}.
14191 mp_primitive(mp, "btex",start_tex,btex_code);
14192 @:btex_}{\&{btex} primitive@>
14193 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14194 @:verbatimtex_}{\&{verbatimtex} primitive@>
14195 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14196 @:etex_}{\&{etex} primitive@>
14197 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14198 @:mpx_break_}{\&{mpxbreak} primitive@>
14200 @ @<Cases of |print_cmd...@>=
14201 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14202 else mp_print(mp, "verbatimtex"); break;
14203 case etex_marker: mp_print(mp, "etex"); break;
14204 case mpx_break: mp_print(mp, "mpxbreak"); break;
14206 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14207 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14210 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14213 static void mp_start_mpx_input (MP mp);
14216 static void mp_t_next (MP mp) {
14217 int old_status; /* saves the |scanner_status| */
14218 integer old_info; /* saves the |warning_info| */
14219 while ( mp->cur_cmd<=max_pre_command ) {
14220 if ( mp->cur_cmd==mpx_break ) {
14221 if ( ! file_state || (mp->mpx_name[iindex]==absent) ) {
14222 @<Complain about a misplaced \&{mpxbreak}@>;
14224 mp_end_mpx_reading(mp);
14227 } else if ( mp->cur_cmd==start_tex ) {
14228 if ( token_state || (name<=max_spec_src) ) {
14229 @<Complain that we are not reading a file@>;
14230 } else if ( mpx_reading ) {
14231 @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14232 } else if ( (mp->cur_mod!=verbatim_code)&&
14233 (mp->mpx_name[iindex]!=mpx_finished) ) {
14234 if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14239 @<Complain about a misplaced \&{etex}@>;
14241 goto COMMON_ENDING;
14243 @<Flush the \TeX\ material@>;
14249 @ We could be in the middle of an operation such as skipping false conditional
14250 text when \TeX\ material is encountered, so we must be careful to save the
14253 @<Flush the \TeX\ material@>=
14254 old_status=mp->scanner_status;
14255 old_info=mp->warning_info;
14256 mp->scanner_status=tex_flushing;
14257 mp->warning_info=line;
14258 do { mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14259 mp->scanner_status=old_status;
14260 mp->warning_info=old_info
14262 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14263 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14264 help4("This file contains picture expressions for btex...etex",
14265 "blocks. Such files are normally generated automatically",
14266 "but this one seems to be messed up. I'll just keep going",
14267 "and hope for the best.");
14271 @ @<Complain that we are not reading a file@>=
14272 { print_err("You can only use `btex' or `verbatimtex' in a file");
14273 help3("I'll have to ignore this preprocessor command because it",
14274 "only works when there is a file to preprocess. You might",
14275 "want to delete everything up to the next `etex`.");
14279 @ @<Complain about a misplaced \&{mpxbreak}@>=
14280 { print_err("Misplaced mpxbreak");
14281 help2("I'll ignore this preprocessor command because it",
14282 "doesn't belong here");
14286 @ @<Complain about a misplaced \&{etex}@>=
14287 { print_err("Extra etex will be ignored");
14288 help1("There is no btex or verbatimtex for this to match");
14292 @* \[31] Scanning macro definitions.
14293 \MP\ has a variety of ways to tuck tokens away into token lists for later
14294 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14295 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14296 All such operations are handled by the routines in this part of the program.
14298 The modifier part of each command code is zero for the ``ending delimiters''
14299 like \&{enddef} and \&{endfor}.
14301 @d start_def 1 /* command modifier for \&{def} */
14302 @d var_def 2 /* command modifier for \&{vardef} */
14303 @d end_def 0 /* command modifier for \&{enddef} */
14304 @d start_forever 1 /* command modifier for \&{forever} */
14305 @d end_for 0 /* command modifier for \&{endfor} */
14308 mp_primitive(mp, "def",macro_def,start_def);
14309 @:def_}{\&{def} primitive@>
14310 mp_primitive(mp, "vardef",macro_def,var_def);
14311 @:var_def_}{\&{vardef} primitive@>
14312 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14313 @:primary_def_}{\&{primarydef} primitive@>
14314 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14315 @:secondary_def_}{\&{secondarydef} primitive@>
14316 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14317 @:tertiary_def_}{\&{tertiarydef} primitive@>
14318 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14319 @:end_def_}{\&{enddef} primitive@>
14321 mp_primitive(mp, "for",iteration,expr_base);
14322 @:for_}{\&{for} primitive@>
14323 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14324 @:for_suffixes_}{\&{forsuffixes} primitive@>
14325 mp_primitive(mp, "forever",iteration,start_forever);
14326 @:forever_}{\&{forever} primitive@>
14327 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14328 @:end_for_}{\&{endfor} primitive@>
14330 @ @<Cases of |print_cmd...@>=
14332 if ( m<=var_def ) {
14333 if ( m==start_def ) mp_print(mp, "def");
14334 else if ( m<start_def ) mp_print(mp, "enddef");
14335 else mp_print(mp, "vardef");
14336 } else if ( m==secondary_primary_macro ) {
14337 mp_print(mp, "primarydef");
14338 } else if ( m==tertiary_secondary_macro ) {
14339 mp_print(mp, "secondarydef");
14341 mp_print(mp, "tertiarydef");
14345 if ( m<=start_forever ) {
14346 if ( m==start_forever ) mp_print(mp, "forever");
14347 else mp_print(mp, "endfor");
14348 } else if ( m==expr_base ) {
14349 mp_print(mp, "for");
14351 mp_print(mp, "forsuffixes");
14355 @ Different macro-absorbing operations have different syntaxes, but they
14356 also have a lot in common. There is a list of special symbols that are to
14357 be replaced by parameter tokens; there is a special command code that
14358 ends the definition; the quotation conventions are identical. Therefore
14359 it makes sense to have most of the work done by a single subroutine. That
14360 subroutine is called |scan_toks|.
14362 The first parameter to |scan_toks| is the command code that will
14363 terminate scanning (either |macro_def| or |iteration|).
14365 The second parameter, |subst_list|, points to a (possibly empty) list
14366 of two-word nodes whose |info| and |value| fields specify symbol tokens
14367 before and after replacement. The list will be returned to free storage
14370 The third parameter is simply appended to the token list that is built.
14371 And the final parameter tells how many of the special operations
14372 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14373 When such parameters are present, they are called \.{(SUFFIX0)},
14374 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14376 @c static pointer mp_scan_toks (MP mp,command_code terminator, pointer
14377 subst_list, pointer tail_end, quarterword suffix_count) {
14378 pointer p; /* tail of the token list being built */
14379 pointer q; /* temporary for link management */
14380 integer balance; /* left delimiters minus right delimiters */
14381 p=hold_head; balance=1; mp_link(hold_head)=null;
14384 if ( mp->cur_sym>0 ) {
14385 @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14386 if ( mp->cur_cmd==terminator ) {
14387 @<Adjust the balance; |break| if it's zero@>;
14388 } else if ( mp->cur_cmd==macro_special ) {
14389 @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14392 mp_link(p)=mp_cur_tok(mp); p=mp_link(p);
14394 mp_link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14395 return mp_link(hold_head);
14398 @ @<Substitute for |cur_sym|...@>=
14401 while ( q!=null ) {
14402 if ( mp_info(q)==mp->cur_sym ) {
14403 mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14409 @ @<Adjust the balance; |break| if it's zero@>=
14410 if ( mp->cur_mod>0 ) {
14418 @ Four commands are intended to be used only within macro texts: \&{quote},
14419 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14420 code called |macro_special|.
14422 @d quote 0 /* |macro_special| modifier for \&{quote} */
14423 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14424 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14425 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14428 mp_primitive(mp, "quote",macro_special,quote);
14429 @:quote_}{\&{quote} primitive@>
14430 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14431 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14432 mp_primitive(mp, "@@",macro_special,macro_at);
14433 @:]]]\AT!_}{\.{\AT!} primitive@>
14434 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14435 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14437 @ @<Cases of |print_cmd...@>=
14438 case macro_special:
14440 case macro_prefix: mp_print(mp, "#@@"); break;
14441 case macro_at: mp_print_char(mp, xord('@@')); break;
14442 case macro_suffix: mp_print(mp, "@@#"); break;
14443 default: mp_print(mp, "quote"); break;
14447 @ @<Handle quoted...@>=
14449 if ( mp->cur_mod==quote ) { get_t_next; }
14450 else if ( mp->cur_mod<=suffix_count )
14451 mp->cur_sym=suffix_base-1+mp->cur_mod;
14454 @ Here is a routine that's used whenever a token will be redefined. If
14455 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14456 substituted; the latter is redefinable but essentially impossible to use,
14457 hence \MP's tables won't get fouled up.
14459 @c static void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14462 if ( (mp->cur_sym==0)||(mp->cur_sym>(integer)frozen_inaccessible) ) {
14463 print_err("Missing symbolic token inserted");
14464 @.Missing symbolic token...@>
14465 help3("Sorry: You can\'t redefine a number, string, or expr.",
14466 "I've inserted an inaccessible symbol so that your",
14467 "definition will be completed without mixing me up too badly.");
14468 if ( mp->cur_sym>0 )
14469 mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14470 else if ( mp->cur_cmd==string_token )
14471 delete_str_ref(mp->cur_mod);
14472 mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14476 @ Before we actually redefine a symbolic token, we need to clear away its
14477 former value, if it was a variable. The following stronger version of
14478 |get_symbol| does that.
14480 @c static void mp_get_clear_symbol (MP mp) {
14481 mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14484 @ Here's another little subroutine; it checks that an equals sign
14485 or assignment sign comes along at the proper place in a macro definition.
14487 @c static void mp_check_equals (MP mp) {
14488 if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14489 mp_missing_err(mp, "=");
14491 help5("The next thing in this `def' should have been `=',",
14492 "because I've already looked at the definition heading.",
14493 "But don't worry; I'll pretend that an equals sign",
14494 "was present. Everything from here to `enddef'",
14495 "will be the replacement text of this macro.");
14500 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14501 handled now that we have |scan_toks|. In this case there are
14502 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14503 |expr_base| and |expr_base+1|).
14505 @c static void mp_make_op_def (MP mp) {
14506 command_code m; /* the type of definition */
14507 pointer p,q,r; /* for list manipulation */
14509 mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14510 mp_info(q)=mp->cur_sym; value(q)=expr_base;
14511 mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14512 mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14513 mp_info(p)=mp->cur_sym; value(p)=expr_base+1; mp_link(p)=q;
14514 get_t_next; mp_check_equals(mp);
14515 mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14516 r=mp_get_avail(mp); mp_link(q)=r; mp_info(r)=general_macro;
14517 mp_link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14518 mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14519 equiv(mp->warning_info)=q; mp_get_x_next(mp);
14522 @ Parameters to macros are introduced by the keywords \&{expr},
14523 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14526 mp_primitive(mp, "expr",param_type,expr_base);
14527 @:expr_}{\&{expr} primitive@>
14528 mp_primitive(mp, "suffix",param_type,suffix_base);
14529 @:suffix_}{\&{suffix} primitive@>
14530 mp_primitive(mp, "text",param_type,text_base);
14531 @:text_}{\&{text} primitive@>
14532 mp_primitive(mp, "primary",param_type,primary_macro);
14533 @:primary_}{\&{primary} primitive@>
14534 mp_primitive(mp, "secondary",param_type,secondary_macro);
14535 @:secondary_}{\&{secondary} primitive@>
14536 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14537 @:tertiary_}{\&{tertiary} primitive@>
14539 @ @<Cases of |print_cmd...@>=
14541 if ( m>=expr_base ) {
14542 if ( m==expr_base ) mp_print(mp, "expr");
14543 else if ( m==suffix_base ) mp_print(mp, "suffix");
14544 else mp_print(mp, "text");
14545 } else if ( m<secondary_macro ) {
14546 mp_print(mp, "primary");
14547 } else if ( m==secondary_macro ) {
14548 mp_print(mp, "secondary");
14550 mp_print(mp, "tertiary");
14554 @ Let's turn next to the more complex processing associated with \&{def}
14555 and \&{vardef}. When the following procedure is called, |cur_mod|
14556 should be either |start_def| or |var_def|.
14559 static void mp_scan_def (MP mp) {
14560 int m; /* the type of definition */
14561 int n; /* the number of special suffix parameters */
14562 int k; /* the total number of parameters */
14563 int c; /* the kind of macro we're defining */
14564 pointer r; /* parameter-substitution list */
14565 pointer q; /* tail of the macro token list */
14566 pointer p; /* temporary storage */
14567 halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14568 pointer l_delim,r_delim; /* matching delimiters */
14569 m=mp->cur_mod; c=general_macro; mp_link(hold_head)=null;
14570 q=mp_get_avail(mp); ref_count(q)=null; r=null;
14571 @<Scan the token or variable to be defined;
14572 set |n|, |scanner_status|, and |warning_info|@>;
14574 if ( mp->cur_cmd==left_delimiter ) {
14575 @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14577 if ( mp->cur_cmd==param_type ) {
14578 @<Absorb undelimited parameters, putting them into list |r|@>;
14580 mp_check_equals(mp);
14581 p=mp_get_avail(mp); mp_info(p)=c; mp_link(q)=p;
14582 @<Attach the replacement text to the tail of node |p|@>;
14583 mp->scanner_status=normal; mp_get_x_next(mp);
14586 @ We don't put `|frozen_end_group|' into the replacement text of
14587 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14589 @<Attach the replacement text to the tail of node |p|@>=
14590 if ( m==start_def ) {
14591 mp_link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14593 q=mp_get_avail(mp); mp_info(q)=mp->bg_loc; mp_link(p)=q;
14594 p=mp_get_avail(mp); mp_info(p)=mp->eg_loc;
14595 mp_link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14597 if ( mp->warning_info==bad_vardef )
14598 mp_flush_token_list(mp, value(bad_vardef))
14602 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14604 @ @<Scan the token or variable to be defined;...@>=
14605 if ( m==start_def ) {
14606 mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14607 mp->scanner_status=op_defining; n=0;
14608 eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14610 p=mp_scan_declared_variable(mp);
14611 mp_flush_variable(mp, equiv(mp_info(p)),mp_link(p),true);
14612 mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14613 if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14614 mp->scanner_status=var_defining; n=2;
14615 if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14618 mp_type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14619 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14621 @ @<Change to `\.{a bad variable}'@>=
14623 print_err("This variable already starts with a macro");
14624 @.This variable already...@>
14625 help2("After `vardef a' you can\'t say `vardef a.b'.",
14626 "So I'll have to discard this definition.");
14627 mp_error(mp); mp->warning_info=bad_vardef;
14630 @ @<Initialize table entries...@>=
14631 mp_name_type(bad_vardef)=mp_root; mp_link(bad_vardef)=frozen_bad_vardef;
14632 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14634 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14636 l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14637 if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14640 print_err("Missing parameter type; `expr' will be assumed");
14641 @.Missing parameter type@>
14642 help1("You should've had `expr' or `suffix' or `text' here.");
14643 mp_back_error(mp); base=expr_base;
14645 @<Absorb parameter tokens for type |base|@>;
14646 mp_check_delimiter(mp, l_delim,r_delim);
14648 } while (mp->cur_cmd==left_delimiter)
14650 @ @<Absorb parameter tokens for type |base|@>=
14652 mp_link(q)=mp_get_avail(mp); q=mp_link(q); mp_info(q)=base+k;
14653 mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14654 value(p)=base+k; mp_info(p)=mp->cur_sym;
14655 if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14656 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14657 incr(k); mp_link(p)=r; r=p; get_t_next;
14658 } while (mp->cur_cmd==comma)
14660 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14662 p=mp_get_node(mp, token_node_size);
14663 if ( mp->cur_mod<expr_base ) {
14664 c=mp->cur_mod; value(p)=expr_base+k;
14666 value(p)=mp->cur_mod+k;
14667 if ( mp->cur_mod==expr_base ) c=expr_macro;
14668 else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14671 if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14672 incr(k); mp_get_symbol(mp); mp_info(p)=mp->cur_sym; mp_link(p)=r; r=p; get_t_next;
14673 if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14674 c=of_macro; p=mp_get_node(mp, token_node_size);
14675 if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14676 value(p)=expr_base+k; mp_get_symbol(mp); mp_info(p)=mp->cur_sym;
14677 mp_link(p)=r; r=p; get_t_next;
14681 @* \[32] Expanding the next token.
14682 Only a few command codes |<min_command| can possibly be returned by
14683 |get_t_next|; in increasing order, they are
14684 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14685 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14687 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14688 like |get_t_next| except that it keeps getting more tokens until
14689 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14690 macros and removes conditionals or iterations or input instructions that
14693 It follows that |get_x_next| might invoke itself recursively. In fact,
14694 there is massive recursion, since macro expansion can involve the
14695 scanning of arbitrarily complex expressions, which in turn involve
14696 macro expansion and conditionals, etc.
14699 Therefore it's necessary to declare a whole bunch of |forward|
14700 procedures at this point, and to insert some other procedures
14701 that will be invoked by |get_x_next|.
14704 static void mp_scan_primary (MP mp);
14705 static void mp_scan_secondary (MP mp);
14706 static void mp_scan_tertiary (MP mp);
14707 static void mp_scan_expression (MP mp);
14708 static void mp_scan_suffix (MP mp);
14709 static void mp_get_boolean (MP mp);
14710 static void mp_pass_text (MP mp);
14711 static void mp_conditional (MP mp);
14712 static void mp_start_input (MP mp);
14713 static void mp_begin_iteration (MP mp);
14714 static void mp_resume_iteration (MP mp);
14715 static void mp_stop_iteration (MP mp);
14717 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14718 when it has to do exotic expansion commands.
14721 static void mp_expand (MP mp) {
14722 pointer p; /* for list manipulation */
14723 size_t k; /* something that we hope is |<=buf_size| */
14724 pool_pointer j; /* index into |str_pool| */
14725 if ( mp->internal[mp_tracing_commands]>unity )
14726 if ( mp->cur_cmd!=defined_macro )
14728 switch (mp->cur_cmd) {
14730 mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14733 @<Terminate the current conditional and skip to \&{fi}@>;
14736 @<Initiate or terminate input from a file@>;
14739 if ( mp->cur_mod==end_for ) {
14740 @<Scold the user for having an extra \&{endfor}@>;
14742 mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14749 @<Exit a loop if the proper time has come@>;
14754 @<Expand the token after the next token@>;
14757 @<Put a string into the input buffer@>;
14759 case defined_macro:
14760 mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14762 }; /* there are no other cases */
14765 @ @<Scold the user...@>=
14767 print_err("Extra `endfor'");
14769 help2("I'm not currently working on a for loop,",
14770 "so I had better not try to end anything.");
14774 @ The processing of \&{input} involves the |start_input| subroutine,
14775 which will be declared later; the processing of \&{endinput} is trivial.
14778 mp_primitive(mp, "input",input,0);
14779 @:input_}{\&{input} primitive@>
14780 mp_primitive(mp, "endinput",input,1);
14781 @:end_input_}{\&{endinput} primitive@>
14783 @ @<Cases of |print_cmd_mod|...@>=
14785 if ( m==0 ) mp_print(mp, "input");
14786 else mp_print(mp, "endinput");
14789 @ @<Initiate or terminate input...@>=
14790 if ( mp->cur_mod>0 ) mp->force_eof=true;
14791 else mp_start_input(mp)
14793 @ We'll discuss the complicated parts of loop operations later. For now
14794 it suffices to know that there's a global variable called |loop_ptr|
14795 that will be |null| if no loop is in progress.
14798 { while ( token_state &&(loc==null) )
14799 mp_end_token_list(mp); /* conserve stack space */
14800 if ( mp->loop_ptr==null ) {
14801 print_err("Lost loop");
14803 help2("I'm confused; after exiting from a loop, I still seem",
14804 "to want to repeat it. I'll try to forget the problem.");
14807 mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14811 @ @<Exit a loop if the proper time has come@>=
14812 { mp_get_boolean(mp);
14813 if ( mp->internal[mp_tracing_commands]>unity )
14814 mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14815 if ( mp->cur_exp==true_code ) {
14816 if ( mp->loop_ptr==null ) {
14817 print_err("No loop is in progress");
14818 @.No loop is in progress@>
14819 help1("Why say `exitif' when there's nothing to exit from?");
14820 if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14822 @<Exit prematurely from an iteration@>;
14824 } else if ( mp->cur_cmd!=semicolon ) {
14825 mp_missing_err(mp, ";");
14827 help2("After `exitif <boolean exp>' I expect to see a semicolon.",
14828 "I shall pretend that one was there."); mp_back_error(mp);
14832 @ Here we use the fact that |forever_text| is the only |token_type| that
14833 is less than |loop_text|.
14835 @<Exit prematurely...@>=
14838 if ( file_state ) {
14839 mp_end_file_reading(mp);
14841 if ( token_type<=loop_text ) p=start;
14842 mp_end_token_list(mp);
14845 if ( p!=mp_info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14847 mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14850 @ @<Expand the token after the next token@>=
14852 p=mp_cur_tok(mp); get_t_next;
14853 if ( mp->cur_cmd<min_command ) mp_expand(mp);
14854 else mp_back_input(mp);
14858 @ @<Put a string into the input buffer@>=
14859 { mp_get_x_next(mp); mp_scan_primary(mp);
14860 if ( mp->cur_type!=mp_string_type ) {
14861 mp_disp_err(mp, null,"Not a string");
14863 help2("I'm going to flush this expression, since",
14864 "scantokens should be followed by a known string.");
14865 mp_put_get_flush_error(mp, 0);
14868 if ( length(mp->cur_exp)>0 )
14869 @<Pretend we're reading a new one-line file@>;
14873 @ @<Pretend we're reading a new one-line file@>=
14874 { mp_begin_file_reading(mp); name=is_scantok;
14875 k=mp->first+length(mp->cur_exp);
14876 if ( k>=mp->max_buf_stack ) {
14877 while ( k>=mp->buf_size ) {
14878 mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size/4)));
14880 mp->max_buf_stack=k+1;
14882 j=mp->str_start[mp->cur_exp]; limit=(halfword)k;
14883 while ( mp->first<(size_t)limit ) {
14884 mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14886 mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start;
14887 mp_flush_cur_exp(mp, 0);
14890 @ Here finally is |get_x_next|.
14892 The expression scanning routines to be considered later
14893 communicate via the global quantities |cur_type| and |cur_exp|;
14894 we must be very careful to save and restore these quantities while
14895 macros are being expanded.
14899 static void mp_get_x_next (MP mp);
14901 @ @c void mp_get_x_next (MP mp) {
14902 pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14904 if ( mp->cur_cmd<min_command ) {
14905 save_exp=mp_stash_cur_exp(mp);
14907 if ( mp->cur_cmd==defined_macro )
14908 mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14912 } while (mp->cur_cmd<min_command);
14913 mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14917 @ Now let's consider the |macro_call| procedure, which is used to start up
14918 all user-defined macros. Since the arguments to a macro might be expressions,
14919 |macro_call| is recursive.
14922 The first parameter to |macro_call| points to the reference count of the
14923 token list that defines the macro. The second parameter contains any
14924 arguments that have already been parsed (see below). The third parameter
14925 points to the symbolic token that names the macro. If the third parameter
14926 is |null|, the macro was defined by \&{vardef}, so its name can be
14927 reconstructed from the prefix and ``at'' arguments found within the
14930 What is this second parameter? It's simply a linked list of one-word items,
14931 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14932 no arguments have been scanned yet; otherwise |mp_info(arg_list)| points to
14933 the first scanned argument, and |mp_link(arg_list)| points to the list of
14934 further arguments (if any).
14936 Arguments of type \&{expr} are so-called capsules, which we will
14937 discuss later when we concentrate on expressions; they can be
14938 recognized easily because their |link| field is |void|. Arguments of type
14939 \&{suffix} and \&{text} are token lists without reference counts.
14941 @ After argument scanning is complete, the arguments are moved to the
14942 |param_stack|. (They can't be put on that stack any sooner, because
14943 the stack is growing and shrinking in unpredictable ways as more arguments
14944 are being acquired.) Then the macro body is fed to the scanner; i.e.,
14945 the replacement text of the macro is placed at the top of the \MP's
14946 input stack, so that |get_t_next| will proceed to read it next.
14949 static void mp_macro_call (MP mp,pointer def_ref, pointer arg_list,
14950 pointer macro_name) ;
14953 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list,
14954 pointer macro_name) {
14955 /* invokes a user-defined control sequence */
14956 pointer r; /* current node in the macro's token list */
14957 pointer p,q; /* for list manipulation */
14958 integer n; /* the number of arguments */
14959 pointer tail = 0; /* tail of the argument list */
14960 pointer l_delim=0,r_delim=0; /* a delimiter pair */
14961 r=mp_link(def_ref); add_mac_ref(def_ref);
14962 if ( arg_list==null ) {
14965 @<Determine the number |n| of arguments already supplied,
14966 and set |tail| to the tail of |arg_list|@>;
14968 if ( mp->internal[mp_tracing_macros]>0 ) {
14969 @<Show the text of the macro being expanded, and the existing arguments@>;
14971 @<Scan the remaining arguments, if any; set |r| to the first token
14972 of the replacement text@>;
14973 @<Feed the arguments and replacement text to the scanner@>;
14976 @ @<Show the text of the macro...@>=
14977 mp_begin_diagnostic(mp); mp_print_ln(mp);
14978 mp_print_macro_name(mp, arg_list,macro_name);
14979 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14980 mp_show_macro(mp, def_ref,null,100000);
14981 if ( arg_list!=null ) {
14985 mp_print_arg(mp, q,n,0);
14986 incr(n); p=mp_link(p);
14989 mp_end_diagnostic(mp, false)
14992 @ @<Declarations@>=
14993 static void mp_print_macro_name (MP mp,pointer a, pointer n);
14996 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14997 pointer p,q; /* they traverse the first part of |a| */
15003 mp_print_text(mp_info(mp_info(mp_link(a))));
15006 while ( mp_link(q)!=null ) q=mp_link(q);
15007 mp_link(q)=mp_info(mp_link(a));
15008 mp_show_token_list(mp, p,null,1000,0);
15014 @ @<Declarations@>=
15015 static void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
15018 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
15019 if ( mp_link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
15020 else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
15021 else mp_print_nl(mp, "(TEXT");
15022 mp_print_int(mp, n); mp_print(mp, ")<-");
15023 if ( mp_link(q)==mp_void ) mp_print_exp(mp, q,1);
15024 else mp_show_token_list(mp, q,null,1000,0);
15027 @ @<Determine the number |n| of arguments already supplied...@>=
15029 n=1; tail=arg_list;
15030 while ( mp_link(tail)!=null ) {
15031 incr(n); tail=mp_link(tail);
15035 @ @<Scan the remaining arguments, if any; set |r|...@>=
15036 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
15037 while ( mp_info(r)>=expr_base ) {
15038 @<Scan the delimited argument represented by |mp_info(r)|@>;
15041 if ( mp->cur_cmd==comma ) {
15042 print_err("Too many arguments to ");
15043 @.Too many arguments...@>
15044 mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, xord(';'));
15045 mp_print_nl(mp, " Missing `"); mp_print_text(r_delim);
15047 mp_print(mp, "' has been inserted");
15048 help3("I'm going to assume that the comma I just read was a",
15049 "right delimiter, and then I'll begin expanding the macro.",
15050 "You might want to delete some tokens before continuing.");
15053 if ( mp_info(r)!=general_macro ) {
15054 @<Scan undelimited argument(s)@>;
15058 @ At this point, the reader will find it advisable to review the explanation
15059 of token list format that was presented earlier, paying special attention to
15060 the conventions that apply only at the beginning of a macro's token list.
15062 On the other hand, the reader will have to take the expression-parsing
15063 aspects of the following program on faith; we will explain |cur_type|
15064 and |cur_exp| later. (Several things in this program depend on each other,
15065 and it's necessary to jump into the circle somewhere.)
15067 @<Scan the delimited argument represented by |mp_info(r)|@>=
15068 if ( mp->cur_cmd!=comma ) {
15070 if ( mp->cur_cmd!=left_delimiter ) {
15071 print_err("Missing argument to ");
15072 @.Missing argument...@>
15073 mp_print_macro_name(mp, arg_list,macro_name);
15074 help3("That macro has more parameters than you thought.",
15075 "I'll continue by pretending that each missing argument",
15076 "is either zero or null.");
15077 if ( mp_info(r)>=suffix_base ) {
15078 mp->cur_exp=null; mp->cur_type=mp_token_list;
15080 mp->cur_exp=0; mp->cur_type=mp_known;
15082 mp_back_error(mp); mp->cur_cmd=right_delimiter;
15085 l_delim=mp->cur_sym; r_delim=mp->cur_mod;
15087 @<Scan the argument represented by |mp_info(r)|@>;
15088 if ( mp->cur_cmd!=comma )
15089 @<Check that the proper right delimiter was present@>;
15091 @<Append the current expression to |arg_list|@>
15093 @ @<Check that the proper right delim...@>=
15094 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15095 if ( mp_info(mp_link(r))>=expr_base ) {
15096 mp_missing_err(mp, ",");
15098 help3("I've finished reading a macro argument and am about to",
15099 "read another; the arguments weren't delimited correctly.",
15100 "You might want to delete some tokens before continuing.");
15101 mp_back_error(mp); mp->cur_cmd=comma;
15103 mp_missing_err(mp, str(text(r_delim)));
15105 help2("I've gotten to the end of the macro parameter list.",
15106 "You might want to delete some tokens before continuing.");
15111 @ A \&{suffix} or \&{text} parameter will have been scanned as
15112 a token list pointed to by |cur_exp|, in which case we will have
15113 |cur_type=token_list|.
15115 @<Append the current expression to |arg_list|@>=
15117 p=mp_get_avail(mp);
15118 if ( mp->cur_type==mp_token_list ) mp_info(p)=mp->cur_exp;
15119 else mp_info(p)=mp_stash_cur_exp(mp);
15120 if ( mp->internal[mp_tracing_macros]>0 ) {
15121 mp_begin_diagnostic(mp); mp_print_arg(mp, mp_info(p),n,mp_info(r));
15122 mp_end_diagnostic(mp, false);
15124 if ( arg_list==null ) arg_list=p;
15125 else mp_link(tail)=p;
15129 @ @<Scan the argument represented by |mp_info(r)|@>=
15130 if ( mp_info(r)>=text_base ) {
15131 mp_scan_text_arg(mp, l_delim,r_delim);
15134 if ( mp_info(r)>=suffix_base ) mp_scan_suffix(mp);
15135 else mp_scan_expression(mp);
15138 @ The parameters to |scan_text_arg| are either a pair of delimiters
15139 or zero; the latter case is for undelimited text arguments, which
15140 end with the first semicolon or \&{endgroup} or \&{end} that is not
15141 contained in a group.
15144 static void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
15147 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
15148 integer balance; /* excess of |l_delim| over |r_delim| */
15149 pointer p; /* list tail */
15150 mp->warning_info=l_delim; mp->scanner_status=absorbing;
15151 p=hold_head; balance=1; mp_link(hold_head)=null;
15154 if ( l_delim==0 ) {
15155 @<Adjust the balance for an undelimited argument; |break| if done@>;
15157 @<Adjust the balance for a delimited argument; |break| if done@>;
15159 mp_link(p)=mp_cur_tok(mp); p=mp_link(p);
15161 mp->cur_exp=mp_link(hold_head); mp->cur_type=mp_token_list;
15162 mp->scanner_status=normal;
15165 @ @<Adjust the balance for a delimited argument...@>=
15166 if ( mp->cur_cmd==right_delimiter ) {
15167 if ( mp->cur_mod==l_delim ) {
15169 if ( balance==0 ) break;
15171 } else if ( mp->cur_cmd==left_delimiter ) {
15172 if ( mp->cur_mod==r_delim ) incr(balance);
15175 @ @<Adjust the balance for an undelimited...@>=
15176 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
15177 if ( balance==1 ) { break; }
15178 else { if ( mp->cur_cmd==end_group ) decr(balance); }
15179 } else if ( mp->cur_cmd==begin_group ) {
15183 @ @<Scan undelimited argument(s)@>=
15185 if ( mp_info(r)<text_macro ) {
15187 if ( mp_info(r)!=suffix_macro ) {
15188 if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15191 switch (mp_info(r)) {
15192 case primary_macro:mp_scan_primary(mp); break;
15193 case secondary_macro:mp_scan_secondary(mp); break;
15194 case tertiary_macro:mp_scan_tertiary(mp); break;
15195 case expr_macro:mp_scan_expression(mp); break;
15197 @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15200 @<Scan a suffix with optional delimiters@>;
15202 case text_macro:mp_scan_text_arg(mp, 0,0); break;
15203 } /* there are no other cases */
15205 @<Append the current expression to |arg_list|@>;
15208 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15210 mp_scan_expression(mp); p=mp_get_avail(mp); mp_info(p)=mp_stash_cur_exp(mp);
15211 if ( mp->internal[mp_tracing_macros]>0 ) {
15212 mp_begin_diagnostic(mp); mp_print_arg(mp, mp_info(p),n,0);
15213 mp_end_diagnostic(mp, false);
15215 if ( arg_list==null ) arg_list=p; else mp_link(tail)=p;
15217 if ( mp->cur_cmd!=of_token ) {
15218 mp_missing_err(mp, "of"); mp_print(mp, " for ");
15220 mp_print_macro_name(mp, arg_list,macro_name);
15221 help1("I've got the first argument; will look now for the other.");
15224 mp_get_x_next(mp); mp_scan_primary(mp);
15227 @ @<Scan a suffix with optional delimiters@>=
15229 if ( mp->cur_cmd!=left_delimiter ) {
15232 l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15234 mp_scan_suffix(mp);
15235 if ( l_delim!=null ) {
15236 if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15237 mp_missing_err(mp, str(text(r_delim)));
15239 help2("I've gotten to the end of the macro parameter list.",
15240 "You might want to delete some tokens before continuing.");
15247 @ Before we put a new token list on the input stack, it is wise to clean off
15248 all token lists that have recently been depleted. Then a user macro that ends
15249 with a call to itself will not require unbounded stack space.
15251 @<Feed the arguments and replacement text to the scanner@>=
15252 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15253 if ( mp->param_ptr+n>mp->max_param_stack ) {
15254 mp->max_param_stack=mp->param_ptr+n;
15255 if ( mp->max_param_stack>mp->param_size )
15256 mp_overflow(mp, "parameter stack size",mp->param_size);
15257 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15259 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15263 mp->param_stack[mp->param_ptr]=mp_info(p); incr(mp->param_ptr); p=mp_link(p);
15265 mp_flush_list(mp, arg_list);
15268 @ It's sometimes necessary to put a single argument onto |param_stack|.
15269 The |stack_argument| subroutine does this.
15272 static void mp_stack_argument (MP mp,pointer p) {
15273 if ( mp->param_ptr==mp->max_param_stack ) {
15274 incr(mp->max_param_stack);
15275 if ( mp->max_param_stack>mp->param_size )
15276 mp_overflow(mp, "parameter stack size",mp->param_size);
15277 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15279 mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15282 @* \[33] Conditional processing.
15283 Let's consider now the way \&{if} commands are handled.
15285 Conditions can be inside conditions, and this nesting has a stack
15286 that is independent of other stacks.
15287 Four global variables represent the top of the condition stack:
15288 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15289 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15290 the largest code of a |fi_or_else| command that is syntactically legal;
15291 and |if_line| is the line number at which the current conditional began.
15293 If no conditions are currently in progress, the condition stack has the
15294 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15295 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15296 |link| fields of the first word contain |if_limit|, |cur_if|, and
15297 |cond_ptr| at the next level, and the second word contains the
15298 corresponding |if_line|.
15300 @d if_node_size 2 /* number of words in stack entry for conditionals */
15301 @d if_line_field(A) mp->mem[(A)+1].cint
15302 @d if_code 1 /* code for \&{if} being evaluated */
15303 @d fi_code 2 /* code for \&{fi} */
15304 @d else_code 3 /* code for \&{else} */
15305 @d else_if_code 4 /* code for \&{elseif} */
15308 pointer cond_ptr; /* top of the condition stack */
15309 integer if_limit; /* upper bound on |fi_or_else| codes */
15310 quarterword cur_if; /* type of conditional being worked on */
15311 integer if_line; /* line where that conditional began */
15314 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15317 mp_primitive(mp, "if",if_test,if_code);
15318 @:if_}{\&{if} primitive@>
15319 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15320 @:fi_}{\&{fi} primitive@>
15321 mp_primitive(mp, "else",fi_or_else,else_code);
15322 @:else_}{\&{else} primitive@>
15323 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15324 @:else_if_}{\&{elseif} primitive@>
15326 @ @<Cases of |print_cmd_mod|...@>=
15330 case if_code:mp_print(mp, "if"); break;
15331 case fi_code:mp_print(mp, "fi"); break;
15332 case else_code:mp_print(mp, "else"); break;
15333 default: mp_print(mp, "elseif"); break;
15337 @ Here is a procedure that ignores text until coming to an \&{elseif},
15338 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15339 nesting. After it has acted, |cur_mod| will indicate the token that
15342 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15343 makes the skipping process a bit simpler.
15346 void mp_pass_text (MP mp) {
15348 mp->scanner_status=skipping;
15349 mp->warning_info=mp_true_line(mp);
15352 if ( mp->cur_cmd<=fi_or_else ) {
15353 if ( mp->cur_cmd<fi_or_else ) {
15357 if ( mp->cur_mod==fi_code ) decr(l);
15360 @<Decrease the string reference count,
15361 if the current token is a string@>;
15364 mp->scanner_status=normal;
15367 @ @<Decrease the string reference count...@>=
15368 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15370 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15371 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15372 condition has been evaluated, a colon will be inserted.
15373 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15375 @<Push the condition stack@>=
15376 { p=mp_get_node(mp, if_node_size); mp_link(p)=mp->cond_ptr; mp_type(p)=mp->if_limit;
15377 mp_name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15378 mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp);
15379 mp->cur_if=if_code;
15382 @ @<Pop the condition stack@>=
15383 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15384 mp->cur_if=mp_name_type(p); mp->if_limit=mp_type(p); mp->cond_ptr=mp_link(p);
15385 mp_free_node(mp, p,if_node_size);
15388 @ Here's a procedure that changes the |if_limit| code corresponding to
15389 a given value of |cond_ptr|.
15392 static void mp_change_if_limit (MP mp,quarterword l, pointer p) {
15394 if ( p==mp->cond_ptr ) {
15395 mp->if_limit=l; /* that's the easy case */
15399 if ( q==null ) mp_confusion(mp, "if");
15400 @:this can't happen if}{\quad if@>
15401 if ( mp_link(q)==p ) {
15402 mp_type(q)=l; return;
15409 @ The user is supposed to put colons into the proper parts of conditional
15410 statements. Therefore, \MP\ has to check for their presence.
15413 static void mp_check_colon (MP mp) {
15414 if ( mp->cur_cmd!=colon ) {
15415 mp_missing_err(mp, ":");
15417 help2("There should've been a colon after the condition.",
15418 "I shall pretend that one was there.");
15423 @ A condition is started when the |get_x_next| procedure encounters
15424 an |if_test| command; in that case |get_x_next| calls |conditional|,
15425 which is a recursive procedure.
15429 void mp_conditional (MP mp) {
15430 pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15431 int new_if_limit; /* future value of |if_limit| */
15432 pointer p; /* temporary register */
15433 @<Push the condition stack@>;
15434 save_cond_ptr=mp->cond_ptr;
15436 mp_get_boolean(mp); new_if_limit=else_if_code;
15437 if ( mp->internal[mp_tracing_commands]>unity ) {
15438 @<Display the boolean value of |cur_exp|@>;
15441 mp_check_colon(mp);
15442 if ( mp->cur_exp==true_code ) {
15443 mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15444 return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15446 @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15448 mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15449 if ( mp->cur_mod==fi_code ) {
15450 @<Pop the condition stack@>
15451 } else if ( mp->cur_mod==else_if_code ) {
15454 mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp);
15459 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15460 \&{else}: \\{bar} \&{fi}', the first \&{else}
15461 that we come to after learning that the \&{if} is false is not the
15462 \&{else} we're looking for. Hence the following curious logic is needed.
15464 @<Skip to \&{elseif}...@>=
15467 if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15468 else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15472 @ @<Display the boolean value...@>=
15473 { mp_begin_diagnostic(mp);
15474 if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15475 else mp_print(mp, "{false}");
15476 mp_end_diagnostic(mp, false);
15479 @ The processing of conditionals is complete except for the following
15480 code, which is actually part of |get_x_next|. It comes into play when
15481 \&{elseif}, \&{else}, or \&{fi} is scanned.
15483 @<Terminate the current conditional and skip to \&{fi}@>=
15484 if ( mp->cur_mod>mp->if_limit ) {
15485 if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15486 mp_missing_err(mp, ":");
15488 mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15490 print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15494 help1("I'm ignoring this; it doesn't match any if.");
15498 while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15499 @<Pop the condition stack@>;
15502 @* \[34] Iterations.
15503 To bring our treatment of |get_x_next| to a close, we need to consider what
15504 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15506 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15507 that are currently active. If |loop_ptr=null|, no loops are in progress;
15508 otherwise |mp_info(loop_ptr)| points to the iterative text of the current
15509 (innermost) loop, and |mp_link(loop_ptr)| points to the data for any other
15510 loops that enclose the current one.
15512 A loop-control node also has two other fields, called |loop_type| and
15513 |loop_list|, whose contents depend on the type of loop:
15515 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15516 points to a list of one-word nodes whose |info| fields point to the
15517 remaining argument values of a suffix list and expression list.
15519 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15522 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15523 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15524 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15527 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15528 header and |loop_list(loop_ptr)| points into the graphical object list for
15531 \yskip\noindent In the case of a progression node, the first word is not used
15532 because the link field of words in the dynamic memory area cannot be arbitrary.
15534 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15535 @d loop_type(A) mp_info(loop_list_loc((A))) /* the type of \&{for} loop */
15536 @d loop_list(A) mp_link(loop_list_loc((A))) /* the remaining list elements */
15537 @d loop_node_size 2 /* the number of words in a loop control node */
15538 @d progression_node_size 4 /* the number of words in a progression node */
15539 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15540 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15541 @d progression_flag (null+2)
15542 /* |loop_type| value when |loop_list| points to a progression node */
15545 pointer loop_ptr; /* top of the loop-control-node stack */
15550 @ If the expressions that define an arithmetic progression in
15551 a \&{for} loop don't have known numeric values, the |bad_for|
15552 subroutine screams at the user.
15555 static void mp_bad_for (MP mp, const char * s) {
15556 mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15557 @.Improper...replaced by 0@>
15558 mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15559 help4("When you say `for x=a step b until c',",
15560 "the initial value `a' and the step size `b'",
15561 "and the final value `c' must have known numeric values.",
15562 "I'm zeroing this one. Proceed, with fingers crossed.");
15563 mp_put_get_flush_error(mp, 0);
15566 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15567 has just been scanned. (This code requires slight familiarity with
15568 expression-parsing routines that we have not yet discussed; but it seems
15569 to belong in the present part of the program, even though the original author
15570 didn't write it until later. The reader may wish to come back to it.)
15572 @c void mp_begin_iteration (MP mp) {
15573 halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15574 halfword n; /* hash address of the current symbol */
15575 pointer s; /* the new loop-control node */
15576 pointer p; /* substitution list for |scan_toks| */
15577 pointer q; /* link manipulation register */
15578 pointer pp; /* a new progression node */
15579 m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15580 if ( m==start_forever ){
15581 loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15583 mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15584 mp_info(p)=mp->cur_sym; value(p)=m;
15586 if ( mp->cur_cmd==within_token ) {
15587 @<Set up a picture iteration@>;
15589 @<Check for the |"="| or |":="| in a loop header@>;
15590 @<Scan the values to be used in the loop@>;
15593 @<Check for the presence of a colon@>;
15594 @<Scan the loop text and put it on the loop control stack@>;
15595 mp_resume_iteration(mp);
15598 @ @<Check for the |"="| or |":="| in a loop header@>=
15599 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) {
15600 mp_missing_err(mp, "=");
15602 help3("The next thing in this loop should have been `=' or `:='.",
15603 "But don't worry; I'll pretend that an equals sign",
15604 "was present, and I'll look for the values next.");
15608 @ @<Check for the presence of a colon@>=
15609 if ( mp->cur_cmd!=colon ) {
15610 mp_missing_err(mp, ":");
15612 help3("The next thing in this loop should have been a `:'.",
15613 "So I'll pretend that a colon was present;",
15614 "everything from here to `endfor' will be iterated.");
15618 @ We append a special |frozen_repeat_loop| token in place of the
15619 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15620 at the proper time to cause the loop to be repeated.
15622 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15623 he will be foiled by the |get_symbol| routine, which keeps frozen
15624 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15625 token, so it won't be lost accidentally.)
15627 @ @<Scan the loop text...@>=
15628 q=mp_get_avail(mp); mp_info(q)=frozen_repeat_loop;
15629 mp->scanner_status=loop_defining; mp->warning_info=n;
15630 mp_info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15631 mp_link(s)=mp->loop_ptr; mp->loop_ptr=s
15633 @ @<Initialize table...@>=
15634 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15635 text(frozen_repeat_loop)=intern(" ENDFOR");
15637 @ The loop text is inserted into \MP's scanning apparatus by the
15638 |resume_iteration| routine.
15640 @c void mp_resume_iteration (MP mp) {
15641 pointer p,q; /* link registers */
15642 p=loop_type(mp->loop_ptr);
15643 if ( p==progression_flag ) {
15644 p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15645 mp->cur_exp=value(p);
15646 if ( @<The arithmetic progression has ended@> ) {
15647 mp_stop_iteration(mp);
15650 mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15651 value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15652 } else if ( p==null ) {
15653 p=loop_list(mp->loop_ptr);
15655 mp_stop_iteration(mp);
15658 loop_list(mp->loop_ptr)=mp_link(p); q=mp_info(p); free_avail(p);
15659 } else if ( p==mp_void ) {
15660 mp_begin_token_list(mp, mp_info(mp->loop_ptr),forever_text); return;
15662 @<Make |q| a capsule containing the next picture component from
15663 |loop_list(loop_ptr)| or |goto not_found|@>;
15665 mp_begin_token_list(mp, mp_info(mp->loop_ptr),loop_text);
15666 mp_stack_argument(mp, q);
15667 if ( mp->internal[mp_tracing_commands]>unity ) {
15668 @<Trace the start of a loop@>;
15672 mp_stop_iteration(mp);
15675 @ @<The arithmetic progression has ended@>=
15676 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15677 ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15679 @ @<Trace the start of a loop@>=
15681 mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15683 if ( (q!=null)&&(mp_link(q)==mp_void) ) mp_print_exp(mp, q,1);
15684 else mp_show_token_list(mp, q,null,50,0);
15685 mp_print_char(mp, xord('}')); mp_end_diagnostic(mp, false);
15688 @ @<Make |q| a capsule containing the next picture component from...@>=
15689 { q=loop_list(mp->loop_ptr);
15690 if ( q==null ) goto NOT_FOUND;
15691 skip_component(q) goto NOT_FOUND;
15692 mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15693 mp_init_bbox(mp, mp->cur_exp);
15694 mp->cur_type=mp_picture_type;
15695 loop_list(mp->loop_ptr)=q;
15696 q=mp_stash_cur_exp(mp);
15699 @ A level of loop control disappears when |resume_iteration| has decided
15700 not to resume, or when an \&{exitif} construction has removed the loop text
15701 from the input stack.
15703 @c void mp_stop_iteration (MP mp) {
15704 pointer p,q; /* the usual */
15705 p=loop_type(mp->loop_ptr);
15706 if ( p==progression_flag ) {
15707 mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15708 } else if ( p==null ){
15709 q=loop_list(mp->loop_ptr);
15710 while ( q!=null ) {
15713 if ( mp_link(p)==mp_void ) { /* it's an \&{expr} parameter */
15714 mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15716 mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15719 p=q; q=mp_link(q); free_avail(p);
15721 } else if ( p>progression_flag ) {
15722 delete_edge_ref(p);
15724 p=mp->loop_ptr; mp->loop_ptr=mp_link(p); mp_flush_token_list(mp, mp_info(p));
15725 mp_free_node(mp, p,loop_node_size);
15728 @ Now that we know all about loop control, we can finish up
15729 the missing portion of |begin_iteration| and we'll be done.
15731 The following code is performed after the `\.=' has been scanned in
15732 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15733 (if |m=suffix_base|).
15735 @<Scan the values to be used in the loop@>=
15736 loop_type(s)=null; q=loop_list_loc(s); mp_link(q)=null; /* |mp_link(q)=loop_list(s)| */
15739 if ( m!=expr_base ) {
15740 mp_scan_suffix(mp);
15742 if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma )
15744 mp_scan_expression(mp);
15745 if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15746 @<Prepare for step-until construction and |break|@>;
15748 mp->cur_exp=mp_stash_cur_exp(mp);
15750 mp_link(q)=mp_get_avail(mp); q=mp_link(q);
15751 mp_info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15754 } while (mp->cur_cmd==comma)
15756 @ @<Prepare for step-until construction and |break|@>=
15758 if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15759 pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15760 mp_get_x_next(mp); mp_scan_expression(mp);
15761 if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15762 step_size(pp)=mp->cur_exp;
15763 if ( mp->cur_cmd!=until_token ) {
15764 mp_missing_err(mp, "until");
15765 @.Missing `until'@>
15766 help2("I assume you meant to say `until' after `step'.",
15767 "So I'll look for the final value and colon next.");
15770 mp_get_x_next(mp); mp_scan_expression(mp);
15771 if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15772 final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15773 loop_type(s)=progression_flag;
15777 @ The last case is when we have just seen ``\&{within}'', and we need to
15778 parse a picture expression and prepare to iterate over it.
15780 @<Set up a picture iteration@>=
15781 { mp_get_x_next(mp);
15782 mp_scan_expression(mp);
15783 @<Make sure the current expression is a known picture@>;
15784 loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15785 q=mp_link(dummy_loc(mp->cur_exp));
15787 if ( is_start_or_stop(q) )
15788 if ( mp_skip_1component(mp, q)==null ) q=mp_link(q);
15792 @ @<Make sure the current expression is a known picture@>=
15793 if ( mp->cur_type!=mp_picture_type ) {
15794 mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15795 help1("When you say `for x in p', p must be a known picture.");
15796 mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15797 mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15800 @* \[35] File names.
15801 It's time now to fret about file names. Besides the fact that different
15802 operating systems treat files in different ways, we must cope with the
15803 fact that completely different naming conventions are used by different
15804 groups of people. The following programs show what is required for one
15805 particular operating system; similar routines for other systems are not
15806 difficult to devise.
15807 @^system dependencies@>
15809 \MP\ assumes that a file name has three parts: the name proper; its
15810 ``extension''; and a ``file area'' where it is found in an external file
15811 system. The extension of an input file is assumed to be
15812 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15813 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15814 metric files that describe characters in any fonts created by \MP; it is
15815 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15816 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15817 The file area can be arbitrary on input files, but files are usually
15818 output to the user's current area. If an input file cannot be
15819 found on the specified area, \MP\ will look for it on a special system
15820 area; this special area is intended for commonly used input files.
15822 Simple uses of \MP\ refer only to file names that have no explicit
15823 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15824 instead of `\.{input} \.{cmr10.new}'. Simple file
15825 names are best, because they make the \MP\ source files portable;
15826 whenever a file name consists entirely of letters and digits, it should be
15827 treated in the same way by all implementations of \MP. However, users
15828 need the ability to refer to other files in their environment, especially
15829 when responding to error messages concerning unopenable files; therefore
15830 we want to let them use the syntax that appears in their favorite
15833 @ \MP\ uses the same conventions that have proved to be satisfactory for
15834 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15835 @^system dependencies@>
15836 the system-independent parts of \MP\ are expressed in terms
15837 of three system-dependent
15838 procedures called |begin_name|, |more_name|, and |end_name|. In
15839 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15840 the system-independent driver program does the operations
15841 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;\,|more_name|(c_n);
15843 These three procedures communicate with each other via global variables.
15844 Afterwards the file name will appear in the string pool as three strings
15845 called |cur_name|\penalty10000\hskip-.05em,
15846 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15847 |""|), unless they were explicitly specified by the user.
15849 Actually the situation is slightly more complicated, because \MP\ needs
15850 to know when the file name ends. The |more_name| routine is a function
15851 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15852 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15853 returns |false|; or, it returns |true| and $c_n$ is the last character
15854 on the current input line. In other words,
15855 |more_name| is supposed to return |true| unless it is sure that the
15856 file name has been completely scanned; and |end_name| is supposed to be able
15857 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15858 whether $|more_name|(c_n)$ returned |true| or |false|.
15861 char * cur_name; /* name of file just scanned */
15862 char * cur_area; /* file area just scanned, or \.{""} */
15863 char * cur_ext; /* file extension just scanned, or \.{""} */
15865 @ It is easier to maintain reference counts if we assign initial values.
15868 mp->cur_name=xstrdup("");
15869 mp->cur_area=xstrdup("");
15870 mp->cur_ext=xstrdup("");
15872 @ @<Dealloc variables@>=
15873 xfree(mp->cur_area);
15874 xfree(mp->cur_name);
15875 xfree(mp->cur_ext);
15877 @ The file names we shall deal with for illustrative purposes have the
15878 following structure: If the name contains `\.>' or `\.:', the file area
15879 consists of all characters up to and including the final such character;
15880 otherwise the file area is null. If the remaining file name contains
15881 `\..', the file extension consists of all such characters from the first
15882 remaining `\..' to the end, otherwise the file extension is null.
15883 @^system dependencies@>
15885 We can scan such file names easily by using two global variables that keep track
15886 of the occurrences of area and extension delimiters. Note that these variables
15887 cannot be of type |pool_pointer| because a string pool compaction could occur
15888 while scanning a file name.
15891 integer area_delimiter;
15892 /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15893 integer ext_delimiter; /* the relevant `\..', if any */
15895 @ Here now is the first of the system-dependent routines for file name scanning.
15896 @^system dependencies@>
15898 The file name length is limited to |file_name_size|. That is good, because
15899 in the current configuration we cannot call |mp_do_compaction| while a name
15900 is being scanned, |mp->area_delimiter| and |mp->ext_delimiter| are direct
15901 offsets into |mp->str_pool|. I am not in a great hurry to fix this, because
15902 calling |str_room()| just once is more efficient anyway. TODO.
15905 static void mp_begin_name (MP mp);
15906 static boolean mp_more_name (MP mp, ASCII_code c);
15907 static void mp_end_name (MP mp);
15910 void mp_begin_name (MP mp) {
15911 xfree(mp->cur_name);
15912 xfree(mp->cur_area);
15913 xfree(mp->cur_ext);
15914 mp->area_delimiter=-1;
15915 mp->ext_delimiter=-1;
15916 str_room(file_name_size);
15919 @ And here's the second.
15920 @^system dependencies@>
15923 boolean mp_more_name (MP mp, ASCII_code c) {
15927 if ( (c=='>')||(c==':') ) {
15928 mp->area_delimiter=mp->pool_ptr;
15929 mp->ext_delimiter=-1;
15930 } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15931 mp->ext_delimiter=mp->pool_ptr;
15933 append_char(c); /* contribute |c| to the current string */
15939 @^system dependencies@>
15941 @d copy_pool_segment(A,B,C) {
15942 A = xmalloc(C+1,sizeof(char));
15943 strncpy(A,(char *)(mp->str_pool+B),C);
15947 void mp_end_name (MP mp) {
15948 pool_pointer s; /* length of area, name, and extension */
15951 s = mp->str_start[mp->str_ptr];
15952 if ( mp->area_delimiter<0 ) {
15953 mp->cur_area=xstrdup("");
15955 len = (unsigned)(mp->area_delimiter-s);
15956 copy_pool_segment(mp->cur_area,s,len);
15959 if ( mp->ext_delimiter<0 ) {
15960 mp->cur_ext=xstrdup("");
15961 len = (unsigned)(mp->pool_ptr-s);
15963 copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(size_t)(mp->pool_ptr-mp->ext_delimiter));
15964 len = (unsigned)(mp->ext_delimiter-s);
15966 copy_pool_segment(mp->cur_name,s,len);
15967 mp->pool_ptr=s; /* don't need this partial string */
15970 @ Conversely, here is a routine that takes three strings and prints a file
15971 name that might have produced them. (The routine is system dependent, because
15972 some operating systems put the file area last instead of first.)
15973 @^system dependencies@>
15975 @<Basic printing...@>=
15976 static void mp_print_file_name (MP mp, char * n, char * a, char * e) {
15977 mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15980 @ Another system-dependent routine is needed to convert three internal
15982 to the |name_of_file| value that is used to open files. The present code
15983 allows both lowercase and uppercase letters in the file name.
15984 @^system dependencies@>
15986 @d append_to_name(A) { c=xord((int)(A));
15987 if ( k<file_name_size ) {
15988 mp->name_of_file[k]=(char)xchr(c);
15994 void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e) {
15995 integer k; /* number of positions filled in |name_of_file| */
15996 ASCII_code c; /* character being packed */
15997 const char *j; /* a character index */
16001 for (j=a;*j!='\0';j++) { append_to_name(*j); }
16003 for (j=n;*j!='\0';j++) { append_to_name(*j); }
16005 for (j=e;*j!='\0';j++) { append_to_name(*j); }
16007 mp->name_of_file[k]=0;
16011 @ @<Internal library declarations@>=
16012 void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e) ;
16014 @ @<Option variables@>=
16015 char *mem_name; /* for commandline */
16017 @ @<Find constant sizes@>=
16018 mp->mem_name = xstrdup(opt->mem_name);
16019 if (mp->mem_name) {
16020 size_t l = strlen(mp->mem_name);
16022 char *test = strstr(mp->mem_name,".mem");
16023 if (test == mp->mem_name+l-4) {
16030 @ @<Dealloc variables@>=
16031 xfree(mp->mem_name);
16033 @ This part of the program becomes active when a ``virgin'' \MP\ is
16034 trying to get going, just after the preliminary initialization, or
16035 when the user is substituting another mem file by typing `\.\&' after
16036 the initial `\.{**}' prompt. The buffer contains the first line of
16037 input in |buffer[loc..(last-1)]|, where |loc<last| and |buffer[loc]<>""|.
16040 static boolean mp_open_mem_name (MP mp) ;
16041 static boolean mp_open_mem_file (MP mp) ;
16044 boolean mp_open_mem_name (MP mp) {
16045 if (mp->mem_name!=NULL) {
16046 size_t l = strlen(mp->mem_name);
16047 char *s = xstrdup (mp->mem_name);
16049 char *test = strstr(s,".mem");
16050 if (test == NULL || test != s+l-4) {
16051 s = xrealloc (s, l+5, 1);
16052 strcat (s, ".mem");
16055 s = xrealloc (s, l+5, 1);
16056 strcat (s, ".mem");
16058 mp->mem_file = (mp->open_file)(mp,s, "r", mp_filetype_memfile);
16060 if ( mp->mem_file ) return true;
16064 boolean mp_open_mem_file (MP mp) {
16065 if (mp->mem_file != NULL)
16067 if (mp_open_mem_name(mp))
16069 if (mp_xstrcmp(mp->mem_name, "plain")) {
16071 wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
16072 @.Sorry, I can't find...@>
16074 /* now pull out all the stops: try for the system \.{plain} file */
16075 xfree(mp->mem_name);
16076 mp->mem_name = xstrdup("plain");
16077 if (mp_open_mem_name(mp))
16081 wterm_ln("I can\'t find the PLAIN mem file!");
16082 @.I can't find PLAIN...@>
16087 @ Operating systems often make it possible to determine the exact name (and
16088 possible version number) of a file that has been opened. The following routine,
16089 which simply makes a \MP\ string from the value of |name_of_file|, should
16090 ideally be changed to deduce the full name of file~|f|, which is the file
16091 most recently opened, if it is possible to do this.
16092 @^system dependencies@>
16095 #define mp_a_make_name_string(A,B) mp_make_name_string(A)
16096 #define mp_b_make_name_string(A,B) mp_make_name_string(A)
16097 #define mp_w_make_name_string(A,B) mp_make_name_string(A)
16100 static str_number mp_make_name_string (MP mp) {
16101 int k; /* index into |name_of_file| */
16102 str_room(mp->name_length);
16103 for (k=0;k<mp->name_length;k++) {
16104 append_char(xord((int)mp->name_of_file[k]));
16106 return mp_make_string(mp);
16109 @ Now let's consider the ``driver''
16110 routines by which \MP\ deals with file names
16111 in a system-independent manner. First comes a procedure that looks for a
16112 file name in the input by taking the information from the input buffer.
16113 (We can't use |get_next|, because the conversion to tokens would
16114 destroy necessary information.)
16116 This procedure doesn't allow semicolons or percent signs to be part of
16117 file names, because of other conventions of \MP.
16118 {\sl The {\logos METAFONT\/}book} doesn't
16119 use semicolons or percents immediately after file names, but some users
16120 no doubt will find it natural to do so; therefore system-dependent
16121 changes to allow such characters in file names should probably
16122 be made with reluctance, and only when an entire file name that
16123 includes special characters is ``quoted'' somehow.
16124 @^system dependencies@>
16127 static void mp_scan_file_name (MP mp) {
16129 while ( mp->buffer[loc]==' ' ) incr(loc);
16131 if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
16132 if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
16138 @ Here is another version that takes its input from a string.
16140 @<Declare subroutines for parsing file names@>=
16141 void mp_str_scan_file (MP mp, str_number s) ;
16144 void mp_str_scan_file (MP mp, str_number s) {
16145 pool_pointer p,q; /* current position and stopping point */
16147 p=mp->str_start[s]; q=str_stop(s);
16149 if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
16155 @ And one that reads from a |char*|.
16157 @<Declare subroutines for parsing file names@>=
16158 extern void mp_ptr_scan_file (MP mp, char *s);
16161 void mp_ptr_scan_file (MP mp, char *s) {
16162 char *p, *q; /* current position and stopping point */
16164 p=s; q=p+strlen(s);
16166 if ( ! mp_more_name(mp, xord((int)(*p)))) break;
16173 @ The global variable |job_name| contains the file name that was first
16174 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16175 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16178 boolean log_opened; /* has the transcript file been opened? */
16179 char *log_name; /* full name of the log file */
16181 @ @<Option variables@>=
16182 char *job_name; /* principal file name */
16184 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16185 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16186 except of course for a short time just after |job_name| has become nonzero.
16188 @<Allocate or ...@>=
16189 mp->job_name=mp_xstrdup(mp, opt->job_name);
16190 if (opt->noninteractive && opt->ini_version) {
16191 if (mp->job_name == NULL)
16192 mp->job_name=mp_xstrdup(mp,mp->mem_name);
16193 if (mp->job_name != NULL) {
16194 size_t l = strlen(mp->job_name);
16196 char *test = strstr(mp->job_name,".mem");
16197 if (test == mp->job_name+l-4)
16202 mp->log_opened=false;
16204 @ @<Dealloc variables@>=
16205 xfree(mp->job_name);
16207 @ Here is a routine that manufactures the output file names, assuming that
16208 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16211 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16213 @<Internal library ...@>=
16214 void mp_pack_job_name (MP mp, const char *s) ;
16217 void mp_pack_job_name (MP mp, const char *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16218 xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16219 xfree(mp->cur_area); mp->cur_area=xstrdup("");
16220 xfree(mp->cur_ext); mp->cur_ext=xstrdup(s);
16224 @ If some trouble arises when \MP\ tries to open a file, the following
16225 routine calls upon the user to supply another file name. Parameter~|s|
16226 is used in the error message to identify the type of file; parameter~|e|
16227 is the default extension if none is given. Upon exit from the routine,
16228 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16229 ready for another attempt at file opening.
16231 @<Internal library ...@>=
16232 void mp_prompt_file_name (MP mp, const char * s, const char * e) ;
16234 @ @c void mp_prompt_file_name (MP mp, const char * s, const char * e) {
16235 size_t k; /* index into |buffer| */
16236 char * saved_cur_name;
16237 if ( mp->interaction==mp_scroll_mode )
16239 if (strcmp(s,"input file name")==0) {
16240 print_err("I can\'t find file `");
16241 @.I can't find file x@>
16243 print_err("I can\'t write on file `");
16244 @.I can't write on file x@>
16246 mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext);
16247 mp_print(mp, "'.");
16248 if (strcmp(e,"")==0)
16249 mp_show_context(mp);
16250 mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16252 if (mp->noninteractive || mp->interaction<mp_scroll_mode )
16253 mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16254 @.job aborted, file error...@>
16255 saved_cur_name = xstrdup(mp->cur_name);
16256 clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16257 if (strcmp(mp->cur_ext,"")==0)
16258 mp->cur_ext=xstrdup(e);
16259 if (strlen(mp->cur_name)==0) {
16260 mp->cur_name=saved_cur_name;
16262 xfree(saved_cur_name);
16267 @ @<Scan file name in the buffer@>=
16269 mp_begin_name(mp); k=mp->first;
16270 while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16272 if ( k==mp->last ) break;
16273 if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16279 @ The |open_log_file| routine is used to open the transcript file and to help
16280 it catch up to what has previously been printed on the terminal.
16282 @c void mp_open_log_file (MP mp) {
16283 unsigned old_setting; /* previous |selector| setting */
16284 int k; /* index into |months| and |buffer| */
16285 int l; /* end of first input line */
16286 integer m; /* the current month */
16287 const char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
16288 /* abbreviations of month names */
16289 old_setting=mp->selector;
16290 if ( mp->job_name==NULL ) {
16291 mp->job_name=xstrdup("mpout");
16293 mp_pack_job_name(mp,".log");
16294 while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16295 @<Try to get a different log file name@>;
16297 mp->log_name=xstrdup(mp->name_of_file);
16298 mp->selector=log_only; mp->log_opened=true;
16299 @<Print the banner line, including the date and time@>;
16300 mp->input_stack[mp->input_ptr]=mp->cur_input;
16301 /* make sure bottom level is in memory */
16302 if (!mp->noninteractive) {
16303 mp_print_nl(mp, "**");
16305 l=mp->input_stack[0].limit_field-1; /* last position of first line */
16306 for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16307 mp_print_ln(mp); /* now the transcript file contains the first line of input */
16309 mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16312 @ @<Dealloc variables@>=
16313 xfree(mp->log_name);
16315 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16316 unable to print error messages or even to |show_context|.
16317 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16318 routine will not be invoked because |log_opened| will be false.
16320 The normal idea of |mp_batch_mode| is that nothing at all should be written
16321 on the terminal. However, in the unusual case that
16322 no log file could be opened, we make an exception and allow
16323 an explanatory message to be seen.
16325 Incidentally, the program always refers to the log file as a `\.{transcript
16326 file}', because some systems cannot use the extension `\.{.log}' for
16329 @<Try to get a different log file name@>=
16331 mp->selector=term_only;
16332 mp_prompt_file_name(mp, "transcript file name",".log");
16335 @ @<Print the banner...@>=
16338 mp_print(mp, mp->mem_ident); mp_print(mp, " ");
16339 mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day]));
16340 mp_print_char(mp, xord(' '));
16341 m=mp_round_unscaled(mp, mp->internal[mp_month]);
16342 for (k=3*m-3;k<3*m;k++) { wlog_chr((unsigned char)months[k]); }
16343 mp_print_char(mp, xord(' '));
16344 mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year]));
16345 mp_print_char(mp, xord(' '));
16346 m=mp_round_unscaled(mp, mp->internal[mp_time]);
16347 mp_print_dd(mp, m / 60); mp_print_char(mp, xord(':')); mp_print_dd(mp, m % 60);
16350 @ The |try_extension| function tries to open an input file determined by
16351 |cur_name|, |cur_area|, and the argument |ext|. It returns |false| if it
16352 can't find the file in |cur_area| or the appropriate system area.
16355 static boolean mp_try_extension (MP mp, const char *ext) {
16356 mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16357 in_name=xstrdup(mp->cur_name);
16358 in_area=xstrdup(mp->cur_area);
16359 if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16362 mp_pack_file_name(mp, mp->cur_name,NULL,ext);
16363 return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16367 @ Let's turn now to the procedure that is used to initiate file reading
16368 when an `\.{input}' command is being processed.
16370 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16371 char *fname = NULL;
16372 @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16374 mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16375 if ( strlen(mp->cur_ext)==0 ) {
16376 if ( mp_try_extension(mp, ".mp") ) break;
16377 else if ( mp_try_extension(mp, "") ) break;
16378 else if ( mp_try_extension(mp, ".mf") ) break;
16379 /* |else do_nothing; | */
16380 } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16383 mp_end_file_reading(mp); /* remove the level that didn't work */
16384 mp_prompt_file_name(mp, "input file name","");
16386 name=mp_a_make_name_string(mp, cur_file);
16387 fname = xstrdup(mp->name_of_file);
16388 if ( mp->job_name==NULL ) {
16389 mp->job_name=xstrdup(mp->cur_name);
16390 mp_open_log_file(mp);
16391 } /* |open_log_file| doesn't |show_context|, so |limit|
16392 and |loc| needn't be set to meaningful values yet */
16393 if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16394 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, xord(' '));
16395 mp_print_char(mp, xord('(')); incr(mp->open_parens); mp_print(mp, fname);
16398 @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16399 @<Read the first line of the new file@>;
16402 @ This code should be omitted if |a_make_name_string| returns something other
16403 than just a copy of its argument and the full file name is needed for opening
16404 \.{MPX} files or implementing the switch-to-editor option.
16405 @^system dependencies@>
16407 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16408 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16410 @ If the file is empty, it is considered to contain a single blank line,
16411 so there is no need to test the return value.
16413 @<Read the first line...@>=
16416 (void)mp_input_ln(mp, cur_file );
16417 mp_firm_up_the_line(mp);
16418 mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start;
16421 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16422 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16423 if ( token_state ) {
16424 print_err("File names can't appear within macros");
16425 @.File names can't...@>
16426 help3("Sorry...I've converted what follows to tokens,",
16427 "possibly garbaging the name you gave.",
16428 "Please delete the tokens and insert the name again.");
16431 if ( file_state ) {
16432 mp_scan_file_name(mp);
16434 xfree(mp->cur_name); mp->cur_name=xstrdup("");
16435 xfree(mp->cur_ext); mp->cur_ext =xstrdup("");
16436 xfree(mp->cur_area); mp->cur_area=xstrdup("");
16439 @ The following simple routine starts reading the \.{MPX} file associated
16440 with the current input file.
16442 @c void mp_start_mpx_input (MP mp) {
16443 char *origname = NULL; /* a copy of nameoffile */
16444 mp_pack_file_name(mp, in_name, in_area, ".mpx");
16445 @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16446 |goto not_found| if there is a problem@>;
16447 mp_begin_file_reading(mp);
16448 if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16449 mp_end_file_reading(mp);
16452 name=mp_a_make_name_string(mp, cur_file);
16453 mp->mpx_name[iindex]=name; add_str_ref(name);
16454 @<Read the first line of the new file@>;
16458 @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16462 @ This should ideally be changed to do whatever is necessary to create the
16463 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16464 of date. This requires invoking \.{MPtoTeX} on the |origname| and passing
16465 the results through \TeX\ and \.{DVItoMP}. (It is possible to use a
16466 completely different typesetting program if suitable postprocessor is
16467 available to perform the function of \.{DVItoMP}.)
16468 @^system dependencies@>
16470 @ @<Exported types@>=
16471 typedef int (*mp_makempx_cmd)(MP mp, char *origname, char *mtxname);
16473 @ @<Option variables@>=
16474 mp_makempx_cmd run_make_mpx;
16476 @ @<Allocate or initialize ...@>=
16477 set_callback_option(run_make_mpx);
16479 @ @<Declarations@>=
16480 static int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16482 @ The default does nothing.
16484 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16491 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16492 |goto not_found| if there is a problem@>=
16493 origname = mp_xstrdup(mp,mp->name_of_file);
16494 *(origname+strlen(origname)-1)=0; /* drop the x */
16495 if (!(mp->run_make_mpx)(mp, origname, mp->name_of_file))
16498 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16499 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16500 mp_print_nl(mp, ">> ");
16501 mp_print(mp, origname);
16502 mp_print_nl(mp, ">> ");
16503 mp_print(mp, mp->name_of_file);
16504 mp_print_nl(mp, "! Unable to make mpx file");
16505 help4("The two files given above are one of your source files",
16506 "and an auxiliary file I need to read to find out what your",
16507 "btex..etex blocks mean. If you don't know why I had trouble,",
16508 "try running it manually through MPtoTeX, TeX, and DVItoMP");
16511 @ The last file-opening commands are for files accessed via the \&{readfrom}
16512 @:read_from_}{\&{readfrom} primitive@>
16513 operator and the \&{write} command. Such files are stored in separate arrays.
16514 @:write_}{\&{write} primitive@>
16516 @<Types in the outer block@>=
16517 typedef unsigned int readf_index; /* |0..max_read_files| */
16518 typedef unsigned int write_index; /* |0..max_write_files| */
16521 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16522 void ** rd_file; /* \&{readfrom} files */
16523 char ** rd_fname; /* corresponding file name or 0 if file not open */
16524 readf_index read_files; /* number of valid entries in the above arrays */
16525 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16526 void ** wr_file; /* \&{write} files */
16527 char ** wr_fname; /* corresponding file name or 0 if file not open */
16528 write_index write_files; /* number of valid entries in the above arrays */
16530 @ @<Allocate or initialize ...@>=
16531 mp->max_read_files=8;
16532 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(void *));
16533 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16534 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16535 mp->max_write_files=8;
16536 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(void *));
16537 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16538 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16541 @ This routine starts reading the file named by string~|s| without setting
16542 |loc|, |limit|, or |name|. It returns |false| if the file is empty or cannot
16543 be opened. Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16546 static boolean mp_start_read_input (MP mp,char *s, readf_index n) {
16547 mp_ptr_scan_file(mp, s);
16549 mp_begin_file_reading(mp);
16550 if ( ! mp_a_open_in(mp, &mp->rd_file[n], (int)(mp_filetype_text+n)) )
16552 if ( ! mp_input_ln(mp, mp->rd_file[n] ) ) {
16553 (mp->close_file)(mp,mp->rd_file[n]);
16556 mp->rd_fname[n]=xstrdup(s);
16559 mp_end_file_reading(mp);
16563 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16566 static void mp_open_write_file (MP mp, char *s, readf_index n) ;
16568 @ @c void mp_open_write_file (MP mp,char *s, readf_index n) {
16569 mp_ptr_scan_file(mp, s);
16571 while ( ! mp_a_open_out(mp, &mp->wr_file[n], (int)(mp_filetype_text+n)) )
16572 mp_prompt_file_name(mp, "file name for write output","");
16573 mp->wr_fname[n]=xstrdup(s);
16577 @* \[36] Introduction to the parsing routines.
16578 We come now to the central nervous system that sparks many of \MP's activities.
16579 By evaluating expressions, from their primary constituents to ever larger
16580 subexpressions, \MP\ builds the structures that ultimately define complete
16581 pictures or fonts of type.
16583 Four mutually recursive subroutines are involved in this process: We call them
16584 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16585 and |scan_expression|.}$$
16587 Each of them is parameterless and begins with the first token to be scanned
16588 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16589 the value of the primary or secondary or tertiary or expression that was
16590 found will appear in the global variables |cur_type| and |cur_exp|. The
16591 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16594 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16595 backup mechanisms have been added in order to provide reasonable error
16599 quarterword cur_type; /* the type of the expression just found */
16600 integer cur_exp; /* the value of the expression just found */
16605 @ Many different kinds of expressions are possible, so it is wise to have
16606 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16609 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16610 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16611 construction in which there was no expression before the \&{endgroup}.
16612 In this case |cur_exp| has some irrelevant value.
16615 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16619 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16621 a ring of equivalent booleans whose value has not yet been defined.
16624 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16625 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16626 includes this particular reference.
16629 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16631 a ring of equivalent strings whose value has not yet been defined.
16634 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen. Nobody
16635 else points to any of the nodes in this pen. The pen may be polygonal or
16639 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16641 a ring of equivalent pens whose value has not yet been defined.
16644 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16645 a path; nobody else points to this particular path. The control points of
16646 the path will have been chosen.
16649 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16651 a ring of equivalent paths whose value has not yet been defined.
16654 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16655 There may be other pointers to this particular set of edges. The header node
16656 contains a reference count that includes this particular reference.
16659 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16661 a ring of equivalent pictures whose value has not yet been defined.
16664 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16665 capsule node. The |value| part of this capsule
16666 points to a transform node that contains six numeric values,
16667 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16670 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16671 capsule node. The |value| part of this capsule
16672 points to a color node that contains three numeric values,
16673 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16676 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16677 capsule node. The |value| part of this capsule
16678 points to a color node that contains four numeric values,
16679 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16682 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16683 node whose type is |mp_pair_type|. The |value| part of this capsule
16684 points to a pair node that contains two numeric values,
16685 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16688 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16691 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16692 is |dependent|. The |dep_list| field in this capsule points to the associated
16696 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16697 capsule node. The |dep_list| field in this capsule
16698 points to the associated dependency list.
16701 |cur_type=independent| means that |cur_exp| points to a capsule node
16702 whose type is |independent|. This somewhat unusual case can arise, for
16703 example, in the expression
16704 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16707 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16710 \smallskip\noindent
16711 The possible settings of |cur_type| have been listed here in increasing
16712 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16713 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16714 are allowed. Conversely, \MP\ has no variables of type |mp_vacuous| or
16717 @ Capsules are two-word nodes that have a similar meaning
16718 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|,
16719 and their |type| field is one of the possibilities for |cur_type| listed above.
16720 Also |link<=void| in capsules that aren't part of a token list.
16722 The |value| field of a capsule is, in most cases, the value that
16723 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16724 However, when |cur_exp| would point to a capsule,
16725 no extra layer of indirection is present; the |value|
16726 field is what would have been called |value(cur_exp)| if it had not been
16727 encapsulated. Furthermore, if the type is |dependent| or
16728 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16729 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16730 always part of the general |dep_list| structure.
16732 The |get_x_next| routine is careful not to change the values of |cur_type|
16733 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16734 call a macro, which might parse an expression, which might execute lots of
16735 commands in a group; hence it's possible that |cur_type| might change
16736 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16737 |known| or |independent|, during the time |get_x_next| is called. The
16738 programs below are careful to stash sensitive intermediate results in
16739 capsules, so that \MP's generality doesn't cause trouble.
16741 Here's a procedure that illustrates these conventions. It takes
16742 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16743 and stashes them away in a
16744 capsule. It is not used when |cur_type=mp_token_list|.
16745 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16746 copy path lists or to update reference counts, etc.
16748 The special link |mp_void| is put on the capsule returned by
16749 |stash_cur_exp|, because this procedure is used to store macro parameters
16750 that must be easily distinguishable from token lists.
16752 @<Declare the stashing/unstashing routines@>=
16753 static pointer mp_stash_cur_exp (MP mp) {
16754 pointer p; /* the capsule that will be returned */
16755 switch (mp->cur_type) {
16756 case unknown_types:
16757 case mp_transform_type:
16758 case mp_color_type:
16761 case mp_proto_dependent:
16762 case mp_independent:
16763 case mp_cmykcolor_type:
16767 p=mp_get_node(mp, value_node_size); mp_name_type(p)=mp_capsule;
16768 mp_type(p)=mp->cur_type; value(p)=mp->cur_exp;
16771 mp->cur_type=mp_vacuous; mp_link(p)=mp_void;
16775 @ The inverse of |stash_cur_exp| is the following procedure, which
16776 deletes an unnecessary capsule and puts its contents into |cur_type|
16779 The program steps of \MP\ can be divided into two categories: those in
16780 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16781 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16782 information or not. It's important not to ignore them when they're alive,
16783 and it's important not to pay attention to them when they're dead.
16785 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16786 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16787 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16788 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16789 only when they are alive or dormant.
16791 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16792 are alive or dormant. The \\{unstash} procedure assumes that they are
16793 dead or dormant; it resuscitates them.
16795 @<Declare the stashing/unstashing...@>=
16796 static void mp_unstash_cur_exp (MP mp,pointer p) ;
16799 void mp_unstash_cur_exp (MP mp,pointer p) {
16800 mp->cur_type=mp_type(p);
16801 switch (mp->cur_type) {
16802 case unknown_types:
16803 case mp_transform_type:
16804 case mp_color_type:
16807 case mp_proto_dependent:
16808 case mp_independent:
16809 case mp_cmykcolor_type:
16813 mp->cur_exp=value(p);
16814 mp_free_node(mp, p,value_node_size);
16819 @ The following procedure prints the values of expressions in an
16820 abbreviated format. If its first parameter |p| is null, the value of
16821 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16822 containing the desired value. The second parameter controls the amount of
16823 output. If it is~0, dependency lists will be abbreviated to
16824 `\.{linearform}' unless they consist of a single term. If it is greater
16825 than~1, complicated structures (pens, pictures, and paths) will be displayed
16830 @<Declare the procedure called |print_dp|@>
16831 @<Declare the stashing/unstashing routines@>
16832 static void mp_print_exp (MP mp,pointer p, quarterword verbosity) ;
16835 void mp_print_exp (MP mp,pointer p, quarterword verbosity) {
16836 boolean restore_cur_exp; /* should |cur_exp| be restored? */
16837 quarterword t; /* the type of the expression */
16838 pointer q; /* a big node being displayed */
16839 integer v=0; /* the value of the expression */
16841 restore_cur_exp=false;
16843 p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16846 if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16847 @<Print an abbreviated value of |v| with format depending on |t|@>;
16848 if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16851 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16853 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16854 case mp_boolean_type:
16855 if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16857 case unknown_types: case mp_numeric_type:
16858 @<Display a variable that's been declared but not defined@>;
16860 case mp_string_type:
16861 mp_print_char(mp, xord('"')); mp_print_str(mp, v); mp_print_char(mp, xord('"'));
16863 case mp_pen_type: case mp_path_type: case mp_picture_type:
16864 @<Display a complex type@>;
16866 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16867 if ( v==null ) mp_print_type(mp, t);
16868 else @<Display a big node@>;
16870 case mp_known:mp_print_scaled(mp, v); break;
16871 case mp_dependent: case mp_proto_dependent:
16872 mp_print_dp(mp, t,v,verbosity);
16874 case mp_independent:mp_print_variable_name(mp, p); break;
16875 default: mp_confusion(mp, "exp"); break;
16876 @:this can't happen exp}{\quad exp@>
16879 @ @<Display a big node@>=
16881 mp_print_char(mp, xord('(')); q=v+mp->big_node_size[t];
16883 if ( mp_type(v)==mp_known ) mp_print_scaled(mp, value(v));
16884 else if ( mp_type(v)==mp_independent ) mp_print_variable_name(mp, v);
16885 else mp_print_dp(mp, mp_type(v),dep_list(v),verbosity);
16887 if ( v!=q ) mp_print_char(mp, xord(','));
16889 mp_print_char(mp, xord(')'));
16892 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16893 in the log file only, unless the user has given a positive value to
16896 @<Display a complex type@>=
16897 if ( verbosity<=1 ) {
16898 mp_print_type(mp, t);
16900 if ( mp->selector==term_and_log )
16901 if ( mp->internal[mp_tracing_online]<=0 ) {
16902 mp->selector=term_only;
16903 mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16904 mp->selector=term_and_log;
16907 case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16908 case mp_path_type:mp_print_path(mp, v,"",false); break;
16909 case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16910 } /* there are no other cases */
16913 @ @<Declare the procedure called |print_dp|@>=
16914 static void mp_print_dp (MP mp, quarterword t, pointer p,
16915 quarterword verbosity) {
16916 pointer q; /* the node following |p| */
16918 if ( (mp_info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16919 else mp_print(mp, "linearform");
16922 @ The displayed name of a variable in a ring will not be a capsule unless
16923 the ring consists entirely of capsules.
16925 @<Display a variable that's been declared but not defined@>=
16926 { mp_print_type(mp, t);
16928 { mp_print_char(mp, xord(' '));
16929 while ( (mp_name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16930 mp_print_variable_name(mp, v);
16934 @ When errors are detected during parsing, it is often helpful to
16935 display an expression just above the error message, using |exp_err|
16936 or |disp_err| instead of |print_err|.
16938 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16941 static void mp_disp_err (MP mp,pointer p, const char *s) ;
16944 void mp_disp_err (MP mp,pointer p, const char *s) {
16945 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16946 mp_print_nl(mp, ">> ");
16948 mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16950 mp_print_nl(mp, "! "); mp_print(mp, s);
16955 @ If |cur_type| and |cur_exp| contain relevant information that should
16956 be recycled, we will use the following procedure, which changes |cur_type|
16957 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16958 and |cur_exp| as either alive or dormant after this has been done,
16959 because |cur_exp| will not contain a pointer value.
16962 static void mp_flush_cur_exp (MP mp,scaled v) {
16963 switch (mp->cur_type) {
16964 case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16965 case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16966 mp_recycle_value(mp, mp->cur_exp);
16967 mp_free_node(mp, mp->cur_exp,value_node_size);
16969 case mp_string_type:
16970 delete_str_ref(mp->cur_exp); break;
16971 case mp_pen_type: case mp_path_type:
16972 mp_toss_knot_list(mp, mp->cur_exp); break;
16973 case mp_picture_type:
16974 delete_edge_ref(mp->cur_exp); break;
16978 mp->cur_type=mp_known; mp->cur_exp=v;
16981 @ There's a much more general procedure that is capable of releasing
16982 the storage associated with any two-word value packet.
16985 static void mp_recycle_value (MP mp,pointer p) ;
16988 static void mp_recycle_value (MP mp,pointer p) {
16989 quarterword t; /* a type code */
16990 integer vv; /* another value */
16991 pointer q,r,s,pp; /* link manipulation registers */
16992 integer v=0; /* a value */
16994 if ( t<mp_dependent ) v=value(p);
16996 case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16997 case mp_numeric_type:
16999 case unknown_types:
17000 mp_ring_delete(mp, p); break;
17001 case mp_string_type:
17002 delete_str_ref(v); break;
17003 case mp_path_type: case mp_pen_type:
17004 mp_toss_knot_list(mp, v); break;
17005 case mp_picture_type:
17006 delete_edge_ref(v); break;
17007 case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
17008 case mp_transform_type:
17009 @<Recycle a big node@>; break;
17010 case mp_dependent: case mp_proto_dependent:
17011 @<Recycle a dependency list@>; break;
17012 case mp_independent:
17013 @<Recycle an independent variable@>; break;
17014 case mp_token_list: case mp_structured:
17015 mp_confusion(mp, "recycle"); break;
17016 @:this can't happen recycle}{\quad recycle@>
17017 case mp_unsuffixed_macro: case mp_suffixed_macro:
17018 mp_delete_mac_ref(mp, value(p)); break;
17019 } /* there are no other cases */
17020 mp_type(p)=undefined;
17023 @ @<Recycle a big node@>=
17025 q=v+mp->big_node_size[t];
17027 q=q-2; mp_recycle_value(mp, q);
17029 mp_free_node(mp, v,mp->big_node_size[t]);
17032 @ @<Recycle a dependency list@>=
17035 while ( mp_info(q)!=null ) q=mp_link(q);
17036 mp_link(prev_dep(p))=mp_link(q);
17037 prev_dep(mp_link(q))=prev_dep(p);
17038 mp_link(q)=null; mp_flush_node_list(mp, dep_list(p));
17041 @ When an independent variable disappears, it simply fades away, unless
17042 something depends on it. In the latter case, a dependent variable whose
17043 coefficient of dependence is maximal will take its place.
17044 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
17045 as part of his Ph.D. thesis (Stanford University, December 1982).
17046 @^Zabala Salelles, Ignacio Andr\'es@>
17048 For example, suppose that variable $x$ is being recycled, and that the
17049 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
17050 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
17051 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
17052 we will print `\.{\#\#\# -2x=-y+a}'.
17054 There's a slight complication, however: An independent variable $x$
17055 can occur both in dependency lists and in proto-dependency lists.
17056 This makes it necessary to be careful when deciding which coefficient
17059 Furthermore, this complication is not so slight when
17060 a proto-dependent variable is chosen to become independent. For example,
17061 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
17062 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
17063 large coefficient `50'.
17065 In order to deal with these complications without wasting too much time,
17066 we shall link together the occurrences of~$x$ among all the linear
17067 dependencies, maintaining separate lists for the dependent and
17068 proto-dependent cases.
17070 @<Recycle an independent variable@>=
17072 mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
17073 mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
17074 q=mp_link(dep_head);
17075 while ( q!=dep_head ) {
17076 s=value_loc(q); /* now |mp_link(s)=dep_list(q)| */
17079 if ( mp_info(r)==null ) break;
17080 if ( mp_info(r)!=p ) {
17083 t=mp_type(q); mp_link(s)=mp_link(r); mp_info(r)=q;
17084 if ( abs(value(r))>mp->max_c[t] ) {
17085 @<Record a new maximum coefficient of type |t|@>;
17087 mp_link(r)=mp->max_link[t]; mp->max_link[t]=r;
17093 if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
17094 @<Choose a dependent variable to take the place of the disappearing
17095 independent variable, and change all remaining dependencies
17100 @ The code for independency removal makes use of three two-word arrays.
17103 integer max_c[mp_proto_dependent+1]; /* max coefficient magnitude */
17104 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
17105 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
17107 @ @<Record a new maximum coefficient...@>=
17109 if ( mp->max_c[t]>0 ) {
17110 mp_link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17112 mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
17115 @ @<Choose a dependent...@>=
17117 if ( (mp->max_c[mp_dependent] / 010000) >= mp->max_c[mp_proto_dependent] )
17120 t=mp_proto_dependent;
17121 @<Determine the dependency list |s| to substitute for the independent
17123 t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
17124 if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */
17125 mp_link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17127 if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
17128 else { @<Substitute new proto-dependencies in place of |p|@>;}
17129 mp_flush_node_list(mp, s);
17130 if ( mp->fix_needed ) mp_fix_dependencies(mp);
17134 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
17135 and |mp_info(s)| points to the dependent variable~|pp| of type~|t| from
17136 whose dependency list we have removed node~|s|. We must reinsert
17137 node~|s| into the dependency list, with coefficient $-1.0$, and with
17138 |pp| as the new independent variable. Since |pp| will have a larger serial
17139 number than any other variable, we can put node |s| at the head of the
17142 @<Determine the dep...@>=
17143 s=mp->max_ptr[t]; pp=mp_info(s); v=value(s);
17144 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
17145 r=dep_list(pp); mp_link(s)=r;
17146 while ( mp_info(r)!=null ) r=mp_link(r);
17147 q=mp_link(r); mp_link(r)=null;
17148 prev_dep(q)=prev_dep(pp); mp_link(prev_dep(pp))=q;
17150 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
17151 if ( mp->internal[mp_tracing_equations]>0 ) {
17152 @<Show the transformed dependency@>;
17155 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
17156 by the dependency list~|s|.
17158 @<Show the transformed...@>=
17159 if ( mp_interesting(mp, p) ) {
17160 mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
17161 @:]]]\#\#\#_}{\.{\#\#\#}@>
17162 if ( v>0 ) mp_print_char(mp, xord('-'));
17163 if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
17164 else vv=mp->max_c[mp_proto_dependent];
17165 if ( vv!=unity ) mp_print_scaled(mp, vv);
17166 mp_print_variable_name(mp, p);
17167 while ( value(p) % s_scale>0 ) {
17168 mp_print(mp, "*4"); value(p)=value(p)-2;
17170 if ( t==mp_dependent ) mp_print_char(mp, xord('=')); else mp_print(mp, " = ");
17171 mp_print_dependency(mp, s,t);
17172 mp_end_diagnostic(mp, false);
17175 @ Finally, there are dependent and proto-dependent variables whose
17176 dependency lists must be brought up to date.
17178 @<Substitute new dependencies...@>=
17179 for (t=mp_dependent;t<=mp_proto_dependent;t++){
17181 while ( r!=null ) {
17183 dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17184 mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
17185 if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17186 q=r; r=mp_link(r); mp_free_node(mp, q,dep_node_size);
17190 @ @<Substitute new proto...@>=
17191 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17193 while ( r!=null ) {
17195 if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17196 if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17197 mp->cur_type=mp_proto_dependent;
17198 dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,
17199 mp_dependent,mp_proto_dependent);
17200 mp_type(q)=mp_proto_dependent;
17201 value(r)=mp_round_fraction(mp, value(r));
17203 dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17204 mp_make_scaled(mp, value(r),-v),s,
17205 mp_proto_dependent,mp_proto_dependent);
17206 if ( dep_list(q)==mp->dep_final )
17207 mp_make_known(mp, q,mp->dep_final);
17208 q=r; r=mp_link(r); mp_free_node(mp, q,dep_node_size);
17212 @ Here are some routines that provide handy combinations of actions
17213 that are often needed during error recovery. For example,
17214 `|flush_error|' flushes the current expression, replaces it by
17215 a given value, and calls |error|.
17217 Errors often are detected after an extra token has already been scanned.
17218 The `\\{put\_get}' routines put that token back before calling |error|;
17219 then they get it back again. (Or perhaps they get another token, if
17220 the user has changed things.)
17223 static void mp_flush_error (MP mp,scaled v);
17224 static void mp_put_get_error (MP mp);
17225 static void mp_put_get_flush_error (MP mp,scaled v) ;
17228 void mp_flush_error (MP mp,scaled v) {
17229 mp_error(mp); mp_flush_cur_exp(mp, v);
17231 void mp_put_get_error (MP mp) {
17232 mp_back_error(mp); mp_get_x_next(mp);
17234 void mp_put_get_flush_error (MP mp,scaled v) {
17235 mp_put_get_error(mp);
17236 mp_flush_cur_exp(mp, v);
17239 @ A global variable |var_flag| is set to a special command code
17240 just before \MP\ calls |scan_expression|, if the expression should be
17241 treated as a variable when this command code immediately follows. For
17242 example, |var_flag| is set to |assignment| at the beginning of a
17243 statement, because we want to know the {\sl location\/} of a variable at
17244 the left of `\.{:=}', not the {\sl value\/} of that variable.
17246 The |scan_expression| subroutine calls |scan_tertiary|,
17247 which calls |scan_secondary|, which calls |scan_primary|, which sets
17248 |var_flag:=0|. In this way each of the scanning routines ``knows''
17249 when it has been called with a special |var_flag|, but |var_flag| is
17252 A variable preceding a command that equals |var_flag| is converted to a
17253 token list rather than a value. Furthermore, an `\.{=}' sign following an
17254 expression with |var_flag=assignment| is not considered to be a relation
17255 that produces boolean expressions.
17259 int var_flag; /* command that wants a variable */
17264 @* \[37] Parsing primary expressions.
17265 The first parsing routine, |scan_primary|, is also the most complicated one,
17266 since it involves so many different cases. But each case---with one
17267 exception---is fairly simple by itself.
17269 When |scan_primary| begins, the first token of the primary to be scanned
17270 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17271 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17272 earlier. If |cur_cmd| is not between |min_primary_command| and
17273 |max_primary_command|, inclusive, a syntax error will be signaled.
17275 @<Declare the basic parsing subroutines@>=
17276 void mp_scan_primary (MP mp) {
17277 pointer p,q,r; /* for list manipulation */
17278 quarterword c; /* a primitive operation code */
17279 int my_var_flag; /* initial value of |my_var_flag| */
17280 pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17281 @<Other local variables for |scan_primary|@>;
17282 my_var_flag=mp->var_flag; mp->var_flag=0;
17285 @<Supply diagnostic information, if requested@>;
17286 switch (mp->cur_cmd) {
17287 case left_delimiter:
17288 @<Scan a delimited primary@>; break;
17290 @<Scan a grouped primary@>; break;
17292 @<Scan a string constant@>; break;
17293 case numeric_token:
17294 @<Scan a primary that starts with a numeric token@>; break;
17296 @<Scan a nullary operation@>; break;
17297 case unary: case type_name: case cycle: case plus_or_minus:
17298 @<Scan a unary operation@>; break;
17299 case primary_binary:
17300 @<Scan a binary operation with `\&{of}' between its operands@>; break;
17302 @<Convert a suffix to a string@>; break;
17303 case internal_quantity:
17304 @<Scan an internal numeric quantity@>; break;
17305 case capsule_token:
17306 mp_make_exp_copy(mp, mp->cur_mod); break;
17308 @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17310 mp_bad_exp(mp, "A primary"); goto RESTART; break;
17311 @.A primary expression...@>
17313 mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17315 if ( mp->cur_cmd==left_bracket ) {
17316 if ( mp->cur_type>=mp_known ) {
17317 @<Scan a mediation construction@>;
17324 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17327 static void mp_bad_exp (MP mp, const char * s) {
17329 print_err(s); mp_print(mp, " expression can't begin with `");
17330 mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
17331 mp_print_char(mp, xord('\''));
17332 help4("I'm afraid I need some sort of value in order to continue,",
17333 "so I've tentatively inserted `0'. You may want to",
17334 "delete this zero and insert something else;",
17335 "see Chapter 27 of The METAFONTbook for an example.");
17336 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17337 mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token;
17338 mp->cur_mod=0; mp_ins_error(mp);
17339 save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17340 mp->var_flag=save_flag;
17343 @ @<Supply diagnostic information, if requested@>=
17345 if ( mp->panicking ) mp_check_mem(mp, false);
17347 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17348 mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17351 @ @<Scan a delimited primary@>=
17353 l_delim=mp->cur_sym; r_delim=mp->cur_mod;
17354 mp_get_x_next(mp); mp_scan_expression(mp);
17355 if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17356 @<Scan the rest of a delimited set of numerics@>;
17358 mp_check_delimiter(mp, l_delim,r_delim);
17362 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17363 within a ``big node.''
17366 static void mp_stash_in (MP mp,pointer p) {
17367 pointer q; /* temporary register */
17368 mp_type(p)=mp->cur_type;
17369 if ( mp->cur_type==mp_known ) {
17370 value(p)=mp->cur_exp;
17372 if ( mp->cur_type==mp_independent ) {
17373 @<Stash an independent |cur_exp| into a big node@>;
17375 mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17376 /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17377 mp_link(prev_dep(p))=p;
17379 mp_free_node(mp, mp->cur_exp,value_node_size);
17381 mp->cur_type=mp_vacuous;
17384 @ In rare cases the current expression can become |independent|. There
17385 may be many dependency lists pointing to such an independent capsule,
17386 so we can't simply move it into place within a big node. Instead,
17387 we copy it, then recycle it.
17389 @ @<Stash an independent |cur_exp|...@>=
17391 q=mp_single_dependency(mp, mp->cur_exp);
17392 if ( q==mp->dep_final ){
17393 mp_type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17395 mp_type(p)=mp_dependent; mp_new_dep(mp, p,q);
17397 mp_recycle_value(mp, mp->cur_exp);
17400 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17401 are synonymous with |x_part_loc| and |y_part_loc|.
17403 @<Scan the rest of a delimited set of numerics@>=
17405 p=mp_stash_cur_exp(mp);
17406 mp_get_x_next(mp); mp_scan_expression(mp);
17407 @<Make sure the second part of a pair or color has a numeric type@>;
17408 q=mp_get_node(mp, value_node_size); mp_name_type(q)=mp_capsule;
17409 if ( mp->cur_cmd==comma ) mp_type(q)=mp_color_type;
17410 else mp_type(q)=mp_pair_type;
17411 mp_init_big_node(mp, q); r=value(q);
17412 mp_stash_in(mp, y_part_loc(r));
17413 mp_unstash_cur_exp(mp, p);
17414 mp_stash_in(mp, x_part_loc(r));
17415 if ( mp->cur_cmd==comma ) {
17416 @<Scan the last of a triplet of numerics@>;
17418 if ( mp->cur_cmd==comma ) {
17419 mp_type(q)=mp_cmykcolor_type;
17420 mp_init_big_node(mp, q); t=value(q);
17421 mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17422 value(cyan_part_loc(t))=value(red_part_loc(r));
17423 mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17424 value(magenta_part_loc(t))=value(green_part_loc(r));
17425 mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17426 value(yellow_part_loc(t))=value(blue_part_loc(r));
17427 mp_recycle_value(mp, r);
17429 @<Scan the last of a quartet of numerics@>;
17431 mp_check_delimiter(mp, l_delim,r_delim);
17432 mp->cur_type=mp_type(q);
17436 @ @<Make sure the second part of a pair or color has a numeric type@>=
17437 if ( mp->cur_type<mp_known ) {
17438 exp_err("Nonnumeric ypart has been replaced by 0");
17439 @.Nonnumeric...replaced by 0@>
17440 help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';",
17441 "but after finding a nice `a' I found a `b' that isn't",
17442 "of numeric type. So I've changed that part to zero.",
17443 "(The b that I didn't like appears above the error message.)");
17444 mp_put_get_flush_error(mp, 0);
17447 @ @<Scan the last of a triplet of numerics@>=
17449 mp_get_x_next(mp); mp_scan_expression(mp);
17450 if ( mp->cur_type<mp_known ) {
17451 exp_err("Nonnumeric third part has been replaced by 0");
17452 @.Nonnumeric...replaced by 0@>
17453 help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'",
17454 "isn't of numeric type. So I've changed that part to zero.",
17455 "(The c that I didn't like appears above the error message.)");
17456 mp_put_get_flush_error(mp, 0);
17458 mp_stash_in(mp, blue_part_loc(r));
17461 @ @<Scan the last of a quartet of numerics@>=
17463 mp_get_x_next(mp); mp_scan_expression(mp);
17464 if ( mp->cur_type<mp_known ) {
17465 exp_err("Nonnumeric blackpart has been replaced by 0");
17466 @.Nonnumeric...replaced by 0@>
17467 help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't",
17468 "of numeric type. So I've changed that part to zero.",
17469 "(The k that I didn't like appears above the error message.)");
17470 mp_put_get_flush_error(mp, 0);
17472 mp_stash_in(mp, black_part_loc(r));
17475 @ The local variable |group_line| keeps track of the line
17476 where a \&{begingroup} command occurred; this will be useful
17477 in an error message if the group doesn't actually end.
17479 @<Other local variables for |scan_primary|@>=
17480 integer group_line; /* where a group began */
17482 @ @<Scan a grouped primary@>=
17484 group_line=mp_true_line(mp);
17485 if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17486 save_boundary_item(p);
17488 mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17489 } while (mp->cur_cmd==semicolon);
17490 if ( mp->cur_cmd!=end_group ) {
17491 print_err("A group begun on line ");
17492 @.A group...never ended@>
17493 mp_print_int(mp, group_line);
17494 mp_print(mp, " never ended");
17495 help2("I saw a `begingroup' back there that hasn't been matched",
17496 "by `endgroup'. So I've inserted `endgroup' now.");
17497 mp_back_error(mp); mp->cur_cmd=end_group;
17500 /* this might change |cur_type|, if independent variables are recycled */
17501 if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17504 @ @<Scan a string constant@>=
17506 mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17509 @ Later we'll come to procedures that perform actual operations like
17510 addition, square root, and so on; our purpose now is to do the parsing.
17511 But we might as well mention those future procedures now, so that the
17512 suspense won't be too bad:
17515 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17516 `\&{true}' or `\&{pencircle}');
17519 |do_unary(c)| applies a primitive operation to the current expression;
17522 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17523 and the current expression.
17525 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17527 @ @<Scan a unary operation@>=
17529 c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp);
17530 mp_do_unary(mp, c); goto DONE;
17533 @ A numeric token might be a primary by itself, or it might be the
17534 numerator of a fraction composed solely of numeric tokens, or it might
17535 multiply the primary that follows (provided that the primary doesn't begin
17536 with a plus sign or a minus sign). The code here uses the facts that
17537 |max_primary_command=plus_or_minus| and
17538 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17539 than unity, we try to retain higher precision when we use it in scalar
17542 @<Other local variables for |scan_primary|@>=
17543 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17545 @ @<Scan a primary that starts with a numeric token@>=
17547 mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17548 if ( mp->cur_cmd!=slash ) {
17552 if ( mp->cur_cmd!=numeric_token ) {
17554 mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17557 num=mp->cur_exp; denom=mp->cur_mod;
17558 if ( denom==0 ) { @<Protest division by zero@>; }
17559 else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17560 check_arith; mp_get_x_next(mp);
17562 if ( mp->cur_cmd>=min_primary_command ) {
17563 if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17564 p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17565 if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17566 mp_do_binary(mp, p,times);
17568 mp_frac_mult(mp, num,denom);
17569 mp_free_node(mp, p,value_node_size);
17576 @ @<Protest division...@>=
17578 print_err("Division by zero");
17579 @.Division by zero@>
17580 help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17583 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17585 c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17586 if ( mp->cur_cmd!=of_token ) {
17587 mp_missing_err(mp, "of"); mp_print(mp, " for ");
17588 mp_print_cmd_mod(mp, primary_binary,c);
17590 help1("I've got the first argument; will look now for the other.");
17593 p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp);
17594 mp_do_binary(mp, p,c); goto DONE;
17597 @ @<Convert a suffix to a string@>=
17599 mp_get_x_next(mp); mp_scan_suffix(mp);
17600 mp->old_setting=mp->selector; mp->selector=new_string;
17601 mp_show_token_list(mp, mp->cur_exp,null,100000,0);
17602 mp_flush_token_list(mp, mp->cur_exp);
17603 mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting;
17604 mp->cur_type=mp_string_type;
17608 @ If an internal quantity appears all by itself on the left of an
17609 assignment, we return a token list of length one, containing the address
17610 of the internal quantity plus |hash_end|. (This accords with the conventions
17611 of the save stack, as described earlier.)
17613 @<Scan an internal...@>=
17616 if ( my_var_flag==assignment ) {
17618 if ( mp->cur_cmd==assignment ) {
17619 mp->cur_exp=mp_get_avail(mp);
17620 mp_info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list;
17625 mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17628 @ The most difficult part of |scan_primary| has been saved for last, since
17629 it was necessary to build up some confidence first. We can now face the task
17630 of scanning a variable.
17632 As we scan a variable, we build a token list containing the relevant
17633 names and subscript values, simultaneously following along in the
17634 ``collective'' structure to see if we are actually dealing with a macro
17635 instead of a value.
17637 The local variables |pre_head| and |post_head| will point to the beginning
17638 of the prefix and suffix lists; |tail| will point to the end of the list
17639 that is currently growing.
17641 Another local variable, |tt|, contains partial information about the
17642 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17643 relation |tt=mp_type(q)| will always hold. If |tt=undefined|, the routine
17644 doesn't bother to update its information about type. And if
17645 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17647 @ @<Other local variables for |scan_primary|@>=
17648 pointer pre_head,post_head,tail;
17649 /* prefix and suffix list variables */
17650 quarterword tt; /* approximation to the type of the variable-so-far */
17651 pointer t; /* a token */
17652 pointer macro_ref = 0; /* reference count for a suffixed macro */
17654 @ @<Scan a variable primary...@>=
17656 fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17658 t=mp_cur_tok(mp); mp_link(tail)=t;
17659 if ( tt!=undefined ) {
17660 @<Find the approximate type |tt| and corresponding~|q|@>;
17661 if ( tt>=mp_unsuffixed_macro ) {
17662 @<Either begin an unsuffixed macro call or
17663 prepare for a suffixed one@>;
17666 mp_get_x_next(mp); tail=t;
17667 if ( mp->cur_cmd==left_bracket ) {
17668 @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17670 if ( mp->cur_cmd>max_suffix_token ) break;
17671 if ( mp->cur_cmd<min_suffix_token ) break;
17672 } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17673 @<Handle unusual cases that masquerade as variables, and |goto restart|
17674 or |goto done| if appropriate;
17675 otherwise make a copy of the variable and |goto done|@>;
17678 @ @<Either begin an unsuffixed macro call or...@>=
17680 mp_link(tail)=null;
17681 if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17682 post_head=mp_get_avail(mp); tail=post_head; mp_link(tail)=t;
17683 tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17685 @<Set up unsuffixed macro call and |goto restart|@>;
17689 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17691 mp_get_x_next(mp); mp_scan_expression(mp);
17692 if ( mp->cur_cmd!=right_bracket ) {
17693 @<Put the left bracket and the expression back to be rescanned@>;
17695 if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17696 mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17700 @ The left bracket that we thought was introducing a subscript might have
17701 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17702 So we don't issue an error message at this point; but we do want to back up
17703 so as to avoid any embarrassment about our incorrect assumption.
17705 @<Put the left bracket and the expression back to be rescanned@>=
17707 mp_back_input(mp); /* that was the token following the current expression */
17708 mp_back_expr(mp); mp->cur_cmd=left_bracket;
17709 mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17712 @ Here's a routine that puts the current expression back to be read again.
17715 static void mp_back_expr (MP mp) {
17716 pointer p; /* capsule token */
17717 p=mp_stash_cur_exp(mp); mp_link(p)=null; back_list(p);
17720 @ Unknown subscripts lead to the following error message.
17723 static void mp_bad_subscript (MP mp) {
17724 exp_err("Improper subscript has been replaced by zero");
17725 @.Improper subscript...@>
17726 help3("A bracketed subscript must have a known numeric value;",
17727 "unfortunately, what I found was the value that appears just",
17728 "above this error message. So I'll try a zero subscript.");
17729 mp_flush_error(mp, 0);
17732 @ Every time we call |get_x_next|, there's a chance that the variable we've
17733 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17734 into the variable structure; we need to start searching from the root each time.
17736 @<Find the approximate type |tt| and corresponding~|q|@>=
17739 p=mp_link(pre_head); q=mp_info(p); tt=undefined;
17740 if ( eq_type(q) % outer_tag==tag_token ) {
17742 if ( q==null ) goto DONE2;
17746 tt=mp_type(q); goto DONE2;
17748 if ( mp_type(q)!=mp_structured ) goto DONE2;
17749 q=mp_link(attr_head(q)); /* the |collective_subscript| attribute */
17750 if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17751 do { q=mp_link(q); } while (! (attr_loc(q)>=mp_info(p)));
17752 if ( attr_loc(q)>mp_info(p) ) goto DONE2;
17760 @ How do things stand now? Well, we have scanned an entire variable name,
17761 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17762 |cur_sym| represent the token that follows. If |post_head=null|, a
17763 token list for this variable name starts at |mp_link(pre_head)|, with all
17764 subscripts evaluated. But if |post_head<>null|, the variable turned out
17765 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17766 |post_head| is the head of a token list containing both `\.{\AT!}' and
17769 Our immediate problem is to see if this variable still exists. (Variable
17770 structures can change drastically whenever we call |get_x_next|; users
17771 aren't supposed to do this, but the fact that it is possible means that
17772 we must be cautious.)
17774 The following procedure prints an error message when a variable
17775 unexpectedly disappears. Its help message isn't quite right for
17776 our present purposes, but we'll be able to fix that up.
17779 static void mp_obliterated (MP mp,pointer q) {
17780 print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17781 mp_print(mp, " has been obliterated");
17782 @.Variable...obliterated@>
17783 help5("It seems you did a nasty thing---probably by accident,",
17784 "but nevertheless you nearly hornswoggled me...",
17785 "While I was evaluating the right-hand side of this",
17786 "command, something happened, and the left-hand side",
17787 "is no longer a variable! So I won't change anything.");
17790 @ If the variable does exist, we also need to check
17791 for a few other special cases before deciding that a plain old ordinary
17792 variable has, indeed, been scanned.
17794 @<Handle unusual cases that masquerade as variables...@>=
17795 if ( post_head!=null ) {
17796 @<Set up suffixed macro call and |goto restart|@>;
17798 q=mp_link(pre_head); free_avail(pre_head);
17799 if ( mp->cur_cmd==my_var_flag ) {
17800 mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17802 p=mp_find_variable(mp, q);
17804 mp_make_exp_copy(mp, p);
17806 mp_obliterated(mp, q);
17807 mp->help_line[2]="While I was evaluating the suffix of this variable,";
17808 mp->help_line[1]="something was redefined, and it's no longer a variable!";
17809 mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17810 mp_put_get_flush_error(mp, 0);
17812 mp_flush_node_list(mp, q);
17815 @ The only complication associated with macro calling is that the prefix
17816 and ``at'' parameters must be packaged in an appropriate list of lists.
17818 @<Set up unsuffixed macro call and |goto restart|@>=
17820 p=mp_get_avail(mp); mp_info(pre_head)=mp_link(pre_head); mp_link(pre_head)=p;
17821 mp_info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17826 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17827 we don't care, because we have reserved a pointer (|macro_ref|) to its
17830 @<Set up suffixed macro call and |goto restart|@>=
17832 mp_back_input(mp); p=mp_get_avail(mp); q=mp_link(post_head);
17833 mp_info(pre_head)=mp_link(pre_head); mp_link(pre_head)=post_head;
17834 mp_info(post_head)=q; mp_link(post_head)=p; mp_info(p)=mp_link(q); mp_link(q)=null;
17835 mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17836 mp_get_x_next(mp); goto RESTART;
17839 @ Our remaining job is simply to make a copy of the value that has been
17840 found. Some cases are harder than others, but complexity arises solely
17841 because of the multiplicity of possible cases.
17843 @<Declare the procedure called |make_exp_copy|@>=
17844 @<Declare subroutines needed by |make_exp_copy|@>
17845 static void mp_make_exp_copy (MP mp,pointer p) {
17846 pointer q,r,t; /* registers for list manipulation */
17848 mp->cur_type=mp_type(p);
17849 switch (mp->cur_type) {
17850 case mp_vacuous: case mp_boolean_type: case mp_known:
17851 mp->cur_exp=value(p); break;
17852 case unknown_types:
17853 mp->cur_exp=mp_new_ring_entry(mp, p);
17855 case mp_string_type:
17856 mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17858 case mp_picture_type:
17859 mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17862 mp->cur_exp=copy_pen(value(p));
17865 mp->cur_exp=mp_copy_path(mp, value(p));
17867 case mp_transform_type: case mp_color_type:
17868 case mp_cmykcolor_type: case mp_pair_type:
17869 @<Copy the big node |p|@>;
17871 case mp_dependent: case mp_proto_dependent:
17872 mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17874 case mp_numeric_type:
17875 new_indep(p); goto RESTART;
17877 case mp_independent:
17878 q=mp_single_dependency(mp, p);
17879 if ( q==mp->dep_final ){
17880 mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,dep_node_size);
17882 mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17886 mp_confusion(mp, "copy");
17887 @:this can't happen copy}{\quad copy@>
17892 @ The |encapsulate| subroutine assumes that |dep_final| is the
17893 tail of dependency list~|p|.
17895 @<Declare subroutines needed by |make_exp_copy|@>=
17896 static void mp_encapsulate (MP mp,pointer p) {
17897 mp->cur_exp=mp_get_node(mp, value_node_size); mp_type(mp->cur_exp)=mp->cur_type;
17898 mp_name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17901 @ The most tedious case arises when the user refers to a
17902 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17903 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17906 @<Copy the big node |p|@>=
17908 if ( value(p)==null )
17909 mp_init_big_node(mp, p);
17910 t=mp_get_node(mp, value_node_size); mp_name_type(t)=mp_capsule; mp_type(t)=mp->cur_type;
17911 mp_init_big_node(mp, t);
17912 q=value(p)+mp->big_node_size[mp->cur_type];
17913 r=value(t)+mp->big_node_size[mp->cur_type];
17915 q=q-2; r=r-2; mp_install(mp, r,q);
17916 } while (q!=value(p));
17920 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17921 a big node that will be part of a capsule.
17923 @<Declare subroutines needed by |make_exp_copy|@>=
17924 static void mp_install (MP mp,pointer r, pointer q) {
17925 pointer p; /* temporary register */
17926 if ( mp_type(q)==mp_known ){
17927 value(r)=value(q); mp_type(r)=mp_known;
17928 } else if ( mp_type(q)==mp_independent ) {
17929 p=mp_single_dependency(mp, q);
17930 if ( p==mp->dep_final ) {
17931 mp_type(r)=mp_known; value(r)=0; mp_free_node(mp, p,dep_node_size);
17933 mp_type(r)=mp_dependent; mp_new_dep(mp, r,p);
17936 mp_type(r)=mp_type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17940 @ Expressions of the form `\.{a[b,c]}' are converted into
17941 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17942 provided that \.a is numeric.
17944 @<Scan a mediation...@>=
17946 p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17947 if ( mp->cur_cmd!=comma ) {
17948 @<Put the left bracket and the expression back...@>;
17949 mp_unstash_cur_exp(mp, p);
17951 q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17952 if ( mp->cur_cmd!=right_bracket ) {
17953 mp_missing_err(mp, "]");
17955 help3("I've scanned an expression of the form `a[b,c',",
17956 "so a right bracket should have come next.",
17957 "I shall pretend that one was there.");
17960 r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17961 mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times);
17962 mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17966 @ Here is a comparatively simple routine that is used to scan the
17967 \&{suffix} parameters of a macro.
17969 @<Declare the basic parsing subroutines@>=
17970 static void mp_scan_suffix (MP mp) {
17971 pointer h,t; /* head and tail of the list being built */
17972 pointer p; /* temporary register */
17973 h=mp_get_avail(mp); t=h;
17975 if ( mp->cur_cmd==left_bracket ) {
17976 @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17978 if ( mp->cur_cmd==numeric_token ) {
17979 p=mp_new_num_tok(mp, mp->cur_mod);
17980 } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17981 p=mp_get_avail(mp); mp_info(p)=mp->cur_sym;
17985 mp_link(t)=p; t=p; mp_get_x_next(mp);
17987 mp->cur_exp=mp_link(h); free_avail(h); mp->cur_type=mp_token_list;
17990 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17992 mp_get_x_next(mp); mp_scan_expression(mp);
17993 if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17994 if ( mp->cur_cmd!=right_bracket ) {
17995 mp_missing_err(mp, "]");
17997 help3("I've seen a `[' and a subscript value, in a suffix,",
17998 "so a right bracket should have come next.",
17999 "I shall pretend that one was there.");
18002 mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
18005 @* \[38] Parsing secondary and higher expressions.
18007 After the intricacies of |scan_primary|\kern-1pt,
18008 the |scan_secondary| routine is
18009 refreshingly simple. It's not trivial, but the operations are relatively
18010 straightforward; the main difficulty is, again, that expressions and data
18011 structures might change drastically every time we call |get_x_next|, so a
18012 cautious approach is mandatory. For example, a macro defined by
18013 \&{primarydef} might have disappeared by the time its second argument has
18014 been scanned; we solve this by increasing the reference count of its token
18015 list, so that the macro can be called even after it has been clobbered.
18017 @<Declare the basic parsing subroutines@>=
18018 static void mp_scan_secondary (MP mp) {
18019 pointer p; /* for list manipulation */
18020 halfword c,d; /* operation codes or modifiers */
18021 pointer mac_name; /* token defined with \&{primarydef} */
18023 if ((mp->cur_cmd<min_primary_command)||
18024 (mp->cur_cmd>max_primary_command) )
18025 mp_bad_exp(mp, "A secondary");
18026 @.A secondary expression...@>
18027 mp_scan_primary(mp);
18029 if ( mp->cur_cmd<=max_secondary_command &&
18030 mp->cur_cmd>=min_secondary_command ) {
18031 p=mp_stash_cur_exp(mp);
18032 c=mp->cur_mod; d=mp->cur_cmd;
18033 if ( d==secondary_primary_macro ) {
18034 mac_name=mp->cur_sym;
18038 mp_scan_primary(mp);
18039 if ( d!=secondary_primary_macro ) {
18040 mp_do_binary(mp, p,c);
18043 mp_binary_mac(mp, p,c,mac_name);
18044 decr(ref_count(c));
18052 @ The following procedure calls a macro that has two parameters,
18056 static void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
18057 pointer q,r; /* nodes in the parameter list */
18058 q=mp_get_avail(mp); r=mp_get_avail(mp); mp_link(q)=r;
18059 mp_info(q)=p; mp_info(r)=mp_stash_cur_exp(mp);
18060 mp_macro_call(mp, c,q,n);
18063 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
18065 @<Declare the basic parsing subroutines@>=
18066 static void mp_scan_tertiary (MP mp) {
18067 pointer p; /* for list manipulation */
18068 halfword c,d; /* operation codes or modifiers */
18069 pointer mac_name; /* token defined with \&{secondarydef} */
18071 if ((mp->cur_cmd<min_primary_command)||
18072 (mp->cur_cmd>max_primary_command) )
18073 mp_bad_exp(mp, "A tertiary");
18074 @.A tertiary expression...@>
18075 mp_scan_secondary(mp);
18077 if ( mp->cur_cmd<=max_tertiary_command ) {
18078 if ( mp->cur_cmd>=min_tertiary_command ) {
18079 p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
18080 if ( d==tertiary_secondary_macro ) {
18081 mac_name=mp->cur_sym; add_mac_ref(c);
18083 mp_get_x_next(mp); mp_scan_secondary(mp);
18084 if ( d!=tertiary_secondary_macro ) {
18085 mp_do_binary(mp, p,c);
18087 mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18088 decr(ref_count(c)); mp_get_x_next(mp);
18096 @ Finally we reach the deepest level in our quartet of parsing routines.
18097 This one is much like the others; but it has an extra complication from
18098 paths, which materialize here.
18100 @d continue_path 25 /* a label inside of |scan_expression| */
18101 @d finish_path 26 /* another */
18103 @<Declare the basic parsing subroutines@>=
18104 static void mp_scan_expression (MP mp) {
18105 pointer p,q,r,pp,qq; /* for list manipulation */
18106 halfword c,d; /* operation codes or modifiers */
18107 int my_var_flag; /* initial value of |var_flag| */
18108 pointer mac_name; /* token defined with \&{tertiarydef} */
18109 boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
18110 scaled x,y; /* explicit coordinates or tension at a path join */
18111 int t; /* knot type following a path join */
18113 my_var_flag=mp->var_flag; mac_name=null;
18115 if ((mp->cur_cmd<min_primary_command)||
18116 (mp->cur_cmd>max_primary_command) )
18117 mp_bad_exp(mp, "An");
18118 @.An expression...@>
18119 mp_scan_tertiary(mp);
18121 if ( mp->cur_cmd<=max_expression_command )
18122 if ( mp->cur_cmd>=min_expression_command ) {
18123 if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
18124 p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
18125 if ( d==expression_tertiary_macro ) {
18126 mac_name=mp->cur_sym; add_mac_ref(c);
18128 if ( (d<ampersand)||((d==ampersand)&&
18129 ((mp_type(p)==mp_pair_type)||(mp_type(p)==mp_path_type))) ) {
18130 @<Scan a path construction operation;
18131 but |return| if |p| has the wrong type@>;
18133 mp_get_x_next(mp); mp_scan_tertiary(mp);
18134 if ( d!=expression_tertiary_macro ) {
18135 mp_do_binary(mp, p,c);
18137 mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18138 decr(ref_count(c)); mp_get_x_next(mp);
18147 @ The reader should review the data structure conventions for paths before
18148 hoping to understand the next part of this code.
18150 @<Scan a path construction operation...@>=
18153 @<Convert the left operand, |p|, into a partial path ending at~|q|;
18154 but |return| if |p| doesn't have a suitable type@>;
18156 @<Determine the path join parameters;
18157 but |goto finish_path| if there's only a direction specifier@>;
18158 if ( mp->cur_cmd==cycle ) {
18159 @<Get ready to close a cycle@>;
18161 mp_scan_tertiary(mp);
18162 @<Convert the right operand, |cur_exp|,
18163 into a partial path from |pp| to~|qq|@>;
18165 @<Join the partial paths and reset |p| and |q| to the head and tail
18167 if ( mp->cur_cmd>=min_expression_command )
18168 if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
18170 @<Choose control points for the path and put the result into |cur_exp|@>;
18173 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
18175 mp_unstash_cur_exp(mp, p);
18176 if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
18177 else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
18180 while ( mp_link(q)!=p ) q=mp_link(q);
18181 if ( mp_left_type(p)!=mp_endpoint ) { /* open up a cycle */
18182 r=mp_copy_knot(mp, p); mp_link(q)=r; q=r;
18184 mp_left_type(p)=mp_open; mp_right_type(q)=mp_open;
18187 @ A pair of numeric values is changed into a knot node for a one-point path
18188 when \MP\ discovers that the pair is part of a path.
18191 static pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
18192 pointer q; /* the new node */
18193 q=mp_get_node(mp, knot_node_size); mp_left_type(q)=mp_endpoint;
18194 mp_right_type(q)=mp_endpoint; mp_originator(q)=mp_metapost_user; mp_link(q)=q;
18195 mp_known_pair(mp); mp_x_coord(q)=mp->cur_x; mp_y_coord(q)=mp->cur_y;
18199 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
18200 of the current expression, assuming that the current expression is a
18201 pair of known numerics. Unknown components are zeroed, and the
18202 current expression is flushed.
18205 static void mp_known_pair (MP mp);
18208 void mp_known_pair (MP mp) {
18209 pointer p; /* the pair node */
18210 if ( mp->cur_type!=mp_pair_type ) {
18211 exp_err("Undefined coordinates have been replaced by (0,0)");
18212 @.Undefined coordinates...@>
18213 help5("I need x and y numbers for this part of the path.",
18214 "The value I found (see above) was no good;",
18215 "so I'll try to keep going by using zero instead.",
18216 "(Chapter 27 of The METAFONTbook explains that",
18217 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18218 "you might want to type `I ??" "?' now.)");
18219 mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18221 p=value(mp->cur_exp);
18222 @<Make sure that both |x| and |y| parts of |p| are known;
18223 copy them into |cur_x| and |cur_y|@>;
18224 mp_flush_cur_exp(mp, 0);
18228 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18229 if ( mp_type(x_part_loc(p))==mp_known ) {
18230 mp->cur_x=value(x_part_loc(p));
18232 mp_disp_err(mp, x_part_loc(p),
18233 "Undefined x coordinate has been replaced by 0");
18234 @.Undefined coordinates...@>
18235 help5("I need a `known' x value for this part of the path.",
18236 "The value I found (see above) was no good;",
18237 "so I'll try to keep going by using zero instead.",
18238 "(Chapter 27 of The METAFONTbook explains that",
18239 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18240 "you might want to type `I ??" "?' now.)");
18241 mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18243 if ( mp_type(y_part_loc(p))==mp_known ) {
18244 mp->cur_y=value(y_part_loc(p));
18246 mp_disp_err(mp, y_part_loc(p),
18247 "Undefined y coordinate has been replaced by 0");
18248 help5("I need a `known' y value for this part of the path.",
18249 "The value I found (see above) was no good;",
18250 "so I'll try to keep going by using zero instead.",
18251 "(Chapter 27 of The METAFONTbook explains that",
18252 "you might want to type `I ??" "?' now.)");
18253 mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18256 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18258 @<Determine the path join parameters...@>=
18259 if ( mp->cur_cmd==left_brace ) {
18260 @<Put the pre-join direction information into node |q|@>;
18263 if ( d==path_join ) {
18264 @<Determine the tension and/or control points@>;
18265 } else if ( d!=ampersand ) {
18269 if ( mp->cur_cmd==left_brace ) {
18270 @<Put the post-join direction information into |x| and |t|@>;
18271 } else if ( mp_right_type(q)!=mp_explicit ) {
18275 @ The |scan_direction| subroutine looks at the directional information
18276 that is enclosed in braces, and also scans ahead to the following character.
18277 A type code is returned, either |open| (if the direction was $(0,0)$),
18278 or |curl| (if the direction was a curl of known value |cur_exp|), or
18279 |given| (if the direction is given by the |angle| value that now
18280 appears in |cur_exp|).
18282 There's nothing difficult about this subroutine, but the program is rather
18283 lengthy because a variety of potential errors need to be nipped in the bud.
18286 static quarterword mp_scan_direction (MP mp) {
18287 int t; /* the type of information found */
18288 scaled x; /* an |x| coordinate */
18290 if ( mp->cur_cmd==curl_command ) {
18291 @<Scan a curl specification@>;
18293 @<Scan a given direction@>;
18295 if ( mp->cur_cmd!=right_brace ) {
18296 mp_missing_err(mp, "}");
18297 @.Missing `\char`\}'@>
18298 help3("I've scanned a direction spec for part of a path,",
18299 "so a right brace should have come next.",
18300 "I shall pretend that one was there.");
18307 @ @<Scan a curl specification@>=
18308 { mp_get_x_next(mp); mp_scan_expression(mp);
18309 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){
18310 exp_err("Improper curl has been replaced by 1");
18312 help1("A curl must be a known, nonnegative number.");
18313 mp_put_get_flush_error(mp, unity);
18318 @ @<Scan a given direction@>=
18319 { mp_scan_expression(mp);
18320 if ( mp->cur_type>mp_pair_type ) {
18321 @<Get given directions separated by commas@>;
18325 if ( (mp->cur_x==0)&&(mp->cur_y==0) ) t=mp_open;
18326 else { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18329 @ @<Get given directions separated by commas@>=
18331 if ( mp->cur_type!=mp_known ) {
18332 exp_err("Undefined x coordinate has been replaced by 0");
18333 @.Undefined coordinates...@>
18334 help5("I need a `known' x value for this part of the path.",
18335 "The value I found (see above) was no good;",
18336 "so I'll try to keep going by using zero instead.",
18337 "(Chapter 27 of The METAFONTbook explains that",
18338 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18339 "you might want to type `I ??" "?' now.)");
18340 mp_put_get_flush_error(mp, 0);
18343 if ( mp->cur_cmd!=comma ) {
18344 mp_missing_err(mp, ",");
18346 help2("I've got the x coordinate of a path direction;",
18347 "will look for the y coordinate next.");
18350 mp_get_x_next(mp); mp_scan_expression(mp);
18351 if ( mp->cur_type!=mp_known ) {
18352 exp_err("Undefined y coordinate has been replaced by 0");
18353 help5("I need a `known' y value for this part of the path.",
18354 "The value I found (see above) was no good;",
18355 "so I'll try to keep going by using zero instead.",
18356 "(Chapter 27 of The METAFONTbook explains that",
18357 "you might want to type `I ??" "?' now.)");
18358 mp_put_get_flush_error(mp, 0);
18360 mp->cur_y=mp->cur_exp; mp->cur_x=x;
18363 @ At this point |mp_right_type(q)| is usually |open|, but it may have been
18364 set to some other value by a previous operation. We must maintain
18365 the value of |mp_right_type(q)| in cases such as
18366 `\.{..\{curl2\}z\{0,0\}..}'.
18368 @<Put the pre-join...@>=
18370 t=mp_scan_direction(mp);
18371 if ( t!=mp_open ) {
18372 mp_right_type(q)=t; right_given(q)=mp->cur_exp;
18373 if ( mp_left_type(q)==mp_open ) {
18374 mp_left_type(q)=t; left_given(q)=mp->cur_exp;
18375 } /* note that |left_given(q)=left_curl(q)| */
18379 @ Since |left_tension| and |mp_left_y| share the same position in knot nodes,
18380 and since |left_given| is similarly equivalent to |mp_left_x|, we use
18381 |x| and |y| to hold the given direction and tension information when
18382 there are no explicit control points.
18384 @<Put the post-join...@>=
18386 t=mp_scan_direction(mp);
18387 if ( mp_right_type(q)!=mp_explicit ) x=mp->cur_exp;
18388 else t=mp_explicit; /* the direction information is superfluous */
18391 @ @<Determine the tension and/or...@>=
18394 if ( mp->cur_cmd==tension ) {
18395 @<Set explicit tensions@>;
18396 } else if ( mp->cur_cmd==controls ) {
18397 @<Set explicit control points@>;
18399 right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18402 if ( mp->cur_cmd!=path_join ) {
18403 mp_missing_err(mp, "..");
18405 help1("A path join command should end with two dots.");
18412 @ @<Set explicit tensions@>=
18414 mp_get_x_next(mp); y=mp->cur_cmd;
18415 if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18416 mp_scan_primary(mp);
18417 @<Make sure that the current expression is a valid tension setting@>;
18418 if ( y==at_least ) negate(mp->cur_exp);
18419 right_tension(q)=mp->cur_exp;
18420 if ( mp->cur_cmd==and_command ) {
18421 mp_get_x_next(mp); y=mp->cur_cmd;
18422 if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18423 mp_scan_primary(mp);
18424 @<Make sure that the current expression is a valid tension setting@>;
18425 if ( y==at_least ) negate(mp->cur_exp);
18430 @ @d min_tension three_quarter_unit
18432 @<Make sure that the current expression is a valid tension setting@>=
18433 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18434 exp_err("Improper tension has been set to 1");
18435 @.Improper tension@>
18436 help1("The expression above should have been a number >=3/4.");
18437 mp_put_get_flush_error(mp, unity);
18440 @ @<Set explicit control points@>=
18442 mp_right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18443 mp_known_pair(mp); mp_right_x(q)=mp->cur_x; mp_right_y(q)=mp->cur_y;
18444 if ( mp->cur_cmd!=and_command ) {
18445 x=mp_right_x(q); y=mp_right_y(q);
18447 mp_get_x_next(mp); mp_scan_primary(mp);
18448 mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18452 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18454 if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18455 else pp=mp->cur_exp;
18457 while ( mp_link(qq)!=pp ) qq=mp_link(qq);
18458 if ( mp_left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18459 r=mp_copy_knot(mp, pp); mp_link(qq)=r; qq=r;
18461 mp_left_type(pp)=mp_open; mp_right_type(qq)=mp_open;
18464 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18465 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18466 shouldn't have length zero.
18468 @<Get ready to close a cycle@>=
18470 cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18471 if ( d==ampersand ) if ( p==q ) {
18472 d=path_join; right_tension(q)=unity; y=unity;
18476 @ @<Join the partial paths and reset |p| and |q|...@>=
18478 if ( d==ampersand ) {
18479 if ( (mp_x_coord(q)!=mp_x_coord(pp))||(mp_y_coord(q)!=mp_y_coord(pp)) ) {
18480 print_err("Paths don't touch; `&' will be changed to `..'");
18481 @.Paths don't touch@>
18482 help3("When you join paths `p&q', the ending point of p",
18483 "must be exactly equal to the starting point of q.",
18484 "So I'm going to pretend that you said `p..q' instead.");
18485 mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18488 @<Plug an opening in |mp_right_type(pp)|, if possible@>;
18489 if ( d==ampersand ) {
18490 @<Splice independent paths together@>;
18492 @<Plug an opening in |mp_right_type(q)|, if possible@>;
18493 mp_link(q)=pp; mp_left_y(pp)=y;
18494 if ( t!=mp_open ) { mp_left_x(pp)=x; mp_left_type(pp)=t; };
18499 @ @<Plug an opening in |mp_right_type(q)|...@>=
18500 if ( mp_right_type(q)==mp_open ) {
18501 if ( (mp_left_type(q)==mp_curl)||(mp_left_type(q)==mp_given) ) {
18502 mp_right_type(q)=mp_left_type(q); right_given(q)=left_given(q);
18506 @ @<Plug an opening in |mp_right_type(pp)|...@>=
18507 if ( mp_right_type(pp)==mp_open ) {
18508 if ( (t==mp_curl)||(t==mp_given) ) {
18509 mp_right_type(pp)=t; right_given(pp)=x;
18513 @ @<Splice independent paths together@>=
18515 if ( mp_left_type(q)==mp_open ) if ( mp_right_type(q)==mp_open ) {
18516 mp_left_type(q)=mp_curl; left_curl(q)=unity;
18518 if ( mp_right_type(pp)==mp_open ) if ( t==mp_open ) {
18519 mp_right_type(pp)=mp_curl; right_curl(pp)=unity;
18521 mp_right_type(q)=mp_right_type(pp); mp_link(q)=mp_link(pp);
18522 mp_right_x(q)=mp_right_x(pp); mp_right_y(q)=mp_right_y(pp);
18523 mp_free_node(mp, pp,knot_node_size);
18524 if ( qq==pp ) qq=q;
18527 @ @<Choose control points for the path...@>=
18529 if ( d==ampersand ) p=q;
18531 mp_left_type(p)=mp_endpoint;
18532 if ( mp_right_type(p)==mp_open ) {
18533 mp_right_type(p)=mp_curl; right_curl(p)=unity;
18535 mp_right_type(q)=mp_endpoint;
18536 if ( mp_left_type(q)==mp_open ) {
18537 mp_left_type(q)=mp_curl; left_curl(q)=unity;
18541 mp_make_choices(mp, p);
18542 mp->cur_type=mp_path_type; mp->cur_exp=p
18544 @ Finally, we sometimes need to scan an expression whose value is
18545 supposed to be either |true_code| or |false_code|.
18547 @<Declare the basic parsing subroutines@>=
18548 static void mp_get_boolean (MP mp) {
18549 mp_get_x_next(mp); mp_scan_expression(mp);
18550 if ( mp->cur_type!=mp_boolean_type ) {
18551 exp_err("Undefined condition will be treated as `false'");
18552 @.Undefined condition...@>
18553 help2("The expression shown above should have had a definite",
18554 "true-or-false value. I'm changing it to `false'.");
18555 mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18559 @* \[39] Doing the operations.
18560 The purpose of parsing is primarily to permit people to avoid piles of
18561 parentheses. But the real work is done after the structure of an expression
18562 has been recognized; that's when new expressions are generated. We
18563 turn now to the guts of \MP, which handles individual operators that
18564 have come through the parsing mechanism.
18566 We'll start with the easy ones that take no operands, then work our way
18567 up to operators with one and ultimately two arguments. In other words,
18568 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18569 that are invoked periodically by the expression scanners.
18571 First let's make sure that all of the primitive operators are in the
18572 hash table. Although |scan_primary| and its relatives made use of the
18573 \\{cmd} code for these operators, the \\{do} routines base everything
18574 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18575 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18578 mp_primitive(mp, "true",nullary,true_code);
18579 @:true_}{\&{true} primitive@>
18580 mp_primitive(mp, "false",nullary,false_code);
18581 @:false_}{\&{false} primitive@>
18582 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18583 @:null_picture_}{\&{nullpicture} primitive@>
18584 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18585 @:null_pen_}{\&{nullpen} primitive@>
18586 mp_primitive(mp, "jobname",nullary,job_name_op);
18587 @:job_name_}{\&{jobname} primitive@>
18588 mp_primitive(mp, "readstring",nullary,read_string_op);
18589 @:read_string_}{\&{readstring} primitive@>
18590 mp_primitive(mp, "pencircle",nullary,pen_circle);
18591 @:pen_circle_}{\&{pencircle} primitive@>
18592 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18593 @:normal_deviate_}{\&{normaldeviate} primitive@>
18594 mp_primitive(mp, "readfrom",unary,read_from_op);
18595 @:read_from_}{\&{readfrom} primitive@>
18596 mp_primitive(mp, "closefrom",unary,close_from_op);
18597 @:close_from_}{\&{closefrom} primitive@>
18598 mp_primitive(mp, "odd",unary,odd_op);
18599 @:odd_}{\&{odd} primitive@>
18600 mp_primitive(mp, "known",unary,known_op);
18601 @:known_}{\&{known} primitive@>
18602 mp_primitive(mp, "unknown",unary,unknown_op);
18603 @:unknown_}{\&{unknown} primitive@>
18604 mp_primitive(mp, "not",unary,not_op);
18605 @:not_}{\&{not} primitive@>
18606 mp_primitive(mp, "decimal",unary,decimal);
18607 @:decimal_}{\&{decimal} primitive@>
18608 mp_primitive(mp, "reverse",unary,reverse);
18609 @:reverse_}{\&{reverse} primitive@>
18610 mp_primitive(mp, "makepath",unary,make_path_op);
18611 @:make_path_}{\&{makepath} primitive@>
18612 mp_primitive(mp, "makepen",unary,make_pen_op);
18613 @:make_pen_}{\&{makepen} primitive@>
18614 mp_primitive(mp, "oct",unary,oct_op);
18615 @:oct_}{\&{oct} primitive@>
18616 mp_primitive(mp, "hex",unary,hex_op);
18617 @:hex_}{\&{hex} primitive@>
18618 mp_primitive(mp, "ASCII",unary,ASCII_op);
18619 @:ASCII_}{\&{ASCII} primitive@>
18620 mp_primitive(mp, "char",unary,char_op);
18621 @:char_}{\&{char} primitive@>
18622 mp_primitive(mp, "length",unary,length_op);
18623 @:length_}{\&{length} primitive@>
18624 mp_primitive(mp, "turningnumber",unary,turning_op);
18625 @:turning_number_}{\&{turningnumber} primitive@>
18626 mp_primitive(mp, "xpart",unary,x_part);
18627 @:x_part_}{\&{xpart} primitive@>
18628 mp_primitive(mp, "ypart",unary,y_part);
18629 @:y_part_}{\&{ypart} primitive@>
18630 mp_primitive(mp, "xxpart",unary,xx_part);
18631 @:xx_part_}{\&{xxpart} primitive@>
18632 mp_primitive(mp, "xypart",unary,xy_part);
18633 @:xy_part_}{\&{xypart} primitive@>
18634 mp_primitive(mp, "yxpart",unary,yx_part);
18635 @:yx_part_}{\&{yxpart} primitive@>
18636 mp_primitive(mp, "yypart",unary,yy_part);
18637 @:yy_part_}{\&{yypart} primitive@>
18638 mp_primitive(mp, "redpart",unary,red_part);
18639 @:red_part_}{\&{redpart} primitive@>
18640 mp_primitive(mp, "greenpart",unary,green_part);
18641 @:green_part_}{\&{greenpart} primitive@>
18642 mp_primitive(mp, "bluepart",unary,blue_part);
18643 @:blue_part_}{\&{bluepart} primitive@>
18644 mp_primitive(mp, "cyanpart",unary,cyan_part);
18645 @:cyan_part_}{\&{cyanpart} primitive@>
18646 mp_primitive(mp, "magentapart",unary,magenta_part);
18647 @:magenta_part_}{\&{magentapart} primitive@>
18648 mp_primitive(mp, "yellowpart",unary,yellow_part);
18649 @:yellow_part_}{\&{yellowpart} primitive@>
18650 mp_primitive(mp, "blackpart",unary,black_part);
18651 @:black_part_}{\&{blackpart} primitive@>
18652 mp_primitive(mp, "greypart",unary,grey_part);
18653 @:grey_part_}{\&{greypart} primitive@>
18654 mp_primitive(mp, "colormodel",unary,color_model_part);
18655 @:color_model_part_}{\&{colormodel} primitive@>
18656 mp_primitive(mp, "fontpart",unary,font_part);
18657 @:font_part_}{\&{fontpart} primitive@>
18658 mp_primitive(mp, "textpart",unary,text_part);
18659 @:text_part_}{\&{textpart} primitive@>
18660 mp_primitive(mp, "pathpart",unary,path_part);
18661 @:path_part_}{\&{pathpart} primitive@>
18662 mp_primitive(mp, "penpart",unary,pen_part);
18663 @:pen_part_}{\&{penpart} primitive@>
18664 mp_primitive(mp, "dashpart",unary,dash_part);
18665 @:dash_part_}{\&{dashpart} primitive@>
18666 mp_primitive(mp, "sqrt",unary,sqrt_op);
18667 @:sqrt_}{\&{sqrt} primitive@>
18668 mp_primitive(mp, "mexp",unary,mp_m_exp_op);
18669 @:m_exp_}{\&{mexp} primitive@>
18670 mp_primitive(mp, "mlog",unary,mp_m_log_op);
18671 @:m_log_}{\&{mlog} primitive@>
18672 mp_primitive(mp, "sind",unary,sin_d_op);
18673 @:sin_d_}{\&{sind} primitive@>
18674 mp_primitive(mp, "cosd",unary,cos_d_op);
18675 @:cos_d_}{\&{cosd} primitive@>
18676 mp_primitive(mp, "floor",unary,floor_op);
18677 @:floor_}{\&{floor} primitive@>
18678 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18679 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18680 mp_primitive(mp, "charexists",unary,char_exists_op);
18681 @:char_exists_}{\&{charexists} primitive@>
18682 mp_primitive(mp, "fontsize",unary,font_size);
18683 @:font_size_}{\&{fontsize} primitive@>
18684 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18685 @:ll_corner_}{\&{llcorner} primitive@>
18686 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18687 @:lr_corner_}{\&{lrcorner} primitive@>
18688 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18689 @:ul_corner_}{\&{ulcorner} primitive@>
18690 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18691 @:ur_corner_}{\&{urcorner} primitive@>
18692 mp_primitive(mp, "arclength",unary,arc_length);
18693 @:arc_length_}{\&{arclength} primitive@>
18694 mp_primitive(mp, "angle",unary,angle_op);
18695 @:angle_}{\&{angle} primitive@>
18696 mp_primitive(mp, "cycle",cycle,cycle_op);
18697 @:cycle_}{\&{cycle} primitive@>
18698 mp_primitive(mp, "stroked",unary,stroked_op);
18699 @:stroked_}{\&{stroked} primitive@>
18700 mp_primitive(mp, "filled",unary,filled_op);
18701 @:filled_}{\&{filled} primitive@>
18702 mp_primitive(mp, "textual",unary,textual_op);
18703 @:textual_}{\&{textual} primitive@>
18704 mp_primitive(mp, "clipped",unary,clipped_op);
18705 @:clipped_}{\&{clipped} primitive@>
18706 mp_primitive(mp, "bounded",unary,bounded_op);
18707 @:bounded_}{\&{bounded} primitive@>
18708 mp_primitive(mp, "+",plus_or_minus,plus);
18709 @:+ }{\.{+} primitive@>
18710 mp_primitive(mp, "-",plus_or_minus,minus);
18711 @:- }{\.{-} primitive@>
18712 mp_primitive(mp, "*",secondary_binary,times);
18713 @:* }{\.{*} primitive@>
18714 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18715 @:/ }{\.{/} primitive@>
18716 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18717 @:++_}{\.{++} primitive@>
18718 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18719 @:+-+_}{\.{+-+} primitive@>
18720 mp_primitive(mp, "or",tertiary_binary,or_op);
18721 @:or_}{\&{or} primitive@>
18722 mp_primitive(mp, "and",and_command,and_op);
18723 @:and_}{\&{and} primitive@>
18724 mp_primitive(mp, "<",expression_binary,less_than);
18725 @:< }{\.{<} primitive@>
18726 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18727 @:<=_}{\.{<=} primitive@>
18728 mp_primitive(mp, ">",expression_binary,greater_than);
18729 @:> }{\.{>} primitive@>
18730 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18731 @:>=_}{\.{>=} primitive@>
18732 mp_primitive(mp, "=",equals,equal_to);
18733 @:= }{\.{=} primitive@>
18734 mp_primitive(mp, "<>",expression_binary,unequal_to);
18735 @:<>_}{\.{<>} primitive@>
18736 mp_primitive(mp, "substring",primary_binary,substring_of);
18737 @:substring_}{\&{substring} primitive@>
18738 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18739 @:subpath_}{\&{subpath} primitive@>
18740 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18741 @:direction_time_}{\&{directiontime} primitive@>
18742 mp_primitive(mp, "point",primary_binary,point_of);
18743 @:point_}{\&{point} primitive@>
18744 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18745 @:precontrol_}{\&{precontrol} primitive@>
18746 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18747 @:postcontrol_}{\&{postcontrol} primitive@>
18748 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18749 @:pen_offset_}{\&{penoffset} primitive@>
18750 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18751 @:arc_time_of_}{\&{arctime} primitive@>
18752 mp_primitive(mp, "mpversion",nullary,mp_version);
18753 @:mp_verison_}{\&{mpversion} primitive@>
18754 mp_primitive(mp, "&",ampersand,concatenate);
18755 @:!!!}{\.{\&} primitive@>
18756 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18757 @:rotated_}{\&{rotated} primitive@>
18758 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18759 @:slanted_}{\&{slanted} primitive@>
18760 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18761 @:scaled_}{\&{scaled} primitive@>
18762 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18763 @:shifted_}{\&{shifted} primitive@>
18764 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18765 @:transformed_}{\&{transformed} primitive@>
18766 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18767 @:x_scaled_}{\&{xscaled} primitive@>
18768 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18769 @:y_scaled_}{\&{yscaled} primitive@>
18770 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18771 @:z_scaled_}{\&{zscaled} primitive@>
18772 mp_primitive(mp, "infont",secondary_binary,in_font);
18773 @:in_font_}{\&{infont} primitive@>
18774 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18775 @:intersection_times_}{\&{intersectiontimes} primitive@>
18776 mp_primitive(mp, "envelope",primary_binary,envelope_of);
18777 @:envelope_}{\&{envelope} primitive@>
18779 @ @<Cases of |print_cmd...@>=
18782 case primary_binary:
18783 case secondary_binary:
18784 case tertiary_binary:
18785 case expression_binary:
18787 case plus_or_minus:
18792 mp_print_op(mp, m);
18795 @ OK, let's look at the simplest \\{do} procedure first.
18797 @c @<Declare nullary action procedure@>
18798 static void mp_do_nullary (MP mp,quarterword c) {
18800 if ( mp->internal[mp_tracing_commands]>two )
18801 mp_show_cmd_mod(mp, nullary,c);
18803 case true_code: case false_code:
18804 mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18806 case null_picture_code:
18807 mp->cur_type=mp_picture_type;
18808 mp->cur_exp=mp_get_node(mp, edge_header_size);
18809 mp_init_edges(mp, mp->cur_exp);
18811 case null_pen_code:
18812 mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18814 case normal_deviate:
18815 mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18818 mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18821 if ( mp->job_name==NULL ) mp_open_log_file(mp);
18822 mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18825 mp->cur_type=mp_string_type;
18826 mp->cur_exp=intern(metapost_version) ;
18828 case read_string_op:
18829 @<Read a string from the terminal@>;
18831 } /* there are no other cases */
18835 @ @<Read a string...@>=
18837 if (mp->noninteractive || mp->interaction<=mp_nonstop_mode )
18838 mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18839 mp_begin_file_reading(mp); name=is_read;
18840 limit=start; prompt_input("");
18841 mp_finish_read(mp);
18844 @ @<Declare nullary action procedure@>=
18845 static void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18847 str_room((int)mp->last-start);
18848 for (k=(size_t)start;k<=mp->last-1;k++) {
18849 append_char(mp->buffer[k]);
18851 mp_end_file_reading(mp); mp->cur_type=mp_string_type;
18852 mp->cur_exp=mp_make_string(mp);
18855 @ Things get a bit more interesting when there's an operand. The
18856 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18858 @c @<Declare unary action procedures@>
18859 static void mp_do_unary (MP mp,quarterword c) {
18860 pointer p,q,r; /* for list manipulation */
18861 integer x; /* a temporary register */
18863 if ( mp->internal[mp_tracing_commands]>two )
18864 @<Trace the current unary operation@>;
18867 if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18870 @<Negate the current expression@>;
18872 @<Additional cases of unary operators@>;
18873 } /* there are no other cases */
18877 @ The |nice_pair| function returns |true| if both components of a pair
18880 @<Declare unary action procedures@>=
18881 static boolean mp_nice_pair (MP mp,integer p, quarterword t) {
18882 if ( t==mp_pair_type ) {
18884 if ( mp_type(x_part_loc(p))==mp_known )
18885 if ( mp_type(y_part_loc(p))==mp_known )
18891 @ The |nice_color_or_pair| function is analogous except that it also accepts
18892 fully known colors.
18894 @<Declare unary action procedures@>=
18895 static boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18896 pointer q,r; /* for scanning the big node */
18897 if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18901 r=q+mp->big_node_size[mp_type(p)];
18904 if ( mp_type(r)!=mp_known )
18911 @ @<Declare unary action...@>=
18912 static void mp_print_known_or_unknown_type (MP mp,quarterword t, integer v) {
18913 mp_print_char(mp, xord('('));
18914 if ( t>mp_known ) mp_print(mp, "unknown numeric");
18915 else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18916 if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18917 mp_print_type(mp, t);
18919 mp_print_char(mp, xord(')'));
18922 @ @<Declare unary action...@>=
18923 static void mp_bad_unary (MP mp,quarterword c) {
18924 exp_err("Not implemented: "); mp_print_op(mp, c);
18925 @.Not implemented...@>
18926 mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18927 help3("I'm afraid I don't know how to apply that operation to that",
18928 "particular type. Continue, and I'll simply return the",
18929 "argument (shown above) as the result of the operation.");
18930 mp_put_get_error(mp);
18933 @ @<Trace the current unary operation@>=
18935 mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
18936 mp_print_op(mp, c); mp_print_char(mp, xord('('));
18937 mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18938 mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18941 @ Negation is easy except when the current expression
18942 is of type |independent|, or when it is a pair with one or more
18943 |independent| components.
18945 It is tempting to argue that the negative of an independent variable
18946 is an independent variable, hence we don't have to do anything when
18947 negating it. The fallacy is that other dependent variables pointing
18948 to the current expression must change the sign of their
18949 coefficients if we make no change to the current expression.
18951 Instead, we work around the problem by copying the current expression
18952 and recycling it afterwards (cf.~the |stash_in| routine).
18954 @<Negate the current expression@>=
18955 switch (mp->cur_type) {
18956 case mp_color_type:
18957 case mp_cmykcolor_type:
18959 case mp_independent:
18960 q=mp->cur_exp; mp_make_exp_copy(mp, q);
18961 if ( mp->cur_type==mp_dependent ) {
18962 mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18963 } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18964 p=value(mp->cur_exp);
18965 r=p+mp->big_node_size[mp->cur_type];
18968 if ( mp_type(r)==mp_known ) negate(value(r));
18969 else mp_negate_dep_list(mp, dep_list(r));
18971 } /* if |cur_type=mp_known| then |cur_exp=0| */
18972 mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18975 case mp_proto_dependent:
18976 mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18979 negate(mp->cur_exp);
18982 mp_bad_unary(mp, minus);
18986 @ @<Declare unary action...@>=
18987 static void mp_negate_dep_list (MP mp,pointer p) {
18990 if ( mp_info(p)==null ) return;
18995 @ @<Additional cases of unary operators@>=
18997 if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18998 else mp->cur_exp=true_code+false_code-mp->cur_exp;
19001 @ @d three_sixty_units 23592960 /* that's |360*unity| */
19002 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
19004 @<Additional cases of unary operators@>=
19011 case uniform_deviate:
19013 case char_exists_op:
19014 if ( mp->cur_type!=mp_known ) {
19015 mp_bad_unary(mp, c);
19018 case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
19019 case mp_m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
19020 case mp_m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
19023 mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
19024 if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
19025 else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
19027 case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
19028 case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
19030 boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
19031 mp->cur_type=mp_boolean_type;
19033 case char_exists_op:
19034 @<Determine if a character has been shipped out@>;
19036 } /* there are no other cases */
19040 @ @<Additional cases of unary operators@>=
19042 if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
19043 p=value(mp->cur_exp);
19044 x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
19045 if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
19046 else mp_flush_cur_exp(mp, -((-x+8)/ 16));
19048 mp_bad_unary(mp, angle_op);
19052 @ If the current expression is a pair, but the context wants it to
19053 be a path, we call |pair_to_path|.
19055 @<Declare unary action...@>=
19056 static void mp_pair_to_path (MP mp) {
19057 mp->cur_exp=mp_new_knot(mp);
19058 mp->cur_type=mp_path_type;
19062 @d pict_color_type(A) ((mp_link(dummy_loc(mp->cur_exp))!=null) &&
19063 (has_color(mp_link(dummy_loc(mp->cur_exp)))) &&
19064 ((mp_color_model(mp_link(dummy_loc(mp->cur_exp)))==A)
19066 ((mp_color_model(mp_link(dummy_loc(mp->cur_exp)))==mp_uninitialized_model) &&
19067 (mp->internal[mp_default_color_model]/unity)==(A))))
19069 @<Additional cases of unary operators@>=
19072 if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
19073 mp_take_part(mp, c);
19074 else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19075 else mp_bad_unary(mp, c);
19081 if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
19082 else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19083 else mp_bad_unary(mp, c);
19088 if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
19089 else if ( mp->cur_type==mp_picture_type ) {
19090 if pict_color_type(mp_rgb_model) mp_take_pict_part(mp, c);
19091 else mp_bad_color_part(mp, c);
19093 else mp_bad_unary(mp, c);
19099 if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c);
19100 else if ( mp->cur_type==mp_picture_type ) {
19101 if pict_color_type(mp_cmyk_model) mp_take_pict_part(mp, c);
19102 else mp_bad_color_part(mp, c);
19104 else mp_bad_unary(mp, c);
19107 if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
19108 else if ( mp->cur_type==mp_picture_type ) {
19109 if pict_color_type(mp_grey_model) mp_take_pict_part(mp, c);
19110 else mp_bad_color_part(mp, c);
19112 else mp_bad_unary(mp, c);
19114 case color_model_part:
19115 if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19116 else mp_bad_unary(mp, c);
19119 @ @<Declarations@>=
19120 static void mp_bad_color_part(MP mp, quarterword c);
19123 static void mp_bad_color_part(MP mp, quarterword c) {
19124 pointer p; /* the big node */
19125 p=mp_link(dummy_loc(mp->cur_exp));
19126 exp_err("Wrong picture color model: "); mp_print_op(mp, c);
19127 @.Wrong picture color model...@>
19128 if (mp_color_model(p)==mp_grey_model)
19129 mp_print(mp, " of grey object");
19130 else if (mp_color_model(p)==mp_cmyk_model)
19131 mp_print(mp, " of cmyk object");
19132 else if (mp_color_model(p)==mp_rgb_model)
19133 mp_print(mp, " of rgb object");
19134 else if (mp_color_model(p)==mp_no_model)
19135 mp_print(mp, " of marking object");
19137 mp_print(mp," of defaulted object");
19138 help3("You can only ask for the redpart, greenpart, bluepart of a rgb object,",
19139 "the cyanpart, magentapart, yellowpart or blackpart of a cmyk object, ",
19140 "or the greypart of a grey object. No mixing and matching, please.");
19143 mp_flush_cur_exp(mp,unity);
19145 mp_flush_cur_exp(mp,0);
19148 @ In the following procedure, |cur_exp| points to a capsule, which points to
19149 a big node. We want to delete all but one part of the big node.
19151 @<Declare unary action...@>=
19152 static void mp_take_part (MP mp,quarterword c) {
19153 pointer p; /* the big node */
19154 p=value(mp->cur_exp); value(temp_val)=p; mp_type(temp_val)=mp->cur_type;
19155 mp_link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
19156 mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
19157 mp_recycle_value(mp, temp_val);
19160 @ @<Initialize table entries...@>=
19161 mp_name_type(temp_val)=mp_capsule;
19163 @ @<Additional cases of unary operators@>=
19169 if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19170 else mp_bad_unary(mp, c);
19173 @ @<Declarations@>=
19174 static void mp_scale_edges (MP mp);
19176 @ @<Declare unary action...@>=
19177 static void mp_take_pict_part (MP mp,quarterword c) {
19178 pointer p; /* first graphical object in |cur_exp| */
19179 p=mp_link(dummy_loc(mp->cur_exp));
19182 case x_part: case y_part: case xx_part:
19183 case xy_part: case yx_part: case yy_part:
19184 if ( mp_type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
19185 else goto NOT_FOUND;
19187 case red_part: case green_part: case blue_part:
19188 if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
19189 else goto NOT_FOUND;
19191 case cyan_part: case magenta_part: case yellow_part:
19193 if ( has_color(p) ) {
19194 if ( mp_color_model(p)==mp_uninitialized_model && c==black_part)
19195 mp_flush_cur_exp(mp, unity);
19197 mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
19198 } else goto NOT_FOUND;
19201 if ( has_color(p) )
19202 mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
19203 else goto NOT_FOUND;
19205 case color_model_part:
19206 if ( has_color(p) ) {
19207 if ( mp_color_model(p)==mp_uninitialized_model )
19208 mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
19210 mp_flush_cur_exp(mp, mp_color_model(p)*unity);
19211 } else goto NOT_FOUND;
19213 @<Handle other cases in |take_pict_part| or |goto not_found|@>;
19214 } /* all cases have been enumerated */
19218 @<Convert the current expression to a null value appropriate
19222 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
19224 if ( mp_type(p)!=mp_text_code ) goto NOT_FOUND;
19226 mp_flush_cur_exp(mp, mp_text_p(p));
19227 add_str_ref(mp->cur_exp);
19228 mp->cur_type=mp_string_type;
19232 if ( mp_type(p)!=mp_text_code ) goto NOT_FOUND;
19234 mp_flush_cur_exp(mp, rts(mp->font_name[mp_font_n(p)]));
19235 add_str_ref(mp->cur_exp);
19236 mp->cur_type=mp_string_type;
19240 if ( mp_type(p)==mp_text_code ) goto NOT_FOUND;
19241 else if ( is_stop(p) ) mp_confusion(mp, "pict");
19242 @:this can't happen pict}{\quad pict@>
19244 mp_flush_cur_exp(mp, mp_copy_path(mp, mp_path_p(p)));
19245 mp->cur_type=mp_path_type;
19249 if ( ! has_pen(p) ) goto NOT_FOUND;
19251 if ( mp_pen_p(p)==null ) goto NOT_FOUND;
19252 else { mp_flush_cur_exp(mp, copy_pen(mp_pen_p(p)));
19253 mp->cur_type=mp_pen_type;
19258 if ( mp_type(p)!=mp_stroked_code ) goto NOT_FOUND;
19259 else { if ( mp_dash_p(p)==null ) goto NOT_FOUND;
19260 else { add_edge_ref(mp_dash_p(p));
19261 mp->se_sf=dash_scale(p);
19262 mp->se_pic=mp_dash_p(p);
19263 mp_scale_edges(mp);
19264 mp_flush_cur_exp(mp, mp->se_pic);
19265 mp->cur_type=mp_picture_type;
19270 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19271 parameterless procedure even though it really takes two arguments and updates
19272 one of them. Hence the following globals are needed.
19275 pointer se_pic; /* edge header used and updated by |scale_edges| */
19276 scaled se_sf; /* the scale factor argument to |scale_edges| */
19278 @ @<Convert the current expression to a null value appropriate...@>=
19280 case text_part: case font_part:
19281 mp_flush_cur_exp(mp, null_str);
19282 mp->cur_type=mp_string_type;
19285 mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19286 mp_left_type(mp->cur_exp)=mp_endpoint;
19287 mp_right_type(mp->cur_exp)=mp_endpoint;
19288 mp_link(mp->cur_exp)=mp->cur_exp;
19289 mp_x_coord(mp->cur_exp)=0;
19290 mp_y_coord(mp->cur_exp)=0;
19291 mp_originator(mp->cur_exp)=mp_metapost_user;
19292 mp->cur_type=mp_path_type;
19295 mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19296 mp->cur_type=mp_pen_type;
19299 mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19300 mp_init_edges(mp, mp->cur_exp);
19301 mp->cur_type=mp_picture_type;
19304 mp_flush_cur_exp(mp, 0);
19308 @ @<Additional cases of unary...@>=
19310 if ( mp->cur_type!=mp_known ) {
19311 mp_bad_unary(mp, char_op);
19313 mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
19314 mp->cur_type=mp_string_type;
19315 if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19319 if ( mp->cur_type!=mp_known ) {
19320 mp_bad_unary(mp, decimal);
19322 mp->old_setting=mp->selector; mp->selector=new_string;
19323 mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19324 mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19330 if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19331 else mp_str_to_num(mp, c);
19334 if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19335 else @<Find the design size of the font whose name is |cur_exp|@>;
19338 @ @<Declare unary action...@>=
19339 static void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19340 integer n; /* accumulator */
19341 ASCII_code m; /* current character */
19342 pool_pointer k; /* index into |str_pool| */
19343 int b; /* radix of conversion */
19344 boolean bad_char; /* did the string contain an invalid digit? */
19345 if ( c==ASCII_op ) {
19346 if ( length(mp->cur_exp)==0 ) n=-1;
19347 else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19349 if ( c==oct_op ) b=8; else b=16;
19350 n=0; bad_char=false;
19351 for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19353 if ( (m>='0')&&(m<='9') ) m=m-'0';
19354 else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19355 else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19356 else { bad_char=true; m=0; };
19357 if ( (int)m>=b ) { bad_char=true; m=0; };
19358 if ( n<32768 / b ) n=n*b+m; else n=32767;
19360 @<Give error messages if |bad_char| or |n>=4096|@>;
19362 mp_flush_cur_exp(mp, n*unity);
19365 @ @<Give error messages if |bad_char|...@>=
19367 exp_err("String contains illegal digits");
19368 @.String contains illegal digits@>
19370 help1("I zeroed out characters that weren't in the range 0..7.");
19372 help1("I zeroed out characters that weren't hex digits.");
19374 mp_put_get_error(mp);
19377 if ( mp->internal[mp_warning_check]>0 ) {
19378 print_err("Number too large (");
19379 mp_print_int(mp, n); mp_print_char(mp, xord(')'));
19380 @.Number too large@>
19381 help2("I have trouble with numbers greater than 4095; watch out.",
19382 "(Set warningcheck:=0 to suppress this message.)");
19383 mp_put_get_error(mp);
19387 @ The length operation is somewhat unusual in that it applies to a variety
19388 of different types of operands.
19390 @<Additional cases of unary...@>=
19392 switch (mp->cur_type) {
19393 case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19394 case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19395 case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19396 case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19398 if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19399 mp_flush_cur_exp(mp, mp_pyth_add(mp,
19400 value(x_part_loc(value(mp->cur_exp))),
19401 value(y_part_loc(value(mp->cur_exp)))));
19402 else mp_bad_unary(mp, c);
19407 @ @<Declare unary action...@>=
19408 static scaled mp_path_length (MP mp) { /* computes the length of the current path */
19409 scaled n; /* the path length so far */
19410 pointer p; /* traverser */
19412 if ( mp_left_type(p)==mp_endpoint ) n=-unity; else n=0;
19413 do { p=mp_link(p); n=n+unity; } while (p!=mp->cur_exp);
19417 @ @<Declare unary action...@>=
19418 static scaled mp_pict_length (MP mp) {
19419 /* counts interior components in picture |cur_exp| */
19420 scaled n; /* the count so far */
19421 pointer p; /* traverser */
19423 p=mp_link(dummy_loc(mp->cur_exp));
19425 if ( is_start_or_stop(p) )
19426 if ( mp_skip_1component(mp, p)==null ) p=mp_link(p);
19427 while ( p!=null ) {
19428 skip_component(p) return n;
19435 @ Implement |turningnumber|
19437 @<Additional cases of unary...@>=
19439 if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19440 else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19441 else if ( mp_left_type(mp->cur_exp)==mp_endpoint )
19442 mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19444 mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19447 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19448 argument is |origin|.
19450 @<Declare unary action...@>=
19451 static angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19452 if ( (! ((xpar==0) && (ypar==0))) )
19453 return mp_n_arg(mp, xpar,ypar);
19458 @ The actual turning number is (for the moment) computed in a C function
19459 that receives eight integers corresponding to the four controlling points,
19460 and returns a single angle. Besides those, we have to account for discrete
19461 moves at the actual points.
19463 @d mp_floor(a) ((a)>=0 ? (int)(a) : -(int)(-(a)))
19464 @d bezier_error (720*(256*256*16))+1
19465 @d mp_sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19466 @d mp_out(A) (double)((A)/(256*256*16))
19467 @d divisor (256*256)
19468 @d double2angle(a) (int)mp_floor(a*256.0*256.0*16.0)
19470 @<Declare unary action...@>=
19471 static angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19472 integer CX,integer CY,integer DX,integer DY);
19475 static angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19476 integer CX,integer CY,integer DX,integer DY) {
19478 integer deltax,deltay;
19479 double ax,ay,bx,by,cx,cy,dx,dy;
19480 angle xi = 0, xo = 0, xm = 0;
19482 ax=(double)(AX/divisor); ay=(double)(AY/divisor);
19483 bx=(double)(BX/divisor); by=(double)(BY/divisor);
19484 cx=(double)(CX/divisor); cy=(double)(CY/divisor);
19485 dx=(double)(DX/divisor); dy=(double)(DY/divisor);
19487 deltax = (BX-AX); deltay = (BY-AY);
19488 if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19489 if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19490 xi = mp_an_angle(mp,deltax,deltay);
19492 deltax = (CX-BX); deltay = (CY-BY);
19493 xm = mp_an_angle(mp,deltax,deltay);
19495 deltax = (DX-CX); deltay = (DY-CY);
19496 if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19497 if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19498 xo = mp_an_angle(mp,deltax,deltay);
19500 a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19501 b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19502 c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19504 if ((a==0)&&(c==0)) {
19505 res = (b==0 ? 0 : (mp_out(xo)-mp_out(xi)));
19506 } else if ((a==0)||(c==0)) {
19507 if ((mp_sign(b) == mp_sign(a)) || (mp_sign(b) == mp_sign(c))) {
19508 res = mp_out(xo)-mp_out(xi); /* ? */
19511 else if (res>180.0)
19514 res = mp_out(xo)-mp_out(xi); /* ? */
19516 } else if ((mp_sign(a)*mp_sign(c))<0) {
19517 res = mp_out(xo)-mp_out(xi); /* ? */
19520 else if (res>180.0)
19523 if (mp_sign(a) == mp_sign(b)) {
19524 res = mp_out(xo)-mp_out(xi); /* ? */
19527 else if (res>180.0)
19530 if ((b*b) == (4*a*c)) {
19531 res = (double)bezier_error;
19532 } else if ((b*b) < (4*a*c)) {
19533 res = mp_out(xo)-mp_out(xi); /* ? */
19534 if (res<=0.0 &&res>-180.0)
19536 else if (res>=0.0 && res<180.0)
19539 res = mp_out(xo)-mp_out(xi);
19542 else if (res>180.0)
19547 return double2angle(res);
19551 @d p_nextnext mp_link(mp_link(p))
19552 @d p_next mp_link(p)
19553 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19555 @<Declare unary action...@>=
19556 static scaled mp_new_turn_cycles (MP mp,pointer c) {
19557 angle res,ang; /* the angles of intermediate results */
19558 scaled turns; /* the turn counter */
19559 pointer p; /* for running around the path */
19560 integer xp,yp; /* coordinates of next point */
19561 integer x,y; /* helper coordinates */
19562 angle in_angle,out_angle; /* helper angles */
19563 unsigned old_setting; /* saved |selector| setting */
19567 old_setting = mp->selector; mp->selector=term_only;
19568 if ( mp->internal[mp_tracing_commands]>unity ) {
19569 mp_begin_diagnostic(mp);
19570 mp_print_nl(mp, "");
19571 mp_end_diagnostic(mp, false);
19574 xp = mp_x_coord(p_next); yp = mp_y_coord(p_next);
19575 ang = mp_bezier_slope(mp,mp_x_coord(p), mp_y_coord(p), mp_right_x(p), mp_right_y(p),
19576 mp_left_x(p_next), mp_left_y(p_next), xp, yp);
19577 if ( ang>seven_twenty_deg ) {
19578 print_err("Strange path");
19580 mp->selector=old_setting;
19584 if ( res > one_eighty_deg ) {
19585 res = res - three_sixty_deg;
19586 turns = turns + unity;
19588 if ( res <= -one_eighty_deg ) {
19589 res = res + three_sixty_deg;
19590 turns = turns - unity;
19592 /* incoming angle at next point */
19593 x = mp_left_x(p_next); y = mp_left_y(p_next);
19594 if ( (xp==x)&&(yp==y) ) { x = mp_right_x(p); y = mp_right_y(p); };
19595 if ( (xp==x)&&(yp==y) ) { x = mp_x_coord(p); y = mp_y_coord(p); };
19596 in_angle = mp_an_angle(mp, xp - x, yp - y);
19597 /* outgoing angle at next point */
19598 x = mp_right_x(p_next); y = mp_right_y(p_next);
19599 if ( (xp==x)&&(yp==y) ) { x = mp_left_x(p_nextnext); y = mp_left_y(p_nextnext); };
19600 if ( (xp==x)&&(yp==y) ) { x = mp_x_coord(p_nextnext); y = mp_y_coord(p_nextnext); };
19601 out_angle = mp_an_angle(mp, x - xp, y- yp);
19602 ang = (out_angle - in_angle);
19606 if ( res >= one_eighty_deg ) {
19607 res = res - three_sixty_deg;
19608 turns = turns + unity;
19610 if ( res <= -one_eighty_deg ) {
19611 res = res + three_sixty_deg;
19612 turns = turns - unity;
19617 mp->selector=old_setting;
19622 @ This code is based on Bogus\l{}av Jackowski's
19623 |emergency_turningnumber| macro, with some minor changes by Taco
19624 Hoekwater. The macro code looked more like this:
19626 vardef turning\_number primary p =
19627 ~~save res, ang, turns;
19629 ~~if length p <= 2:
19630 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0: 1 else: -1 fi
19632 ~~~~for t = 0 upto length p-1 :
19633 ~~~~~~angc := Angle ((point t+1 of p) - (point t of p))
19634 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19635 ~~~~~~if angc > 180: angc := angc - 360; fi;
19636 ~~~~~~if angc < -180: angc := angc + 360; fi;
19637 ~~~~~~res := res + angc;
19642 The general idea is to calculate only the sum of the angles of
19643 straight lines between the points, of a path, not worrying about cusps
19644 or self-intersections in the segments at all. If the segment is not
19645 well-behaved, the result is not necesarily correct. But the old code
19646 was not always correct either, and worse, it sometimes failed for
19647 well-behaved paths as well. All known bugs that were triggered by the
19648 original code no longer occur with this code, and it runs roughly 3
19649 times as fast because the algorithm is much simpler.
19651 @ It is possible to overflow the return value of the |turn_cycles|
19652 function when the path is sufficiently long and winding, but I am not
19653 going to bother testing for that. In any case, it would only return
19654 the looped result value, which is not a big problem.
19656 The macro code for the repeat loop was a bit nicer to look
19657 at than the pascal code, because it could use |point -1 of p|. In
19658 pascal, the fastest way to loop around the path is not to look
19659 backward once, but forward twice. These defines help hide the trick.
19661 @d p_to mp_link(mp_link(p))
19662 @d p_here mp_link(p)
19665 @<Declare unary action...@>=
19666 static scaled mp_turn_cycles (MP mp,pointer c) {
19667 angle res,ang; /* the angles of intermediate results */
19668 scaled turns; /* the turn counter */
19669 pointer p; /* for running around the path */
19670 res=0; turns= 0; p=c;
19672 ang = mp_an_angle (mp, mp_x_coord(p_to) - mp_x_coord(p_here),
19673 mp_y_coord(p_to) - mp_y_coord(p_here))
19674 - mp_an_angle (mp, mp_x_coord(p_here) - mp_x_coord(p_from),
19675 mp_y_coord(p_here) - mp_y_coord(p_from));
19678 if ( res >= three_sixty_deg ) {
19679 res = res - three_sixty_deg;
19680 turns = turns + unity;
19682 if ( res <= -three_sixty_deg ) {
19683 res = res + three_sixty_deg;
19684 turns = turns - unity;
19691 @ @<Declare unary action...@>=
19692 static scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19694 scaled saved_t_o; /* tracing\_online saved */
19695 if ( (mp_link(c)==c)||(mp_link(mp_link(c))==c) ) {
19696 if ( mp_an_angle (mp, mp_x_coord(c) - mp_right_x(c), mp_y_coord(c) - mp_right_y(c)) > 0 )
19701 nval = mp_new_turn_cycles(mp, c);
19702 oval = mp_turn_cycles(mp, c);
19703 if ( nval!=oval ) {
19704 saved_t_o=mp->internal[mp_tracing_online];
19705 mp->internal[mp_tracing_online]=unity;
19706 mp_begin_diagnostic(mp);
19707 mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19708 " The current computed value is ");
19709 mp_print_scaled(mp, nval);
19710 mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19711 mp_print_scaled(mp, oval);
19712 mp_end_diagnostic(mp, false);
19713 mp->internal[mp_tracing_online]=saved_t_o;
19719 @ @d type_range(A,B) {
19720 if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) )
19721 mp_flush_cur_exp(mp, true_code);
19722 else mp_flush_cur_exp(mp, false_code);
19723 mp->cur_type=mp_boolean_type;
19726 if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19727 else mp_flush_cur_exp(mp, false_code);
19728 mp->cur_type=mp_boolean_type;
19731 @<Additional cases of unary operators@>=
19732 case mp_boolean_type:
19733 type_range(mp_boolean_type,mp_unknown_boolean); break;
19734 case mp_string_type:
19735 type_range(mp_string_type,mp_unknown_string); break;
19737 type_range(mp_pen_type,mp_unknown_pen); break;
19739 type_range(mp_path_type,mp_unknown_path); break;
19740 case mp_picture_type:
19741 type_range(mp_picture_type,mp_unknown_picture); break;
19742 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19744 type_test(c); break;
19745 case mp_numeric_type:
19746 type_range(mp_known,mp_independent); break;
19747 case known_op: case unknown_op:
19748 mp_test_known(mp, c); break;
19750 @ @<Declare unary action procedures@>=
19751 static void mp_test_known (MP mp,quarterword c) {
19752 int b; /* is the current expression known? */
19753 pointer p,q; /* locations in a big node */
19755 switch (mp->cur_type) {
19756 case mp_vacuous: case mp_boolean_type: case mp_string_type:
19757 case mp_pen_type: case mp_path_type: case mp_picture_type:
19761 case mp_transform_type:
19762 case mp_color_type: case mp_cmykcolor_type: case mp_pair_type:
19763 p=value(mp->cur_exp);
19764 q=p+mp->big_node_size[mp->cur_type];
19767 if ( mp_type(q)!=mp_known )
19776 if ( c==known_op ) mp_flush_cur_exp(mp, b);
19777 else mp_flush_cur_exp(mp, true_code+false_code-b);
19778 mp->cur_type=mp_boolean_type;
19781 @ @<Additional cases of unary operators@>=
19783 if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19784 else if ( mp_left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19785 else mp_flush_cur_exp(mp, false_code);
19786 mp->cur_type=mp_boolean_type;
19789 @ @<Additional cases of unary operators@>=
19791 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19792 if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19793 else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19796 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19798 @^data structure assumptions@>
19800 @<Additional cases of unary operators@>=
19806 if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19807 else if ( mp_link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19808 else if ( mp_type(mp_link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19809 mp_flush_cur_exp(mp, true_code);
19810 else mp_flush_cur_exp(mp, false_code);
19811 mp->cur_type=mp_boolean_type;
19814 @ @<Additional cases of unary operators@>=
19816 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19817 if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19819 mp->cur_type=mp_pen_type;
19820 mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19824 if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19826 mp->cur_type=mp_path_type;
19827 mp_make_path(mp, mp->cur_exp);
19831 if ( mp->cur_type==mp_path_type ) {
19832 p=mp_htap_ypoc(mp, mp->cur_exp);
19833 if ( mp_right_type(p)==mp_endpoint ) p=mp_link(p);
19834 mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19835 } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19836 else mp_bad_unary(mp, reverse);
19839 @ The |pair_value| routine changes the current expression to a
19840 given ordered pair of values.
19842 @<Declare unary action procedures@>=
19843 static void mp_pair_value (MP mp,scaled x, scaled y) {
19844 pointer p; /* a pair node */
19845 p=mp_get_node(mp, value_node_size);
19846 mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19847 mp_type(p)=mp_pair_type; mp_name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19849 mp_type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19850 mp_type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19853 @ @<Additional cases of unary operators@>=
19855 if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19856 else mp_pair_value(mp, mp_minx, mp_miny);
19859 if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19860 else mp_pair_value(mp, mp_maxx, mp_miny);
19863 if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19864 else mp_pair_value(mp, mp_minx, mp_maxy);
19867 if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19868 else mp_pair_value(mp, mp_maxx, mp_maxy);
19871 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19872 box of the current expression. The boolean result is |false| if the expression
19873 has the wrong type.
19875 @<Declare unary action procedures@>=
19876 static boolean mp_get_cur_bbox (MP mp) {
19877 switch (mp->cur_type) {
19878 case mp_picture_type:
19879 mp_set_bbox(mp, mp->cur_exp,true);
19880 if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19881 mp_minx=0; mp_maxx=0; mp_miny=0; mp_maxy=0;
19883 mp_minx=minx_val(mp->cur_exp);
19884 mp_maxx=maxx_val(mp->cur_exp);
19885 mp_miny=miny_val(mp->cur_exp);
19886 mp_maxy=maxy_val(mp->cur_exp);
19890 mp_path_bbox(mp, mp->cur_exp);
19893 mp_pen_bbox(mp, mp->cur_exp);
19901 @ @<Additional cases of unary operators@>=
19903 case close_from_op:
19904 if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19905 else mp_do_read_or_close(mp,c);
19908 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19909 a line from the file or to close the file.
19911 @<Declare unary action procedures@>=
19912 static void mp_do_read_or_close (MP mp,quarterword c) {
19913 readf_index n,n0; /* indices for searching |rd_fname| */
19914 @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19915 call |start_read_input| and |goto found| or |not_found|@>;
19916 mp_begin_file_reading(mp);
19918 if ( mp_input_ln(mp, mp->rd_file[n] ) )
19920 mp_end_file_reading(mp);
19922 @<Record the end of file and set |cur_exp| to a dummy value@>;
19925 mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
19928 mp_flush_cur_exp(mp, 0);
19929 mp_finish_read(mp);
19932 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19935 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19940 fn = str(mp->cur_exp);
19941 while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) {
19944 } else if ( c==close_from_op ) {
19947 if ( n0==mp->read_files ) {
19948 if ( mp->read_files<mp->max_read_files ) {
19949 incr(mp->read_files);
19954 l = mp->max_read_files + (mp->max_read_files/4);
19955 rd_file = xmalloc((l+1), sizeof(void *));
19956 rd_fname = xmalloc((l+1), sizeof(char *));
19957 for (k=0;k<=l;k++) {
19958 if (k<=mp->max_read_files) {
19959 rd_file[k]=mp->rd_file[k];
19960 rd_fname[k]=mp->rd_fname[k];
19966 xfree(mp->rd_file); xfree(mp->rd_fname);
19967 mp->max_read_files = l;
19968 mp->rd_file = rd_file;
19969 mp->rd_fname = rd_fname;
19973 if ( mp_start_read_input(mp,fn,n) )
19978 if ( mp->rd_fname[n]==NULL ) { n0=n; }
19980 if ( c==close_from_op ) {
19981 (mp->close_file)(mp,mp->rd_file[n]);
19986 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19987 xfree(mp->rd_fname[n]);
19988 mp->rd_fname[n]=NULL;
19989 if ( n==mp->read_files-1 ) mp->read_files=n;
19990 if ( c==close_from_op )
19992 mp_flush_cur_exp(mp, mp->eof_line);
19993 mp->cur_type=mp_string_type
19995 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19998 str_number eof_line;
20003 @ Finally, we have the operations that combine a capsule~|p|
20004 with the current expression.
20006 @d binary_return { mp_finish_binary(mp, old_p, old_exp); return; }
20008 @c @<Declare binary action procedures@>
20009 static void mp_finish_binary (MP mp, pointer old_p, pointer old_exp ){
20011 @<Recycle any sidestepped |independent| capsules@>;
20013 static void mp_do_binary (MP mp,pointer p, quarterword c) {
20014 pointer q,r,rr; /* for list manipulation */
20015 pointer old_p,old_exp; /* capsules to recycle */
20016 integer v; /* for numeric manipulation */
20018 if ( mp->internal[mp_tracing_commands]>two ) {
20019 @<Trace the current binary operation@>;
20021 @<Sidestep |independent| cases in capsule |p|@>;
20022 @<Sidestep |independent| cases in the current expression@>;
20024 case plus: case minus:
20025 @<Add or subtract the current expression from |p|@>;
20027 @<Additional cases of binary operators@>;
20028 }; /* there are no other cases */
20029 mp_recycle_value(mp, p);
20030 mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
20031 mp_finish_binary(mp, old_p, old_exp);
20034 @ @<Declare binary action...@>=
20035 static void mp_bad_binary (MP mp,pointer p, quarterword c) {
20036 mp_disp_err(mp, p,"");
20037 exp_err("Not implemented: ");
20038 @.Not implemented...@>
20039 if ( c>=min_of ) mp_print_op(mp, c);
20040 mp_print_known_or_unknown_type(mp, mp_type(p),p);
20041 if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
20042 mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
20043 help3("I'm afraid I don't know how to apply that operation to that",
20044 "combination of types. Continue, and I'll return the second",
20045 "argument (see above) as the result of the operation.");
20046 mp_put_get_error(mp);
20048 static void mp_bad_envelope_pen (MP mp) {
20049 mp_disp_err(mp, null,"");
20050 exp_err("Not implemented: envelope(elliptical pen)of(path)");
20051 @.Not implemented...@>
20052 help3("I'm afraid I don't know how to apply that operation to that",
20053 "combination of types. Continue, and I'll return the second",
20054 "argument (see above) as the result of the operation.");
20055 mp_put_get_error(mp);
20058 @ @<Trace the current binary operation@>=
20060 mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
20061 mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
20062 mp_print_char(mp,xord(')')); mp_print_op(mp,c); mp_print_char(mp,xord('('));
20063 mp_print_exp(mp,null,0); mp_print(mp,")}");
20064 mp_end_diagnostic(mp, false);
20067 @ Several of the binary operations are potentially complicated by the
20068 fact that |independent| values can sneak into capsules. For example,
20069 we've seen an instance of this difficulty in the unary operation
20070 of negation. In order to reduce the number of cases that need to be
20071 handled, we first change the two operands (if necessary)
20072 to rid them of |independent| components. The original operands are
20073 put into capsules called |old_p| and |old_exp|, which will be
20074 recycled after the binary operation has been safely carried out.
20076 @<Recycle any sidestepped |independent| capsules@>=
20077 if ( old_p!=null ) {
20078 mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
20080 if ( old_exp!=null ) {
20081 mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
20084 @ A big node is considered to be ``tarnished'' if it contains at least one
20085 independent component. We will define a simple function called `|tarnished|'
20086 that returns |null| if and only if its argument is not tarnished.
20088 @<Sidestep |independent| cases in capsule |p|@>=
20089 switch (mp_type(p)) {
20090 case mp_transform_type:
20091 case mp_color_type:
20092 case mp_cmykcolor_type:
20094 old_p=mp_tarnished(mp, p);
20096 case mp_independent: old_p=mp_void; break;
20097 default: old_p=null; break;
20099 if ( old_p!=null ) {
20100 q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
20101 p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
20104 @ @<Sidestep |independent| cases in the current expression@>=
20105 switch (mp->cur_type) {
20106 case mp_transform_type:
20107 case mp_color_type:
20108 case mp_cmykcolor_type:
20110 old_exp=mp_tarnished(mp, mp->cur_exp);
20112 case mp_independent:old_exp=mp_void; break;
20113 default: old_exp=null; break;
20115 if ( old_exp!=null ) {
20116 old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20119 @ @<Declare binary action...@>=
20120 static pointer mp_tarnished (MP mp,pointer p) {
20121 pointer q; /* beginning of the big node */
20122 pointer r; /* current position in the big node */
20123 q=value(p); r=q+mp->big_node_size[mp_type(p)];
20126 if ( mp_type(r)==mp_independent ) return mp_void;
20131 @ @<Add or subtract the current expression from |p|@>=
20132 if ( (mp->cur_type<mp_color_type)||(mp_type(p)<mp_color_type) ) {
20133 mp_bad_binary(mp, p,c);
20135 if ((mp->cur_type>mp_pair_type)&&(mp_type(p)>mp_pair_type) ) {
20136 mp_add_or_subtract(mp, p,null,c);
20138 if ( mp->cur_type!=mp_type(p) ) {
20139 mp_bad_binary(mp, p,c);
20141 q=value(p); r=value(mp->cur_exp);
20142 rr=r+mp->big_node_size[mp->cur_type];
20144 mp_add_or_subtract(mp, q,r,c);
20151 @ The first argument to |add_or_subtract| is the location of a value node
20152 in a capsule or pair node that will soon be recycled. The second argument
20153 is either a location within a pair or transform node of |cur_exp|,
20154 or it is null (which means that |cur_exp| itself should be the second
20155 argument). The third argument is either |plus| or |minus|.
20157 The sum or difference of the numeric quantities will replace the second
20158 operand. Arithmetic overflow may go undetected; users aren't supposed to
20159 be monkeying around with really big values.
20160 @^overflow in arithmetic@>
20162 @<Declare binary action...@>=
20163 @<Declare the procedure called |dep_finish|@>
20164 static void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
20165 quarterword s,t; /* operand types */
20166 pointer r; /* list traverser */
20167 integer v; /* second operand value */
20170 if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
20173 if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
20175 if ( t==mp_known ) {
20176 if ( c==minus ) negate(v);
20177 if ( mp_type(p)==mp_known ) {
20178 v=mp_slow_add(mp, value(p),v);
20179 if ( q==null ) mp->cur_exp=v; else value(q)=v;
20182 @<Add a known value to the constant term of |dep_list(p)|@>;
20184 if ( c==minus ) mp_negate_dep_list(mp, v);
20185 @<Add operand |p| to the dependency list |v|@>;
20189 @ @<Add a known value to the constant term of |dep_list(p)|@>=
20191 while ( mp_info(r)!=null ) r=mp_link(r);
20192 value(r)=mp_slow_add(mp, value(r),v);
20194 q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=mp_type(p);
20195 mp_name_type(q)=mp_capsule;
20197 dep_list(q)=dep_list(p); mp_type(q)=mp_type(p);
20198 prev_dep(q)=prev_dep(p); mp_link(prev_dep(p))=q;
20199 mp_type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
20201 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
20202 nice to retain the extra accuracy of |fraction| coefficients.
20203 But we have to handle both kinds, and mixtures too.
20205 @<Add operand |p| to the dependency list |v|@>=
20206 if ( mp_type(p)==mp_known ) {
20207 @<Add the known |value(p)| to the constant term of |v|@>;
20209 s=mp_type(p); r=dep_list(p);
20210 if ( t==mp_dependent ) {
20211 if ( s==mp_dependent ) {
20212 if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
20213 v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
20214 } /* |fix_needed| will necessarily be false */
20215 t=mp_proto_dependent;
20216 v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
20218 if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
20219 else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
20221 @<Output the answer, |v| (which might have become |known|)@>;
20224 @ @<Add the known |value(p)| to the constant term of |v|@>=
20226 while ( mp_info(v)!=null ) v=mp_link(v);
20227 value(v)=mp_slow_add(mp, value(p),value(v));
20230 @ @<Output the answer, |v| (which might have become |known|)@>=
20231 if ( q!=null ) mp_dep_finish(mp, v,q,t);
20232 else { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
20234 @ Here's the current situation: The dependency list |v| of type |t|
20235 should either be put into the current expression (if |q=null|) or
20236 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20237 or |q|) formerly held a dependency list with the same
20238 final pointer as the list |v|.
20240 @<Declare the procedure called |dep_finish|@>=
20241 static void mp_dep_finish (MP mp, pointer v, pointer q, quarterword t) {
20242 pointer p; /* the destination */
20243 scaled vv; /* the value, if it is |known| */
20244 if ( q==null ) p=mp->cur_exp; else p=q;
20245 dep_list(p)=v; mp_type(p)=t;
20246 if ( mp_info(v)==null ) {
20249 mp_flush_cur_exp(mp, vv);
20251 mp_recycle_value(mp, p); mp_type(q)=mp_known; value(q)=vv;
20253 } else if ( q==null ) {
20256 if ( mp->fix_needed ) mp_fix_dependencies(mp);
20259 @ Let's turn now to the six basic relations of comparison.
20261 @<Additional cases of binary operators@>=
20262 case less_than: case less_or_equal: case greater_than:
20263 case greater_or_equal: case equal_to: case unequal_to:
20264 check_arith; /* at this point |arith_error| should be |false|? */
20265 if ( (mp->cur_type>mp_pair_type)&&(mp_type(p)>mp_pair_type) ) {
20266 mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20267 } else if ( mp->cur_type!=mp_type(p) ) {
20268 mp_bad_binary(mp, p,c); goto DONE;
20269 } else if ( mp->cur_type==mp_string_type ) {
20270 mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20271 } else if ((mp->cur_type==mp_unknown_string)||
20272 (mp->cur_type==mp_unknown_boolean) ) {
20273 @<Check if unknowns have been equated@>;
20274 } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20275 @<Reduce comparison of big nodes to comparison of scalars@>;
20276 } else if ( mp->cur_type==mp_boolean_type ) {
20277 mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20279 mp_bad_binary(mp, p,c); goto DONE;
20281 @<Compare the current expression with zero@>;
20283 mp->arith_error=false; /* ignore overflow in comparisons */
20286 @ @<Compare the current expression with zero@>=
20287 if ( mp->cur_type!=mp_known ) {
20288 if ( mp->cur_type<mp_known ) {
20289 mp_disp_err(mp, p,"");
20290 help1("The quantities shown above have not been equated.")
20292 help2("Oh dear. I can\'t decide if the expression above is positive,",
20293 "negative, or zero. So this comparison test won't be `true'.");
20295 exp_err("Unknown relation will be considered false");
20296 @.Unknown relation...@>
20297 mp_put_get_flush_error(mp, false_code);
20300 case less_than: boolean_reset(mp->cur_exp<0); break;
20301 case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20302 case greater_than: boolean_reset(mp->cur_exp>0); break;
20303 case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20304 case equal_to: boolean_reset(mp->cur_exp==0); break;
20305 case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20306 }; /* there are no other cases */
20308 mp->cur_type=mp_boolean_type
20310 @ When two unknown strings are in the same ring, we know that they are
20311 equal. Otherwise, we don't know whether they are equal or not, so we
20314 @<Check if unknowns have been equated@>=
20316 q=value(mp->cur_exp);
20317 while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20318 if ( q==p ) mp_flush_cur_exp(mp, 0);
20321 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20323 q=value(p); r=value(mp->cur_exp);
20324 rr=r+mp->big_node_size[mp->cur_type]-2;
20325 while (1) { mp_add_or_subtract(mp, q,r,minus);
20326 if ( mp_type(r)!=mp_known ) break;
20327 if ( value(r)!=0 ) break;
20328 if ( r==rr ) break;
20331 mp_take_part(mp, mp_name_type(r)+x_part-mp_x_part_sector);
20334 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20336 @<Additional cases of binary operators@>=
20339 if ( (mp_type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20340 mp_bad_binary(mp, p,c);
20341 else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20344 @ @<Additional cases of binary operators@>=
20346 if ( (mp->cur_type<mp_color_type)||(mp_type(p)<mp_color_type) ) {
20347 mp_bad_binary(mp, p,times);
20348 } else if ( (mp->cur_type==mp_known)||(mp_type(p)==mp_known) ) {
20349 @<Multiply when at least one operand is known@>;
20350 } else if ( (mp_nice_color_or_pair(mp, p,mp_type(p))&&(mp->cur_type>mp_pair_type))
20351 ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20352 (mp_type(p)>mp_pair_type)) ) {
20353 mp_hard_times(mp, p);
20356 mp_bad_binary(mp, p,times);
20360 @ @<Multiply when at least one operand is known@>=
20362 if ( mp_type(p)==mp_known ) {
20363 v=value(p); mp_free_node(mp, p,value_node_size);
20365 v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20367 if ( mp->cur_type==mp_known ) {
20368 mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20369 } else if ( (mp->cur_type==mp_pair_type)||
20370 (mp->cur_type==mp_color_type)||
20371 (mp->cur_type==mp_cmykcolor_type) ) {
20372 p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20374 p=p-2; mp_dep_mult(mp, p,v,true);
20375 } while (p!=value(mp->cur_exp));
20377 mp_dep_mult(mp, null,v,true);
20382 @ @<Declare binary action...@>=
20383 static void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20384 pointer q; /* the dependency list being multiplied by |v| */
20385 quarterword s,t; /* its type, before and after */
20388 } else if ( mp_type(p)!=mp_known ) {
20391 if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20392 else value(p)=mp_take_fraction(mp, value(p),v);
20395 t=mp_type(q); q=dep_list(q); s=t;
20396 if ( t==mp_dependent ) if ( v_is_scaled )
20397 if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 )
20398 t=mp_proto_dependent;
20399 q=mp_p_times_v(mp, q,v,s,t,v_is_scaled);
20400 mp_dep_finish(mp, q,p,t);
20403 @ Here is a routine that is similar to |times|; but it is invoked only
20404 internally, when |v| is a |fraction| whose magnitude is at most~1,
20405 and when |cur_type>=mp_color_type|.
20408 static void mp_frac_mult (MP mp,scaled n, scaled d) {
20409 /* multiplies |cur_exp| by |n/d| */
20410 pointer p; /* a pair node */
20411 pointer old_exp; /* a capsule to recycle */
20412 fraction v; /* |n/d| */
20413 if ( mp->internal[mp_tracing_commands]>two ) {
20414 @<Trace the fraction multiplication@>;
20416 switch (mp->cur_type) {
20417 case mp_transform_type:
20418 case mp_color_type:
20419 case mp_cmykcolor_type:
20421 old_exp=mp_tarnished(mp, mp->cur_exp);
20423 case mp_independent: old_exp=mp_void; break;
20424 default: old_exp=null; break;
20426 if ( old_exp!=null ) {
20427 old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20429 v=mp_make_fraction(mp, n,d);
20430 if ( mp->cur_type==mp_known ) {
20431 mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20432 } else if ( mp->cur_type<=mp_pair_type ) {
20433 p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20436 mp_dep_mult(mp, p,v,false);
20437 } while (p!=value(mp->cur_exp));
20439 mp_dep_mult(mp, null,v,false);
20441 if ( old_exp!=null ) {
20442 mp_recycle_value(mp, old_exp);
20443 mp_free_node(mp, old_exp,value_node_size);
20447 @ @<Trace the fraction multiplication@>=
20449 mp_begin_diagnostic(mp);
20450 mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,xord('/'));
20451 mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0);
20453 mp_end_diagnostic(mp, false);
20456 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20458 @<Declare binary action procedures@>=
20459 static void mp_hard_times (MP mp,pointer p) {
20460 pointer q; /* a copy of the dependent variable |p| */
20461 pointer r; /* a component of the big node for the nice color or pair */
20462 scaled v; /* the known value for |r| */
20463 if ( mp_type(p)<=mp_pair_type ) {
20464 q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20465 }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20466 r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20470 mp_type(r)=mp_type(p);
20471 if ( r==value(mp->cur_exp) )
20473 mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20474 mp_dep_mult(mp, r,v,true);
20476 mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20477 mp_link(prev_dep(p))=r;
20478 mp_free_node(mp, p,value_node_size);
20479 mp_dep_mult(mp, r,v,true);
20482 @ @<Additional cases of binary operators@>=
20484 if ( (mp->cur_type!=mp_known)||(mp_type(p)<mp_color_type) ) {
20485 mp_bad_binary(mp, p,over);
20487 v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20489 @<Squeal about division by zero@>;
20491 if ( mp->cur_type==mp_known ) {
20492 mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20493 } else if ( mp->cur_type<=mp_pair_type ) {
20494 p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20496 p=p-2; mp_dep_div(mp, p,v);
20497 } while (p!=value(mp->cur_exp));
20499 mp_dep_div(mp, null,v);
20506 @ @<Declare binary action...@>=
20507 static void mp_dep_div (MP mp,pointer p, scaled v) {
20508 pointer q; /* the dependency list being divided by |v| */
20509 quarterword s,t; /* its type, before and after */
20510 if ( p==null ) q=mp->cur_exp;
20511 else if ( mp_type(p)!=mp_known ) q=p;
20512 else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20513 t=mp_type(q); q=dep_list(q); s=t;
20514 if ( t==mp_dependent )
20515 if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 )
20516 t=mp_proto_dependent;
20517 q=mp_p_over_v(mp, q,v,s,t);
20518 mp_dep_finish(mp, q,p,t);
20521 @ @<Squeal about division by zero@>=
20523 exp_err("Division by zero");
20524 @.Division by zero@>
20525 help2("You're trying to divide the quantity shown above the error",
20526 "message by zero. I'm going to divide it by one instead.");
20527 mp_put_get_error(mp);
20530 @ @<Additional cases of binary operators@>=
20533 if ( (mp->cur_type==mp_known)&&(mp_type(p)==mp_known) ) {
20534 if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20535 else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20536 } else mp_bad_binary(mp, p,c);
20539 @ The next few sections of the program deal with affine transformations
20540 of coordinate data.
20542 @<Additional cases of binary operators@>=
20543 case rotated_by: case slanted_by:
20544 case scaled_by: case shifted_by: case transformed_by:
20545 case x_scaled: case y_scaled: case z_scaled:
20546 if ( mp_type(p)==mp_path_type ) {
20547 path_trans(c,p); binary_return;
20548 } else if ( mp_type(p)==mp_pen_type ) {
20550 mp->cur_exp=mp_convex_hull(mp, mp->cur_exp);
20551 /* rounding error could destroy convexity */
20553 } else if ( (mp_type(p)==mp_pair_type)||(mp_type(p)==mp_transform_type) ) {
20554 mp_big_trans(mp, p,c);
20555 } else if ( mp_type(p)==mp_picture_type ) {
20556 mp_do_edges_trans(mp, p,c); binary_return;
20558 mp_bad_binary(mp, p,c);
20562 @ Let |c| be one of the eight transform operators. The procedure call
20563 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20564 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20565 change at all if |c=transformed_by|.)
20567 Then, if all components of the resulting transform are |known|, they are
20568 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20569 and |cur_exp| is changed to the known value zero.
20571 @<Declare binary action...@>=
20572 static void mp_set_up_trans (MP mp,quarterword c) {
20573 pointer p,q,r; /* list manipulation registers */
20574 if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20575 @<Put the current transform into |cur_exp|@>;
20577 @<If the current transform is entirely known, stash it in global variables;
20578 otherwise |return|@>;
20587 scaled ty; /* current transform coefficients */
20589 @ @<Put the current transform...@>=
20591 p=mp_stash_cur_exp(mp);
20592 mp->cur_exp=mp_id_transform(mp);
20593 mp->cur_type=mp_transform_type;
20594 q=value(mp->cur_exp);
20596 @<For each of the eight cases, change the relevant fields of |cur_exp|
20598 but do nothing if capsule |p| doesn't have the appropriate type@>;
20599 }; /* there are no other cases */
20600 mp_disp_err(mp, p,"Improper transformation argument");
20601 @.Improper transformation argument@>
20602 help3("The expression shown above has the wrong type,",
20603 "so I can\'t transform anything using it.",
20604 "Proceed, and I'll omit the transformation.");
20605 mp_put_get_error(mp);
20607 mp_recycle_value(mp, p);
20608 mp_free_node(mp, p,value_node_size);
20611 @ @<If the current transform is entirely known, ...@>=
20612 q=value(mp->cur_exp); r=q+transform_node_size;
20615 if ( mp_type(r)!=mp_known ) return;
20617 mp->txx=value(xx_part_loc(q));
20618 mp->txy=value(xy_part_loc(q));
20619 mp->tyx=value(yx_part_loc(q));
20620 mp->tyy=value(yy_part_loc(q));
20621 mp->tx=value(x_part_loc(q));
20622 mp->ty=value(y_part_loc(q));
20623 mp_flush_cur_exp(mp, 0)
20625 @ @<For each of the eight cases...@>=
20627 if ( mp_type(p)==mp_known )
20628 @<Install sines and cosines, then |goto done|@>;
20631 if ( mp_type(p)>mp_pair_type ) {
20632 mp_install(mp, xy_part_loc(q),p); goto DONE;
20636 if ( mp_type(p)>mp_pair_type ) {
20637 mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p);
20642 if ( mp_type(p)==mp_pair_type ) {
20643 r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20644 mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20648 if ( mp_type(p)>mp_pair_type ) {
20649 mp_install(mp, xx_part_loc(q),p); goto DONE;
20653 if ( mp_type(p)>mp_pair_type ) {
20654 mp_install(mp, yy_part_loc(q),p); goto DONE;
20658 if ( mp_type(p)==mp_pair_type )
20659 @<Install a complex multiplier, then |goto done|@>;
20661 case transformed_by:
20665 @ @<Install sines and cosines, then |goto done|@>=
20666 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20667 value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20668 value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20669 value(xy_part_loc(q))=-value(yx_part_loc(q));
20670 value(yy_part_loc(q))=value(xx_part_loc(q));
20674 @ @<Install a complex multiplier, then |goto done|@>=
20677 mp_install(mp, xx_part_loc(q),x_part_loc(r));
20678 mp_install(mp, yy_part_loc(q),x_part_loc(r));
20679 mp_install(mp, yx_part_loc(q),y_part_loc(r));
20680 if ( mp_type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20681 else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20682 mp_install(mp, xy_part_loc(q),y_part_loc(r));
20686 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20687 insists that the transformation be entirely known.
20689 @<Declare binary action...@>=
20690 static void mp_set_up_known_trans (MP mp,quarterword c) {
20691 mp_set_up_trans(mp, c);
20692 if ( mp->cur_type!=mp_known ) {
20693 exp_err("Transform components aren't all known");
20694 @.Transform components...@>
20695 help3("I'm unable to apply a partially specified transformation",
20696 "except to a fully known pair or transform.",
20697 "Proceed, and I'll omit the transformation.");
20698 mp_put_get_flush_error(mp, 0);
20699 mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity;
20700 mp->tx=0; mp->ty=0;
20704 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20705 coordinates in locations |p| and~|q|.
20707 @<Declare binary action...@>=
20708 static void mp_trans (MP mp,pointer p, pointer q) {
20709 scaled v; /* the new |x| value */
20710 v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20711 mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20712 mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20713 mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20717 @ The simplest transformation procedure applies a transform to all
20718 coordinates of a path. The |path_trans(c)(p)| macro applies
20719 a transformation defined by |cur_exp| and the transform operator |c|
20722 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A));
20723 mp_unstash_cur_exp(mp, (B));
20724 mp_do_path_trans(mp, mp->cur_exp); }
20726 @<Declare binary action...@>=
20727 static void mp_do_path_trans (MP mp,pointer p) {
20728 pointer q; /* list traverser */
20731 if ( mp_left_type(q)!=mp_endpoint )
20732 mp_trans(mp, q+3,q+4); /* that's |mp_left_x| and |mp_left_y| */
20733 mp_trans(mp, q+1,q+2); /* that's |mp_x_coord| and |mp_y_coord| */
20734 if ( mp_right_type(q)!=mp_endpoint )
20735 mp_trans(mp, q+5,q+6); /* that's |mp_right_x| and |mp_right_y| */
20736 @^data structure assumptions@>
20741 @ Transforming a pen is very similar, except that there are no |mp_left_type|
20742 and |mp_right_type| fields.
20744 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A));
20745 mp_unstash_cur_exp(mp, (B));
20746 mp_do_pen_trans(mp, mp->cur_exp); }
20748 @<Declare binary action...@>=
20749 static void mp_do_pen_trans (MP mp,pointer p) {
20750 pointer q; /* list traverser */
20751 if ( pen_is_elliptical(p) ) {
20752 mp_trans(mp, p+3,p+4); /* that's |mp_left_x| and |mp_left_y| */
20753 mp_trans(mp, p+5,p+6); /* that's |mp_right_x| and |mp_right_y| */
20757 mp_trans(mp, q+1,q+2); /* that's |mp_x_coord| and |mp_y_coord| */
20758 @^data structure assumptions@>
20763 @ The next transformation procedure applies to edge structures. It will do
20764 any transformation, but the results may be substandard if the picture contains
20765 text that uses downloaded bitmap fonts. The binary action procedure is
20766 |do_edges_trans|, but we also need a function that just scales a picture.
20767 That routine is |scale_edges|. Both it and the underlying routine |edges_trans|
20768 should be thought of as procedures that update an edge structure |h|, except
20769 that they have to return a (possibly new) structure because of the need to call
20772 @<Declare binary action...@>=
20773 static pointer mp_edges_trans (MP mp, pointer h) {
20774 pointer q; /* the object being transformed */
20775 pointer r,s; /* for list manipulation */
20776 scaled sx,sy; /* saved transformation parameters */
20777 scaled sqdet; /* square root of determinant for |dash_scale| */
20778 integer sgndet; /* sign of the determinant */
20779 scaled v; /* a temporary value */
20780 h=mp_private_edges(mp, h);
20781 sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20782 sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20783 if ( dash_list(h)!=null_dash ) {
20784 @<Try to transform the dash list of |h|@>;
20786 @<Make the bounding box of |h| unknown if it can't be updated properly
20787 without scanning the whole structure@>;
20788 q=mp_link(dummy_loc(h));
20789 while ( q!=null ) {
20790 @<Transform graphical object |q|@>;
20795 static void mp_do_edges_trans (MP mp,pointer p, quarterword c) {
20796 mp_set_up_known_trans(mp, c);
20797 value(p)=mp_edges_trans(mp, value(p));
20798 mp_unstash_cur_exp(mp, p);
20800 static void mp_scale_edges (MP mp) {
20801 mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20802 mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20803 mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20806 @ @<Try to transform the dash list of |h|@>=
20807 if ( (mp->txy!=0)||(mp->tyx!=0)||
20808 (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20809 mp_flush_dash_list(mp, h);
20811 if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; }
20812 @<Scale the dash list by |txx| and shift it by |tx|@>;
20813 dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20816 @ @<Reverse the dash list of |h|@>=
20819 dash_list(h)=null_dash;
20820 while ( r!=null_dash ) {
20822 v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20823 mp_link(s)=dash_list(h);
20828 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20830 while ( r!=null_dash ) {
20831 start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20832 stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20836 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20837 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20838 @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20839 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20840 mp_init_bbox(mp, h);
20843 if ( minx_val(h)<=maxx_val(h) ) {
20844 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20851 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20853 v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20854 v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20857 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero. The other
20860 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20862 minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20863 maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20864 miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20865 maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20866 if ( mp->txx+mp->txy<0 ) {
20867 v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20869 if ( mp->tyx+mp->tyy<0 ) {
20870 v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20874 @ Now we ready for the main task of transforming the graphical objects in edge
20877 @<Transform graphical object |q|@>=
20878 switch (mp_type(q)) {
20879 case mp_fill_code: case mp_stroked_code:
20880 mp_do_path_trans(mp, mp_path_p(q));
20881 @<Transform |mp_pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20883 case mp_start_clip_code: case mp_start_bounds_code:
20884 mp_do_path_trans(mp, mp_path_p(q));
20888 @<Transform the compact transformation starting at |r|@>;
20890 case mp_stop_clip_code: case mp_stop_bounds_code:
20892 } /* there are no other cases */
20894 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20895 The |dash_scale| has to be adjusted to scale the dash lengths in |mp_dash_p(q)|
20896 since the \ps\ output procedures will try to compensate for the transformation
20897 we are applying to |mp_pen_p(q)|. Since this compensation is based on the square
20898 root of the determinant, |sqdet| is the appropriate factor.
20900 @<Transform |mp_pen_p(q)|, making sure...@>=
20901 if ( mp_pen_p(q)!=null ) {
20902 sx=mp->tx; sy=mp->ty;
20903 mp->tx=0; mp->ty=0;
20904 mp_do_pen_trans(mp, mp_pen_p(q));
20905 if ( ((mp_type(q)==mp_stroked_code)&&(mp_dash_p(q)!=null)) )
20906 dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20907 if ( ! pen_is_elliptical(mp_pen_p(q)) )
20909 mp_pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, mp_pen_p(q)),true);
20910 /* this unreverses the pen */
20911 mp->tx=sx; mp->ty=sy;
20914 @ This uses the fact that transformations are stored in the order
20915 |(tx,ty,txx,txy,tyx,tyy)|.
20916 @^data structure assumptions@>
20918 @<Transform the compact transformation starting at |r|@>=
20919 mp_trans(mp, r,r+1);
20920 sx=mp->tx; sy=mp->ty;
20921 mp->tx=0; mp->ty=0;
20922 mp_trans(mp, r+2,r+4);
20923 mp_trans(mp, r+3,r+5);
20924 mp->tx=sx; mp->ty=sy
20926 @ The hard cases of transformation occur when big nodes are involved,
20927 and when some of their components are unknown.
20929 @<Declare binary action...@>=
20930 @<Declare subroutines needed by |big_trans|@>
20931 static void mp_big_trans (MP mp,pointer p, quarterword c) {
20932 pointer q,r,pp,qq; /* list manipulation registers */
20933 quarterword s; /* size of a big node */
20934 s=mp->big_node_size[mp_type(p)]; q=value(p); r=q+s;
20937 if ( mp_type(r)!=mp_known ) {
20938 @<Transform an unknown big node and |return|@>;
20941 @<Transform a known big node@>;
20942 } /* node |p| will now be recycled by |do_binary| */
20944 @ @<Transform an unknown big node and |return|@>=
20946 mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p);
20947 r=value(mp->cur_exp);
20948 if ( mp->cur_type==mp_transform_type ) {
20949 mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20950 mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20951 mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20952 mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20954 mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20955 mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20959 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20960 and let |q| point to a another value field. The |bilin1| procedure
20961 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20963 @<Declare subroutines needed by |big_trans|@>=
20964 static void mp_bilin1 (MP mp, pointer p, scaled t, pointer q,
20965 scaled u, scaled delta) {
20966 pointer r; /* list traverser */
20967 if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20969 if ( mp_type(q)==mp_known ) {
20970 delta+=mp_take_scaled(mp, value(q),u);
20972 @<Ensure that |type(p)=mp_proto_dependent|@>;
20973 dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20974 mp_proto_dependent,mp_type(q));
20977 if ( mp_type(p)==mp_known ) {
20981 while ( mp_info(r)!=null ) r=mp_link(r);
20983 if ( r!=dep_list(p) ) value(r)=delta;
20984 else { mp_recycle_value(mp, p); mp_type(p)=mp_known; value(p)=delta; };
20986 if ( mp->fix_needed ) mp_fix_dependencies(mp);
20989 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20990 if ( mp_type(p)!=mp_proto_dependent ) {
20991 if ( mp_type(p)==mp_known )
20992 mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20994 dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20995 mp_proto_dependent,true);
20996 mp_type(p)=mp_proto_dependent;
20999 @ @<Transform a known big node@>=
21000 mp_set_up_trans(mp, c);
21001 if ( mp->cur_type==mp_known ) {
21002 @<Transform known by known@>;
21004 pp=mp_stash_cur_exp(mp); qq=value(pp);
21005 mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
21006 if ( mp->cur_type==mp_transform_type ) {
21007 mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
21008 value(xy_part_loc(q)),yx_part_loc(qq),null);
21009 mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
21010 value(xx_part_loc(q)),yx_part_loc(qq),null);
21011 mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
21012 value(yy_part_loc(q)),xy_part_loc(qq),null);
21013 mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
21014 value(yx_part_loc(q)),xy_part_loc(qq),null);
21016 mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
21017 value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
21018 mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
21019 value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
21020 mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
21023 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
21024 at |dep_final|. The following procedure adds |v| times another
21025 numeric quantity to~|p|.
21027 @<Declare subroutines needed by |big_trans|@>=
21028 static void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) {
21029 if ( mp_type(r)==mp_known ) {
21030 value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
21032 dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
21033 mp_proto_dependent,mp_type(r));
21034 if ( mp->fix_needed ) mp_fix_dependencies(mp);
21038 @ The |bilin2| procedure is something like |bilin1|, but with known
21039 and unknown quantities reversed. Parameter |p| points to a value field
21040 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
21041 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
21042 unless it is |null| (which stands for zero). Location~|p| will be
21043 replaced by $p\cdot t+v\cdot u+q$.
21045 @<Declare subroutines needed by |big_trans|@>=
21046 static void mp_bilin2 (MP mp,pointer p, pointer t, scaled v,
21047 pointer u, pointer q) {
21048 scaled vv; /* temporary storage for |value(p)| */
21049 vv=value(p); mp_type(p)=mp_proto_dependent;
21050 mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
21052 mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
21053 if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
21054 if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
21055 if ( dep_list(p)==mp->dep_final ) {
21056 vv=value(mp->dep_final); mp_recycle_value(mp, p);
21057 mp_type(p)=mp_known; value(p)=vv;
21061 @ @<Transform known by known@>=
21063 mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
21064 if ( mp->cur_type==mp_transform_type ) {
21065 mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
21066 mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
21067 mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
21068 mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
21070 mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
21071 mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
21074 @ Finally, in |bilin3| everything is |known|.
21076 @<Declare subroutines needed by |big_trans|@>=
21077 static void mp_bilin3 (MP mp,pointer p, scaled t,
21078 scaled v, scaled u, scaled delta) {
21080 delta+=mp_take_scaled(mp, value(p),t);
21083 if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
21084 else value(p)=delta;
21087 @ @<Additional cases of binary operators@>=
21089 if ( (mp->cur_type==mp_string_type)&&(mp_type(p)==mp_string_type) ) mp_cat(mp, p);
21090 else mp_bad_binary(mp, p,concatenate);
21093 if ( mp_nice_pair(mp, p,mp_type(p))&&(mp->cur_type==mp_string_type) )
21094 mp_chop_string(mp, value(p));
21095 else mp_bad_binary(mp, p,substring_of);
21098 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21099 if ( mp_nice_pair(mp, p,mp_type(p))&&(mp->cur_type==mp_path_type) )
21100 mp_chop_path(mp, value(p));
21101 else mp_bad_binary(mp, p,subpath_of);
21104 @ @<Declare binary action...@>=
21105 static void mp_cat (MP mp,pointer p) {
21106 str_number a,b; /* the strings being concatenated */
21107 pool_pointer k; /* index into |str_pool| */
21108 a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
21109 for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
21110 append_char(mp->str_pool[k]);
21112 for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
21113 append_char(mp->str_pool[k]);
21115 mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
21118 @ @<Declare binary action...@>=
21119 static void mp_chop_string (MP mp,pointer p) {
21120 integer a, b; /* start and stop points */
21121 integer l; /* length of the original string */
21122 integer k; /* runs from |a| to |b| */
21123 str_number s; /* the original string */
21124 boolean reversed; /* was |a>b|? */
21125 a=mp_round_unscaled(mp, value(x_part_loc(p)));
21126 b=mp_round_unscaled(mp, value(y_part_loc(p)));
21127 if ( a<=b ) reversed=false;
21128 else { reversed=true; k=a; a=b; b=k; };
21129 s=mp->cur_exp; l=length(s);
21140 for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--) {
21141 append_char(mp->str_pool[k]);
21144 for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++) {
21145 append_char(mp->str_pool[k]);
21148 mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
21151 @ @<Declare binary action...@>=
21152 static void mp_chop_path (MP mp,pointer p) {
21153 pointer q; /* a knot in the original path */
21154 pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
21155 scaled a,b,k,l; /* indices for chopping */
21156 boolean reversed; /* was |a>b|? */
21157 l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
21158 if ( a<=b ) reversed=false;
21159 else { reversed=true; k=a; a=b; b=k; };
21160 @<Dispense with the cases |a<0| and/or |b>l|@>;
21162 while ( a>=unity ) {
21163 q=mp_link(q); a=a-unity; b=b-unity;
21166 @<Construct a path from |pp| to |qq| of length zero@>;
21168 @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>;
21170 mp_left_type(pp)=mp_endpoint; mp_right_type(qq)=mp_endpoint; mp_link(qq)=pp;
21171 mp_toss_knot_list(mp, mp->cur_exp);
21173 mp->cur_exp=mp_link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
21179 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
21181 if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
21182 a=0; if ( b<0 ) b=0;
21184 do { a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
21188 if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
21189 b=l; if ( a>l ) a=l;
21197 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
21199 pp=mp_copy_knot(mp, q); qq=pp;
21201 q=mp_link(q); rr=qq; qq=mp_copy_knot(mp, q); mp_link(rr)=qq; b=b-unity;
21204 ss=pp; pp=mp_link(pp);
21205 mp_split_cubic(mp, ss,a*010000); pp=mp_link(ss);
21206 mp_free_node(mp, ss,knot_node_size);
21208 b=mp_make_scaled(mp, b,unity-a); rr=pp;
21212 mp_split_cubic(mp, rr,(b+unity)*010000);
21213 mp_free_node(mp, qq,knot_node_size);
21218 @ @<Construct a path from |pp| to |qq| of length zero@>=
21220 if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=mp_link(q); };
21221 pp=mp_copy_knot(mp, q); qq=pp;
21224 @ @<Additional cases of binary operators@>=
21225 case point_of: case precontrol_of: case postcontrol_of:
21226 if ( mp->cur_type==mp_pair_type )
21227 mp_pair_to_path(mp);
21228 if ( (mp->cur_type==mp_path_type)&&(mp_type(p)==mp_known) )
21229 mp_find_point(mp, value(p),c);
21231 mp_bad_binary(mp, p,c);
21233 case pen_offset_of:
21234 if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,mp_type(p)) )
21235 mp_set_up_offset(mp, value(p));
21237 mp_bad_binary(mp, p,pen_offset_of);
21239 case direction_time_of:
21240 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21241 if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,mp_type(p)) )
21242 mp_set_up_direction_time(mp, value(p));
21244 mp_bad_binary(mp, p,direction_time_of);
21247 if ( (mp_type(p) != mp_pen_type) || (mp->cur_type != mp_path_type) )
21248 mp_bad_binary(mp, p,envelope_of);
21250 mp_set_up_envelope(mp, p);
21253 @ @<Declare binary action...@>=
21254 static void mp_set_up_offset (MP mp,pointer p) {
21255 mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21256 mp_pair_value(mp, mp->cur_x,mp->cur_y);
21258 static void mp_set_up_direction_time (MP mp,pointer p) {
21259 mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21260 value(y_part_loc(p)),mp->cur_exp));
21262 static void mp_set_up_envelope (MP mp,pointer p) {
21263 quarterword ljoin, lcap;
21265 pointer q = mp_copy_path(mp, mp->cur_exp); /* the original path */
21266 /* TODO: accept elliptical pens for straight paths */
21267 if (pen_is_elliptical(value(p))) {
21268 mp_bad_envelope_pen(mp);
21270 mp->cur_type = mp_path_type;
21273 if ( mp->internal[mp_linejoin]>unity ) ljoin=2;
21274 else if ( mp->internal[mp_linejoin]>0 ) ljoin=1;
21276 if ( mp->internal[mp_linecap]>unity ) lcap=2;
21277 else if ( mp->internal[mp_linecap]>0 ) lcap=1;
21279 if ( mp->internal[mp_miterlimit]<unity )
21282 miterlim=mp->internal[mp_miterlimit];
21283 mp->cur_exp = mp_make_envelope(mp, q, value(p), ljoin,lcap,miterlim);
21284 mp->cur_type = mp_path_type;
21287 @ @<Declare binary action...@>=
21288 static void mp_find_point (MP mp,scaled v, quarterword c) {
21289 pointer p; /* the path */
21290 scaled n; /* its length */
21292 if ( mp_left_type(p)==mp_endpoint ) n=-unity; else n=0;
21293 do { p=mp_link(p); n=n+unity; } while (p!=mp->cur_exp);
21296 } else if ( v<0 ) {
21297 if ( mp_left_type(p)==mp_endpoint ) v=0;
21298 else v=n-1-((-v-1) % n);
21299 } else if ( v>n ) {
21300 if ( mp_left_type(p)==mp_endpoint ) v=n;
21304 while ( v>=unity ) { p=mp_link(p); v=v-unity; };
21306 @<Insert a fractional node by splitting the cubic@>;
21308 @<Set the current expression to the desired path coordinates@>;
21311 @ @<Insert a fractional node...@>=
21312 { mp_split_cubic(mp, p,v*010000); p=mp_link(p); }
21314 @ @<Set the current expression to the desired path coordinates...@>=
21317 mp_pair_value(mp, mp_x_coord(p),mp_y_coord(p));
21319 case precontrol_of:
21320 if ( mp_left_type(p)==mp_endpoint ) mp_pair_value(mp, mp_x_coord(p),mp_y_coord(p));
21321 else mp_pair_value(mp, mp_left_x(p),mp_left_y(p));
21323 case postcontrol_of:
21324 if ( mp_right_type(p)==mp_endpoint ) mp_pair_value(mp, mp_x_coord(p),mp_y_coord(p));
21325 else mp_pair_value(mp, mp_right_x(p),mp_right_y(p));
21327 } /* there are no other cases */
21329 @ @<Additional cases of binary operators@>=
21331 if ( mp->cur_type==mp_pair_type )
21332 mp_pair_to_path(mp);
21333 if ( (mp->cur_type==mp_path_type)&&(mp_type(p)==mp_known) )
21334 mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21336 mp_bad_binary(mp, p,c);
21339 @ @<Additional cases of bin...@>=
21341 if ( mp_type(p)==mp_pair_type ) {
21342 q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21343 mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21345 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21346 if ( (mp->cur_type==mp_path_type)&&(mp_type(p)==mp_path_type) ) {
21347 mp_path_intersection(mp, value(p),mp->cur_exp);
21348 mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21350 mp_bad_binary(mp, p,intersect);
21354 @ @<Additional cases of bin...@>=
21356 if ( (mp->cur_type!=mp_string_type)||(mp_type(p)!=mp_string_type))
21357 mp_bad_binary(mp, p,in_font);
21358 else { mp_do_infont(mp, p); binary_return; }
21361 @ Function |new_text_node| owns the reference count for its second argument
21362 (the text string) but not its first (the font name).
21364 @<Declare binary action...@>=
21365 static void mp_do_infont (MP mp,pointer p) {
21367 q=mp_get_node(mp, edge_header_size);
21368 mp_init_edges(mp, q);
21369 mp_link(obj_tail(q))=mp_new_text_node(mp,str(mp->cur_exp),value(p));
21370 obj_tail(q)=mp_link(obj_tail(q));
21371 mp_free_node(mp, p,value_node_size);
21372 mp_flush_cur_exp(mp, q);
21373 mp->cur_type=mp_picture_type;
21376 @* \[40] Statements and commands.
21377 The chief executive of \MP\ is the |do_statement| routine, which
21378 contains the master switch that causes all the various pieces of \MP\
21379 to do their things, in the right order.
21381 In a sense, this is the grand climax of the program: It applies all the
21382 tools that we have worked so hard to construct. In another sense, this is
21383 the messiest part of the program: It necessarily refers to other pieces
21384 of code all over the place, so that a person can't fully understand what is
21385 going on without paging back and forth to be reminded of conventions that
21386 are defined elsewhere. We are now at the hub of the web.
21388 The structure of |do_statement| itself is quite simple. The first token
21389 of the statement is fetched using |get_x_next|. If it can be the first
21390 token of an expression, we look for an equation, an assignment, or a
21391 title. Otherwise we use a \&{case} construction to branch at high speed to
21392 the appropriate routine for various and sundry other types of commands,
21393 each of which has an ``action procedure'' that does the necessary work.
21395 The program uses the fact that
21396 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21397 to interpret a statement that starts with, e.g., `\&{string}',
21398 as a type declaration rather than a boolean expression.
21400 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21401 mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21402 if ( mp->cur_cmd>max_primary_command ) {
21403 @<Worry about bad statement@>;
21404 } else if ( mp->cur_cmd>max_statement_command ) {
21405 @<Do an equation, assignment, title, or
21406 `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21408 @<Do a statement that doesn't begin with an expression@>;
21410 if ( mp->cur_cmd<semicolon )
21411 @<Flush unparsable junk that was found after the statement@>;
21415 @ @<Declarations@>=
21416 @<Declare action procedures for use by |do_statement|@>
21418 @ The only command codes |>max_primary_command| that can be present
21419 at the beginning of a statement are |semicolon| and higher; these
21420 occur when the statement is null.
21422 @<Worry about bad statement@>=
21424 if ( mp->cur_cmd<semicolon ) {
21425 print_err("A statement can't begin with `");
21426 @.A statement can't begin with x@>
21427 mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, xord('\''));
21428 help5("I was looking for the beginning of a new statement.",
21429 "If you just proceed without changing anything, I'll ignore",
21430 "everything up to the next `;'. Please insert a semicolon",
21431 "now in front of anything that you don't want me to delete.",
21432 "(See Chapter 27 of The METAFONTbook for an example.)");
21433 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21434 mp_back_error(mp); mp_get_x_next(mp);
21438 @ The help message printed here says that everything is flushed up to
21439 a semicolon, but actually the commands |end_group| and |stop| will
21440 also terminate a statement.
21442 @<Flush unparsable junk that was found after the statement@>=
21444 print_err("Extra tokens will be flushed");
21445 @.Extra tokens will be flushed@>
21446 help6("I've just read as much of that statement as I could fathom,",
21447 "so a semicolon should have been next. It's very puzzling...",
21448 "but I'll try to get myself back together, by ignoring",
21449 "everything up to the next `;'. Please insert a semicolon",
21450 "now in front of anything that you don't want me to delete.",
21451 "(See Chapter 27 of The METAFONTbook for an example.)");
21452 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21453 mp_back_error(mp); mp->scanner_status=flushing;
21456 @<Decrease the string reference count...@>;
21457 } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21458 mp->scanner_status=normal;
21461 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21462 |cur_type=mp_vacuous| unless the statement was simply an expression;
21463 in the latter case, |cur_type| and |cur_exp| should represent that
21466 @<Do a statement that doesn't...@>=
21468 if ( mp->internal[mp_tracing_commands]>0 )
21470 switch (mp->cur_cmd ) {
21471 case type_name:mp_do_type_declaration(mp); break;
21473 if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21474 else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21476 @<Cases of |do_statement| that invoke particular commands@>;
21477 } /* there are no other cases */
21478 mp->cur_type=mp_vacuous;
21481 @ The most important statements begin with expressions.
21483 @<Do an equation, assignment, title, or...@>=
21485 mp->var_flag=assignment; mp_scan_expression(mp);
21486 if ( mp->cur_cmd<end_group ) {
21487 if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21488 else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21489 else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21490 else if ( mp->cur_type!=mp_vacuous ){
21491 exp_err("Isolated expression");
21492 @.Isolated expression@>
21493 help3("I couldn't find an `=' or `:=' after the",
21494 "expression that is shown above this error message,",
21495 "so I guess I'll just ignore it and carry on.");
21496 mp_put_get_error(mp);
21498 mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21504 if ( mp->internal[mp_tracing_titles]>0 ) {
21505 mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp); update_terminal;
21509 @ Equations and assignments are performed by the pair of mutually recursive
21511 routines |do_equation| and |do_assignment|. These routines are called when
21512 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21513 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21514 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21515 will be equal to the right-hand side (which will normally be equal
21516 to the left-hand side).
21519 @<Declare the procedure called |make_eq|@>
21520 static void mp_do_equation (MP mp) ;
21523 void mp_do_equation (MP mp) {
21524 pointer lhs; /* capsule for the left-hand side */
21525 pointer p; /* temporary register */
21526 lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp);
21527 mp->var_flag=assignment; mp_scan_expression(mp);
21528 if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21529 else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21530 if ( mp->internal[mp_tracing_commands]>two )
21531 @<Trace the current equation@>;
21532 if ( mp->cur_type==mp_unknown_path ) if ( mp_type(lhs)==mp_pair_type ) {
21533 p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21534 }; /* in this case |make_eq| will change the pair to a path */
21535 mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21538 @ And |do_assignment| is similar to |do_equation|:
21541 static void mp_do_assignment (MP mp);
21544 void mp_do_assignment (MP mp) {
21545 pointer lhs; /* token list for the left-hand side */
21546 pointer p; /* where the left-hand value is stored */
21547 pointer q; /* temporary capsule for the right-hand value */
21548 if ( mp->cur_type!=mp_token_list ) {
21549 exp_err("Improper `:=' will be changed to `='");
21551 help2("I didn't find a variable name at the left of the `:=',",
21552 "so I'm going to pretend that you said `=' instead.");
21553 mp_error(mp); mp_do_equation(mp);
21555 lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21556 mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21557 if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21558 else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21559 if ( mp->internal[mp_tracing_commands]>two )
21560 @<Trace the current assignment@>;
21561 if ( mp_info(lhs)>hash_end ) {
21562 @<Assign the current expression to an internal variable@>;
21564 @<Assign the current expression to the variable |lhs|@>;
21566 mp_flush_node_list(mp, lhs);
21570 @ @<Trace the current equation@>=
21572 mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21573 mp_print(mp,")=("); mp_print_exp(mp,null,0);
21574 mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21577 @ @<Trace the current assignment@>=
21579 mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21580 if ( mp_info(lhs)>hash_end )
21581 mp_print(mp, mp->int_name[mp_info(lhs)-(hash_end)]);
21583 mp_show_token_list(mp, lhs,null,1000,0);
21584 mp_print(mp, ":="); mp_print_exp(mp, null,0);
21585 mp_print_char(mp, xord('}')); mp_end_diagnostic(mp, false);
21588 @ @<Assign the current expression to an internal variable@>=
21589 if ( mp->cur_type==mp_known ) {
21590 mp->internal[mp_info(lhs)-(hash_end)]=mp->cur_exp;
21592 exp_err("Internal quantity `");
21593 @.Internal quantity...@>
21594 mp_print(mp, mp->int_name[mp_info(lhs)-(hash_end)]);
21595 mp_print(mp, "' must receive a known value");
21596 help2("I can\'t set an internal quantity to anything but a known",
21597 "numeric value, so I'll have to ignore this assignment.");
21598 mp_put_get_error(mp);
21601 @ @<Assign the current expression to the variable |lhs|@>=
21603 p=mp_find_variable(mp, lhs);
21605 q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p);
21606 mp_recycle_value(mp, p);
21607 mp_type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21608 p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21610 mp_obliterated(mp, lhs); mp_put_get_error(mp);
21615 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21616 a pointer to a capsule that is to be equated to the current expression.
21618 @<Declare the procedure called |make_eq|@>=
21619 static void mp_make_eq (MP mp,pointer lhs) ;
21623 @c void mp_make_eq (MP mp,pointer lhs) {
21624 quarterword t; /* type of the left-hand side */
21625 pointer p,q; /* pointers inside of big nodes */
21626 integer v=0; /* value of the left-hand side */
21629 if ( t<=mp_pair_type ) v=value(lhs);
21631 @<For each type |t|, make an equation and |goto done| unless |cur_type|
21632 is incompatible with~|t|@>;
21633 } /* all cases have been listed */
21634 @<Announce that the equation cannot be performed@>;
21636 check_arith; mp_recycle_value(mp, lhs);
21637 mp_free_node(mp, lhs,value_node_size);
21640 @ @<Announce that the equation cannot be performed@>=
21641 mp_disp_err(mp, lhs,"");
21642 exp_err("Equation cannot be performed (");
21643 @.Equation cannot be performed@>
21644 if ( mp_type(lhs)<=mp_pair_type ) mp_print_type(mp, mp_type(lhs));
21645 else mp_print(mp, "numeric");
21646 mp_print_char(mp, xord('='));
21647 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21648 else mp_print(mp, "numeric");
21649 mp_print_char(mp, xord(')'));
21650 help2("I'm sorry, but I don't know how to make such things equal.",
21651 "(See the two expressions just above the error message.)");
21652 mp_put_get_error(mp)
21654 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21655 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21656 case mp_path_type: case mp_picture_type:
21657 if ( mp->cur_type==t+unknown_tag ) {
21658 mp_nonlinear_eq(mp, v,mp->cur_exp,false);
21659 mp_unstash_cur_exp(mp, mp->cur_exp); goto DONE;
21660 } else if ( mp->cur_type==t ) {
21661 @<Report redundant or inconsistent equation and |goto done|@>;
21664 case unknown_types:
21665 if ( mp->cur_type==t-unknown_tag ) {
21666 mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21667 } else if ( mp->cur_type==t ) {
21668 mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21669 } else if ( mp->cur_type==mp_pair_type ) {
21670 if ( t==mp_unknown_path ) {
21671 mp_pair_to_path(mp); goto RESTART;
21675 case mp_transform_type: case mp_color_type:
21676 case mp_cmykcolor_type: case mp_pair_type:
21677 if ( mp->cur_type==t ) {
21678 @<Do multiple equations and |goto done|@>;
21681 case mp_known: case mp_dependent:
21682 case mp_proto_dependent: case mp_independent:
21683 if ( mp->cur_type>=mp_known ) {
21684 mp_try_eq(mp, lhs,null); goto DONE;
21690 @ @<Report redundant or inconsistent equation and |goto done|@>=
21692 if ( mp->cur_type<=mp_string_type ) {
21693 if ( mp->cur_type==mp_string_type ) {
21694 if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21697 } else if ( v!=mp->cur_exp ) {
21700 @<Exclaim about a redundant equation@>; goto DONE;
21702 print_err("Redundant or inconsistent equation");
21703 @.Redundant or inconsistent equation@>
21704 help2("An equation between already-known quantities can't help.",
21705 "But don't worry; continue and I'll just ignore it.");
21706 mp_put_get_error(mp); goto DONE;
21708 print_err("Inconsistent equation");
21709 @.Inconsistent equation@>
21710 help2("The equation I just read contradicts what was said before.",
21711 "But don't worry; continue and I'll just ignore it.");
21712 mp_put_get_error(mp); goto DONE;
21715 @ @<Do multiple equations and |goto done|@>=
21717 p=v+mp->big_node_size[t];
21718 q=value(mp->cur_exp)+mp->big_node_size[t];
21720 p=p-2; q=q-2; mp_try_eq(mp, p,q);
21725 @ The first argument to |try_eq| is the location of a value node
21726 in a capsule that will soon be recycled. The second argument is
21727 either a location within a pair or transform node pointed to by
21728 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21729 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21730 but to equate the two operands.
21733 static void mp_try_eq (MP mp,pointer l, pointer r) ;
21736 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21737 pointer p; /* dependency list for right operand minus left operand */
21738 int t; /* the type of list |p| */
21739 pointer q; /* the constant term of |p| is here */
21740 pointer pp; /* dependency list for right operand */
21741 int tt; /* the type of list |pp| */
21742 boolean copied; /* have we copied a list that ought to be recycled? */
21743 @<Remove the left operand from its container, negate it, and
21744 put it into dependency list~|p| with constant term~|q|@>;
21745 @<Add the right operand to list |p|@>;
21746 if ( mp_info(p)==null ) {
21747 @<Deal with redundant or inconsistent equation@>;
21749 mp_linear_eq(mp, p,t);
21750 if ( r==null ) if ( mp->cur_type!=mp_known ) {
21751 if ( mp_type(mp->cur_exp)==mp_known ) {
21752 pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21753 mp_free_node(mp, pp,value_node_size);
21759 @ @<Remove the left operand from its container, negate it, and...@>=
21761 if ( t==mp_known ) {
21762 t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21763 } else if ( t==mp_independent ) {
21764 t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21767 p=dep_list(l); q=p;
21770 if ( mp_info(q)==null ) break;
21773 mp_link(prev_dep(l))=mp_link(q); prev_dep(mp_link(q))=prev_dep(l);
21774 mp_type(l)=mp_known;
21777 @ @<Deal with redundant or inconsistent equation@>=
21779 if ( abs(value(p))>64 ) { /* off by .001 or more */
21780 print_err("Inconsistent equation");
21781 @.Inconsistent equation@>
21782 mp_print(mp, " (off by "); mp_print_scaled(mp, value(p));
21783 mp_print_char(mp, xord(')'));
21784 help2("The equation I just read contradicts what was said before.",
21785 "But don't worry; continue and I'll just ignore it.");
21786 mp_put_get_error(mp);
21787 } else if ( r==null ) {
21788 @<Exclaim about a redundant equation@>;
21790 mp_free_node(mp, p,dep_node_size);
21793 @ @<Add the right operand to list |p|@>=
21795 if ( mp->cur_type==mp_known ) {
21796 value(q)=value(q)+mp->cur_exp; goto DONE1;
21799 if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21800 else pp=dep_list(mp->cur_exp);
21803 if ( mp_type(r)==mp_known ) {
21804 value(q)=value(q)+value(r); goto DONE1;
21807 if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21808 else pp=dep_list(r);
21811 if ( tt!=mp_independent ) copied=false;
21812 else { copied=true; tt=mp_dependent; };
21813 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21814 if ( copied ) mp_flush_node_list(mp, pp);
21817 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21818 mp->watch_coefs=false;
21820 p=mp_p_plus_q(mp, p,pp,t);
21821 } else if ( t==mp_proto_dependent ) {
21822 p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21825 while ( mp_info(q)!=null ) {
21826 value(q)=mp_round_fraction(mp, value(q)); q=mp_link(q);
21828 t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21830 mp->watch_coefs=true;
21832 @ Our next goal is to process type declarations. For this purpose it's
21833 convenient to have a procedure that scans a $\langle\,$declared
21834 variable$\,\rangle$ and returns the corresponding token list. After the
21835 following procedure has acted, the token after the declared variable
21836 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21840 static pointer mp_scan_declared_variable (MP mp) ;
21843 pointer mp_scan_declared_variable (MP mp) {
21844 pointer x; /* hash address of the variable's root */
21845 pointer h,t; /* head and tail of the token list to be returned */
21846 pointer l; /* hash address of left bracket */
21847 mp_get_symbol(mp); x=mp->cur_sym;
21848 if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21849 h=mp_get_avail(mp); mp_info(h)=x; t=h;
21852 if ( mp->cur_sym==0 ) break;
21853 if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity) {
21854 if ( mp->cur_cmd==left_bracket ) {
21855 @<Descend past a collective subscript@>;
21860 mp_link(t)=mp_get_avail(mp); t=mp_link(t); mp_info(t)=mp->cur_sym;
21862 if ( (eq_type(x)%outer_tag)!=tag_token ) mp_clear_symbol(mp, x,false);
21863 if ( equiv(x)==null ) mp_new_root(mp, x);
21867 @ If the subscript isn't collective, we don't accept it as part of the
21870 @<Descend past a collective subscript@>=
21872 l=mp->cur_sym; mp_get_x_next(mp);
21873 if ( mp->cur_cmd!=right_bracket ) {
21874 mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21876 mp->cur_sym=collective_subscript;
21880 @ Type declarations are introduced by the following primitive operations.
21883 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21884 @:numeric_}{\&{numeric} primitive@>
21885 mp_primitive(mp, "string",type_name,mp_string_type);
21886 @:string_}{\&{string} primitive@>
21887 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21888 @:boolean_}{\&{boolean} primitive@>
21889 mp_primitive(mp, "path",type_name,mp_path_type);
21890 @:path_}{\&{path} primitive@>
21891 mp_primitive(mp, "pen",type_name,mp_pen_type);
21892 @:pen_}{\&{pen} primitive@>
21893 mp_primitive(mp, "picture",type_name,mp_picture_type);
21894 @:picture_}{\&{picture} primitive@>
21895 mp_primitive(mp, "transform",type_name,mp_transform_type);
21896 @:transform_}{\&{transform} primitive@>
21897 mp_primitive(mp, "color",type_name,mp_color_type);
21898 @:color_}{\&{color} primitive@>
21899 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21900 @:color_}{\&{rgbcolor} primitive@>
21901 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21902 @:color_}{\&{cmykcolor} primitive@>
21903 mp_primitive(mp, "pair",type_name,mp_pair_type);
21904 @:pair_}{\&{pair} primitive@>
21906 @ @<Cases of |print_cmd...@>=
21907 case type_name: mp_print_type(mp, m); break;
21909 @ Now we are ready to handle type declarations, assuming that a
21910 |type_name| has just been scanned.
21912 @<Declare action procedures for use by |do_statement|@>=
21913 static void mp_do_type_declaration (MP mp) ;
21916 void mp_do_type_declaration (MP mp) {
21917 quarterword t; /* the type being declared */
21918 pointer p; /* token list for a declared variable */
21919 pointer q; /* value node for the variable */
21920 if ( mp->cur_mod>=mp_transform_type )
21923 t=mp->cur_mod+unknown_tag;
21925 p=mp_scan_declared_variable(mp);
21926 mp_flush_variable(mp, equiv(mp_info(p)),mp_link(p),false);
21927 q=mp_find_variable(mp, p);
21929 mp_type(q)=t; value(q)=null;
21931 print_err("Declared variable conflicts with previous vardef");
21932 @.Declared variable conflicts...@>
21933 help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.",
21934 "Proceed, and I'll ignore the illegal redeclaration.");
21935 mp_put_get_error(mp);
21937 mp_flush_list(mp, p);
21938 if ( mp->cur_cmd<comma ) {
21939 @<Flush spurious symbols after the declared variable@>;
21941 } while (! end_of_statement);
21944 @ @<Flush spurious symbols after the declared variable@>=
21946 print_err("Illegal suffix of declared variable will be flushed");
21947 @.Illegal suffix...flushed@>
21948 help5("Variables in declarations must consist entirely of",
21949 "names and collective subscripts, e.g., `x[]a'.",
21950 "Are you trying to use a reserved word in a variable name?",
21951 "I'm going to discard the junk I found here,",
21952 "up to the next comma or the end of the declaration.");
21953 if ( mp->cur_cmd==numeric_token )
21954 mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21955 mp_put_get_error(mp); mp->scanner_status=flushing;
21958 @<Decrease the string reference count...@>;
21959 } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21960 mp->scanner_status=normal;
21963 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21964 until coming to the end of the user's program.
21965 Each execution of |do_statement| concludes with
21966 |cur_cmd=semicolon|, |end_group|, or |stop|.
21969 static void mp_main_control (MP mp) {
21971 mp_do_statement(mp);
21972 if ( mp->cur_cmd==end_group ) {
21973 print_err("Extra `endgroup'");
21974 @.Extra `endgroup'@>
21975 help2("I'm not currently working on a `begingroup',",
21976 "so I had better not try to end anything.");
21977 mp_flush_error(mp, 0);
21979 } while (mp->cur_cmd!=stop);
21981 int mp_run (MP mp) {
21982 if (mp->history < mp_fatal_error_stop ) {
21983 xfree(mp->jump_buf);
21984 mp->jump_buf = malloc(sizeof(jmp_buf));
21985 if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0)
21986 return mp->history;
21987 mp_main_control(mp); /* come to life */
21988 mp_final_cleanup(mp); /* prepare for death */
21989 mp_close_files_and_terminate(mp);
21991 return mp->history;
21994 @ For |mp_execute|, we need to define a structure to store the
21995 redirected input and output. This structure holds the five relevant
21996 streams: the three informational output streams, the PostScript
21997 generation stream, and the input stream. These streams have many
21998 things in common, so it makes sense to give them their own structure
22001 \item{fptr} is a virtual file pointer
22002 \item{data} is the data this stream holds
22003 \item{cur} is a cursor pointing into |data|
22004 \item{size} is the allocated length of the data stream
22005 \item{used} is the actual length of the data stream
22007 There are small differences between input and output: |term_in| never
22008 uses |used|, whereas the other four never use |cur|.
22010 @<Exported types@>=
22020 mp_stream term_out;
22021 mp_stream error_out;
22025 struct mp_edge_object *edges;
22028 @ We need a function to clear an output stream, this is called at the
22029 beginning of |mp_execute|. We also need one for destroying an output
22030 stream, this is called just before a stream is (re)opened.
22033 static void mp_reset_stream(mp_stream *str) {
22039 static void mp_free_stream(mp_stream *str) {
22041 mp_reset_stream(str);
22044 @ @<Declarations@>=
22045 static void mp_reset_stream(mp_stream *str);
22046 static void mp_free_stream(mp_stream *str);
22048 @ The global instance contains a pointer instead of the actual structure
22049 even though it is essentially static, because that makes it is easier to move
22053 mp_run_data run_data;
22055 @ Another type is needed: the indirection will overload some of the
22056 file pointer objects in the instance (but not all). For clarity, an
22057 indirect object is used that wraps a |FILE *|.
22060 typedef struct File {
22064 @ Here are all of the functions that need to be overloaded for |mp_execute|.
22067 static void *mplib_open_file(MP mp, const char *fname, const char *fmode, int ftype);
22068 static int mplib_get_char(void *f, mp_run_data * mplib_data);
22069 static void mplib_unget_char(void *f, mp_run_data * mplib_data, int c);
22070 static char *mplib_read_ascii_file(MP mp, void *ff, size_t * size);
22071 static void mplib_write_ascii_file(MP mp, void *ff, const char *s);
22072 static void mplib_read_binary_file(MP mp, void *ff, void **data, size_t * size);
22073 static void mplib_write_binary_file(MP mp, void *ff, void *s, size_t size);
22074 static void mplib_close_file(MP mp, void *ff);
22075 static int mplib_eof_file(MP mp, void *ff);
22076 static void mplib_flush_file(MP mp, void *ff);
22077 static void mplib_shipout_backend(MP mp, int h);
22079 @ The |xmalloc(1,1)| calls make sure the stored indirection values are unique.
22081 @d reset_stream(a) do {
22082 mp_reset_stream(&(a));
22084 ff->f = xmalloc(1,1);
22090 static void *mplib_open_file(MP mp, const char *fname, const char *fmode, int ftype)
22092 File *ff = xmalloc(1, sizeof(File));
22093 mp_run_data *run = mp_rundata(mp);
22095 if (ftype == mp_filetype_terminal) {
22096 if (fmode[0] == 'r') {
22098 ff->f = xmalloc(1,1);
22099 run->term_in.fptr = ff->f;
22102 reset_stream(run->term_out);
22104 } else if (ftype == mp_filetype_error) {
22105 reset_stream(run->error_out);
22106 } else if (ftype == mp_filetype_log) {
22107 reset_stream(run->log_out);
22108 } else if (ftype == mp_filetype_postscript) {
22109 mp_free_stream(&(run->ps_out));
22110 ff->f = xmalloc(1,1);
22111 run->ps_out.fptr = ff->f;
22114 char *f = (mp->find_file)(mp, fname, fmode, ftype);
22117 realmode[0] = *fmode;
22120 ff->f = fopen(f, realmode);
22122 if ((fmode[0] == 'r') && (ff->f == NULL)) {
22130 static int mplib_get_char(void *f, mp_run_data * run)
22133 if (f == run->term_in.fptr && run->term_in.data != NULL) {
22134 if (run->term_in.size == 0) {
22135 if (run->term_in.cur != NULL) {
22136 run->term_in.cur = NULL;
22138 xfree(run->term_in.data);
22142 run->term_in.size--;
22143 c = *(run->term_in.cur)++;
22151 static void mplib_unget_char(void *f, mp_run_data * run, int c)
22153 if (f == run->term_in.fptr && run->term_in.cur != NULL) {
22154 run->term_in.size++;
22155 run->term_in.cur--;
22162 static char *mplib_read_ascii_file(MP mp, void *ff, size_t * size)
22167 size_t len = 0, lim = 128;
22168 mp_run_data *run = mp_rundata(mp);
22169 FILE *f = ((File *) ff)->f;
22173 c = mplib_get_char(f, run);
22179 while (c != EOF && c != '\n' && c != '\r') {
22181 s = xrealloc(s, (lim + (lim >> 2)),1);
22187 c = mplib_get_char(f, run);
22190 c = mplib_get_char(f, run);
22191 if (c != EOF && c != '\n')
22192 mplib_unget_char(f, run, c);
22200 static void mp_append_string (MP mp, mp_stream *a,const char *b) {
22201 size_t l = strlen(b);
22202 if ((a->used+l)>=a->size) {
22203 a->size += 256+(a->size)/5+l;
22204 a->data = xrealloc(a->data,a->size,1);
22206 (void)strcpy(a->data+a->used,b);
22211 static void mplib_write_ascii_file(MP mp, void *ff, const char *s)
22214 void *f = ((File *) ff)->f;
22215 mp_run_data *run = mp_rundata(mp);
22217 if (f == run->term_out.fptr) {
22218 mp_append_string(mp,&(run->term_out), s);
22219 } else if (f == run->error_out.fptr) {
22220 mp_append_string(mp,&(run->error_out), s);
22221 } else if (f == run->log_out.fptr) {
22222 mp_append_string(mp,&(run->log_out), s);
22223 } else if (f == run->ps_out.fptr) {
22224 mp_append_string(mp,&(run->ps_out), s);
22226 fprintf((FILE *) f, "%s", s);
22232 static void mplib_read_binary_file(MP mp, void *ff, void **data, size_t * size)
22237 FILE *f = ((File *) ff)->f;
22239 len = fread(*data, 1, *size, f);
22244 static void mplib_write_binary_file(MP mp, void *ff, void *s, size_t size)
22248 FILE *f = ((File *) ff)->f;
22250 (void)fwrite(s, size, 1, f);
22254 static void mplib_close_file(MP mp, void *ff)
22257 mp_run_data *run = mp_rundata(mp);
22258 void *f = ((File *) ff)->f;
22260 if (f != run->term_out.fptr
22261 && f != run->error_out.fptr
22262 && f != run->log_out.fptr
22263 && f != run->ps_out.fptr
22264 && f != run->term_in.fptr) {
22272 static int mplib_eof_file(MP mp, void *ff)
22275 mp_run_data *run = mp_rundata(mp);
22276 FILE *f = ((File *) ff)->f;
22279 if (f == run->term_in.fptr && run->term_in.data != NULL) {
22280 return (run->term_in.size == 0);
22287 static void mplib_flush_file(MP mp, void *ff)
22294 static void mplib_shipout_backend(MP mp, int h)
22296 mp_edge_object *hh = mp_gr_export(mp, h);
22298 mp_run_data *run = mp_rundata(mp);
22299 if (run->edges==NULL) {
22302 mp_edge_object *p = run->edges;
22303 while (p->next!=NULL) { p = p->next; }
22310 @ This is where we fill them all in.
22311 @<Prepare function pointers for non-interactive use@>=
22313 mp->open_file = mplib_open_file;
22314 mp->close_file = mplib_close_file;
22315 mp->eof_file = mplib_eof_file;
22316 mp->flush_file = mplib_flush_file;
22317 mp->write_ascii_file = mplib_write_ascii_file;
22318 mp->read_ascii_file = mplib_read_ascii_file;
22319 mp->write_binary_file = mplib_write_binary_file;
22320 mp->read_binary_file = mplib_read_binary_file;
22321 mp->shipout_backend = mplib_shipout_backend;
22324 @ Perhaps this is the most important API function in the library.
22326 @<Exported function ...@>=
22327 extern mp_run_data *mp_rundata (MP mp) ;
22330 mp_run_data *mp_rundata (MP mp) {
22331 return &(mp->run_data);
22335 mp_free_stream(&(mp->run_data.term_in));
22336 mp_free_stream(&(mp->run_data.term_out));
22337 mp_free_stream(&(mp->run_data.log_out));
22338 mp_free_stream(&(mp->run_data.error_out));
22339 mp_free_stream(&(mp->run_data.ps_out));
22341 @ @<Finish non-interactive use@>=
22342 xfree(mp->term_out);
22343 xfree(mp->term_in);
22344 xfree(mp->err_out);
22346 @ @<Start non-interactive work@>=
22347 @<Initialize the output routines@>;
22348 mp->input_ptr=0; mp->max_in_stack=0;
22349 mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
22350 mp->param_ptr=0; mp->max_param_stack=0;
22351 start = loc = iindex = 0; mp->first = 0;
22352 line=0; name=is_term;
22353 mp->mpx_name[0]=absent;
22354 mp->force_eof=false;
22356 mp->scanner_status=normal;
22357 if (mp->mem_ident==NULL) {
22358 if ( ! mp_load_mem_file(mp) ) {
22359 (mp->close_file)(mp, mp->mem_file);
22360 mp->history = mp_fatal_error_stop;
22361 return mp->history;
22363 (mp->close_file)(mp, mp->mem_file);
22365 mp_fix_date_and_time(mp);
22366 if (mp->random_seed==0)
22367 mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
22368 mp_init_randoms(mp, mp->random_seed);
22369 @<Initialize the print |selector|...@>;
22370 mp_open_log_file(mp);
22372 mp_init_map_file(mp, mp->troff_mode);
22373 mp->history=mp_spotless; /* ready to go! */
22374 if (mp->troff_mode) {
22375 mp->internal[mp_gtroffmode]=unity;
22376 mp->internal[mp_prologues]=unity;
22378 if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
22379 mp->cur_sym=mp->start_sym; mp_back_input(mp);
22383 int mp_execute (MP mp, char *s, size_t l) {
22384 mp_reset_stream(&(mp->run_data.term_out));
22385 mp_reset_stream(&(mp->run_data.log_out));
22386 mp_reset_stream(&(mp->run_data.error_out));
22387 mp_reset_stream(&(mp->run_data.ps_out));
22388 if (mp->finished) {
22389 return mp->history;
22390 } else if (!mp->noninteractive) {
22391 mp->history = mp_fatal_error_stop ;
22392 return mp->history;
22394 if (mp->history < mp_fatal_error_stop ) {
22395 xfree(mp->jump_buf);
22396 mp->jump_buf = malloc(sizeof(jmp_buf));
22397 if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0) {
22398 return mp->history;
22400 if (s==NULL) { /* this signals EOF */
22401 mp_final_cleanup(mp); /* prepare for death */
22402 mp_close_files_and_terminate(mp);
22403 return mp->history;
22406 mp->term_offset=0; mp->file_offset=0;
22407 /* Perhaps some sort of warning here when |data| is not
22408 * yet exhausted would be nice ... this happens after errors
22410 if (mp->run_data.term_in.data)
22411 xfree(mp->run_data.term_in.data);
22412 mp->run_data.term_in.data = xstrdup(s);
22413 mp->run_data.term_in.cur = mp->run_data.term_in.data;
22414 mp->run_data.term_in.size = l;
22415 if (mp->run_state == 0) {
22416 mp->selector=term_only;
22417 @<Start non-interactive work@>;
22420 (void)mp_input_ln(mp,mp->term_in);
22421 mp_firm_up_the_line(mp);
22422 mp->buffer[limit]=xord('%');
22423 mp->first=(size_t)(limit+1);
22426 mp_do_statement(mp);
22427 } while (mp->cur_cmd!=stop);
22428 mp_final_cleanup(mp);
22429 mp_close_files_and_terminate(mp);
22431 return mp->history;
22434 @ This function cleans up
22436 int mp_finish (MP mp) {
22438 if (mp->finished || mp->history >= mp_fatal_error_stop) {
22439 history = mp->history;
22443 xfree(mp->jump_buf);
22444 mp->jump_buf = malloc(sizeof(jmp_buf));
22445 if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0) {
22446 history = mp->history;
22448 history = mp->history;
22449 mp_final_cleanup(mp); /* prepare for death */
22451 mp_close_files_and_terminate(mp);
22456 @ People may want to know the library version
22458 char * mp_metapost_version (void) {
22459 return mp_strdup(metapost_version);
22462 @ @<Exported function headers@>=
22463 int mp_run (MP mp);
22464 int mp_execute (MP mp, char *s, size_t l);
22465 int mp_finish (MP mp);
22466 char * mp_metapost_version (void);
22469 mp_primitive(mp, "end",stop,0);
22470 @:end_}{\&{end} primitive@>
22471 mp_primitive(mp, "dump",stop,1);
22472 @:dump_}{\&{dump} primitive@>
22474 @ @<Cases of |print_cmd...@>=
22476 if ( m==0 ) mp_print(mp, "end");
22477 else mp_print(mp, "dump");
22481 Let's turn now to statements that are classified as ``commands'' because
22482 of their imperative nature. We'll begin with simple ones, so that it
22483 will be clear how to hook command processing into the |do_statement| routine;
22484 then we'll tackle the tougher commands.
22486 Here's one of the simplest:
22488 @<Cases of |do_statement|...@>=
22489 case mp_random_seed: mp_do_random_seed(mp); break;
22491 @ @<Declare action procedures for use by |do_statement|@>=
22492 static void mp_do_random_seed (MP mp) ;
22494 @ @c void mp_do_random_seed (MP mp) {
22496 if ( mp->cur_cmd!=assignment ) {
22497 mp_missing_err(mp, ":=");
22499 help1("Always say `randomseed:=<numeric expression>'.");
22502 mp_get_x_next(mp); mp_scan_expression(mp);
22503 if ( mp->cur_type!=mp_known ) {
22504 exp_err("Unknown value will be ignored");
22505 @.Unknown value...ignored@>
22506 help2("Your expression was too random for me to handle,",
22507 "so I won't change the random seed just now.");
22508 mp_put_get_flush_error(mp, 0);
22510 @<Initialize the random seed to |cur_exp|@>;
22514 @ @<Initialize the random seed to |cur_exp|@>=
22516 mp_init_randoms(mp, mp->cur_exp);
22517 if ( mp->selector>=log_only && mp->selector<write_file) {
22518 mp->old_setting=mp->selector; mp->selector=log_only;
22519 mp_print_nl(mp, "{randomseed:=");
22520 mp_print_scaled(mp, mp->cur_exp);
22521 mp_print_char(mp, xord('}'));
22522 mp_print_nl(mp, ""); mp->selector=mp->old_setting;
22526 @ And here's another simple one (somewhat different in flavor):
22528 @<Cases of |do_statement|...@>=
22530 mp_print_ln(mp); mp->interaction=mp->cur_mod;
22531 @<Initialize the print |selector| based on |interaction|@>;
22532 if ( mp->log_opened ) mp->selector=mp->selector+2;
22537 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
22538 @:mp_batch_mode_}{\&{batchmode} primitive@>
22539 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
22540 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
22541 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
22542 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
22543 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
22544 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
22546 @ @<Cases of |print_cmd_mod|...@>=
22549 case mp_batch_mode: mp_print(mp, "batchmode"); break;
22550 case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
22551 case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
22552 default: mp_print(mp, "errorstopmode"); break;
22556 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
22558 @<Cases of |do_statement|...@>=
22559 case protection_command: mp_do_protection(mp); break;
22562 mp_primitive(mp, "inner",protection_command,0);
22563 @:inner_}{\&{inner} primitive@>
22564 mp_primitive(mp, "outer",protection_command,1);
22565 @:outer_}{\&{outer} primitive@>
22567 @ @<Cases of |print_cmd...@>=
22568 case protection_command:
22569 if ( m==0 ) mp_print(mp, "inner");
22570 else mp_print(mp, "outer");
22573 @ @<Declare action procedures for use by |do_statement|@>=
22574 static void mp_do_protection (MP mp) ;
22576 @ @c void mp_do_protection (MP mp) {
22577 int m; /* 0 to unprotect, 1 to protect */
22578 halfword t; /* the |eq_type| before we change it */
22581 mp_get_symbol(mp); t=eq_type(mp->cur_sym);
22583 if ( t>=outer_tag )
22584 eq_type(mp->cur_sym)=t-outer_tag;
22585 } else if ( t<outer_tag ) {
22586 eq_type(mp->cur_sym)=t+outer_tag;
22589 } while (mp->cur_cmd==comma);
22592 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
22593 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
22594 declaration assigns the command code |left_delimiter| to `\.{(}' and
22595 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
22596 hash address of its mate.
22598 @<Cases of |do_statement|...@>=
22599 case delimiters: mp_def_delims(mp); break;
22601 @ @<Declare action procedures for use by |do_statement|@>=
22602 static void mp_def_delims (MP mp) ;
22604 @ @c void mp_def_delims (MP mp) {
22605 pointer l_delim,r_delim; /* the new delimiter pair */
22606 mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
22607 mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
22608 eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
22609 eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
22613 @ Here is a procedure that is called when \MP\ has reached a point
22614 where some right delimiter is mandatory.
22617 static void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim);
22620 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
22621 if ( mp->cur_cmd==right_delimiter )
22622 if ( mp->cur_mod==l_delim )
22624 if ( mp->cur_sym!=r_delim ) {
22625 mp_missing_err(mp, str(text(r_delim)));
22627 help2("I found no right delimiter to match a left one. So I've",
22628 "put one in, behind the scenes; this may fix the problem.");
22631 print_err("The token `"); mp_print_text(r_delim);
22632 @.The token...delimiter@>
22633 mp_print(mp, "' is no longer a right delimiter");
22634 help3("Strange: This token has lost its former meaning!",
22635 "I'll read it as a right delimiter this time;",
22636 "but watch out, I'll probably miss it later.");
22641 @ The next four commands save or change the values associated with tokens.
22643 @<Cases of |do_statement|...@>=
22646 mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
22647 } while (mp->cur_cmd==comma);
22649 case interim_command: mp_do_interim(mp); break;
22650 case let_command: mp_do_let(mp); break;
22651 case new_internal: mp_do_new_internal(mp); break;
22653 @ @<Declare action procedures for use by |do_statement|@>=
22654 static void mp_do_statement (MP mp);
22655 static void mp_do_interim (MP mp);
22657 @ @c void mp_do_interim (MP mp) {
22659 if ( mp->cur_cmd!=internal_quantity ) {
22660 print_err("The token `");
22661 @.The token...quantity@>
22662 if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
22663 else mp_print_text(mp->cur_sym);
22664 mp_print(mp, "' isn't an internal quantity");
22665 help1("Something like `tracingonline' should follow `interim'.");
22668 mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
22670 mp_do_statement(mp);
22673 @ The following procedure is careful not to undefine the left-hand symbol
22674 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
22676 @<Declare action procedures for use by |do_statement|@>=
22677 static void mp_do_let (MP mp) ;
22679 @ @c void mp_do_let (MP mp) {
22680 pointer l; /* hash location of the left-hand symbol */
22681 mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
22682 if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
22683 mp_missing_err(mp, "=");
22685 help3("You should have said `let symbol = something'.",
22686 "But don't worry; I'll pretend that an equals sign",
22687 "was present. The next token I read will be `something'.");
22691 switch (mp->cur_cmd) {
22692 case defined_macro: case secondary_primary_macro:
22693 case tertiary_secondary_macro: case expression_tertiary_macro:
22694 add_mac_ref(mp->cur_mod);
22699 mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
22700 if ( mp->cur_cmd==tag_token ) equiv(l)=null;
22701 else equiv(l)=mp->cur_mod;
22705 @ @<Declarations@>=
22706 static void mp_do_new_internal (MP mp) ;
22708 @ @<Internal library ...@>=
22709 void mp_grow_internals (MP mp, int l);
22712 void mp_grow_internals (MP mp, int l) {
22716 if ( hash_end+l>max_halfword ) {
22717 mp_confusion(mp, "out of memory space"); /* can't be reached */
22719 int_name = xmalloc ((l+1),sizeof(char *));
22720 internal = xmalloc ((l+1),sizeof(scaled));
22721 for (k=0;k<=l; k++ ) {
22722 if (k<=mp->max_internal) {
22723 internal[k]=mp->internal[k];
22724 int_name[k]=mp->int_name[k];
22730 xfree(mp->internal); xfree(mp->int_name);
22731 mp->int_name = int_name;
22732 mp->internal = internal;
22733 mp->max_internal = l;
22736 void mp_do_new_internal (MP mp) {
22738 if ( mp->int_ptr==mp->max_internal ) {
22739 mp_grow_internals(mp, (mp->max_internal + (mp->max_internal/4)));
22741 mp_get_clear_symbol(mp); incr(mp->int_ptr);
22742 eq_type(mp->cur_sym)=internal_quantity;
22743 equiv(mp->cur_sym)=mp->int_ptr;
22744 if(mp->int_name[mp->int_ptr]!=NULL)
22745 xfree(mp->int_name[mp->int_ptr]);
22746 mp->int_name[mp->int_ptr]=str(text(mp->cur_sym));
22747 mp->internal[mp->int_ptr]=0;
22749 } while (mp->cur_cmd==comma);
22752 @ @<Dealloc variables@>=
22753 for (k=0;k<=mp->max_internal;k++) {
22754 xfree(mp->int_name[k]);
22756 xfree(mp->internal);
22757 xfree(mp->int_name);
22760 @ The various `\&{show}' commands are distinguished by modifier fields
22763 @d show_token_code 0 /* show the meaning of a single token */
22764 @d show_stats_code 1 /* show current memory and string usage */
22765 @d show_code 2 /* show a list of expressions */
22766 @d show_var_code 3 /* show a variable and its descendents */
22767 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22770 mp_primitive(mp, "showtoken",show_command,show_token_code);
22771 @:show_token_}{\&{showtoken} primitive@>
22772 mp_primitive(mp, "showstats",show_command,show_stats_code);
22773 @:show_stats_}{\&{showstats} primitive@>
22774 mp_primitive(mp, "show",show_command,show_code);
22775 @:show_}{\&{show} primitive@>
22776 mp_primitive(mp, "showvariable",show_command,show_var_code);
22777 @:show_var_}{\&{showvariable} primitive@>
22778 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22779 @:show_dependencies_}{\&{showdependencies} primitive@>
22781 @ @<Cases of |print_cmd...@>=
22784 case show_token_code:mp_print(mp, "showtoken"); break;
22785 case show_stats_code:mp_print(mp, "showstats"); break;
22786 case show_code:mp_print(mp, "show"); break;
22787 case show_var_code:mp_print(mp, "showvariable"); break;
22788 default: mp_print(mp, "showdependencies"); break;
22792 @ @<Cases of |do_statement|...@>=
22793 case show_command:mp_do_show_whatever(mp); break;
22795 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22796 if it's |show_code|, complicated structures are abbreviated, otherwise
22799 @<Declare action procedures for use by |do_statement|@>=
22800 static void mp_do_show (MP mp) ;
22802 @ @c void mp_do_show (MP mp) {
22804 mp_get_x_next(mp); mp_scan_expression(mp);
22805 mp_print_nl(mp, ">> ");
22807 mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22808 } while (mp->cur_cmd==comma);
22811 @ @<Declare action procedures for use by |do_statement|@>=
22812 static void mp_disp_token (MP mp) ;
22814 @ @c void mp_disp_token (MP mp) {
22815 mp_print_nl(mp, "> ");
22817 if ( mp->cur_sym==0 ) {
22818 @<Show a numeric or string or capsule token@>;
22820 mp_print_text(mp->cur_sym); mp_print_char(mp, xord('='));
22821 if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22822 mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22823 if ( mp->cur_cmd==defined_macro ) {
22824 mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22825 } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22830 @ @<Show a numeric or string or capsule token@>=
22832 if ( mp->cur_cmd==numeric_token ) {
22833 mp_print_scaled(mp, mp->cur_mod);
22834 } else if ( mp->cur_cmd==capsule_token ) {
22835 mp_print_capsule(mp,mp->cur_mod);
22837 mp_print_char(mp, xord('"'));
22838 mp_print_str(mp, mp->cur_mod); mp_print_char(mp, xord('"'));
22839 delete_str_ref(mp->cur_mod);
22843 @ The following cases of |print_cmd_mod| might arise in connection
22844 with |disp_token|, although they don't necessarily correspond to
22847 @<Cases of |print_cmd_...@>=
22848 case left_delimiter:
22849 case right_delimiter:
22850 if ( c==left_delimiter ) mp_print(mp, "left");
22851 else mp_print(mp, "right");
22852 mp_print(mp, " delimiter that matches ");
22856 if ( m==null ) mp_print(mp, "tag");
22857 else mp_print(mp, "variable");
22859 case defined_macro:
22860 mp_print(mp, "macro:");
22862 case secondary_primary_macro:
22863 case tertiary_secondary_macro:
22864 case expression_tertiary_macro:
22865 mp_print_cmd_mod(mp, macro_def,c);
22866 mp_print(mp, "'d macro:");
22867 mp_print_ln(mp); mp_show_token_list(mp, mp_link(mp_link(m)),null,1000,0);
22870 mp_print(mp, "[repeat the loop]");
22872 case internal_quantity:
22873 mp_print(mp, mp->int_name[m]);
22876 @ @<Declare action procedures for use by |do_statement|@>=
22877 static void mp_do_show_token (MP mp) ;
22879 @ @c void mp_do_show_token (MP mp) {
22881 get_t_next; mp_disp_token(mp);
22883 } while (mp->cur_cmd==comma);
22886 @ @<Declare action procedures for use by |do_statement|@>=
22887 static void mp_do_show_stats (MP mp) ;
22889 @ @c void mp_do_show_stats (MP mp) {
22890 mp_print_nl(mp, "Memory usage ");
22891 @.Memory usage...@>
22892 mp_print_int(mp, mp->var_used); mp_print_char(mp, xord('&')); mp_print_int(mp, mp->dyn_used);
22893 mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22894 mp_print(mp, " still untouched)"); mp_print_ln(mp);
22895 mp_print_nl(mp, "String usage ");
22896 mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22897 mp_print_char(mp, xord('&')); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22898 mp_print(mp, " (");
22899 mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, xord('&'));
22900 mp_print_int(mp, mp->pool_size-mp->pool_ptr);
22901 mp_print(mp, " now untouched)"); mp_print_ln(mp);
22905 @ Here's a recursive procedure that gives an abbreviated account
22906 of a variable, for use by |do_show_var|.
22908 @<Declare action procedures for use by |do_statement|@>=
22909 static void mp_disp_var (MP mp,pointer p) ;
22911 @ @c void mp_disp_var (MP mp,pointer p) {
22912 pointer q; /* traverses attributes and subscripts */
22913 int n; /* amount of macro text to show */
22914 if ( mp_type(p)==mp_structured ) {
22915 @<Descend the structure@>;
22916 } else if ( mp_type(p)>=mp_unsuffixed_macro ) {
22917 @<Display a variable macro@>;
22918 } else if ( mp_type(p)!=undefined ){
22919 mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22920 mp_print_char(mp, xord('='));
22921 mp_print_exp(mp, p,0);
22925 @ @<Descend the structure@>=
22928 do { mp_disp_var(mp, q); q=mp_link(q); } while (q!=end_attr);
22930 while ( mp_name_type(q)==mp_subscr ) {
22931 mp_disp_var(mp, q); q=mp_link(q);
22935 @ @<Display a variable macro@>=
22937 mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22938 if ( mp_type(p)>mp_unsuffixed_macro )
22939 mp_print(mp, "@@#"); /* |suffixed_macro| */
22940 mp_print(mp, "=macro:");
22941 if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22942 else n=mp->max_print_line-mp->file_offset-15;
22943 mp_show_macro(mp, value(p),null,n);
22946 @ @<Declare action procedures for use by |do_statement|@>=
22947 static void mp_do_show_var (MP mp) ;
22949 @ @c void mp_do_show_var (MP mp) {
22952 if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22953 if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22954 mp_disp_var(mp, mp->cur_mod); goto DONE;
22959 } while (mp->cur_cmd==comma);
22962 @ @<Declare action procedures for use by |do_statement|@>=
22963 static void mp_do_show_dependencies (MP mp) ;
22965 @ @c void mp_do_show_dependencies (MP mp) {
22966 pointer p; /* link that runs through all dependencies */
22967 p=mp_link(dep_head);
22968 while ( p!=dep_head ) {
22969 if ( mp_interesting(mp, p) ) {
22970 mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22971 if ( mp_type(p)==mp_dependent ) mp_print_char(mp, xord('='));
22972 else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22973 mp_print_dependency(mp, dep_list(p),mp_type(p));
22976 while ( mp_info(p)!=null ) p=mp_link(p);
22982 @ Finally we are ready for the procedure that governs all of the
22985 @<Declare action procedures for use by |do_statement|@>=
22986 static void mp_do_show_whatever (MP mp) ;
22988 @ @c void mp_do_show_whatever (MP mp) {
22989 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22990 switch (mp->cur_mod) {
22991 case show_token_code:mp_do_show_token(mp); break;
22992 case show_stats_code:mp_do_show_stats(mp); break;
22993 case show_code:mp_do_show(mp); break;
22994 case show_var_code:mp_do_show_var(mp); break;
22995 case show_dependencies_code:mp_do_show_dependencies(mp); break;
22996 } /* there are no other cases */
22997 if ( mp->internal[mp_showstopping]>0 ){
23000 if ( mp->interaction<mp_error_stop_mode ) {
23001 help0; decr(mp->error_count);
23003 help1("This isn't an error message; I'm just showing something.");
23005 if ( mp->cur_cmd==semicolon ) mp_error(mp);
23006 else mp_put_get_error(mp);
23010 @ The `\&{addto}' command needs the following additional primitives:
23012 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
23013 @d contour_code 1 /* command modifier for `\&{contour}' */
23014 @d also_code 2 /* command modifier for `\&{also}' */
23016 @ Pre and postscripts need two new identifiers:
23018 @d with_mp_pre_script 11
23019 @d with_mp_post_script 13
23022 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
23023 @:double_path_}{\&{doublepath} primitive@>
23024 mp_primitive(mp, "contour",thing_to_add,contour_code);
23025 @:contour_}{\&{contour} primitive@>
23026 mp_primitive(mp, "also",thing_to_add,also_code);
23027 @:also_}{\&{also} primitive@>
23028 mp_primitive(mp, "withpen",with_option,mp_pen_type);
23029 @:with_pen_}{\&{withpen} primitive@>
23030 mp_primitive(mp, "dashed",with_option,mp_picture_type);
23031 @:dashed_}{\&{dashed} primitive@>
23032 mp_primitive(mp, "withprescript",with_option,with_mp_pre_script);
23033 @:with_mp_pre_script_}{\&{withprescript} primitive@>
23034 mp_primitive(mp, "withpostscript",with_option,with_mp_post_script);
23035 @:with_mp_post_script_}{\&{withpostscript} primitive@>
23036 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
23037 @:with_color_}{\&{withoutcolor} primitive@>
23038 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
23039 @:with_color_}{\&{withgreyscale} primitive@>
23040 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
23041 @:with_color_}{\&{withcolor} primitive@>
23042 /* \&{withrgbcolor} is an alias for \&{withcolor} */
23043 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
23044 @:with_color_}{\&{withrgbcolor} primitive@>
23045 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
23046 @:with_color_}{\&{withcmykcolor} primitive@>
23048 @ @<Cases of |print_cmd...@>=
23050 if ( m==contour_code ) mp_print(mp, "contour");
23051 else if ( m==double_path_code ) mp_print(mp, "doublepath");
23052 else mp_print(mp, "also");
23055 if ( m==mp_pen_type ) mp_print(mp, "withpen");
23056 else if ( m==with_mp_pre_script ) mp_print(mp, "withprescript");
23057 else if ( m==with_mp_post_script ) mp_print(mp, "withpostscript");
23058 else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
23059 else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
23060 else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
23061 else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
23062 else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
23063 else mp_print(mp, "dashed");
23066 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
23067 updates the list of graphical objects starting at |p|. Each $\langle$with
23068 clause$\rangle$ updates all graphical objects whose |type| is compatible.
23069 Other objects are ignored.
23071 @<Declare action procedures for use by |do_statement|@>=
23072 static void mp_scan_with_list (MP mp,pointer p) ;
23074 @ @c void mp_scan_with_list (MP mp,pointer p) {
23075 quarterword t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
23076 pointer q; /* for list manipulation */
23077 unsigned old_setting; /* saved |selector| setting */
23078 pointer k; /* for finding the near-last item in a list */
23079 str_number s; /* for string cleanup after combining */
23080 pointer cp,pp,dp,ap,bp;
23081 /* objects being updated; |void| initially; |null| to suppress update */
23082 cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
23084 while ( mp->cur_cmd==with_option ){
23087 if ( t!=mp_no_model ) mp_scan_expression(mp);
23088 if (((t==with_mp_pre_script)&&(mp->cur_type!=mp_string_type))||
23089 ((t==with_mp_post_script)&&(mp->cur_type!=mp_string_type))||
23090 ((t==mp_uninitialized_model)&&
23091 ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
23092 &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
23093 ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
23094 ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
23095 ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
23096 ((t==mp_pen_type)&&(mp->cur_type!=t))||
23097 ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
23098 @<Complain about improper type@>;
23099 } else if ( t==mp_uninitialized_model ) {
23100 if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23102 @<Transfer a color from the current expression to object~|cp|@>;
23103 mp_flush_cur_exp(mp, 0);
23104 } else if ( t==mp_rgb_model ) {
23105 if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23107 @<Transfer a rgbcolor from the current expression to object~|cp|@>;
23108 mp_flush_cur_exp(mp, 0);
23109 } else if ( t==mp_cmyk_model ) {
23110 if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23112 @<Transfer a cmykcolor from the current expression to object~|cp|@>;
23113 mp_flush_cur_exp(mp, 0);
23114 } else if ( t==mp_grey_model ) {
23115 if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23117 @<Transfer a greyscale from the current expression to object~|cp|@>;
23118 mp_flush_cur_exp(mp, 0);
23119 } else if ( t==mp_no_model ) {
23120 if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23122 @<Transfer a noncolor from the current expression to object~|cp|@>;
23123 } else if ( t==mp_pen_type ) {
23124 if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
23126 if ( mp_pen_p(pp)!=null ) mp_toss_knot_list(mp, mp_pen_p(pp));
23127 mp_pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
23129 } else if ( t==with_mp_pre_script ) {
23132 while ( (ap!=null)&&(! has_color(ap)) )
23135 if ( mp_pre_script(ap)!=null ) { /* build a new,combined string */
23136 s=mp_pre_script(ap);
23137 old_setting=mp->selector;
23138 mp->selector=new_string;
23139 str_room(length(mp_pre_script(ap))+length(mp->cur_exp)+2);
23140 mp_print_str(mp, mp->cur_exp);
23141 append_char(13); /* a forced \ps\ newline */
23142 mp_print_str(mp, mp_pre_script(ap));
23143 mp_pre_script(ap)=mp_make_string(mp);
23145 mp->selector=old_setting;
23147 mp_pre_script(ap)=mp->cur_exp;
23149 mp->cur_type=mp_vacuous;
23151 } else if ( t==with_mp_post_script ) {
23155 while ( mp_link(k)!=null ) {
23157 if ( has_color(k) ) bp=k;
23160 if ( mp_post_script(bp)!=null ) {
23161 s=mp_post_script(bp);
23162 old_setting=mp->selector;
23163 mp->selector=new_string;
23164 str_room(length(mp_post_script(bp))+length(mp->cur_exp)+2);
23165 mp_print_str(mp, mp_post_script(bp));
23166 append_char(13); /* a forced \ps\ newline */
23167 mp_print_str(mp, mp->cur_exp);
23168 mp_post_script(bp)=mp_make_string(mp);
23170 mp->selector=old_setting;
23172 mp_post_script(bp)=mp->cur_exp;
23174 mp->cur_type=mp_vacuous;
23177 if ( dp==mp_void ) {
23178 @<Make |dp| a stroked node in list~|p|@>;
23181 if ( mp_dash_p(dp)!=null ) delete_edge_ref(mp_dash_p(dp));
23182 mp_dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
23183 dash_scale(dp)=unity;
23184 mp->cur_type=mp_vacuous;
23188 @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
23192 @ @<Complain about improper type@>=
23193 { exp_err("Improper type");
23195 help2("Next time say `withpen <known pen expression>';",
23196 "I'll ignore the bad `with' clause and look for another.");
23197 if ( t==with_mp_pre_script )
23198 mp->help_line[1]="Next time say `withprescript <known string expression>';";
23199 else if ( t==with_mp_post_script )
23200 mp->help_line[1]="Next time say `withpostscript <known string expression>';";
23201 else if ( t==mp_picture_type )
23202 mp->help_line[1]="Next time say `dashed <known picture expression>';";
23203 else if ( t==mp_uninitialized_model )
23204 mp->help_line[1]="Next time say `withcolor <known color expression>';";
23205 else if ( t==mp_rgb_model )
23206 mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
23207 else if ( t==mp_cmyk_model )
23208 mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
23209 else if ( t==mp_grey_model )
23210 mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
23211 mp_put_get_flush_error(mp, 0);
23214 @ Forcing the color to be between |0| and |unity| here guarantees that no
23215 picture will ever contain a color outside the legal range for \ps\ graphics.
23217 @<Transfer a color from the current expression to object~|cp|@>=
23218 { if ( mp->cur_type==mp_color_type )
23219 @<Transfer a rgbcolor from the current expression to object~|cp|@>
23220 else if ( mp->cur_type==mp_cmykcolor_type )
23221 @<Transfer a cmykcolor from the current expression to object~|cp|@>
23222 else if ( mp->cur_type==mp_known )
23223 @<Transfer a greyscale from the current expression to object~|cp|@>
23224 else if ( mp->cur_exp==false_code )
23225 @<Transfer a noncolor from the current expression to object~|cp|@>;
23228 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
23229 { q=value(mp->cur_exp);
23234 red_val(cp)=value(red_part_loc(q));
23235 green_val(cp)=value(green_part_loc(q));
23236 blue_val(cp)=value(blue_part_loc(q));
23237 mp_color_model(cp)=mp_rgb_model;
23238 if ( red_val(cp)<0 ) red_val(cp)=0;
23239 if ( green_val(cp)<0 ) green_val(cp)=0;
23240 if ( blue_val(cp)<0 ) blue_val(cp)=0;
23241 if ( red_val(cp)>unity ) red_val(cp)=unity;
23242 if ( green_val(cp)>unity ) green_val(cp)=unity;
23243 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
23246 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
23247 { q=value(mp->cur_exp);
23248 cyan_val(cp)=value(cyan_part_loc(q));
23249 magenta_val(cp)=value(magenta_part_loc(q));
23250 yellow_val(cp)=value(yellow_part_loc(q));
23251 black_val(cp)=value(black_part_loc(q));
23252 mp_color_model(cp)=mp_cmyk_model;
23253 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
23254 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
23255 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
23256 if ( black_val(cp)<0 ) black_val(cp)=0;
23257 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
23258 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
23259 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
23260 if ( black_val(cp)>unity ) black_val(cp)=unity;
23263 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
23270 mp_color_model(cp)=mp_grey_model;
23271 if ( grey_val(cp)<0 ) grey_val(cp)=0;
23272 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
23275 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
23282 mp_color_model(cp)=mp_no_model;
23285 @ @<Make |cp| a colored object in object list~|p|@>=
23287 while ( cp!=null ){
23288 if ( has_color(cp) ) break;
23293 @ @<Make |pp| an object in list~|p| that needs a pen@>=
23295 while ( pp!=null ) {
23296 if ( has_pen(pp) ) break;
23301 @ @<Make |dp| a stroked node in list~|p|@>=
23303 while ( dp!=null ) {
23304 if ( mp_type(dp)==mp_stroked_code ) break;
23309 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
23310 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
23311 if ( pp>mp_void ) {
23312 @<Copy |mp_pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
23314 if ( dp>mp_void ) {
23315 @<Make stroked nodes linked to |dp| refer to |mp_dash_p(dp)|@>;
23319 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
23321 while ( q!=null ) {
23322 if ( has_color(q) ) {
23323 red_val(q)=red_val(cp);
23324 green_val(q)=green_val(cp);
23325 blue_val(q)=blue_val(cp);
23326 black_val(q)=black_val(cp);
23327 mp_color_model(q)=mp_color_model(cp);
23333 @ @<Copy |mp_pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
23335 while ( q!=null ) {
23336 if ( has_pen(q) ) {
23337 if ( mp_pen_p(q)!=null ) mp_toss_knot_list(mp, mp_pen_p(q));
23338 mp_pen_p(q)=copy_pen(mp_pen_p(pp));
23344 @ @<Make stroked nodes linked to |dp| refer to |mp_dash_p(dp)|@>=
23346 while ( q!=null ) {
23347 if ( mp_type(q)==mp_stroked_code ) {
23348 if ( mp_dash_p(q)!=null ) delete_edge_ref(mp_dash_p(q));
23349 mp_dash_p(q)=mp_dash_p(dp);
23350 dash_scale(q)=unity;
23351 if ( mp_dash_p(q)!=null ) add_edge_ref(mp_dash_p(q));
23357 @ One of the things we need to do when we've parsed an \&{addto} or
23358 similar command is find the header of a supposed \&{picture} variable, given
23359 a token list for that variable. Since the edge structure is about to be
23360 updated, we use |private_edges| to make sure that this is possible.
23362 @<Declare action procedures for use by |do_statement|@>=
23363 static pointer mp_find_edges_var (MP mp, pointer t) ;
23365 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
23367 pointer cur_edges; /* the return value */
23368 p=mp_find_variable(mp, t); cur_edges=null;
23370 mp_obliterated(mp, t); mp_put_get_error(mp);
23371 } else if ( mp_type(p)!=mp_picture_type ) {
23372 print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
23373 @.Variable x is the wrong type@>
23374 mp_print(mp, " is the wrong type (");
23375 mp_print_type(mp, mp_type(p)); mp_print_char(mp, xord(')'));
23376 help2("I was looking for a \"known\" picture variable.",
23377 "So I'll not change anything just now.");
23378 mp_put_get_error(mp);
23380 value(p)=mp_private_edges(mp, value(p));
23381 cur_edges=value(p);
23383 mp_flush_node_list(mp, t);
23387 @ @<Cases of |do_statement|...@>=
23388 case add_to_command: mp_do_add_to(mp); break;
23389 case bounds_command:mp_do_bounds(mp); break;
23392 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
23393 @:clip_}{\&{clip} primitive@>
23394 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
23395 @:set_bounds_}{\&{setbounds} primitive@>
23397 @ @<Cases of |print_cmd...@>=
23398 case bounds_command:
23399 if ( m==mp_start_clip_code ) mp_print(mp, "clip");
23400 else mp_print(mp, "setbounds");
23403 @ The following function parses the beginning of an \&{addto} or \&{clip}
23404 command: it expects a variable name followed by a token with |cur_cmd=sep|
23405 and then an expression. The function returns the token list for the variable
23406 and stores the command modifier for the separator token in the global variable
23407 |last_add_type|. We must be careful because this variable might get overwritten
23408 any time we call |get_x_next|.
23411 quarterword last_add_type;
23412 /* command modifier that identifies the last \&{addto} command */
23414 @ @<Declare action procedures for use by |do_statement|@>=
23415 static pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
23417 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
23418 pointer lhv; /* variable to add to left */
23419 quarterword add_type=0; /* value to be returned in |last_add_type| */
23421 mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
23422 if ( mp->cur_type!=mp_token_list ) {
23423 @<Abandon edges command because there's no variable@>;
23425 lhv=mp->cur_exp; add_type=mp->cur_mod;
23426 mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
23428 mp->last_add_type=add_type;
23432 @ @<Abandon edges command because there's no variable@>=
23433 { exp_err("Not a suitable variable");
23434 @.Not a suitable variable@>
23435 help4("At this point I needed to see the name of a picture variable.",
23436 "(Or perhaps you have indeed presented me with one; I might",
23437 "have missed it, if it wasn't followed by the proper token.)",
23438 "So I'll not change anything just now.");
23439 mp_put_get_flush_error(mp, 0);
23442 @ Here is an example of how to use |start_draw_cmd|.
23444 @<Declare action procedures for use by |do_statement|@>=
23445 static void mp_do_bounds (MP mp) ;
23447 @ @c void mp_do_bounds (MP mp) {
23448 pointer lhv,lhe; /* variable on left, the corresponding edge structure */
23449 pointer p; /* for list manipulation */
23450 integer m; /* initial value of |cur_mod| */
23452 lhv=mp_start_draw_cmd(mp, to_token);
23454 lhe=mp_find_edges_var(mp, lhv);
23456 mp_flush_cur_exp(mp, 0);
23457 } else if ( mp->cur_type!=mp_path_type ) {
23458 exp_err("Improper `clip'");
23459 @.Improper `addto'@>
23460 help2("This expression should have specified a known path.",
23461 "So I'll not change anything just now.");
23462 mp_put_get_flush_error(mp, 0);
23463 } else if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
23464 @<Complain about a non-cycle@>;
23466 @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
23471 @ @<Complain about a non-cycle@>=
23472 { print_err("Not a cycle");
23474 help2("That contour should have ended with `..cycle' or `&cycle'.",
23475 "So I'll not change anything just now."); mp_put_get_error(mp);
23478 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
23479 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
23480 mp_link(p)=mp_link(dummy_loc(lhe));
23481 mp_link(dummy_loc(lhe))=p;
23482 if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
23483 p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
23484 mp_type(p)=stop_type(m);
23485 mp_link(obj_tail(lhe))=p;
23487 mp_init_bbox(mp, lhe);
23490 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
23491 cases to deal with.
23493 @<Declare action procedures for use by |do_statement|@>=
23494 static void mp_do_add_to (MP mp) ;
23496 @ @c void mp_do_add_to (MP mp) {
23497 pointer lhv,lhe; /* variable on left, the corresponding edge structure */
23498 pointer p; /* the graphical object or list for |scan_with_list| to update */
23499 pointer e; /* an edge structure to be merged */
23500 quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
23501 lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
23503 if ( add_type==also_code ) {
23504 @<Make sure the current expression is a suitable picture and set |e| and |p|
23507 @<Create a graphical object |p| based on |add_type| and the current
23510 mp_scan_with_list(mp, p);
23511 @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
23515 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
23516 setting |e:=null| prevents anything from being added to |lhe|.
23518 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
23521 if ( mp->cur_type!=mp_picture_type ) {
23522 exp_err("Improper `addto'");
23523 @.Improper `addto'@>
23524 help2("This expression should have specified a known picture.",
23525 "So I'll not change anything just now.");
23526 mp_put_get_flush_error(mp, 0);
23528 e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
23529 p=mp_link(dummy_loc(e));
23533 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
23534 attempts to add to the edge structure.
23536 @<Create a graphical object |p| based on |add_type| and the current...@>=
23538 if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
23539 if ( mp->cur_type!=mp_path_type ) {
23540 exp_err("Improper `addto'");
23541 @.Improper `addto'@>
23542 help2("This expression should have specified a known path.",
23543 "So I'll not change anything just now.");
23544 mp_put_get_flush_error(mp, 0);
23545 } else if ( add_type==contour_code ) {
23546 if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
23547 @<Complain about a non-cycle@>;
23549 p=mp_new_fill_node(mp, mp->cur_exp);
23550 mp->cur_type=mp_vacuous;
23553 p=mp_new_stroked_node(mp, mp->cur_exp);
23554 mp->cur_type=mp_vacuous;
23558 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
23559 lhe=mp_find_edges_var(mp, lhv);
23561 if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
23562 if ( e!=null ) delete_edge_ref(e);
23563 } else if ( add_type==also_code ) {
23565 @<Merge |e| into |lhe| and delete |e|@>;
23569 } else if ( p!=null ) {
23570 mp_link(obj_tail(lhe))=p;
23572 if ( add_type==double_path_code )
23573 if ( mp_pen_p(p)==null )
23574 mp_pen_p(p)=mp_get_pen_circle(mp, 0);
23577 @ @<Merge |e| into |lhe| and delete |e|@>=
23578 { if ( mp_link(dummy_loc(e))!=null ) {
23579 mp_link(obj_tail(lhe))=mp_link(dummy_loc(e));
23580 obj_tail(lhe)=obj_tail(e);
23581 obj_tail(e)=dummy_loc(e);
23582 mp_link(dummy_loc(e))=null;
23583 mp_flush_dash_list(mp, lhe);
23585 mp_toss_edges(mp, e);
23588 @ @<Cases of |do_statement|...@>=
23589 case ship_out_command: mp_do_ship_out(mp); break;
23591 @ @<Declare action procedures for use by |do_statement|@>=
23592 @<Declare the \ps\ output procedures@>
23593 static void mp_do_ship_out (MP mp) ;
23595 @ @c void mp_do_ship_out (MP mp) {
23596 integer c; /* the character code */
23597 mp_get_x_next(mp); mp_scan_expression(mp);
23598 if ( mp->cur_type!=mp_picture_type ) {
23599 @<Complain that it's not a known picture@>;
23601 c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
23602 if ( c<0 ) c=c+256;
23603 @<Store the width information for character code~|c|@>;
23604 mp_ship_out(mp, mp->cur_exp);
23605 mp_flush_cur_exp(mp, 0);
23609 @ @<Complain that it's not a known picture@>=
23611 exp_err("Not a known picture");
23612 help1("I can only output known pictures.");
23613 mp_put_get_flush_error(mp, 0);
23616 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
23619 @<Cases of |do_statement|...@>=
23620 case every_job_command:
23621 mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
23625 halfword start_sym; /* a symbolic token to insert at beginning of job */
23630 @ Finally, we have only the ``message'' commands remaining.
23633 @d err_message_code 1
23635 @d filename_template_code 3
23636 @d print_with_leading_zeroes(A) g = mp->pool_ptr;
23637 mp_print_int(mp, (A)); g = mp->pool_ptr-g;
23639 mp->pool_ptr = mp->pool_ptr - g;
23641 mp_print_char(mp, xord('0'));
23644 mp_print_int(mp, (A));
23649 mp_primitive(mp, "message",message_command,message_code);
23650 @:message_}{\&{message} primitive@>
23651 mp_primitive(mp, "errmessage",message_command,err_message_code);
23652 @:err_message_}{\&{errmessage} primitive@>
23653 mp_primitive(mp, "errhelp",message_command,err_help_code);
23654 @:err_help_}{\&{errhelp} primitive@>
23655 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
23656 @:filename_template_}{\&{filenametemplate} primitive@>
23658 @ @<Cases of |print_cmd...@>=
23659 case message_command:
23660 if ( m<err_message_code ) mp_print(mp, "message");
23661 else if ( m==err_message_code ) mp_print(mp, "errmessage");
23662 else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
23663 else mp_print(mp, "errhelp");
23666 @ @<Cases of |do_statement|...@>=
23667 case message_command: mp_do_message(mp); break;
23669 @ @<Declare action procedures for use by |do_statement|@>=
23670 @<Declare a procedure called |no_string_err|@>
23671 static void mp_do_message (MP mp) ;
23674 @c void mp_do_message (MP mp) {
23675 int m; /* the type of message */
23676 m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
23677 if ( mp->cur_type!=mp_string_type )
23678 mp_no_string_err(mp, "A message should be a known string expression.");
23682 mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
23684 case err_message_code:
23685 @<Print string |cur_exp| as an error message@>;
23687 case err_help_code:
23688 @<Save string |cur_exp| as the |err_help|@>;
23690 case filename_template_code:
23691 @<Save the filename template@>;
23693 } /* there are no other cases */
23695 mp_flush_cur_exp(mp, 0);
23698 @ @<Declare a procedure called |no_string_err|@>=
23699 static void mp_no_string_err (MP mp, const char *s) {
23700 exp_err("Not a string");
23703 mp_put_get_error(mp);
23706 @ The global variable |err_help| is zero when the user has most recently
23707 given an empty help string, or if none has ever been given.
23709 @<Save string |cur_exp| as the |err_help|@>=
23711 if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23712 if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23713 else { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23716 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23717 \&{errhelp}, we don't want to give a long help message each time. So we
23718 give a verbose explanation only once.
23721 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23723 @ @<Set init...@>=mp->long_help_seen=false;
23725 @ @<Print string |cur_exp| as an error message@>=
23727 print_err(""); mp_print_str(mp, mp->cur_exp);
23728 if ( mp->err_help!=0 ) {
23729 mp->use_err_help=true;
23730 } else if ( mp->long_help_seen ) {
23731 help1("(That was another `errmessage'.)") ;
23733 if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23734 help4("This error message was generated by an `errmessage'",
23735 "command, so I can\'t give any explicit help.",
23736 "Pretend that you're Miss Marple: Examine all clues,",
23738 "and deduce the truth by inspired guesses.");
23740 mp_put_get_error(mp); mp->use_err_help=false;
23743 @ @<Cases of |do_statement|...@>=
23744 case write_command: mp_do_write(mp); break;
23746 @ @<Declare action procedures for use by |do_statement|@>=
23747 static void mp_do_write (MP mp) ;
23749 @ @c void mp_do_write (MP mp) {
23750 str_number t; /* the line of text to be written */
23751 write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23752 unsigned old_setting; /* for saving |selector| during output */
23754 mp_scan_expression(mp);
23755 if ( mp->cur_type!=mp_string_type ) {
23756 mp_no_string_err(mp, "The text to be written should be a known string expression");
23757 } else if ( mp->cur_cmd!=to_token ) {
23758 print_err("Missing `to' clause");
23759 help1("A write command should end with `to <filename>'");
23760 mp_put_get_error(mp);
23762 t=mp->cur_exp; mp->cur_type=mp_vacuous;
23764 mp_scan_expression(mp);
23765 if ( mp->cur_type!=mp_string_type )
23766 mp_no_string_err(mp, "I can\'t write to that file name. It isn't a known string");
23768 @<Write |t| to the file named by |cur_exp|@>;
23772 mp_flush_cur_exp(mp, 0);
23775 @ @<Write |t| to the file named by |cur_exp|@>=
23777 @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23778 |cur_exp| must be inserted@>;
23779 if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23780 @<Record the end of file on |wr_file[n]|@>;
23782 old_setting=mp->selector;
23783 mp->selector=n+write_file;
23784 mp_print_str(mp, t); mp_print_ln(mp);
23785 mp->selector = old_setting;
23789 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23791 char *fn = str(mp->cur_exp);
23793 n0=mp->write_files;
23794 while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) {
23795 if ( n==0 ) { /* bottom reached */
23796 if ( n0==mp->write_files ) {
23797 if ( mp->write_files<mp->max_write_files ) {
23798 incr(mp->write_files);
23803 l = mp->max_write_files + (mp->max_write_files/4);
23804 wr_file = xmalloc((l+1),sizeof(void *));
23805 wr_fname = xmalloc((l+1),sizeof(char *));
23806 for (k=0;k<=l;k++) {
23807 if (k<=mp->max_write_files) {
23808 wr_file[k]=mp->wr_file[k];
23809 wr_fname[k]=mp->wr_fname[k];
23815 xfree(mp->wr_file); xfree(mp->wr_fname);
23816 mp->max_write_files = l;
23817 mp->wr_file = wr_file;
23818 mp->wr_fname = wr_fname;
23822 mp_open_write_file(mp, fn ,n);
23825 if ( mp->wr_fname[n]==NULL ) n0=n;
23830 @ @<Record the end of file on |wr_file[n]|@>=
23831 { (mp->close_file)(mp,mp->wr_file[n]);
23832 xfree(mp->wr_fname[n]);
23833 if ( n==mp->write_files-1 ) mp->write_files=n;
23837 @* \[42] Writing font metric data.
23838 \TeX\ gets its knowledge about fonts from font metric files, also called
23839 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23840 but other programs know about them too. One of \MP's duties is to
23841 write \.{TFM} files so that the user's fonts can readily be
23842 applied to typesetting.
23843 @:TFM files}{\.{TFM} files@>
23844 @^font metric files@>
23846 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23847 Since the number of bytes is always a multiple of~4, we could
23848 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23849 byte interpretation. The format of \.{TFM} files was designed by
23850 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23851 @^Ramshaw, Lyle Harold@>
23852 of information in a compact but useful form.
23855 void * tfm_file; /* the font metric output goes here */
23856 char * metric_file_name; /* full name of the font metric file */
23858 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23859 integers that give the lengths of the various subsequent portions
23860 of the file. These twelve integers are, in order:
23861 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23862 |lf|&length of the entire file, in words;\cr
23863 |lh|&length of the header data, in words;\cr
23864 |bc|&smallest character code in the font;\cr
23865 |ec|&largest character code in the font;\cr
23866 |nw|&number of words in the width table;\cr
23867 |nh|&number of words in the height table;\cr
23868 |nd|&number of words in the depth table;\cr
23869 |ni|&number of words in the italic correction table;\cr
23870 |nl|&number of words in the lig/kern table;\cr
23871 |nk|&number of words in the kern table;\cr
23872 |ne|&number of words in the extensible character table;\cr
23873 |np|&number of font parameter words.\cr}}$$
23874 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23876 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23877 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23878 and as few as 0 characters (if |bc=ec+1|).
23880 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23881 16 or more bits, the most significant bytes appear first in the file.
23882 This is called BigEndian order.
23883 @^BigEndian order@>
23885 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23888 The most important data type used here is a |fix_word|, which is
23889 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23890 quantity, with the two's complement of the entire word used to represent
23891 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23892 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23893 the smallest is $-2048$. We will see below, however, that all but two of
23894 the |fix_word| values must lie between $-16$ and $+16$.
23896 @ The first data array is a block of header information, which contains
23897 general facts about the font. The header must contain at least two words,
23898 |header[0]| and |header[1]|, whose meaning is explained below. Additional
23899 header information of use to other software routines might also be
23900 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23901 For example, 16 more words of header information are in use at the Xerox
23902 Palo Alto Research Center; the first ten specify the character coding
23903 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23904 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23905 last gives the ``face byte.''
23907 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23908 the \.{GF} output file. This helps ensure consistency between files,
23909 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23910 should match the check sums on actual fonts that are used. The actual
23911 relation between this check sum and the rest of the \.{TFM} file is not
23912 important; the check sum is simply an identification number with the
23913 property that incompatible fonts almost always have distinct check sums.
23916 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23917 font, in units of \TeX\ points. This number must be at least 1.0; it is
23918 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23919 font, i.e., a font that was designed to look best at a 10-point size,
23920 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23921 $\delta$ \.{pt}', the effect is to override the design size and replace it
23922 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23923 the font image by a factor of $\delta$ divided by the design size. {\sl
23924 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23925 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23926 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23927 since many fonts have a design size equal to one em. The other dimensions
23928 must be less than 16 design-size units in absolute value; thus,
23929 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23930 \.{TFM} file whose first byte might be something besides 0 or 255.
23933 @ Next comes the |char_info| array, which contains one |char_info_word|
23934 per character. Each word in this part of the file contains six fields
23935 packed into four bytes as follows.
23937 \yskip\hang first byte: |width_index| (8 bits)\par
23938 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23940 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23942 \hang fourth byte: |remainder| (8 bits)\par
23944 The actual width of a character is \\{width}|[width_index]|, in design-size
23945 units; this is a device for compressing information, since many characters
23946 have the same width. Since it is quite common for many characters
23947 to have the same height, depth, or italic correction, the \.{TFM} format
23948 imposes a limit of 16 different heights, 16 different depths, and
23949 64 different italic corrections.
23951 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23952 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23953 value of zero. The |width_index| should never be zero unless the
23954 character does not exist in the font, since a character is valid if and
23955 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23957 @ The |tag| field in a |char_info_word| has four values that explain how to
23958 interpret the |remainder| field.
23960 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23961 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23962 program starting at location |remainder| in the |lig_kern| array.\par
23963 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23964 characters of ascending sizes, and not the largest in the chain. The
23965 |remainder| field gives the character code of the next larger character.\par
23966 \hang|tag=3| (|ext_tag|) means that this character code represents an
23967 extensible character, i.e., a character that is built up of smaller pieces
23968 so that it can be made arbitrarily large. The pieces are specified in
23969 |exten[remainder]|.\par
23971 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23972 unless they are used in special circumstances in math formulas. For example,
23973 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23974 operation looks for both |list_tag| and |ext_tag|.
23976 @d no_tag 0 /* vanilla character */
23977 @d lig_tag 1 /* character has a ligature/kerning program */
23978 @d list_tag 2 /* character has a successor in a charlist */
23979 @d ext_tag 3 /* character is extensible */
23981 @ The |lig_kern| array contains instructions in a simple programming language
23982 that explains what to do for special letter pairs. Each word in this array is a
23983 |lig_kern_command| of four bytes.
23985 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23986 step if the byte is 128 or more, otherwise the next step is obtained by
23987 skipping this number of intervening steps.\par
23988 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23989 then perform the operation and stop, otherwise continue.''\par
23990 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23991 a kern step otherwise.\par
23992 \hang fourth byte: |remainder|.\par
23995 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23996 between the current character and |next_char|. This amount is
23997 often negative, so that the characters are brought closer together
23998 by kerning; but it might be positive.
24000 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
24001 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
24002 |remainder| is inserted between the current character and |next_char|;
24003 then the current character is deleted if $b=0$, and |next_char| is
24004 deleted if $c=0$; then we pass over $a$~characters to reach the next
24005 current character (which may have a ligature/kerning program of its own).
24007 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
24008 the |next_char| byte is the so-called right boundary character of this font;
24009 the value of |next_char| need not lie between |bc| and~|ec|.
24010 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
24011 there is a special ligature/kerning program for a left boundary character,
24012 beginning at location |256*op_byte+remainder|.
24013 The interpretation is that \TeX\ puts implicit boundary characters
24014 before and after each consecutive string of characters from the same font.
24015 These implicit characters do not appear in the output, but they can affect
24016 ligatures and kerning.
24018 If the very first instruction of a character's |lig_kern| program has
24019 |skip_byte>128|, the program actually begins in location
24020 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
24021 arrays, because the first instruction must otherwise
24022 appear in a location |<=255|.
24024 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
24026 $$\hbox{|256*op_byte+remainder<nl|.}$$
24027 If such an instruction is encountered during
24028 normal program execution, it denotes an unconditional halt; no ligature
24029 command is performed.
24032 /* value indicating `\.{STOP}' in a lig/kern program */
24033 @d kern_flag (128) /* op code for a kern step */
24034 @d skip_byte(A) mp->lig_kern[(A)].b0
24035 @d next_char(A) mp->lig_kern[(A)].b1
24036 @d op_byte(A) mp->lig_kern[(A)].b2
24037 @d rem_byte(A) mp->lig_kern[(A)].b3
24039 @ Extensible characters are specified by an |extensible_recipe|, which
24040 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
24041 order). These bytes are the character codes of individual pieces used to
24042 build up a large symbol. If |top|, |mid|, or |bot| are zero, they are not
24043 present in the built-up result. For example, an extensible vertical line is
24044 like an extensible bracket, except that the top and bottom pieces are missing.
24046 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
24047 if the piece isn't present. Then the extensible characters have the form
24048 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
24049 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
24050 The width of the extensible character is the width of $R$; and the
24051 height-plus-depth is the sum of the individual height-plus-depths of the
24052 components used, since the pieces are butted together in a vertical list.
24054 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
24055 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
24056 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
24057 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
24059 @ The final portion of a \.{TFM} file is the |param| array, which is another
24060 sequence of |fix_word| values.
24062 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
24063 to help position accents. For example, |slant=.25| means that when you go
24064 up one unit, you also go .25 units to the right. The |slant| is a pure
24065 number; it is the only |fix_word| other than the design size itself that is
24066 not scaled by the design size.
24069 \hang|param[2]=space| is the normal spacing between words in text.
24070 Note that character 040 in the font need not have anything to do with
24073 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
24075 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
24077 \hang|param[5]=x_height| is the size of one ex in the font; it is also
24078 the height of letters for which accents don't have to be raised or lowered.
24080 \hang|param[6]=quad| is the size of one em in the font.
24082 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
24086 If fewer than seven parameters are present, \TeX\ sets the missing parameters
24091 @d space_stretch_code 3
24092 @d space_shrink_code 4
24095 @d extra_space_code 7
24097 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
24098 information, and it does this all at once at the end of a job.
24099 In order to prepare for such frenetic activity, it squirrels away the
24100 necessary facts in various arrays as information becomes available.
24102 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
24103 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
24104 |tfm_ital_corr|. Other information about a character (e.g., about
24105 its ligatures or successors) is accessible via the |char_tag| and
24106 |char_remainder| arrays. Other information about the font as a whole
24107 is kept in additional arrays called |header_byte|, |lig_kern|,
24108 |kern|, |exten|, and |param|.
24110 @d max_tfm_int 32510
24111 @d undefined_label max_tfm_int /* an undefined local label */
24114 #define TFM_ITEMS 257
24116 eight_bits ec; /* smallest and largest character codes shipped out */
24117 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
24118 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
24119 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
24120 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
24121 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
24122 int char_tag[TFM_ITEMS]; /* |remainder| category */
24123 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
24124 char *header_byte; /* bytes of the \.{TFM} header */
24125 int header_last; /* last initialized \.{TFM} header byte */
24126 int header_size; /* size of the \.{TFM} header */
24127 four_quarters *lig_kern; /* the ligature/kern table */
24128 short nl; /* the number of ligature/kern steps so far */
24129 scaled *kern; /* distinct kerning amounts */
24130 short nk; /* the number of distinct kerns so far */
24131 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
24132 short ne; /* the number of extensible characters so far */
24133 scaled *param; /* \&{fontinfo} parameters */
24134 short np; /* the largest \&{fontinfo} parameter specified so far */
24135 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
24136 short skip_table[TFM_ITEMS]; /* local label status */
24137 boolean lk_started; /* has there been a lig/kern step in this command yet? */
24138 integer bchar; /* right boundary character */
24139 short bch_label; /* left boundary starting location */
24140 short ll;short lll; /* registers used for lig/kern processing */
24141 short label_loc[257]; /* lig/kern starting addresses */
24142 eight_bits label_char[257]; /* characters for |label_loc| */
24143 short label_ptr; /* highest position occupied in |label_loc| */
24145 @ @<Allocate or initialize ...@>=
24146 mp->header_size = 128; /* just for init */
24147 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
24149 @ @<Dealloc variables@>=
24150 xfree(mp->header_byte);
24151 xfree(mp->lig_kern);
24156 for (k=0;k<= 255;k++ ) {
24157 mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
24158 mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
24159 mp->skip_table[k]=undefined_label;
24161 memset(mp->header_byte,0,(size_t)mp->header_size);
24162 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
24163 mp->internal[mp_boundary_char]=-unity;
24164 mp->bch_label=undefined_label;
24165 mp->label_loc[0]=-1; mp->label_ptr=0;
24167 @ @<Declarations@>=
24168 static scaled mp_tfm_check (MP mp,quarterword m) ;
24171 static scaled mp_tfm_check (MP mp,quarterword m) {
24172 if ( abs(mp->internal[m])>=fraction_half ) {
24173 print_err("Enormous "); mp_print(mp, mp->int_name[m]);
24174 @.Enormous charwd...@>
24175 @.Enormous chardp...@>
24176 @.Enormous charht...@>
24177 @.Enormous charic...@>
24178 @.Enormous designsize...@>
24179 mp_print(mp, " has been reduced");
24180 help1("Font metric dimensions must be less than 2048pt.");
24181 mp_put_get_error(mp);
24182 if ( mp->internal[m]>0 ) return (fraction_half-1);
24183 else return (1-fraction_half);
24185 return mp->internal[m];
24189 @ @<Store the width information for character code~|c|@>=
24190 if ( c<mp->bc ) mp->bc=(eight_bits)c;
24191 if ( c>mp->ec ) mp->ec=(eight_bits)c;
24192 mp->char_exists[c]=true;
24193 mp->tfm_width[c]=mp_tfm_check(mp,mp_char_wd);
24194 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
24195 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
24196 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
24198 @ Now let's consider \MP's special \.{TFM}-oriented commands.
24200 @<Cases of |do_statement|...@>=
24201 case tfm_command: mp_do_tfm_command(mp); break;
24203 @ @d char_list_code 0
24204 @d lig_table_code 1
24205 @d extensible_code 2
24206 @d header_byte_code 3
24207 @d font_dimen_code 4
24210 mp_primitive(mp, "charlist",tfm_command,char_list_code);
24211 @:char_list_}{\&{charlist} primitive@>
24212 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
24213 @:lig_table_}{\&{ligtable} primitive@>
24214 mp_primitive(mp, "extensible",tfm_command,extensible_code);
24215 @:extensible_}{\&{extensible} primitive@>
24216 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
24217 @:header_byte_}{\&{headerbyte} primitive@>
24218 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
24219 @:font_dimen_}{\&{fontdimen} primitive@>
24221 @ @<Cases of |print_cmd...@>=
24224 case char_list_code:mp_print(mp, "charlist"); break;
24225 case lig_table_code:mp_print(mp, "ligtable"); break;
24226 case extensible_code:mp_print(mp, "extensible"); break;
24227 case header_byte_code:mp_print(mp, "headerbyte"); break;
24228 default: mp_print(mp, "fontdimen"); break;
24232 @ @<Declare action procedures for use by |do_statement|@>=
24233 static eight_bits mp_get_code (MP mp) ;
24235 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
24236 integer c; /* the code value found */
24237 mp_get_x_next(mp); mp_scan_expression(mp);
24238 if ( mp->cur_type==mp_known ) {
24239 c=mp_round_unscaled(mp, mp->cur_exp);
24240 if ( c>=0 ) if ( c<256 ) return (eight_bits)c;
24241 } else if ( mp->cur_type==mp_string_type ) {
24242 if ( length(mp->cur_exp)==1 ) {
24243 c=mp->str_pool[mp->str_start[mp->cur_exp]];
24244 return (eight_bits)c;
24247 exp_err("Invalid code has been replaced by 0");
24248 @.Invalid code...@>
24249 help2("I was looking for a number between 0 and 255, or for a",
24250 "string of length 1. Didn't find it; will use 0 instead.");
24251 mp_put_get_flush_error(mp, 0); c=0;
24252 return (eight_bits)c;
24255 @ @<Declare action procedures for use by |do_statement|@>=
24256 static void mp_set_tag (MP mp,halfword c, quarterword t, halfword r) ;
24258 @ @c void mp_set_tag (MP mp,halfword c, quarterword t, halfword r) {
24259 if ( mp->char_tag[c]==no_tag ) {
24260 mp->char_tag[c]=t; mp->char_remainder[c]=r;
24262 incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r;
24263 mp->label_char[mp->label_ptr]=(eight_bits)c;
24266 @<Complain about a character tag conflict@>;
24270 @ @<Complain about a character tag conflict@>=
24272 print_err("Character ");
24273 if ( (c>' ')&&(c<127) ) mp_print_char(mp,xord(c));
24274 else if ( c==256 ) mp_print(mp, "||");
24275 else { mp_print(mp, "code "); mp_print_int(mp, c); };
24276 mp_print(mp, " is already ");
24277 @.Character c is already...@>
24278 switch (mp->char_tag[c]) {
24279 case lig_tag: mp_print(mp, "in a ligtable"); break;
24280 case list_tag: mp_print(mp, "in a charlist"); break;
24281 case ext_tag: mp_print(mp, "extensible"); break;
24282 } /* there are no other cases */
24283 help2("It's not legal to label a character more than once.",
24284 "So I'll not change anything just now.");
24285 mp_put_get_error(mp);
24288 @ @<Declare action procedures for use by |do_statement|@>=
24289 static void mp_do_tfm_command (MP mp) ;
24291 @ @c void mp_do_tfm_command (MP mp) {
24292 int c,cc; /* character codes */
24293 int k; /* index into the |kern| array */
24294 int j; /* index into |header_byte| or |param| */
24295 switch (mp->cur_mod) {
24296 case char_list_code:
24298 /* we will store a list of character successors */
24299 while ( mp->cur_cmd==colon ) {
24300 cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
24303 case lig_table_code:
24304 if (mp->lig_kern==NULL)
24305 mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
24306 if (mp->kern==NULL)
24307 mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
24308 @<Store a list of ligature/kern steps@>;
24310 case extensible_code:
24311 @<Define an extensible recipe@>;
24313 case header_byte_code:
24314 case font_dimen_code:
24315 c=mp->cur_mod; mp_get_x_next(mp);
24316 mp_scan_expression(mp);
24317 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
24318 exp_err("Improper location");
24319 @.Improper location@>
24320 help2("I was looking for a known, positive number.",
24321 "For safety's sake I'll ignore the present command.");
24322 mp_put_get_error(mp);
24324 j=mp_round_unscaled(mp, mp->cur_exp);
24325 if ( mp->cur_cmd!=colon ) {
24326 mp_missing_err(mp, ":");
24328 help1("A colon should follow a headerbyte or fontinfo location.");
24331 if ( c==header_byte_code ) {
24332 @<Store a list of header bytes@>;
24334 if (mp->param==NULL)
24335 mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
24336 @<Store a list of font dimensions@>;
24340 } /* there are no other cases */
24343 @ @<Store a list of ligature/kern steps@>=
24345 mp->lk_started=false;
24348 if ((mp->cur_cmd==skip_to)&& mp->lk_started )
24349 @<Process a |skip_to| command and |goto done|@>;
24350 if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
24351 else { mp_back_input(mp); c=mp_get_code(mp); };
24352 if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
24353 @<Record a label in a lig/kern subprogram and |goto continue|@>;
24355 if ( mp->cur_cmd==lig_kern_token ) {
24356 @<Compile a ligature/kern command@>;
24358 print_err("Illegal ligtable step");
24359 @.Illegal ligtable step@>
24360 help1("I was looking for `=:' or `kern' here.");
24361 mp_back_error(mp); next_char(mp->nl)=qi(0);
24362 op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
24363 skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
24365 if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
24367 if ( mp->cur_cmd==comma ) goto CONTINUE;
24368 if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
24373 mp_primitive(mp, "=:",lig_kern_token,0);
24374 @:=:_}{\.{=:} primitive@>
24375 mp_primitive(mp, "=:|",lig_kern_token,1);
24376 @:=:/_}{\.{=:\char'174} primitive@>
24377 mp_primitive(mp, "=:|>",lig_kern_token,5);
24378 @:=:/>_}{\.{=:\char'174>} primitive@>
24379 mp_primitive(mp, "|=:",lig_kern_token,2);
24380 @:=:/_}{\.{\char'174=:} primitive@>
24381 mp_primitive(mp, "|=:>",lig_kern_token,6);
24382 @:=:/>_}{\.{\char'174=:>} primitive@>
24383 mp_primitive(mp, "|=:|",lig_kern_token,3);
24384 @:=:/_}{\.{\char'174=:\char'174} primitive@>
24385 mp_primitive(mp, "|=:|>",lig_kern_token,7);
24386 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
24387 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
24388 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
24389 mp_primitive(mp, "kern",lig_kern_token,128);
24390 @:kern_}{\&{kern} primitive@>
24392 @ @<Cases of |print_cmd...@>=
24393 case lig_kern_token:
24395 case 0:mp_print(mp, "=:"); break;
24396 case 1:mp_print(mp, "=:|"); break;
24397 case 2:mp_print(mp, "|=:"); break;
24398 case 3:mp_print(mp, "|=:|"); break;
24399 case 5:mp_print(mp, "=:|>"); break;
24400 case 6:mp_print(mp, "|=:>"); break;
24401 case 7:mp_print(mp, "|=:|>"); break;
24402 case 11:mp_print(mp, "|=:|>>"); break;
24403 default: mp_print(mp, "kern"); break;
24407 @ Local labels are implemented by maintaining the |skip_table| array,
24408 where |skip_table[c]| is either |undefined_label| or the address of the
24409 most recent lig/kern instruction that skips to local label~|c|. In the
24410 latter case, the |skip_byte| in that instruction will (temporarily)
24411 be zero if there were no prior skips to this label, or it will be the
24412 distance to the prior skip.
24414 We may need to cancel skips that span more than 127 lig/kern steps.
24416 @d cancel_skips(A) mp->ll=(A);
24418 mp->lll=qo(skip_byte(mp->ll));
24419 skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
24420 } while (mp->lll!=0)
24421 @d skip_error(A) { print_err("Too far to skip");
24422 @.Too far to skip@>
24423 help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
24424 mp_error(mp); cancel_skips((A));
24427 @<Process a |skip_to| command and |goto done|@>=
24430 if ( mp->nl-mp->skip_table[c]>128 ) {
24431 skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
24433 if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
24434 else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
24435 mp->skip_table[c]=mp->nl-1; goto DONE;
24438 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
24440 if ( mp->cur_cmd==colon ) {
24441 if ( c==256 ) mp->bch_label=mp->nl;
24442 else mp_set_tag(mp, c,lig_tag,mp->nl);
24443 } else if ( mp->skip_table[c]<undefined_label ) {
24444 mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
24446 mp->lll=qo(skip_byte(mp->ll));
24447 if ( mp->nl-mp->ll>128 ) {
24448 skip_error(mp->ll); goto CONTINUE;
24450 skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
24451 } while (mp->lll!=0);
24456 @ @<Compile a ligature/kern...@>=
24458 next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
24459 if ( mp->cur_mod<128 ) { /* ligature op */
24460 op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
24462 mp_get_x_next(mp); mp_scan_expression(mp);
24463 if ( mp->cur_type!=mp_known ) {
24464 exp_err("Improper kern");
24466 help2("The amount of kern should be a known numeric value.",
24467 "I'm zeroing this one. Proceed, with fingers crossed.");
24468 mp_put_get_flush_error(mp, 0);
24470 mp->kern[mp->nk]=mp->cur_exp;
24472 while ( mp->kern[k]!=mp->cur_exp ) incr(k);
24474 if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
24477 op_byte(mp->nl)=kern_flag+(k / 256);
24478 rem_byte(mp->nl)=qi((k % 256));
24480 mp->lk_started=true;
24483 @ @d missing_extensible_punctuation(A)
24484 { mp_missing_err(mp, (A));
24485 @.Missing `\char`\#'@>
24486 help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
24489 @<Define an extensible recipe@>=
24491 if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
24492 c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
24493 if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
24494 ext_top(mp->ne)=qi(mp_get_code(mp));
24495 if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
24496 ext_mid(mp->ne)=qi(mp_get_code(mp));
24497 if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
24498 ext_bot(mp->ne)=qi(mp_get_code(mp));
24499 if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
24500 ext_rep(mp->ne)=qi(mp_get_code(mp));
24504 @ The header could contain ASCII zeroes, so can't use |strdup|.
24506 @<Store a list of header bytes@>=
24508 if ( j>=mp->header_size ) {
24509 size_t l = (size_t)(mp->header_size + (mp->header_size/4));
24510 char *t = xmalloc(l,1);
24512 memcpy(t,mp->header_byte,(size_t)mp->header_size);
24513 xfree (mp->header_byte);
24514 mp->header_byte = t;
24515 mp->header_size = (int)l;
24517 mp->header_byte[j]=(char)mp_get_code(mp);
24518 incr(j); incr(mp->header_last);
24519 } while (mp->cur_cmd==comma)
24521 @ @<Store a list of font dimensions@>=
24523 if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
24524 while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
24525 mp_get_x_next(mp); mp_scan_expression(mp);
24526 if ( mp->cur_type!=mp_known ){
24527 exp_err("Improper font parameter");
24528 @.Improper font parameter@>
24529 help1("I'm zeroing this one. Proceed, with fingers crossed.");
24530 mp_put_get_flush_error(mp, 0);
24532 mp->param[j]=mp->cur_exp; incr(j);
24533 } while (mp->cur_cmd==comma)
24535 @ OK: We've stored all the data that is needed for the \.{TFM} file.
24536 All that remains is to output it in the correct format.
24538 An interesting problem needs to be solved in this connection, because
24539 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
24540 and 64~italic corrections. If the data has more distinct values than
24541 this, we want to meet the necessary restrictions by perturbing the
24542 given values as little as possible.
24544 \MP\ solves this problem in two steps. First the values of a given
24545 kind (widths, heights, depths, or italic corrections) are sorted;
24546 then the list of sorted values is perturbed, if necessary.
24548 The sorting operation is facilitated by having a special node of
24549 essentially infinite |value| at the end of the current list.
24551 @<Initialize table entries...@>=
24552 value(inf_val)=fraction_four;
24554 @ Straight linear insertion is good enough for sorting, since the lists
24555 are usually not terribly long. As we work on the data, the current list
24556 will start at |mp_link(temp_head)| and end at |inf_val|; the nodes in this
24557 list will be in increasing order of their |value| fields.
24559 Given such a list, the |sort_in| function takes a value and returns a pointer
24560 to where that value can be found in the list. The value is inserted in
24561 the proper place, if necessary.
24563 At the time we need to do these operations, most of \MP's work has been
24564 completed, so we will have plenty of memory to play with. The value nodes
24565 that are allocated for sorting will never be returned to free storage.
24567 @d clear_the_list mp_link(temp_head)=inf_val
24570 static pointer mp_sort_in (MP mp,scaled v) {
24571 pointer p,q,r; /* list manipulation registers */
24575 if ( v<=value(q) ) break;
24578 if ( v<value(q) ) {
24579 r=mp_get_node(mp, value_node_size); value(r)=v; mp_link(r)=q; mp_link(p)=r;
24584 @ Now we come to the interesting part, where we reduce the list if necessary
24585 until it has the required size. The |min_cover| routine is basic to this
24586 process; it computes the minimum number~|m| such that the values of the
24587 current sorted list can be covered by |m|~intervals of width~|d|. It
24588 also sets the global value |perturbation| to the smallest value $d'>d$
24589 such that the covering found by this algorithm would be different.
24591 In particular, |min_cover(0)| returns the number of distinct values in the
24592 current list and sets |perturbation| to the minimum distance between
24596 static integer mp_min_cover (MP mp,scaled d) {
24597 pointer p; /* runs through the current list */
24598 scaled l; /* the least element covered by the current interval */
24599 integer m; /* lower bound on the size of the minimum cover */
24600 m=0; p=mp_link(temp_head); mp->perturbation=el_gordo;
24601 while ( p!=inf_val ){
24602 incr(m); l=value(p);
24603 do { p=mp_link(p); } while (value(p)<=l+d);
24604 if ( value(p)-l<mp->perturbation )
24605 mp->perturbation=value(p)-l;
24611 scaled perturbation; /* quantity related to \.{TFM} rounding */
24612 integer excess; /* the list is this much too long */
24614 @ The smallest |d| such that a given list can be covered with |m| intervals
24615 is determined by the |threshold| routine, which is sort of an inverse
24616 to |min_cover|. The idea is to increase the interval size rapidly until
24617 finding the range, then to go sequentially until the exact borderline has
24621 static scaled mp_threshold (MP mp,integer m) {
24622 scaled d; /* lower bound on the smallest interval size */
24623 mp->excess=mp_min_cover(mp, 0)-m;
24624 if ( mp->excess<=0 ) {
24628 d=mp->perturbation;
24629 } while (mp_min_cover(mp, d+d)>m);
24630 while ( mp_min_cover(mp, d)>m )
24631 d=mp->perturbation;
24636 @ The |skimp| procedure reduces the current list to at most |m| entries,
24637 by changing values if necessary. It also sets |mp_info(p):=k| if |value(p)|
24638 is the |k|th distinct value on the resulting list, and it sets
24639 |perturbation| to the maximum amount by which a |value| field has
24640 been changed. The size of the resulting list is returned as the
24644 static integer mp_skimp (MP mp,integer m) {
24645 scaled d; /* the size of intervals being coalesced */
24646 pointer p,q,r; /* list manipulation registers */
24647 scaled l; /* the least value in the current interval */
24648 scaled v; /* a compromise value */
24649 d=mp_threshold(mp, m); mp->perturbation=0;
24650 q=temp_head; m=0; p=mp_link(temp_head);
24651 while ( p!=inf_val ) {
24652 incr(m); l=value(p); mp_info(p)=m;
24653 if ( value(mp_link(p))<=l+d ) {
24654 @<Replace an interval of values by its midpoint@>;
24661 @ @<Replace an interval...@>=
24664 p=mp_link(p); mp_info(p)=m;
24665 decr(mp->excess); if ( mp->excess==0 ) d=0;
24666 } while (value(mp_link(p))<=l+d);
24667 v=l+halfp(value(p)-l);
24668 if ( value(p)-v>mp->perturbation )
24669 mp->perturbation=value(p)-v;
24672 r=mp_link(r); value(r)=v;
24674 mp_link(q)=p; /* remove duplicate values from the current list */
24677 @ A warning message is issued whenever something is perturbed by
24678 more than 1/16\thinspace pt.
24681 static void mp_tfm_warning (MP mp,quarterword m) {
24682 mp_print_nl(mp, "(some ");
24683 mp_print(mp, mp->int_name[m]);
24684 @.some charwds...@>
24685 @.some chardps...@>
24686 @.some charhts...@>
24687 @.some charics...@>
24688 mp_print(mp, " values had to be adjusted by as much as ");
24689 mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
24692 @ Here's an example of how we use these routines.
24693 The width data needs to be perturbed only if there are 256 distinct
24694 widths, but \MP\ must check for this case even though it is
24697 An integer variable |k| will be defined when we use this code.
24698 The |dimen_head| array will contain pointers to the sorted
24699 lists of dimensions.
24701 @<Massage the \.{TFM} widths@>=
24703 for (k=mp->bc;k<=mp->ec;k++) {
24704 if ( mp->char_exists[k] )
24705 mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
24707 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=mp_link(temp_head);
24708 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24711 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24713 @ Heights, depths, and italic corrections are different from widths
24714 not only because their list length is more severely restricted, but
24715 also because zero values do not need to be put into the lists.
24717 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24719 for (k=mp->bc;k<=mp->ec;k++) {
24720 if ( mp->char_exists[k] ) {
24721 if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24722 else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24725 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=mp_link(temp_head);
24726 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24728 for (k=mp->bc;k<=mp->ec;k++) {
24729 if ( mp->char_exists[k] ) {
24730 if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24731 else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24734 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=mp_link(temp_head);
24735 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24737 for (k=mp->bc;k<=mp->ec;k++) {
24738 if ( mp->char_exists[k] ) {
24739 if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24740 else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24743 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=mp_link(temp_head);
24744 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24746 @ @<Initialize table entries...@>=
24747 value(zero_val)=0; mp_info(zero_val)=0;
24749 @ Bytes 5--8 of the header are set to the design size, unless the user has
24750 some crazy reason for specifying them differently.
24753 Error messages are not allowed at the time this procedure is called,
24754 so a warning is printed instead.
24756 The value of |max_tfm_dimen| is calculated so that
24757 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24758 < \\{three\_bytes}.$$
24760 @d three_bytes 0100000000 /* $2^{24}$ */
24763 static void mp_fix_design_size (MP mp) {
24764 scaled d; /* the design size */
24765 d=mp->internal[mp_design_size];
24766 if ( (d<unity)||(d>=fraction_half) ) {
24768 mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24769 @.illegal design size...@>
24770 d=040000000; mp->internal[mp_design_size]=d;
24772 if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24773 if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24774 mp->header_byte[4]=d / 04000000;
24775 mp->header_byte[5]=(d / 4096) % 256;
24776 mp->header_byte[6]=(d / 16) % 256;
24777 mp->header_byte[7]=(d % 16)*16;
24779 mp->max_tfm_dimen=16*mp->internal[mp_design_size]-1-mp->internal[mp_design_size] / 010000000;
24780 if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24783 @ The |dimen_out| procedure computes a |fix_word| relative to the
24784 design size. If the data was out of range, it is corrected and the
24785 global variable |tfm_changed| is increased by~one.
24788 static integer mp_dimen_out (MP mp,scaled x) {
24789 if ( abs(x)>mp->max_tfm_dimen ) {
24790 incr(mp->tfm_changed);
24791 if ( x>0 ) x=mp->max_tfm_dimen; else x=-mp->max_tfm_dimen;
24793 x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24798 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24799 integer tfm_changed; /* the number of data entries that were out of bounds */
24801 @ If the user has not specified any of the first four header bytes,
24802 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24803 from the |tfm_width| data relative to the design size.
24807 static void mp_fix_check_sum (MP mp) {
24808 eight_bits k; /* runs through character codes */
24809 eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24810 integer x; /* hash value used in check sum computation */
24811 if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24812 mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24813 @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24814 mp->header_byte[0]=(char)B1; mp->header_byte[1]=(char)B2;
24815 mp->header_byte[2]=(char)B3; mp->header_byte[3]=(char)B4;
24820 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24821 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24822 for (k=mp->bc;k<=mp->ec;k++) {
24823 if ( mp->char_exists[k] ) {
24824 x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24825 B1=(eight_bits)((B1+B1+x) % 255);
24826 B2=(eight_bits)((B2+B2+x) % 253);
24827 B3=(eight_bits)((B3+B3+x) % 251);
24828 B4=(eight_bits)((B4+B4+x) % 247);
24832 @ Finally we're ready to actually write the \.{TFM} information.
24833 Here are some utility routines for this purpose.
24835 @d tfm_out(A) do { /* output one byte to |tfm_file| */
24836 unsigned char s=(unsigned char)(A);
24837 (mp->write_binary_file)(mp,mp->tfm_file,(void *)&s,1);
24841 static void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24842 tfm_out(x / 256); tfm_out(x % 256);
24844 static void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24845 if ( x>=0 ) tfm_out(x / three_bytes);
24847 x=x+010000000000; /* use two's complement for negative values */
24849 tfm_out((x / three_bytes) + 128);
24851 x=x % three_bytes; tfm_out(x / unity);
24852 x=x % unity; tfm_out(x / 0400);
24855 static void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24856 tfm_out(qo(x.b0)); tfm_out(qo(x.b1));
24857 tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24860 @ @<Finish the \.{TFM} file@>=
24861 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24862 mp_pack_job_name(mp, ".tfm");
24863 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24864 mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24865 mp->metric_file_name=xstrdup(mp->name_of_file);
24866 @<Output the subfile sizes and header bytes@>;
24867 @<Output the character information bytes, then
24868 output the dimensions themselves@>;
24869 @<Output the ligature/kern program@>;
24870 @<Output the extensible character recipes and the font metric parameters@>;
24871 if ( mp->internal[mp_tracing_stats]>0 )
24872 @<Log the subfile sizes of the \.{TFM} file@>;
24873 mp_print_nl(mp, "Font metrics written on ");
24874 mp_print(mp, mp->metric_file_name); mp_print_char(mp, xord('.'));
24875 @.Font metrics written...@>
24876 (mp->close_file)(mp,mp->tfm_file)
24878 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24881 @<Output the subfile sizes and header bytes@>=
24883 LH=(k+3) / 4; /* this is the number of header words */
24884 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24885 @<Compute the ligature/kern program offset and implant the
24886 left boundary label@>;
24887 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24888 +lk_offset+mp->nk+mp->ne+mp->np);
24889 /* this is the total number of file words that will be output */
24890 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec);
24891 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24892 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset);
24893 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24894 mp_tfm_two(mp, mp->np);
24895 for (k=0;k< 4*LH;k++) {
24896 tfm_out(mp->header_byte[k]);
24899 @ @<Output the character information bytes...@>=
24900 for (k=mp->bc;k<=mp->ec;k++) {
24901 if ( ! mp->char_exists[k] ) {
24902 mp_tfm_four(mp, 0);
24904 tfm_out(mp_info(mp->tfm_width[k])); /* the width index */
24905 tfm_out((mp_info(mp->tfm_height[k]))*16+mp_info(mp->tfm_depth[k]));
24906 tfm_out((mp_info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24907 tfm_out(mp->char_remainder[k]);
24911 for (k=1;k<=4;k++) {
24912 mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24913 while ( p!=inf_val ) {
24914 mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=mp_link(p);
24919 @ We need to output special instructions at the beginning of the
24920 |lig_kern| array in order to specify the right boundary character
24921 and/or to handle starting addresses that exceed 255. The |label_loc|
24922 and |label_char| arrays have been set up to record all the
24923 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24924 \le|label_loc|[|label_ptr]|$.
24926 @<Compute the ligature/kern program offset...@>=
24927 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24928 if ((mp->bchar<0)||(mp->bchar>255))
24929 { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24930 else { mp->lk_started=true; lk_offset=1; };
24931 @<Find the minimum |lk_offset| and adjust all remainders@>;
24932 if ( mp->bch_label<undefined_label )
24933 { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24934 op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24935 rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24936 incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24939 @ @<Find the minimum |lk_offset|...@>=
24940 k=mp->label_ptr; /* pointer to the largest unallocated label */
24941 if ( mp->label_loc[k]+lk_offset>255 ) {
24942 lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24944 mp->char_remainder[mp->label_char[k]]=lk_offset;
24945 while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24946 decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24948 incr(lk_offset); decr(k);
24949 } while (! (lk_offset+mp->label_loc[k]<256));
24950 /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24952 if ( lk_offset>0 ) {
24954 mp->char_remainder[mp->label_char[k]]
24955 =mp->char_remainder[mp->label_char[k]]+lk_offset;
24960 @ @<Output the ligature/kern program@>=
24961 for (k=0;k<= 255;k++ ) {
24962 if ( mp->skip_table[k]<undefined_label ) {
24963 mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24964 @.local label l:: was missing@>
24965 cancel_skips(mp->skip_table[k]);
24968 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24969 tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24971 for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24972 mp->ll=mp->label_loc[mp->label_ptr];
24973 if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0); }
24974 else { tfm_out(255); tfm_out(mp->bchar); };
24975 mp_tfm_two(mp, mp->ll+lk_offset);
24977 decr(mp->label_ptr);
24978 } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24981 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24982 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24984 @ @<Output the extensible character recipes...@>=
24985 for (k=0;k<=mp->ne-1;k++)
24986 mp_tfm_qqqq(mp, mp->exten[k]);
24987 for (k=1;k<=mp->np;k++) {
24989 if ( abs(mp->param[1])<fraction_half ) {
24990 mp_tfm_four(mp, mp->param[1]*16);
24992 incr(mp->tfm_changed);
24993 if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24994 else mp_tfm_four(mp, -el_gordo);
24997 mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
25000 if ( mp->tfm_changed>0 ) {
25001 if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
25002 @.a font metric dimension...@>
25004 mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
25005 @.font metric dimensions...@>
25006 mp_print(mp, " font metric dimensions");
25008 mp_print(mp, " had to be decreased)");
25011 @ @<Log the subfile sizes of the \.{TFM} file@>=
25015 if ( mp->bch_label<undefined_label ) decr(mp->nl);
25016 mp_snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
25017 mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
25021 @* \[43] Reading font metric data.
25023 \MP\ isn't a typesetting program but it does need to find the bounding box
25024 of a sequence of typeset characters. Thus it needs to read \.{TFM} files as
25025 well as write them.
25030 @ All the width, height, and depth information is stored in an array called
25031 |font_info|. This array is allocated sequentially and each font is stored
25032 as a series of |char_info| words followed by the width, height, and depth
25033 tables. Since |font_name| entries are permanent, their |str_ref| values are
25034 set to |max_str_ref|.
25037 typedef unsigned int font_number; /* |0..font_max| */
25039 @ The |font_info| array is indexed via a group directory arrays.
25040 For example, the |char_info| data for character~|c| in font~|f| will be
25041 in |font_info[char_base[f]+c].qqqq|.
25044 font_number font_max; /* maximum font number for included text fonts */
25045 size_t font_mem_size; /* number of words for \.{TFM} information for text fonts */
25046 memory_word *font_info; /* height, width, and depth data */
25047 char **font_enc_name; /* encoding names, if any */
25048 boolean *font_ps_name_fixed; /* are the postscript names fixed already? */
25049 size_t next_fmem; /* next unused entry in |font_info| */
25050 font_number last_fnum; /* last font number used so far */
25051 scaled *font_dsize; /* 16 times the ``design'' size in \ps\ points */
25052 char **font_name; /* name as specified in the \&{infont} command */
25053 char **font_ps_name; /* PostScript name for use when |internal[mp_prologues]>0| */
25054 font_number last_ps_fnum; /* last valid |font_ps_name| index */
25055 eight_bits *font_bc;
25056 eight_bits *font_ec; /* first and last character code */
25057 int *char_base; /* base address for |char_info| */
25058 int *width_base; /* index for zeroth character width */
25059 int *height_base; /* index for zeroth character height */
25060 int *depth_base; /* index for zeroth character depth */
25061 pointer *font_sizes;
25063 @ @<Allocate or initialize ...@>=
25064 mp->font_mem_size = 10000;
25065 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
25066 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
25067 mp->last_fnum = null_font;
25069 @ @<Dealloc variables@>=
25070 for (k=1;k<=(int)mp->last_fnum;k++) {
25071 xfree(mp->font_enc_name[k]);
25072 xfree(mp->font_name[k]);
25073 xfree(mp->font_ps_name[k]);
25075 xfree(mp->font_info);
25076 xfree(mp->font_enc_name);
25077 xfree(mp->font_ps_name_fixed);
25078 xfree(mp->font_dsize);
25079 xfree(mp->font_name);
25080 xfree(mp->font_ps_name);
25081 xfree(mp->font_bc);
25082 xfree(mp->font_ec);
25083 xfree(mp->char_base);
25084 xfree(mp->width_base);
25085 xfree(mp->height_base);
25086 xfree(mp->depth_base);
25087 xfree(mp->font_sizes);
25091 void mp_reallocate_fonts (MP mp, font_number l) {
25093 XREALLOC(mp->font_enc_name, l, char *);
25094 XREALLOC(mp->font_ps_name_fixed, l, boolean);
25095 XREALLOC(mp->font_dsize, l, scaled);
25096 XREALLOC(mp->font_name, l, char *);
25097 XREALLOC(mp->font_ps_name, l, char *);
25098 XREALLOC(mp->font_bc, l, eight_bits);
25099 XREALLOC(mp->font_ec, l, eight_bits);
25100 XREALLOC(mp->char_base, l, int);
25101 XREALLOC(mp->width_base, l, int);
25102 XREALLOC(mp->height_base, l, int);
25103 XREALLOC(mp->depth_base, l, int);
25104 XREALLOC(mp->font_sizes, l, pointer);
25105 for (f=(mp->last_fnum+1);f<=l;f++) {
25106 mp->font_enc_name[f]=NULL;
25107 mp->font_ps_name_fixed[f] = false;
25108 mp->font_name[f]=NULL;
25109 mp->font_ps_name[f]=NULL;
25110 mp->font_sizes[f]=null;
25115 @ @<Internal library declarations@>=
25116 void mp_reallocate_fonts (MP mp, font_number l);
25119 @ A |null_font| containing no characters is useful for error recovery. Its
25120 |font_name| entry starts out empty but is reset each time an erroneous font is
25121 found. This helps to cut down on the number of duplicate error messages without
25122 wasting a lot of space.
25124 @d null_font 0 /* the |font_number| for an empty font */
25126 @<Set initial...@>=
25127 mp->font_dsize[null_font]=0;
25128 mp->font_bc[null_font]=1;
25129 mp->font_ec[null_font]=0;
25130 mp->char_base[null_font]=0;
25131 mp->width_base[null_font]=0;
25132 mp->height_base[null_font]=0;
25133 mp->depth_base[null_font]=0;
25135 mp->last_fnum=null_font;
25136 mp->last_ps_fnum=null_font;
25137 mp->font_name[null_font]=(char *)"nullfont";
25138 mp->font_ps_name[null_font]=(char *)"";
25139 mp->font_ps_name_fixed[null_font] = false;
25140 mp->font_enc_name[null_font]=NULL;
25141 mp->font_sizes[null_font]=null;
25143 @ Each |char_info| word is of type |four_quarters|. The |b0| field contains
25144 the |width index|; the |b1| field contains the height
25145 index; the |b2| fields contains the depth index, and the |b3| field used only
25146 for temporary storage. (It is used to keep track of which characters occur in
25147 an edge structure that is being shipped out.)
25148 The corresponding words in the width, height, and depth tables are stored as
25149 |scaled| values in units of \ps\ points.
25151 With the macros below, the |char_info| word for character~|c| in font~|f| is
25152 |char_mp_info(f,c)| and the width is
25153 $$\hbox{|char_width(f,char_mp_info(f,c)).sc|.}$$
25155 @d char_mp_info(A,B) mp->font_info[mp->char_base[(A)]+(B)].qqqq
25156 @d char_width(A,B) mp->font_info[mp->width_base[(A)]+(B).b0].sc
25157 @d char_height(A,B) mp->font_info[mp->height_base[(A)]+(B).b1].sc
25158 @d char_depth(A,B) mp->font_info[mp->depth_base[(A)]+(B).b2].sc
25159 @d ichar_exists(A) ((A).b0>0)
25161 @ When we have a font name and we don't know whether it has been loaded yet,
25162 we scan the |font_name| array before calling |read_font_info|.
25165 static font_number mp_find_font (MP mp, char *f) ;
25168 font_number mp_find_font (MP mp, char *f) {
25170 for (n=0;n<=mp->last_fnum;n++) {
25171 if (mp_xstrcmp(f,mp->font_name[n])==0 ) {
25176 n = mp_read_font_info(mp, f);
25181 @ This is an interface function for getting the width of character,
25182 as a double in ps units
25184 @c double mp_get_char_dimension (MP mp, char *fname, int c, int t) {
25189 for (n=0;n<=mp->last_fnum;n++) {
25190 if (mp_xstrcmp(fname,mp->font_name[n])==0 ) {
25197 cc = char_mp_info(f,c);
25198 if (! ichar_exists(cc) )
25201 w = (double)char_width(f,cc);
25203 w = (double)char_height(f,cc);
25205 w = (double)char_depth(f,cc);
25206 return w/655.35*(72.27/72);
25209 @ @<Exported function ...@>=
25210 double mp_get_char_dimension (MP mp, char *fname, int n, int t);
25213 @ One simple application of |find_font| is the implementation of the |font_size|
25214 operator that gets the design size for a given font name.
25216 @<Find the design size of the font whose name is |cur_exp|@>=
25217 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
25219 @ If we discover that the font doesn't have a requested character, we omit it
25220 from the bounding box computation and expect the \ps\ interpreter to drop it.
25221 This routine issues a warning message if the user has asked for it.
25224 static void mp_lost_warning (MP mp,font_number f, pool_pointer k);
25227 void mp_lost_warning (MP mp,font_number f, pool_pointer k) {
25228 if ( mp->internal[mp_tracing_lost_chars]>0 ) {
25229 mp_begin_diagnostic(mp);
25230 if ( mp->selector==log_only ) incr(mp->selector);
25231 mp_print_nl(mp, "Missing character: There is no ");
25232 @.Missing character@>
25233 mp_print_str(mp, mp->str_pool[k]);
25234 mp_print(mp, " in font ");
25235 mp_print(mp, mp->font_name[f]); mp_print_char(mp, xord('!'));
25236 mp_end_diagnostic(mp, false);
25240 @ The whole purpose of saving the height, width, and depth information is to be
25241 able to find the bounding box of an item of text in an edge structure. The
25242 |set_text_box| procedure takes a text node and adds this information.
25245 static void mp_set_text_box (MP mp,pointer p);
25248 void mp_set_text_box (MP mp,pointer p) {
25249 font_number f; /* |mp_font_n(p)| */
25250 ASCII_code bc,ec; /* range of valid characters for font |f| */
25251 pool_pointer k,kk; /* current character and character to stop at */
25252 four_quarters cc; /* the |char_info| for the current character */
25253 scaled h,d; /* dimensions of the current character */
25255 height_val(p)=-el_gordo;
25256 depth_val(p)=-el_gordo;
25257 f=(font_number)mp_font_n(p);
25260 kk=str_stop(mp_text_p(p));
25261 k=mp->str_start[mp_text_p(p)];
25263 @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
25265 @<Set the height and depth to zero if the bounding box is empty@>;
25268 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
25270 if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
25271 mp_lost_warning(mp, f,k);
25273 cc=char_mp_info(f,mp->str_pool[k]);
25274 if ( ! ichar_exists(cc) ) {
25275 mp_lost_warning(mp, f,k);
25277 width_val(p)=width_val(p)+char_width(f,cc);
25278 h=char_height(f,cc);
25279 d=char_depth(f,cc);
25280 if ( h>height_val(p) ) height_val(p)=h;
25281 if ( d>depth_val(p) ) depth_val(p)=d;
25287 @ Let's hope modern compilers do comparisons correctly when the difference would
25290 @<Set the height and depth to zero if the bounding box is empty@>=
25291 if ( height_val(p)<-depth_val(p) ) {
25296 @ The new primitives fontmapfile and fontmapline.
25298 @<Declare action procedures for use by |do_statement|@>=
25299 static void mp_do_mapfile (MP mp) ;
25300 static void mp_do_mapline (MP mp) ;
25303 static void mp_do_mapfile (MP mp) {
25304 mp_get_x_next(mp); mp_scan_expression(mp);
25305 if ( mp->cur_type!=mp_string_type ) {
25306 @<Complain about improper map operation@>;
25308 mp_map_file(mp,mp->cur_exp);
25311 static void mp_do_mapline (MP mp) {
25312 mp_get_x_next(mp); mp_scan_expression(mp);
25313 if ( mp->cur_type!=mp_string_type ) {
25314 @<Complain about improper map operation@>;
25316 mp_map_line(mp,mp->cur_exp);
25320 @ @<Complain about improper map operation@>=
25322 exp_err("Unsuitable expression");
25323 help1("Only known strings can be map files or map lines.");
25324 mp_put_get_error(mp);
25327 @ To print |scaled| value to PDF output we need some subroutines to ensure
25330 @d max_integer 0x7FFFFFFF /* $2^{31}-1$ */
25333 scaled one_bp; /* scaled value corresponds to 1bp */
25334 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
25335 scaled one_hundred_inch; /* scaled value corresponds to 100in */
25336 integer ten_pow[10]; /* $10^0..10^9$ */
25337 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
25340 mp->one_bp = 65782; /* 65781.76 */
25341 mp->one_hundred_bp = 6578176;
25342 mp->one_hundred_inch = 473628672;
25343 mp->ten_pow[0] = 1;
25344 for (i = 1;i<= 9; i++ ) {
25345 mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
25348 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
25350 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer dd) {
25354 if ( s < 0 ) { sign = -sign; s = -s; }
25355 if ( m < 0 ) { sign = -sign; m = -m; }
25357 mp_confusion(mp, "arithmetic: divided by zero");
25358 else if ( m >= (max_integer / 10) )
25359 mp_confusion(mp, "arithmetic: number too big");
25362 for (i = 1;i<=dd;i++) {
25363 q = 10*q + (10*r) / m;
25366 if ( 2*r >= m ) { incr(q); r = r - m; }
25367 mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
25371 @* \[44] Shipping pictures out.
25372 The |ship_out| procedure, to be described below, is given a pointer to
25373 an edge structure. Its mission is to output a file containing the \ps\
25374 description of an edge structure.
25376 @ Each time an edge structure is shipped out we write a new \ps\ output
25377 file named according to the current \&{charcode}.
25378 @:char_code_}{\&{charcode} primitive@>
25380 This is the only backend function that remains in the main |mpost.w| file.
25381 There are just too many variable accesses needed for status reporting
25382 etcetera to make it worthwile to move the code to |psout.w|.
25384 @<Internal library declarations@>=
25385 void mp_open_output_file (MP mp) ;
25388 static char *mp_set_output_file_name (MP mp, integer c) {
25389 char *ss = NULL; /* filename extension proposal */
25390 char *nn = NULL; /* temp string for str() */
25391 unsigned old_setting; /* previous |selector| setting */
25392 pool_pointer i; /* indexes into |filename_template| */
25393 integer cc; /* a temporary integer for template building */
25394 integer f,g=0; /* field widths */
25395 if ( mp->job_name==NULL ) mp_open_log_file(mp);
25396 if ( mp->filename_template==0 ) {
25397 char *s; /* a file extension derived from |c| */
25401 @<Use |c| to compute the file extension |s|@>;
25402 mp_pack_job_name(mp, s);
25404 ss = xstrdup(mp->name_of_file);
25405 } else { /* initializations */
25406 str_number s, n; /* a file extension derived from |c| */
25407 old_setting=mp->selector;
25408 mp->selector=new_string;
25410 i = mp->str_start[mp->filename_template];
25411 n = null_str; /* initialize */
25412 while ( i<str_stop(mp->filename_template) ) {
25413 if ( mp->str_pool[i]=='%' ) {
25416 if ( i<str_stop(mp->filename_template) ) {
25417 if ( mp->str_pool[i]=='j' ) {
25418 mp_print(mp, mp->job_name);
25419 } else if ( mp->str_pool[i]=='d' ) {
25420 cc= mp_round_unscaled(mp, mp->internal[mp_day]);
25421 print_with_leading_zeroes(cc);
25422 } else if ( mp->str_pool[i]=='m' ) {
25423 cc= mp_round_unscaled(mp, mp->internal[mp_month]);
25424 print_with_leading_zeroes(cc);
25425 } else if ( mp->str_pool[i]=='y' ) {
25426 cc= mp_round_unscaled(mp, mp->internal[mp_year]);
25427 print_with_leading_zeroes(cc);
25428 } else if ( mp->str_pool[i]=='H' ) {
25429 cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
25430 print_with_leading_zeroes(cc);
25431 } else if ( mp->str_pool[i]=='M' ) {
25432 cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
25433 print_with_leading_zeroes(cc);
25434 } else if ( mp->str_pool[i]=='c' ) {
25435 if ( c<0 ) mp_print(mp, "ps");
25436 else print_with_leading_zeroes(c);
25437 } else if ( (mp->str_pool[i]>='0') &&
25438 (mp->str_pool[i]<='9') ) {
25440 f = (f*10) + mp->str_pool[i]-'0';
25443 mp_print_str(mp, mp->str_pool[i]);
25447 if ( mp->str_pool[i]=='.' )
25449 n = mp_make_string(mp);
25450 mp_print_str(mp, mp->str_pool[i]);
25454 s = mp_make_string(mp);
25455 mp->selector= old_setting;
25456 if (length(n)==0) {
25462 mp_pack_file_name(mp, nn,"",ss);
25470 static char * mp_get_output_file_name (MP mp) {
25472 char *saved_name; /* saved |name_of_file| */
25473 saved_name = xstrdup(mp->name_of_file);
25474 f = xstrdup(mp_set_output_file_name(mp, mp_round_unscaled(mp, mp->internal[mp_char_code])));
25475 mp_pack_file_name(mp, saved_name,NULL,NULL);
25480 void mp_open_output_file (MP mp) {
25481 char *ss; /* filename extension proposal */
25482 integer c; /* \&{charcode} rounded to the nearest integer */
25483 c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25484 ss = mp_set_output_file_name(mp, c);
25485 while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
25486 mp_prompt_file_name(mp, "file name for output",ss);
25488 @<Store the true output file name if appropriate@>;
25491 @ The file extension created here could be up to five characters long in
25492 extreme cases so it may have to be shortened on some systems.
25493 @^system dependencies@>
25495 @<Use |c| to compute the file extension |s|@>=
25498 mp_snprintf(s,7,".%i",(int)c);
25501 @ The user won't want to see all the output file names so we only save the
25502 first and last ones and a count of how many there were. For this purpose
25503 files are ordered primarily by \&{charcode} and secondarily by order of
25505 @:char_code_}{\&{charcode} primitive@>
25507 @<Store the true output file name if appropriate@>=
25508 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
25509 mp->first_output_code=c;
25510 xfree(mp->first_file_name);
25511 mp->first_file_name=xstrdup(mp->name_of_file);
25513 if ( c>=mp->last_output_code ) {
25514 mp->last_output_code=c;
25515 xfree(mp->last_file_name);
25516 mp->last_file_name=xstrdup(mp->name_of_file);
25520 char * first_file_name;
25521 char * last_file_name; /* full file names */
25522 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
25523 @:char_code_}{\&{charcode} primitive@>
25524 integer total_shipped; /* total number of |ship_out| operations completed */
25527 mp->first_file_name=xstrdup("");
25528 mp->last_file_name=xstrdup("");
25529 mp->first_output_code=32768;
25530 mp->last_output_code=-32768;
25531 mp->total_shipped=0;
25533 @ @<Dealloc variables@>=
25534 xfree(mp->first_file_name);
25535 xfree(mp->last_file_name);
25537 @ @<Begin the progress report for the output of picture~|c|@>=
25538 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
25539 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, xord(' '));
25540 mp_print_char(mp, xord('['));
25541 if ( c>=0 ) mp_print_int(mp, c)
25543 @ @<End progress report@>=
25544 mp_print_char(mp, xord(']'));
25546 incr(mp->total_shipped)
25548 @ @<Explain what output files were written@>=
25549 if ( mp->total_shipped>0 ) {
25550 mp_print_nl(mp, "");
25551 mp_print_int(mp, mp->total_shipped);
25552 if (mp->noninteractive) {
25553 mp_print(mp, " figure");
25554 if ( mp->total_shipped>1 ) mp_print_char(mp, xord('s'));
25555 mp_print(mp, " created.");
25557 mp_print(mp, " output file");
25558 if ( mp->total_shipped>1 ) mp_print_char(mp, xord('s'));
25559 mp_print(mp, " written: ");
25560 mp_print(mp, mp->first_file_name);
25561 if ( mp->total_shipped>1 ) {
25562 if ( 31+strlen(mp->first_file_name)+
25563 strlen(mp->last_file_name)> (unsigned)mp->max_print_line)
25565 mp_print(mp, " .. ");
25566 mp_print(mp, mp->last_file_name);
25571 @ @<Internal library declarations@>=
25572 boolean mp_has_font_size(MP mp, font_number f );
25575 boolean mp_has_font_size(MP mp, font_number f ) {
25576 return (mp->font_sizes[f]!=null);
25579 @ The \&{special} command saves up lines of text to be printed during the next
25580 |ship_out| operation. The saved items are stored as a list of capsule tokens.
25583 pointer last_pending; /* the last token in a list of pending specials */
25586 mp->last_pending=spec_head;
25588 @ @<Cases of |do_statement|...@>=
25589 case special_command:
25590 if ( mp->cur_mod==0 ) mp_do_special(mp); else
25591 if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else
25595 @ @<Declare action procedures for use by |do_statement|@>=
25596 static void mp_do_special (MP mp) ;
25598 @ @c void mp_do_special (MP mp) {
25599 mp_get_x_next(mp); mp_scan_expression(mp);
25600 if ( mp->cur_type!=mp_string_type ) {
25601 @<Complain about improper special operation@>;
25603 mp_link(mp->last_pending)=mp_stash_cur_exp(mp);
25604 mp->last_pending=mp_link(mp->last_pending);
25605 mp_link(mp->last_pending)=null;
25609 @ @<Complain about improper special operation@>=
25611 exp_err("Unsuitable expression");
25612 help1("Only known strings are allowed for output as specials.");
25613 mp_put_get_error(mp);
25616 @ On the export side, we need an extra object type for special strings.
25618 @<Graphical object codes@>=
25621 @ @<Export pending specials@>=
25622 p=mp_link(spec_head);
25623 while ( p!=null ) {
25624 mp_special_object *tp;
25625 tp = (mp_special_object *)mp_new_graphic_object(mp,mp_special_code);
25626 gr_pre_script(tp) = str(value(p));
25627 if (hh->body==NULL) hh->body = (mp_graphic_object *)tp;
25628 else gr_link(hp) = (mp_graphic_object *)tp;
25629 hp = (mp_graphic_object *)tp;
25632 mp_flush_token_list(mp, mp_link(spec_head));
25633 mp_link(spec_head)=null;
25634 mp->last_pending=spec_head
25636 @ We are now ready for the main output procedure. Note that the |selector|
25637 setting is saved in a global variable so that |begin_diagnostic| can access it.
25639 @<Declare the \ps\ output procedures@>=
25640 static void mp_ship_out (MP mp, pointer h) ;
25642 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25644 @d export_color(q,p)
25645 if ( mp_color_model(p)==mp_uninitialized_model ) {
25646 gr_color_model(q) = (unsigned char)(mp->internal[mp_default_color_model]/65536);
25647 gr_cyan_val(q) = 0;
25648 gr_magenta_val(q) = 0;
25649 gr_yellow_val(q) = 0;
25650 gr_black_val(q) = (gr_color_model(q)==mp_cmyk_model ? unity : 0);
25652 gr_color_model(q) = (unsigned char)mp_color_model(p);
25653 gr_cyan_val(q) = cyan_val(p);
25654 gr_magenta_val(q) = magenta_val(p);
25655 gr_yellow_val(q) = yellow_val(p);
25656 gr_black_val(q) = black_val(p);
25659 @d export_scripts(q,p)
25660 if (mp_pre_script(p)!=null) gr_pre_script(q) = str(mp_pre_script(p));
25661 if (mp_post_script(p)!=null) gr_post_script(q) = str(mp_post_script(p));
25664 struct mp_edge_object *mp_gr_export(MP mp, pointer h) {
25665 pointer p; /* the current graphical object */
25666 integer t; /* a temporary value */
25667 integer c; /* a rounded charcode */
25668 scaled d_width; /* the current pen width */
25669 mp_edge_object *hh; /* the first graphical object */
25670 mp_graphic_object *hq; /* something |hp| points to */
25671 mp_text_object *tt;
25672 mp_fill_object *tf;
25673 mp_stroked_object *ts;
25674 mp_clip_object *tc;
25675 mp_bounds_object *tb;
25676 mp_graphic_object *hp = NULL; /* the current graphical object */
25677 mp_set_bbox(mp, h, true);
25678 hh = xmalloc(1,sizeof(mp_edge_object));
25682 hh->minx = minx_val(h);
25683 hh->miny = miny_val(h);
25684 hh->maxx = maxx_val(h);
25685 hh->maxy = maxy_val(h);
25686 hh->filename = mp_get_output_file_name(mp);
25687 c = mp_round_unscaled(mp,mp->internal[mp_char_code]);
25689 hh->width = mp->internal[mp_char_wd];
25690 hh->height = mp->internal[mp_char_ht];
25691 hh->depth = mp->internal[mp_char_dp];
25692 hh->ital_corr = mp->internal[mp_char_ic];
25693 @<Export pending specials@>;
25694 p=mp_link(dummy_loc(h));
25695 while ( p!=null ) {
25696 hq = mp_new_graphic_object(mp,mp_type(p));
25697 switch (mp_type(p)) {
25699 tf = (mp_fill_object *)hq;
25700 gr_pen_p(tf) = mp_export_knot_list(mp,mp_pen_p(p));
25701 d_width = mp_get_pen_scale(mp, mp_pen_p(p));
25702 if ((mp_pen_p(p)==null) || pen_is_elliptical(mp_pen_p(p))) {
25703 gr_path_p(tf) = mp_export_knot_list(mp,mp_path_p(p));
25706 pc = mp_copy_path(mp, mp_path_p(p));
25707 pp = mp_make_envelope(mp, pc, mp_pen_p(p),ljoin_val(p),0,miterlim_val(p));
25708 gr_path_p(tf) = mp_export_knot_list(mp,pp);
25709 mp_toss_knot_list(mp, pp);
25710 pc = mp_htap_ypoc(mp, mp_path_p(p));
25711 pp = mp_make_envelope(mp, pc, mp_pen_p(p),ljoin_val(p),0,miterlim_val(p));
25712 gr_htap_p(tf) = mp_export_knot_list(mp,pp);
25713 mp_toss_knot_list(mp, pp);
25715 export_color(tf,p) ;
25716 export_scripts(tf,p);
25717 gr_ljoin_val(tf) = (unsigned char)ljoin_val(p);
25718 gr_miterlim_val(tf) = miterlim_val(p);
25720 case mp_stroked_code:
25721 ts = (mp_stroked_object *)hq;
25722 gr_pen_p(ts) = mp_export_knot_list(mp,mp_pen_p(p));
25723 d_width = mp_get_pen_scale(mp, mp_pen_p(p));
25724 if (pen_is_elliptical(mp_pen_p(p))) {
25725 gr_path_p(ts) = mp_export_knot_list(mp,mp_path_p(p));
25728 pc=mp_copy_path(mp, mp_path_p(p));
25730 if ( mp_left_type(pc)!=mp_endpoint ) {
25731 mp_left_type(mp_insert_knot(mp, pc,mp_x_coord(pc),mp_y_coord(pc)))=mp_endpoint;
25732 mp_right_type(pc)=mp_endpoint;
25736 pc=mp_make_envelope(mp,pc,mp_pen_p(p),ljoin_val(p),t,miterlim_val(p));
25737 gr_path_p(ts) = mp_export_knot_list(mp,pc);
25738 mp_toss_knot_list(mp, pc);
25740 export_color(ts,p) ;
25741 export_scripts(ts,p);
25742 gr_ljoin_val(ts) = (unsigned char)ljoin_val(p);
25743 gr_miterlim_val(ts) = miterlim_val(p);
25744 gr_lcap_val(ts) = (unsigned char)lcap_val(p);
25745 gr_dash_p(ts) = mp_export_dashes(mp,p,&d_width);
25748 tt = (mp_text_object *)hq;
25749 gr_text_p(tt) = str(mp_text_p(p));
25750 gr_font_n(tt) = (unsigned int)mp_font_n(p);
25751 gr_font_name(tt) = mp_xstrdup(mp,mp->font_name[mp_font_n(p)]);
25752 gr_font_dsize(tt) = (unsigned int)mp->font_dsize[mp_font_n(p)];
25753 export_color(tt,p) ;
25754 export_scripts(tt,p);
25755 gr_width_val(tt) = width_val(p);
25756 gr_height_val(tt) = height_val(p);
25757 gr_depth_val(tt) = depth_val(p);
25758 gr_tx_val(tt) = tx_val(p);
25759 gr_ty_val(tt) = ty_val(p);
25760 gr_txx_val(tt) = txx_val(p);
25761 gr_txy_val(tt) = txy_val(p);
25762 gr_tyx_val(tt) = tyx_val(p);
25763 gr_tyy_val(tt) = tyy_val(p);
25765 case mp_start_clip_code:
25766 tc = (mp_clip_object *)hq;
25767 gr_path_p(tc) = mp_export_knot_list(mp,mp_path_p(p));
25769 case mp_start_bounds_code:
25770 tb = (mp_bounds_object *)hq;
25771 gr_path_p(tb) = mp_export_knot_list(mp,mp_path_p(p));
25773 case mp_stop_clip_code:
25774 case mp_stop_bounds_code:
25775 /* nothing to do here */
25778 if (hh->body==NULL) hh->body=hq; else gr_link(hp) = hq;
25785 @ @<Declarations@>=
25786 static struct mp_edge_object *mp_gr_export(MP mp, int h);
25788 @ This function is now nearly trivial.
25791 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25792 integer c; /* \&{charcode} rounded to the nearest integer */
25793 c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25794 @<Begin the progress report for the output of picture~|c|@>;
25795 (mp->shipout_backend) (mp, h);
25796 @<End progress report@>;
25797 if ( mp->internal[mp_tracing_output]>0 )
25798 mp_print_edges(mp, h," (just shipped out)",true);
25801 @ @<Declarations@>=
25802 static void mp_shipout_backend (MP mp, pointer h);
25805 void mp_shipout_backend (MP mp, pointer h) {
25806 mp_edge_object *hh; /* the first graphical object */
25807 hh = mp_gr_export(mp,h);
25808 (void)mp_gr_ship_out (hh,
25809 (mp->internal[mp_prologues]/65536),
25810 (mp->internal[mp_procset]/65536),
25812 mp_gr_toss_objects(hh);
25815 @ @<Exported types@>=
25816 typedef void (*mp_backend_writer)(MP, int);
25818 @ @<Option variables@>=
25819 mp_backend_writer shipout_backend;
25821 @ Now that we've finished |ship_out|, let's look at the other commands
25822 by which a user can send things to the \.{GF} file.
25824 @ @<Determine if a character has been shipped out@>=
25826 mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25827 if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25828 boolean_reset(mp->char_exists[mp->cur_exp]);
25829 mp->cur_type=mp_boolean_type;
25835 @ @<Allocate or initialize ...@>=
25836 mp_backend_initialize(mp);
25839 mp_backend_free(mp);
25842 @* \[45] Dumping and undumping the tables.
25843 After \.{INIMP} has seen a collection of macros, it
25844 can write all the necessary information on an auxiliary file so
25845 that production versions of \MP\ are able to initialize their
25846 memory at high speed. The present section of the program takes
25847 care of such output and input. We shall consider simultaneously
25848 the processes of storing and restoring,
25849 so that the inverse relation between them is clear.
25852 The global variable |mem_ident| is a string that is printed right
25853 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25854 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25855 for example, `\.{(mem=plain 1990.4.14)}', showing the year,
25856 month, and day that the mem file was created. We have |mem_ident=0|
25857 before \MP's tables are loaded.
25861 void * mem_file; /* for input or output of mem information */
25864 mp->mem_ident=NULL;
25866 @ @<Initialize table entries...@>=
25867 mp->mem_ident=xstrdup(" (INIMP)");
25869 @ @<Declarations@>=
25870 extern void mp_store_mem_file (MP mp) ;
25871 extern boolean mp_load_mem_file (MP mp);
25872 extern boolean mp_undump_constants (MP mp);
25874 @ @<Dealloc variables@>=
25875 xfree(mp->mem_ident);
25878 @* \[46] The main program.
25879 This is it: the part of \MP\ that executes all those procedures we have
25882 Well---almost. We haven't put the parsing subroutines into the
25883 program yet; and we'd better leave space for a few more routines that may
25884 have been forgotten.
25886 @c @<Declare the basic parsing subroutines@>
25887 @<Declare miscellaneous procedures that were declared |forward|@>
25889 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
25891 has to be run first; it initializes everything from scratch, without
25892 reading a mem file, and it has the capability of dumping a mem file.
25893 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
25895 to input a mem file in order to get started. \.{VIRMP} typically has
25896 a bit more memory capacity than \.{INIMP}, because it does not need the
25897 space consumed by the dumping/undumping routines and the numerous calls on
25900 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
25901 the best implementations therefore allow for production versions of \MP\ that
25902 not only avoid the loading routine for object code, they also have
25903 a mem file pre-loaded.
25905 @ @<Option variables@>=
25906 int ini_version; /* are we iniMP? */
25908 @ @<Set |ini_version|@>=
25909 mp->ini_version = (opt->ini_version ? true : false);
25911 @ The code below make the final chosen hash size the next larger
25912 multiple of 2 from the requested size, and this array is a list of
25913 suitable prime numbers to go with such values.
25915 The top limit is chosen such that it is definately lower than
25916 |max_halfword-3*param_size|, because |param_size| cannot be larger
25917 than |max_halfword/sizeof(pointer)|.
25920 static int mp_prime_choices[] =
25921 { 12289, 24593, 49157, 98317,
25922 196613, 393241, 786433, 1572869,
25923 3145739, 6291469, 12582917, 25165843,
25924 50331653, 100663319 };
25926 @ @<Find constant sizes@>=
25927 if (mp->ini_version) {
25929 set_value(mp->mem_top,opt->main_memory,5000);
25930 mp->mem_max = mp->mem_top;
25931 set_value(mp->param_size,opt->param_size,150);
25932 set_value(mp->max_in_open,opt->max_in_open,10);
25933 if (opt->hash_size>0x8000000)
25934 opt->hash_size=0x8000000;
25935 set_value(mp->hash_size,(2*opt->hash_size-1),16384);
25936 mp->hash_size = mp->hash_size>>i;
25937 while (mp->hash_size>=2) {
25938 mp->hash_size /= 2;
25941 mp->hash_size = mp->hash_size << i;
25942 if (mp->hash_size>0x8000000)
25943 mp->hash_size=0x8000000;
25944 mp->hash_prime=mp_prime_choices[(i-14)];
25946 if (mp->mem_name == NULL) {
25947 mp->mem_name = mp_xstrdup(mp,"plain");
25949 if (mp_open_mem_file(mp)) {
25950 if (!mp_undump_constants(mp))
25952 set_value(mp->mem_max,opt->main_memory,mp->mem_top);
25956 wterm_ln("(Fatal mem file error; I'm stymied)\n");
25957 mp->history = mp_fatal_error_stop;
25963 @ Here we do whatever is needed to complete \MP's job gracefully on the
25964 local operating system. The code here might come into play after a fatal
25965 error; it must therefore consist entirely of ``safe'' operations that
25966 cannot produce error messages. For example, it would be a mistake to call
25967 |str_room| or |make_string| at this time, because a call on |overflow|
25968 might lead to an infinite loop.
25969 @^system dependencies@>
25971 This program doesn't bother to close the input files that may still be open.
25974 void mp_close_files_and_terminate (MP mp) {
25975 integer k; /* all-purpose index */
25976 integer LH; /* the length of the \.{TFM} header, in words */
25977 int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
25978 pointer p; /* runs through a list of \.{TFM} dimensions */
25979 @<Close all open files in the |rd_file| and |wr_file| arrays@>;
25980 if ( mp->internal[mp_tracing_stats]>0 )
25981 @<Output statistics about this job@>;
25983 @<Do all the finishing work on the \.{TFM} file@>;
25984 @<Explain what output files were written@>;
25985 if ( mp->log_opened && ! mp->noninteractive ){
25987 (mp->close_file)(mp,mp->log_file);
25988 mp->selector=mp->selector-2;
25989 if ( mp->selector==term_only ) {
25990 mp_print_nl(mp, "Transcript written on ");
25991 @.Transcript written...@>
25992 mp_print(mp, mp->log_name); mp_print_char(mp, xord('.'));
25996 mp->finished = true;
25999 @ @<Declarations@>=
26000 static void mp_close_files_and_terminate (MP mp) ;
26002 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
26003 if (mp->rd_fname!=NULL) {
26004 for (k=0;k<=(int)mp->read_files-1;k++ ) {
26005 if ( mp->rd_fname[k]!=NULL ) {
26006 (mp->close_file)(mp,mp->rd_file[k]);
26007 xfree(mp->rd_fname[k]);
26011 if (mp->wr_fname!=NULL) {
26012 for (k=0;k<=(int)mp->write_files-1;k++) {
26013 if ( mp->wr_fname[k]!=NULL ) {
26014 (mp->close_file)(mp,mp->wr_file[k]);
26015 xfree(mp->wr_fname[k]);
26021 for (k=0;k<(int)mp->max_read_files;k++ ) {
26022 if ( mp->rd_fname[k]!=NULL ) {
26023 (mp->close_file)(mp,mp->rd_file[k]);
26024 xfree(mp->rd_fname[k]);
26027 xfree(mp->rd_file);
26028 xfree(mp->rd_fname);
26029 for (k=0;k<(int)mp->max_write_files;k++) {
26030 if ( mp->wr_fname[k]!=NULL ) {
26031 (mp->close_file)(mp,mp->wr_file[k]);
26032 xfree(mp->wr_fname[k]);
26035 xfree(mp->wr_file);
26036 xfree(mp->wr_fname);
26039 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
26041 We reclaim all of the variable-size memory at this point, so that
26042 there is no chance of another memory overflow after the memory capacity
26043 has already been exceeded.
26045 @<Do all the finishing work on the \.{TFM} file@>=
26046 if ( mp->internal[mp_fontmaking]>0 ) {
26047 @<Make the dynamic memory into one big available node@>;
26048 @<Massage the \.{TFM} widths@>;
26049 mp_fix_design_size(mp); mp_fix_check_sum(mp);
26050 @<Massage the \.{TFM} heights, depths, and italic corrections@>;
26051 mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
26052 @<Finish the \.{TFM} file@>;
26055 @ @<Make the dynamic memory into one big available node@>=
26056 mp->rover=lo_mem_stat_max+1; mp_link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
26057 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
26058 node_size(mp->rover)=mp->lo_mem_max-mp->rover;
26059 lmp_link(mp->rover)=mp->rover; rmp_link(mp->rover)=mp->rover;
26060 mp_link(mp->lo_mem_max)=null; mp_info(mp->lo_mem_max)=null
26062 @ The present section goes directly to the log file instead of using
26063 |print| commands, because there's no need for these strings to take
26064 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
26066 @<Output statistics...@>=
26067 if ( mp->log_opened ) {
26070 wlog_ln("Here is how much of MetaPost's memory you used:");
26071 @.Here is how much...@>
26072 mp_snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
26073 (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
26074 (int)(mp->max_strings-1-mp->init_str_use));
26076 mp_snprintf(s,128," %i string characters out of %i",
26077 (int)mp->max_pl_used-mp->init_pool_ptr,
26078 (int)mp->pool_size-mp->init_pool_ptr);
26080 mp_snprintf(s,128," %i words of memory out of %i",
26081 (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
26084 mp_snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
26086 mp_snprintf(s,128," %ii,%in,%ip,%ib stack positions out of %ii,%in,%ip,%ib",
26087 (int)mp->max_in_stack,(int)mp->int_ptr,
26088 (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
26089 (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
26091 mp_snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
26092 (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
26096 @ It is nice to have have some of the stats available from the API.
26098 @<Exported function ...@>=
26099 int mp_memory_usage (MP mp );
26100 int mp_hash_usage (MP mp );
26101 int mp_param_usage (MP mp );
26102 int mp_open_usage (MP mp );
26105 int mp_memory_usage (MP mp ) {
26106 return (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2;
26108 int mp_hash_usage (MP mp ) {
26109 return (int)mp->st_count;
26111 int mp_param_usage (MP mp ) {
26112 return (int)mp->max_param_stack;
26114 int mp_open_usage (MP mp ) {
26115 return (int)mp->max_in_stack;
26118 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
26122 void mp_final_cleanup (MP mp) {
26123 quarterword c; /* 0 for \&{end}, 1 for \&{dump} */
26125 if ( mp->job_name==NULL ) mp_open_log_file(mp);
26126 while ( mp->input_ptr>0 ) {
26127 if ( token_state ) mp_end_token_list(mp);
26128 else mp_end_file_reading(mp);
26130 while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
26131 while ( mp->open_parens>0 ) {
26132 mp_print(mp, " )"); decr(mp->open_parens);
26134 while ( mp->cond_ptr!=null ) {
26135 mp_print_nl(mp, "(end occurred when ");
26136 @.end occurred...@>
26137 mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
26138 /* `\.{if}' or `\.{elseif}' or `\.{else}' */
26139 if ( mp->if_line!=0 ) {
26140 mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
26142 mp_print(mp, " was incomplete)");
26143 mp->if_line=if_line_field(mp->cond_ptr);
26144 mp->cur_if=mp_name_type(mp->cond_ptr); mp->cond_ptr=mp_link(mp->cond_ptr);
26146 if ( mp->history!=mp_spotless )
26147 if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
26148 if ( mp->selector==term_and_log ) {
26149 mp->selector=term_only;
26150 mp_print_nl(mp, "(see the transcript file for additional information)");
26151 @.see the transcript file...@>
26152 mp->selector=term_and_log;
26155 if (mp->ini_version) {
26156 mp_store_mem_file(mp); return;
26158 mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
26159 @.dump...only by INIMP@>
26163 @ @<Declarations@>=
26164 static void mp_final_cleanup (MP mp) ;
26165 static void mp_init_prim (MP mp) ;
26166 static void mp_init_tab (MP mp) ;
26169 void mp_init_prim (MP mp) { /* initialize all the primitives */
26173 void mp_init_tab (MP mp) { /* initialize other tables */
26174 integer k; /* all-purpose index */
26175 @<Initialize table entries (done by \.{INIMP} only)@>;
26179 @ When we begin the following code, \MP's tables may still contain garbage;
26180 thus we must proceed cautiously to get bootstrapped in.
26182 But when we finish this part of the program, \MP\ is ready to call on the
26183 |main_control| routine to do its work.
26185 @<Get the first line...@>=
26187 @<Initialize the input routines@>;
26188 if (mp->mem_ident==NULL) {
26189 if ( ! mp_load_mem_file(mp) ) {
26190 (mp->close_file)(mp, mp->mem_file);
26191 mp->history = mp_fatal_error_stop;
26194 (mp->close_file)(mp, mp->mem_file);
26196 @<Initializations following first line@>;
26199 @ @<Initializations following first line@>=
26200 mp->buffer[limit]=(ASCII_code)'%';
26201 mp_fix_date_and_time(mp);
26202 if (mp->random_seed==0)
26203 mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
26204 mp_init_randoms(mp, mp->random_seed);
26205 @<Initialize the print |selector|...@>;
26206 if ( loc<limit ) if ( mp->buffer[loc]!='\\' )
26207 mp_start_input(mp); /* \&{input} assumed */
26209 @ @<Run inimpost commands@>=
26211 mp_get_strings_started(mp);
26212 mp_init_tab(mp); /* initialize the tables */
26213 mp_init_prim(mp); /* call |primitive| for each primitive */
26214 mp->init_str_use=mp->max_str_ptr=mp->str_ptr;
26215 mp->init_pool_ptr=mp->max_pool_ptr=mp->pool_ptr;
26216 mp_fix_date_and_time(mp);
26219 @ Saving the filename template
26221 @<Save the filename template@>=
26223 if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26224 if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26226 mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26230 @* \[47] Debugging.
26233 @* \[48] System-dependent changes.
26234 This section should be replaced, if necessary, by any special
26235 modification of the program
26236 that are necessary to make \MP\ work at a particular installation.
26237 It is usually best to design your change file so that all changes to
26238 previous sections preserve the section numbering; then everybody's version
26239 will be consistent with the published program. More extensive changes,
26240 which introduce new sections, can be inserted here; then only the index
26241 itself will get a new section number.
26242 @^system dependencies@>
26245 Here is where you can find all uses of each identifier in the program,
26246 with underlined entries pointing to where the identifier was defined.
26247 If the identifier is only one letter long, however, you get to see only
26248 the underlined entries. {\sl All references are to section numbers instead of
26251 This index also lists error messages and other aspects of the program
26252 that you might want to look up some day. For example, the entry
26253 for ``system dependencies'' lists all sections that should receive
26254 special attention from people who are installing \MP\ in a new
26255 operating environment. A list of various things that can't happen appears
26256 under ``this can't happen''.
26257 Approximately 25 sections are listed under ``inner loop''; these account
26258 for more than 60\pct! of \MP's running time, exclusive of input and output.