Debian Codegraph @

texk/web2c/mplibdir/mp.w

raw
1 % This file is part of MetaPost;
2 % the MetaPost program is in the public domain.
3 % See the <Show version...> code in mpost.w for more info.
4
5 % Here is TeX material that gets inserted after \input webmac
6 \def\hang{\hangindent 3em\noindent\ignorespaces}
7 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
8 \def\ps{PostScript}
9 \def\psqrt#1{\sqrt{\mathstrut#1}}
10 \def\k{_{k+1}}
11 \def\pct!{{\char`\%}} % percent sign in ordinary text
12 \font\tenlogo=logo10 % font used for the METAFONT logo
13 \font\logos=logosl10
14 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
15 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
16 \def\<#1>{$\langle#1\rangle$}
17 \def\section{\mathhexbox278}
18 \let\swap=\leftrightarrow
19 \def\round{\mathop{\rm round}\nolimits}
20 \mathchardef\vbv="026A % synonym for `\|'
21 \def\vb{\relax\ifmmode\vbv\else$\vbv$\fi}
22
23 \def\(#1){} % this is used to make section names sort themselves better
24 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
25 \def\title{\MP}
26 \pdfoutput=1 \sanitizecommand\MP{MetaPost}
27 \pageno=3
28
29 @* Introduction.
30
31 This is \MP\ by John Hobby, a graphics-language processor based on D. E. Knuth's \MF.
32
33 Much of the original Pascal version of this program was copied with
34 permission from MF.web Version 1.9. It interprets a language very
35 similar to D.E. Knuth's \MF, but with changes designed to make it
36 more suitable for PostScript output.
37
38 The main purpose of the following program is to explain the algorithms of \MP\
39 as clearly as possible. However, the program has been written so that it
40 can be tuned to run efficiently in a wide variety of operating environments
41 by making comparatively few changes. Such flexibility is possible because
42 the documentation that follows is written in the \.{WEB} language, which is
43 at a higher level than C.
44
45 A large piece of software like \MP\ has inherent complexity that cannot
46 be reduced below a certain level of difficulty, although each individual
47 part is fairly simple by itself. The \.{WEB} language is intended to make
48 the algorithms as readable as possible, by reflecting the way the
49 individual program pieces fit together and by providing the
50 cross-references that connect different parts. Detailed comments about
51 what is going on, and about why things were done in certain ways, have
52 been liberally sprinkled throughout the program. These comments explain
53 features of the implementation, but they rarely attempt to explain the
54 \MP\ language itself, since the reader is supposed to be familiar with
55 {\sl The {\logos METAFONT\/}book} as well as the manual
56 @.WEB@>
57 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
58 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
59 AT\AM T Bell Laboratories.
60
61 @ The present implementation is a preliminary version, but the possibilities
62 for new features are limited by the desire to remain as nearly compatible
63 with \MF\ as possible.
64
65 On the other hand, the \.{WEB} description can be extended without changing
66 the core of the program, and it has been designed so that such
67 extensions are not extremely difficult to make.
68 The |banner| string defined here should be changed whenever \MP\
69 undergoes any modifications, so that it will be clear which version of
70 \MP\ might be the guilty party when a problem arises.
71 @^extensions to \MP@>
72 @^system dependencies@>
73
74 @d default_banner "This is MetaPost, Version "metapost_version /* printed when \MP\ starts */
75
76
77 @<\MP\ version header@>=
78 #define metapost_version "3.00"
79
80 @ The external library header for \MP\ is |mplib.h|. It contains a
81 few typedefs and the header defintions for the externally used
82 functions.
83
84 The most important of the typedefs is the definition of the structure
85 |MP_options|, that acts as a small, configurable front-end to the fairly
86 large |MP_instance| structure.
87
88 @(mplib.h@>=
89 #ifndef MPLIB_H
90 #define MPLIB_H 1
91 #include <stdlib.h>
92 #ifndef HAVE_BOOLEAN
93 typedef int boolean;
94 #endif
95
96 @<\MP\ version header@>@;
97 typedef struct MP_instance *MP;
98 @<Exported types@>@;
99 typedef struct MP_options {
100 @<Option variables@>@;
101 } MP_options;
102 @<Exported function headers@>@;
103 @<MPlib header stuff@>@;
104 #endif
105
106 @ The internal header file is much longer: it not only lists the complete
107 |MP_instance|, but also a lot of functions that have to be available to
108 the \ps\ backend, that is defined in a separate \.{WEB} file.
109
110 The variables from |MP_options| are included inside the |MP_instance|
111 wholesale.
112
113 @(mpmp.h@>=
114 #ifndef MPMP_H
115 #define MPMP_H 1
116 #include "avl.h"
117 #include "mplib.h"
118 #include <setjmp.h>
119 typedef struct psout_data_struct *psout_data;
120 typedef struct svgout_data_struct *svgout_data;
121 typedef struct pngout_data_struct *pngout_data;
122 #ifndef HAVE_BOOLEAN
123 typedef int boolean;
124 #endif
125
126 #ifndef INTEGER_TYPE
127 typedef int integer;
128 #define MPOST_ABS abs
129 #else
130 #define MPOST_ABS llabs
131 #endif /* |ifndef INTEGER_TYPE| */
132 /* integer64 should be alredy defined in source/texk/web2c/w2c/config.h */
133 /* but just in case */
134 #ifndef integer64
135 # if defined(WIN32)
136 typedef __int64 integer64;
137 # else
138 typedef int64_t integer64;
139 # endif
140 #endif
141 typedef int16_t QUARTERWORD; /* Same as quarterword.*/
142
143
144 @<Declare helpers@>@;
145 @<Enumeration types@>@;
146 @<Types in the outer block@>@;
147 @<Constants in the outer block@>@;
148 typedef struct MP_instance {
149 @<Option variables@>@;
150 @<Global variables@>@;
151 } MP_instance;
152 @<Internal library declarations@>@;
153 @<MPlib internal header stuff@>@;
154 #endif
155
156 @ @c
157 /*\#define MPOST_DEBUG_ENVELOPE */
158 #ifdef MPOST_DEBUG_ENVELOPE
159 static int MPOST_DEBUG_ENVELOPECOUNTER=0;
160 #define dbg_str(A) @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] %s", MPOST_DEBUG_ENVELOPECOUNTER++, #A)@]
161 #define dbg_n(A) @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] ['%s']=%s, ", MPOST_DEBUG_ENVELOPECOUNTER++, #A, number_tostring(A))@]
162 #define dbg_in(A) @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] ['%s']=%d, ", MPOST_DEBUG_ENVELOPECOUNTER++, #A, (int)(A))@]
163 #define dbg_dn(A) @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] ['%s']=%.100f, ",MPOST_DEBUG_ENVELOPECOUNTER++, #A, (double)(A))@]
164 #define dbg_key(A) @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] ['%s']= ", MPOST_DEBUG_ENVELOPECOUNTER++, #A)@]
165 #define dbg_key_nval(K,V) @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] ['%s']=%s", MPOST_DEBUG_ENVELOPECOUNTER++, #K,number_tostring(V))@]
166 #define dbg_key_ival(K,V) @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] ['%s']=%d", MPOST_DEBUG_ENVELOPECOUNTER++, #K,(int)(V))@]
167 #define dbg_key_dval(K,V) @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] ['%s']=%.100f", MPOST_DEBUG_ENVELOPECOUNTER++, #K,(double)(V))@]
168 #define dbg_comment(A) @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] --[==[%s]==]", MPOST_DEBUG_ENVELOPECOUNTER++, #A)@]
169 #define dbg_sp @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] ", MPOST_DEBUG_ENVELOPECOUNTER++)@]
170 #define dbg_open_t @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] {", MPOST_DEBUG_ENVELOPECOUNTER++)@]
171 #define dbg_close_t @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] }", MPOST_DEBUG_ENVELOPECOUNTER++)@]
172 #define dbg_comma @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] ,", MPOST_DEBUG_ENVELOPECOUNTER++)@]
173 #define dbg_nl @[printf("\n--[==[%03d MPOST_DEBUG_ENVELOPE ]==] \n", MPOST_DEBUG_ENVELOPECOUNTER++)@]
174 #define dbg_CUBIC dbg_n(p->x_coord); dbg_n(p->y_coord); \
175 dbg_n(p->right_x); dbg_n(p->right_y); \
176 dbg_n(q->left_x); dbg_n(q->left_y); \
177 dbg_n(q->x_coord); dbg_n(q->y_coord)@;
178 #endif
179 #define KPATHSEA_DEBUG_H 1
180 #include "mpconfig.h"
181 #include <w2c/config.h>
182 #include <stdio.h>
183 #include <stdlib.h>
184 #include <string.h>
185 #include <stdarg.h>
186 #include <assert.h>
187 #include <math.h>
188 #ifdef HAVE_UNISTD_H
189 # include <unistd.h> /* for access */
190 #endif
191 #include <time.h> /* for |struct tm| $\AND$ co */
192 #include <zlib.h> /* for |ZLIB_VERSION|, |zlibVersion()| */
193 #include <png.h> /* for |PNG_LIBPNG_VER_STRING|, |png_libpng_ver| */
194 /*|
195 #include <pixman.h>| */ /* for |PIXMAN_VERSION_STRING|, |pixman_version_string()| */
196 /*|
197 #include <cairo.h>| */ /* for |CAIRO_VERSION_STRING|, |cairo_version_string()| */
198 /*|
199 #include <gmp.h>| */ /* for |gmp_version| */
200 /*|
201 #include <mpfr.h>| */ /* for |MPFR_VERSION_STRING|, |mpfr_get_version()| */
202 #include "mplib.h"
203 #include "mplibps.h" /* external header */
204 /*|
205 #include "mplibsvg.h"| */ /* external header */
206 /*|
207 #include "mplibpng.h"| */ /* external header */
208 #include "mpmp.h" /* internal header */
209 #include "mppsout.h" /* internal header */
210 /*|
211 #include "mpsvgout.h"| */ /* internal header */
212 /*|
213 #include "mppngout.h"| */ /* internal header */
214 #include "mpmath.h" /* internal header */
215 #include "mpmathdouble.h" /* internal header */
216 #include "mpmathdecimal.h" /* internal header */
217 /*|
218 #include "mpmathbinary.h"| */ /* internal header */
219 /*|
220 #include "mpmathinterval.h"| */ /* internal header */
221 #include "mpstrings.h" /* internal header */
222 /* BEGIN PATCH */
223 mp_number dx_ap; /* approximation of dx */
224 mp_number dy_ap; /* approximation of dy */
225 mp_number dxin_ap; /* approximation of dxin */
226 mp_number dyin_ap; /* approximation of dyin */
227 mp_number ueps_ap; /* epsilon for above approximations */
228 boolean is_dxdy, is_dxindyin;
229 /* END PATCH */
230
231 @ We move the {\tt cairo} and {\tt pixman} libraries outside {\tt mp.w},
232 to minimize dependencies.
233
234 @c
235 extern const char *COMPILED_CAIRO_VERSION_STRING;
236 extern const char* cairo_version_string (void);
237 extern const char *COMPILED_MPFR_VERSION_STRING;
238 extern const char* mpfr_get_version (void);
239 extern const char *COMPILED_MPFI_VERSION_STRING;
240 extern const char* mpfi_get_version (void);
241 extern void * mp_initialize_binary_math (MP mp) ;
242 extern void * mp_initialize_interval_math(MP mp);
243 extern int COMPILED__GNU_MP_VERSION;
244 extern int COMPILED__GNU_MP_VERSION_MINOR;
245 extern int COMPILED__GNU_MP_VERSION_PATCHLEVEL;
246 extern const char * const COMPILED_gmp_version;
247 extern const char *COMPILED_PIXMAN_VERSION_STRING;
248 extern const char* pixman_version_string (void);
249 extern void mp_png_backend_initialize (MP mp);
250 extern void mp_png_backend_free (MP mp);
251 extern int mp_png_gr_ship_out (void *hh, const char *options, int standalone);
252 extern int mp_png_ship_out (void *hh, const char *options);
253 extern void mp_svg_backend_initialize (MP mp);
254 extern void mp_svg_backend_free (MP mp);
255 extern int mp_svg_ship_out (mp_edge_object *hh, int prologues);
256 extern int mp_svg_gr_ship_out (mp_edge_object *hh, int prologues, int standalone);
257
258 @ @s font_number int @c
259 extern font_number mp_read_font_info (MP mp, char *fname); /* \.{tfmin.w} */
260 @h
261 @<Declarations@>@;
262 @<Basic printing procedures@>@;
263 @<Error handling procedures@>@;
264
265 @ Some debugging support for development. The trick with the variadic macros
266 probably only works in gcc, as this preprocessor feature was not formalized
267 until the c99 standard (and that is too new for us). Lets' hope that at least
268 most compilers understand the non-debug version.
269 @^system dependencies@>
270
271 @<MPlib internal header stuff@>=
272 #if MPOST_DEBUG
273 /* This function occasionally crashes (if something is written after the */
274 /* log file is already closed), but that is not so important while debugging. */
275
276 extern void do_debug_printf(MP mp, const char *prefix, const char *fmt, ...);
277
278 #endif
279
280 #if MPOST_DEBUG
281 #define debug_number(A) @[printf("%d: %s=%.32f (%d)\n", __LINE__, #A, number_to_double(A), number_to_scaled(A))@]
282 #else
283 #define debug_number(A) @[@]
284 #endif
285 #if MPOST_DEBUG>1
286 /*void do_debug_printf(MP mp, const char *prefix, const char *fmt, ...);*/
287 # define debug_printf(a1,a2,a3) @[do_debug_printf(mp, "", a1,a2,a3)@]
288 # define FUNCTION_TRACE1(a1) @[do_debug_printf(mp, "FTRACE: ", a1)@]
289 # define FUNCTION_TRACE2(a1,a2) @[do_debug_printf(mp, "FTRACE: ", a1,a2)@]
290 # define FUNCTION_TRACE3(a1,a2,a3) @[do_debug_printf(mp, "FTRACE: ", a1,a2,a3)@]
291 # define FUNCTION_TRACE3X(a1,a2,a3) @[(void)mp@]
292 # define FUNCTION_TRACE4(a1,a2,a3,a4) @[do_debug_printf(mp, "FTRACE: ", a1,a2,a3,a4)@]
293 #else
294 # define debug_printf(a1,a2,a3) @[@]
295 # define FUNCTION_TRACE1(a1) @[(void)mp@]
296 # define FUNCTION_TRACE2(a1,a2) @[(void)mp@]
297 # define FUNCTION_TRACE3(a1,a2,a3) @[(void)mp@]
298 # define FUNCTION_TRACE3X(a1,a2,a3) @[(void)mp@]
299 # define FUNCTION_TRACE4(a1,a2,a3,a4) @[(void)mp@]
300 #endif
301
302 @ This function occasionally crashes (if something is written after the */
303 log file is already closed), but that is not so important while debugging. */
304
305 @c
306 #if MPOST_DEBUG
307 void do_debug_printf(MP mp, const char *prefix, const char *fmt, ...) {
308 va_list ap;
309 va_start (ap, fmt);
310 #if 0
311 if (mp->log_file && !ferror((FILE *)mp->log_file)) {
312 fputs(prefix, mp->log_file);
313 vfprintf(mp->log_file, fmt, ap);
314 }
315 va_end(ap);
316 va_start (ap, fmt);
317 if (mp->term_out && !ferror((FILE *)mp->term_out)) {
318 #else
319 if (false) {
320 #endif
321 fputs(prefix, mp->term_out);
322 vfprintf(mp->term_out, fmt, ap);
323 } else {
324 fputs(prefix, stdout);
325 vfprintf(stdout, fmt, ap);
326 }
327 va_end(ap);
328 #if 0
329 }
330 #endif
331 }
332 #endif /* |if MPOST_DEBUG| */
333
334 @ Here are the functions that set up the \MP\ instance.
335
336 @<Declarations@>=
337 MP_options *mp_options (void);
338 MP mp_initialize (MP_options * opt);
339
340 @ @c
341 MP_options *mp_options (void) {
342 MP_options *opt;
343 size_t l = sizeof (MP_options);
344 opt = malloc (l);
345 if (opt != NULL) {
346 memset (opt, 0, l);
347 }
348 return opt;
349 }
350
351
352 @ Here are the three primitives of the interval arithmetic adapted to the others number systems:
353 |left_point| and |right_point| of a number |a| simply return |a|, while
354 |interval_set| of the pair |(a,b)| returns the mid point.
355
356 @s mp_number integer64
357
358 @<Declarations@>=
359 static void mp_stub_m_get_left_endpoint(MP mp, mp_number * r, mp_number a);
360 static void mp_stub_m_get_right_endpoint(MP mp, mp_number * r, mp_number a);
361 static void mp_stub_m_interval_set(MP mp, mp_number * r, mp_number a, mp_number b);
362
363
364 @ @c
365 static void mp_stub_m_get_left_endpoint(MP mp, mp_number * r, mp_number a){
366 number_clone(*r,a);
367 }
368 static void mp_stub_m_get_right_endpoint(MP mp, mp_number * r, mp_number a){
369 number_clone(*r,a);
370 }
371 static void mp_stub_m_interval_set(MP mp, mp_number * r, mp_number a, mp_number b){
372 mp_number x;
373 new_number(x);
374 number_add(x,a);number_add(x,b);number_half(x);
375 number_clone(*r,x);
376 free_number(x);
377 }
378
379
380
381
382
383 @ @<Internal library declarations@>=
384 @<Declare subroutines for parsing file names@>
385
386
387 @ The whole instance structure is initialized with zeroes,
388 this greatly reduces the number of statements needed in
389 the |@<Allocate or ...@>| block.
390
391 @d set_callback_option(A) do { mp->A = mp_##A;
392 if (opt->A!=NULL) mp->A = opt->A;
393 } while (0)@;
394
395 @c
396 static MP mp_do_new (jmp_buf * buf) {
397 MP mp = malloc (sizeof (MP_instance));
398 if (mp == NULL) {
399 xfree (buf);
400 return NULL;
401 }
402 memset (mp, 0, sizeof (MP_instance));
403 mp->jump_buf = buf;
404 return mp;
405 }
406
407
408 @ @c
409 static void mp_free (MP mp) {
410 int k; /* loop variable */
411 @<Dealloc variables@>;
412 if (mp->noninteractive)
413 @<Finish non-interactive use@>@;
414 xfree (mp->jump_buf);
415 @<Free table entries@>;
416 free_math();
417 xfree (mp);
418 }
419
420
421 @ @c
422 static void mp_do_initialize (MP mp) {
423 @<Local variables for initialization@>;
424 @<Set initial values of key variables@>;
425 }
426
427 @ For the retargetable math library, we need to have a pointer, at least.
428
429 @<Global variables@>=
430 void *math;
431
432 @ @<Exported types@>=
433 typedef enum {
434 mp_nan_type = 0,
435 mp_scaled_type,
436 mp_fraction_type,
437 mp_angle_type,
438 mp_double_type,
439 mp_binary_type,
440 mp_decimal_type,
441 mp_interval_type
442 } mp_number_type;
443 typedef union {
444 void *num;
445 double dval;
446 integer64 val;
447 } mp_number_store;
448 typedef struct mp_number_data {
449 mp_number_store data;
450 mp_number_type type;
451 } mp_number_data;
452 typedef struct mp_number_data mp_number;
453 #define is_number(A) ((A).type != mp_nan_type)
454
455 typedef void @[@] (*convert_func) (mp_number *r);
456 typedef void @[@] (*m_log_func) (MP mp, mp_number *r, mp_number a);
457 typedef void @[@] (*m_exp_func) (MP mp, mp_number *r, mp_number a);
458 typedef void @[@] (*m_unif_rand_func) (MP mp, mp_number *ret, mp_number x_orig);
459 typedef void @[@] (*m_norm_rand_func) (MP mp, mp_number *ret);
460 typedef void @[@] (*pyth_add_func) (MP mp, mp_number *r, mp_number a, mp_number b);
461 typedef void @[@] (*pyth_sub_func) (MP mp, mp_number *r, mp_number a, mp_number b);
462 typedef void @[@] (*n_arg_func) (MP mp, mp_number *r, mp_number a, mp_number b);
463 typedef void @[@] (*velocity_func) (MP mp, mp_number *r, mp_number a, mp_number b, mp_number c, mp_number d, mp_number e);
464 typedef void @[@] (*ab_vs_cd_func) (MP mp, mp_number *r, mp_number a, mp_number b, mp_number c, mp_number d);
465 typedef void @[@] (*crossing_point_func) (MP mp, mp_number *r, mp_number a, mp_number b, mp_number c);
466 typedef void @[@] (*number_from_int_func) (mp_number *A, integer64 B);
467 typedef void @[@] (*number_from_boolean_func) (mp_number *A, integer64 B);
468 typedef void @[@] (*number_from_scaled_func) (mp_number *A, integer64 B);
469 typedef void @[@] (*number_from_double_func) (mp_number *A, double B);
470 typedef void @[@] (*number_from_addition_func) (mp_number *A, mp_number B, mp_number C);
471 typedef void @[@] (*number_from_substraction_func) (mp_number *A, mp_number B, mp_number C);
472 typedef void @[@] (*number_from_div_func) (mp_number *A, mp_number B, mp_number C);
473 typedef void @[@] (*number_from_mul_func) (mp_number *A, mp_number B, mp_number C);
474 typedef void @[@] (*number_from_int_div_func) (mp_number *A, mp_number B, integer64 C);
475 typedef void @[@] (*number_from_int_mul_func) (mp_number *A, mp_number B, integer64 C);
476 typedef void @[@] (*number_from_oftheway_func) (MP mp, mp_number *A, mp_number t, mp_number B, mp_number C);
477 typedef void @[@] (*number_negate_func) (mp_number *A);
478 typedef void @[@] (*number_add_func) (mp_number *A, mp_number B);
479 typedef void @[@] (*number_substract_func) (mp_number *A, mp_number B);
480 typedef void @[@] (*number_modulo_func) (mp_number *A, mp_number B);
481 typedef void @[@] (*number_half_func) (mp_number *A);
482 typedef void @[@] (*number_halfp_func) (mp_number *A);
483 typedef void @[@] (*number_double_func) (mp_number *A);
484 typedef void @[@] (*number_abs_func) (mp_number *A);
485 typedef void @[@] (*number_clone_func) (mp_number *A, mp_number B);
486 typedef void @[@] (*number_swap_func) (mp_number *A, mp_number *B);
487 typedef void @[@] (*number_add_scaled_func) (mp_number *A, integer64 b);
488 typedef void @[@] (*number_multiply_int_func) (mp_number *A, integer64 b);
489 typedef void @[@] (*number_divide_int_func) (mp_number *A, integer64 b);
490 typedef integer64 @[@] (*number_to_int_func) (mp_number A);
491 typedef integer64 @[@] (*number_to_boolean_func) (mp_number A);
492 typedef integer64 @[@] (*number_to_scaled_func) (mp_number A);
493 typedef integer64 @[@] (*number_round_func) (mp_number A);
494 typedef void @[@] (*number_floor_func) (mp_number *A);
495 typedef double @[@] (*number_to_double_func) (mp_number A);
496 typedef int @[@] (*number_odd_func) (mp_number A);
497 typedef int @[@] (*number_equal_func) (mp_number A, mp_number B);
498 typedef int @[@] (*number_less_func) (mp_number A, mp_number B);
499 typedef int @[@] (*number_greater_func) (mp_number A, mp_number B);
500 typedef int @[@] (*number_nonequalabs_func) (mp_number A, mp_number B);
501 typedef void @[@] (*make_scaled_func) (MP mp, mp_number *ret, mp_number A, mp_number B);
502 typedef void @[@] (*make_fraction_func) (MP mp, mp_number *ret, mp_number A, mp_number B);
503 typedef void @[@] (*take_fraction_func) (MP mp, mp_number *ret, mp_number A, mp_number B);
504 typedef void @[@] (*take_scaled_func) (MP mp, mp_number *ret, mp_number A, mp_number B);
505 typedef void @[@] (*sin_cos_func) (MP mp, mp_number A, mp_number *S, mp_number *C);
506 typedef void @[@] (*slow_add_func) (MP mp, mp_number *A, mp_number S, mp_number C);
507 typedef void @[@] (*sqrt_func) (MP mp, mp_number *ret, mp_number A);
508 typedef void @[@] (*init_randoms_func) (MP mp, int seed);
509 typedef void @[@] (*new_number_func) (MP mp, mp_number *A, mp_number_type t);
510 typedef void @[@] (*free_number_func) (MP mp, mp_number *n);
511 typedef void @[@] (*fraction_to_round_scaled_func) (mp_number *n);
512 typedef void @[@] (*print_func) (MP mp, mp_number A);
513 typedef char * (*tostring_func) (MP mp, mp_number A);
514 typedef void @[@] (*scan_func) (MP mp, integer64 A);
515 typedef void @[@] (*mp_free_func) (MP mp);
516 typedef void @[@] (*set_precision_func) (MP mp);
517 /* math interval new primitives */
518 typedef void @[@] (*m_get_left_endpoint_func) (MP mp, mp_number *r, mp_number a);
519 typedef void @[@] (*m_get_right_endpoint_func) (MP mp, mp_number *r, mp_number a);
520 typedef void @[@] (*m_interval_set_func) (MP mp, mp_number *r, mp_number a, mp_number b);
521
522 typedef struct math_data {
523 mp_number precision_default;
524 mp_number precision_max;
525 mp_number precision_min;
526 mp_number epsilon_t;
527 mp_number inf_t;
528 mp_number one_third_inf_t;
529 mp_number zero_t;
530 mp_number unity_t;
531 mp_number two_t;
532 mp_number three_t;
533 mp_number half_unit_t;
534 mp_number three_quarter_unit_t;
535 mp_number fraction_one_t;
536 mp_number fraction_half_t;
537 mp_number fraction_three_t;
538 mp_number fraction_four_t;
539 mp_number one_eighty_deg_t;
540 mp_number three_sixty_deg_t;
541 mp_number one_k;
542 mp_number sqrt_8_e_k;
543 mp_number twelve_ln_2_k;
544 mp_number coef_bound_k;
545 mp_number coef_bound_minus_1;
546 mp_number twelvebits_3;
547 mp_number arc_tol_k;
548 mp_number twentysixbits_sqrt2_t;
549 mp_number twentyeightbits_d_t;
550 mp_number twentysevenbits_sqrt2_d_t;
551 mp_number fraction_threshold_t;
552 mp_number half_fraction_threshold_t;
553 mp_number scaled_threshold_t;
554 mp_number half_scaled_threshold_t;
555 mp_number near_zero_angle_t;
556 mp_number p_over_v_threshold_t;
557 mp_number equation_threshold_t;
558 mp_number tfm_warn_threshold_t;
559 mp_number warning_limit_t;
560 new_number_func allocate;
561 free_number_func free;
562 number_from_int_func from_int;
563 number_from_boolean_func from_boolean;
564 number_from_scaled_func from_scaled;
565 number_from_double_func from_double;
566 number_from_addition_func from_addition;
567 number_from_substraction_func from_substraction;
568 number_from_div_func from_div;
569 number_from_mul_func from_mul;
570 number_from_int_div_func from_int_div;
571 number_from_int_mul_func from_int_mul;
572 number_from_oftheway_func from_oftheway;
573 number_negate_func negate;
574 number_add_func add;
575 number_substract_func substract;
576 number_half_func half;
577 number_modulo_func modulo;
578 number_halfp_func halfp;
579 number_double_func do_double;
580 number_abs_func abs;
581 number_clone_func clone;
582 number_swap_func swap;
583 number_add_scaled_func add_scaled;
584 number_multiply_int_func multiply_int;
585 number_divide_int_func divide_int;
586 number_to_int_func to_int;
587 number_to_boolean_func to_boolean;
588 number_to_scaled_func to_scaled;
589 number_to_double_func to_double;
590 number_odd_func odd;
591 number_equal_func equal;
592 number_less_func less;
593 number_greater_func greater;
594 number_nonequalabs_func nonequalabs;
595 number_round_func round_unscaled;
596 number_floor_func floor_scaled;
597 make_scaled_func make_scaled;
598 make_fraction_func make_fraction;
599 take_fraction_func take_fraction;
600 take_scaled_func take_scaled;
601 velocity_func velocity;
602 ab_vs_cd_func ab_vs_cd;
603 crossing_point_func crossing_point;
604 n_arg_func n_arg;
605 m_log_func m_log;
606 m_exp_func m_exp;
607 m_unif_rand_func m_unif_rand;
608 m_norm_rand_func m_norm_rand;
609 pyth_add_func pyth_add;
610 pyth_sub_func pyth_sub;
611 fraction_to_round_scaled_func fraction_to_round_scaled;
612 convert_func fraction_to_scaled;
613 convert_func scaled_to_fraction;
614 convert_func scaled_to_angle;
615 convert_func angle_to_scaled;
616 init_randoms_func init_randoms;
617 sin_cos_func sin_cos;
618 sqrt_func sqrt;
619 slow_add_func slow_add;
620 print_func print;
621 tostring_func tostring;
622 scan_func scan_numeric;
623 scan_func scan_fractional;
624 mp_free_func free_math;
625 set_precision_func set_precision;
626 /* math interval new primitives */
627 m_get_left_endpoint_func m_get_left_endpoint;
628 m_get_right_endpoint_func m_get_right_endpoint;
629 m_interval_set_func m_interval_set;
630 } math_data;
631
632
633
634 @ This procedure gets things started properly.
635 @c
636 MP mp_initialize (MP_options * opt) {
637 MP mp;
638 jmp_buf *buf = malloc (sizeof (jmp_buf));
639 if (buf == NULL || setjmp (*buf) != 0)
640 return NULL;
641 mp = mp_do_new (buf);
642 if (mp == NULL)
643 return NULL;
644 mp->userdata = opt->userdata;
645 mp->noninteractive = opt->noninteractive;
646 mp->extensions = opt->extensions;
647 set_callback_option (find_file);
648 set_callback_option (open_file);
649 set_callback_option (read_ascii_file);
650 set_callback_option (read_binary_file);
651 set_callback_option (close_file);
652 set_callback_option (eof_file);
653 set_callback_option (flush_file);
654 set_callback_option (write_ascii_file);
655 set_callback_option (write_binary_file);
656 set_callback_option (shipout_backend);
657 set_callback_option (run_script);
658 set_callback_option (make_text);
659 if (opt->banner && *(opt->banner)) {
660 mp->banner = xstrdup (opt->banner);
661 } else {
662 mp->banner = xstrdup (default_banner);
663 }
664 if (opt->command_line && *(opt->command_line))
665 mp->command_line = xstrdup (opt->command_line);
666 if (mp->noninteractive)
667 @<Prepare function pointers for non-interactive use@>@;
668 t_open_out(); /* open the terminal for output */
669 #if MPOST_DEBUG
670 setvbuf(stdout, (char *) NULL, _IONBF, 0);
671 setvbuf(mp->term_out, (char *) NULL, _IONBF, 0);
672 #endif
673 if (opt->math_mode == mp_math_scaled_mode) {
674 mp->math = mp_initialize_scaled_math(mp);
675 } else if (opt->math_mode == mp_math_decimal_mode) {
676 mp->math = mp_initialize_decimal_math(mp);
677 } else if (opt->math_mode == mp_math_binary_mode) {
678 mp->math = mp_initialize_binary_math(mp);
679 } else if (opt->math_mode == mp_math_interval_mode) {
680 mp->math = mp_initialize_interval_math(mp);
681 } else {
682 mp->math = mp_initialize_double_math(mp);
683 }
684 if (opt->math_mode != mp_math_interval_mode) {
685 ((math_data *)mp->math)->m_get_left_endpoint = mp_stub_m_get_left_endpoint;
686 ((math_data *)mp->math)->m_get_right_endpoint = mp_stub_m_get_right_endpoint;
687 ((math_data *)mp->math)->m_interval_set = mp_stub_m_interval_set ;
688 }
689 @<Find and load preload file, if required@>;
690 @<Allocate or initialize variables@>;
691 mp_reallocate_paths (mp, 1000);
692 mp_reallocate_fonts (mp, 8);
693 mp->history = mp_fatal_error_stop; /* in case we quit during initialization */
694 @<Check the ``constant'' values...@>; /* consider also the raise of the bits for precision */
695 if (mp->bad > 0) {
696 char ss[256];
697 mp_snprintf (ss, 256, "Ouch---my internal constants have been clobbered!\n"
698 "---case %i", (int) mp->bad);
699 mp_fputs ((char *) ss, mp->err_out);
700 @.Ouch...clobbered@>
701 return mp;
702 }
703 mp_do_initialize (mp); /* erase preloaded mem */
704 mp_init_tab (mp); /* initialize the tables */
705 if (opt->math_mode == mp_math_scaled_mode) {
706 set_internal_string (mp_number_system, mp_intern (mp, "scaled"));
707 } else if (opt->math_mode == mp_math_decimal_mode) {
708 set_internal_string (mp_number_system, mp_intern (mp, "decimal"));
709 } else if (opt->math_mode == mp_math_binary_mode) {
710 set_internal_string (mp_number_system, mp_intern (mp, "binary"));
711 } else if (opt->math_mode == mp_math_interval_mode) {
712 set_internal_string (mp_number_system, mp_intern (mp, "interval"));
713 } else {
714 set_internal_string (mp_number_system, mp_intern (mp, "double"));
715 }
716 mp_init_prim (mp); /* call |primitive| for each primitive */
717 mp_fix_date_and_time (mp);
718 if (!mp->noninteractive) {
719 @<Initialize the output routines@>;
720 @<Get the first line of input and prepare to start@>;
721 @<Initializations after first line is read@>;
722 @<Fix up |mp->internal[mp_job_name]|@>;
723 } else {
724 mp->history = mp_spotless;
725 }
726 set_precision();
727 return mp;
728 }
729
730
731 @ @<Initializations after first line is read@>=
732 mp_open_log_file (mp);
733 mp_set_job_id (mp);
734 mp_init_map_file (mp, mp->troff_mode);
735 mp->history = mp_spotless; /* ready to go! */
736 if (mp->troff_mode) {
737 number_clone (internal_value (mp_gtroffmode), unity_t);
738 number_clone (internal_value (mp_prologues), unity_t);
739 }
740 if (mp->start_sym != NULL) { /* insert the `\&{everyjob}' symbol */
741 set_cur_sym (mp->start_sym);
742 mp_back_input (mp);
743 }
744
745 @ @<Exported function headers@>=
746 extern MP_options *mp_options (void);
747 extern MP mp_initialize (MP_options * opt);
748 extern int mp_status (MP mp);
749 extern boolean mp_finished (MP mp);
750 extern void *mp_userdata (MP mp);
751
752 @ @c
753 int mp_status (MP mp) {
754 return mp->history;
755 }
756
757
758 @ @c
759 boolean mp_finished (MP mp) {
760 return mp->finished;
761 }
762
763
764
765 @ @c
766 void *mp_userdata (MP mp) {
767 return mp->userdata;
768 }
769
770
771 @ The overall \MP\ program begins with the heading just shown, after which
772 comes a bunch of procedure declarations and function declarations.
773 Finally we will get to the main program, which begins with the
774 comment `|start_here|'. If you want to skip down to the
775 main program now, you can look up `|start_here|' in the index.
776 But the author suggests that the best way to understand this program
777 is to follow pretty much the order of \MP's components as they appear in the
778 \.{WEB} description you are now reading, since the present ordering is
779 intended to combine the advantages of the ``bottom up'' and ``top down''
780 approaches to the problem of understanding a somewhat complicated system.
781
782 @ Some of the code below is intended to be used only when diagnosing the
783 strange behavior that sometimes occurs when \MP\ is being installed or
784 when system wizards are fooling around with \MP\ without quite knowing
785 what they are doing. Such code will not normally be compiled; it is
786 delimited by the preprocessor test|
787 #ifdef MPOST_DEBUG| $\ldots$|
788 #endif|.
789
790 @ The following parameters can be changed at compile time to extend or
791 reduce \MP's capacity.
792 @^system dependencies@>
793
794 @<Constants...@>=
795 #define bistack_size 1500 /* size of stack for bisection algorithms;
796 should probably be left at this value */
797
798 @ Like the preceding parameters, the following quantities can be changed
799 to extend or reduce \MP's capacity.
800
801 @<Glob...@>=
802 int pool_size; /* maximum number of characters in strings, including all
803 error messages and help texts, and the names of all identifiers */
804 int max_in_open; /* maximum number of input files and error insertions that
805 can be going on simultaneously */
806 int param_size; /* maximum number of simultaneous macro parameters */
807
808 @ @<Option variables@>=
809 int error_line; /* width of context lines on terminal error messages */
810 int half_error_line; /* width of first lines of contexts in terminal
811 error messages; should be between 30 and |error_line-15| */
812 int halt_on_error; /* do we quit at the first error? */
813 int max_print_line; /* width of longest text lines output; should be at least 60 */
814 void *userdata; /* this allows the calling application to setup local */
815 char *banner; /* the banner that is printed to the screen and log */
816 int ini_version;
817 int utf8_mode;
818
819 @ @<Dealloc variables@>=
820 xfree (mp->banner);
821
822 @ @d set_lower_limited_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)@;
823
824 @<Allocate or ...@>=
825 mp->param_size = 4;
826 mp->max_in_open = 0;
827 mp->pool_size = 10000;
828 set_lower_limited_value (mp->error_line, opt->error_line, 79);
829 set_lower_limited_value (mp->half_error_line, opt->half_error_line, 50);
830 if (mp->half_error_line > mp->error_line - 15)
831 mp->half_error_line = mp->error_line - 15;
832 mp->max_print_line = 100;
833 set_lower_limited_value (mp->max_print_line, opt->max_print_line, 79);
834 mp->halt_on_error = (opt->halt_on_error ? true : false);
835 mp->ini_version = (opt->ini_version ? true : false);
836 mp->utf8_mode = (opt->utf8_mode ? true : false);
837
838 @ In case somebody has inadvertently made bad settings of the ``constants,''
839 \MP\ checks them using a global variable called |bad|.
840
841 This is the second of many sections of \MP\ where global variables are
842 defined.
843
844 @<Glob...@>=
845 integer bad; /* is some ``constant'' wrong? */
846
847 @ Later on we will say `|if ( int_packets+(17+2)*int_increment>bistack_size )mp->bad=19;|',
848 or something similar.
849
850 In case you are wondering about the non-consecutive values of |bad|: most
851 of the things that used to be WEB constants are now runtime variables
852 with checking at assignment time.
853
854 @<Check the ``constant'' values for consistency@>=
855 mp->bad = 0;
856
857 @ Here are some macros for common programming idioms.
858
859 @d incr(A) (A)=(A)+1 /* increase a variable by unity */
860 @d decr(A) (A)=(A)-1 /* decrease a variable by unity */
861 @d negate(A) (A)=-(A) /* change the sign of a variable */
862 @d odd(A) (MPOST_ABS(A)%2==1)
863
864 @* The character set.
865 In order to make \MP\ readily portable to a wide variety of
866 computers, all of its input text is converted to an internal eight-bit
867 code that includes standard ASCII, the ``American Standard Code for
868 Information Interchange.'' This conversion is done immediately when each
869 character is read in. Conversely, characters are converted from ASCII to
870 the user's external representation just before they are output to a
871 text file.
872 @^ASCII code@>
873
874 Such an internal code is relevant to users of \MP\ only with respect to
875 the \&{char} and \&{ASCII} operations, and the comparison of strings.
876
877 @ Characters of text that have been converted to \MP's internal form
878 are said to be of type |ASCII_code|, which is a subrange of the integers.
879
880 @<Types...@>=
881 typedef unsigned char ASCII_code; /* eight-bit numbers */
882
883 @ The present specification of \MP\ has been written under the assumption
884 that the character set contains at least the letters and symbols associated
885 with ASCII codes 040 through 0176; all of these characters are now
886 available on most computer terminals.
887
888 @<Types...@>=
889 typedef unsigned char text_char; /* the data type of characters in text files */
890
891 @ @<Local variables for init...@>=
892 integer i;
893
894 @ The \MP\ processor converts between ASCII code and
895 the user's external character set by means of arrays |xord| and |xchr|
896 that are analogous to Pascal's |ord| and |chr| functions.
897
898 @<MPlib internal header stuff@>=
899 #define xchr(A) @[mp->xchr[(A)]@]
900 #define xord(A) @[mp->xord[(A)]@]
901
902 @ @<Glob...@>=
903 ASCII_code xord[256]; /* specifies conversion of input characters */
904 text_char xchr[256]; /* specifies conversion of output characters */
905
906 @ The core system assumes all 8-bit is acceptable. If it is not,
907 a change file has to alter the below section.
908 @^system dependencies@>
909
910 Additionally, people with extended character sets can
911 assign codes arbitrarily, giving an |xchr| equivalent to whatever
912 characters the users of \MP\ are allowed to have in their input files.
913 Appropriate changes to \MP's |char_class| table should then be made.
914 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
915 codes, called the |char_class|.) Such changes make portability of programs
916 more difficult, so they should be introduced cautiously if at all.
917 @^character set dependencies@>
918 @^system dependencies@>
919
920 @<Set initial ...@>=
921 for (i = 0; i <= 0377; i++) {
922 xchr (i) = (text_char) i;
923 }
924
925
926 @ The following system-independent code makes the |xord| array contain a
927 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
928 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
929 |j| or more; hence, standard ASCII code numbers will be used instead of
930 codes below 040 in case there is a coincidence.
931
932 @<Set initial ...@>=
933 for (i = 0; i <= 255; i++) {
934 xord (xchr (i)) = 0177;
935 }
936 for (i = 0200; i <= 0377; i++) {
937 xord (xchr (i)) = (ASCII_code) i;
938 }
939 for (i = 0; i <= 0176; i++) {
940 xord (xchr (i)) = (ASCII_code) i;
941 }
942
943
944 @* Input and output.
945 The bane of portability is the fact that different operating systems treat
946 input and output quite differently, perhaps because computer scientists
947 have not given sufficient attention to this problem. People have felt somehow
948 that input and output are not part of ``real'' programming. Well, it is true
949 that some kinds of programming are more fun than others. With existing
950 input/output conventions being so diverse and so messy, the only sources of
951 joy in such parts of the code are the rare occasions when one can find a
952 way to make the program a little less bad than it might have been. We have
953 two choices, either to attack I/O now and get it over with, or to postpone
954 I/O until near the end. Neither prospect is very attractive, so let's
955 get it over with.
956
957 The basic operations we need to do are (1)~inputting and outputting of
958 text, to or from a file or the user's terminal; (2)~inputting and
959 outputting of eight-bit bytes, to or from a file; (3)~instructing the
960 operating system to initiate (``open'') or to terminate (``close'') input or
961 output from a specified file; (4)~testing whether the end of an input
962 file has been reached; (5)~display of bits on the user's screen.
963 The bit-display operation will be discussed in a later section; we shall
964 deal here only with more traditional kinds of I/O.
965
966 @ Finding files happens in a slightly roundabout fashion: the \MP\
967 instance object contains a field that holds a function pointer that finds a
968 file, and returns its name, or NULL. For this, it receives three
969 parameters: the non-qualified name |fname|, the intended |fopen|
970 operation type |fmode|, and the type of the file |ftype|.
971
972 The file types that are passed on in |ftype| can be used to
973 differentiate file searches if a library like kpathsea is used,
974 the fopen mode is passed along for the same reason.
975
976 @<Types...@>=
977 typedef uint8_t eight_bits; /* unsigned one-byte quantity */
978
979 @ @<Exported types@>=
980 enum mp_filetype {
981 mp_filetype_terminal = 0, /* the terminal */
982 mp_filetype_error, /* the terminal */
983 mp_filetype_program, /* \MP\ language input */
984 mp_filetype_log, /* the log file */
985 mp_filetype_postscript, /* the postscript output */
986 mp_filetype_bitmap, /* the bitmap output file */
987 mp_filetype_memfile, /* memory dumps, obsolete */
988 mp_filetype_metrics, /* \TeX\ font metric files */
989 mp_filetype_fontmap, /* PostScript font mapping files */
990 mp_filetype_font, /* PostScript type1 font programs */
991 mp_filetype_encoding, /* PostScript font encoding files */
992 mp_filetype_text /* first text file for readfrom and writeto primitives */
993 };
994 typedef char *(*mp_file_finder) (MP, const char *, const char *, int);
995 typedef char *(*mp_script_runner) (MP, const char *, size_t);
996 typedef char *(*mp_text_maker) (MP, const char *, size_t, int);
997 typedef void *(*mp_file_opener) (MP, const char *, const char *, int);
998 typedef char *(*mp_file_reader) (MP, void *, size_t *);
999 typedef void @[@] (*mp_binfile_reader) (MP, void *, void **, size_t *);
1000 typedef void @[@] (*mp_file_closer) (MP, void *);
1001 typedef int @[@] (*mp_file_eoftest) (MP, void *);
1002 typedef void @[@] (*mp_file_flush) (MP, void *);
1003 typedef void @[@] (*mp_file_writer) (MP, void *, const char *);
1004 typedef void @[@] (*mp_binfile_writer) (MP, void *, void *, size_t);
1005
1006 @ @<Option variables@>=
1007 mp_file_finder find_file;
1008 mp_file_opener open_file;
1009 mp_script_runner run_script;
1010 mp_text_maker make_text;
1011 mp_file_reader read_ascii_file;
1012 mp_binfile_reader read_binary_file;
1013 mp_file_closer close_file;
1014 mp_file_eoftest eof_file;
1015 mp_file_flush flush_file;
1016 mp_file_writer write_ascii_file;
1017 mp_binfile_writer write_binary_file;
1018
1019 @ The default function for finding files is |mp_find_file|. It is
1020 pretty stupid: it will only find files in the current directory.
1021
1022 @c
1023 static char *mp_find_file (MP mp, const char *fname, const char *fmode,
1024 int ftype) {
1025 (void) mp;
1026 if (fmode[0] != 'r' || (!access (fname, R_OK)) || ftype) {
1027 return mp_strdup (fname);
1028 }
1029 return NULL;
1030 }
1031
1032 @ @c
1033 static char *mp_run_script (MP mp, const char *str, size_t len) {
1034 (void) mp;
1035 return mp_strldup (str, len);
1036 }
1037
1038 @ @c
1039 static char *mp_make_text (MP mp, const char *str, size_t len, int mode) {
1040 (void)mp;
1041 (void)mode;
1042 return mp_strldup (str, len);
1043 }
1044
1045 @ Because |mp_find_file| is used so early, it has to be in the helpers
1046 section.
1047
1048 @<Declarations@>=
1049 static char *mp_find_file (MP mp, const char *fname, const char *fmode, int ftype);
1050 static void *mp_open_file (MP mp, const char *fname, const char *fmode, int ftype);
1051 static char *mp_read_ascii_file (MP mp, void *f, size_t * size);
1052 static void mp_read_binary_file (MP mp, void *f, void **d, size_t * size);
1053 static void mp_close_file (MP mp, void *f);
1054 static int mp_eof_file (MP mp, void *f);
1055 static void mp_flush_file (MP mp, void *f);
1056 static void mp_write_ascii_file (MP mp, void *f, const char *s);
1057 static void mp_write_binary_file (MP mp, void *f, void *s, size_t t);
1058 static char *mp_run_script (MP mp, const char *str, size_t len);
1059 static char *mp_make_text (MP mp, const char *str, size_t len, int mode);
1060
1061 @ The function to open files can now be very short.
1062
1063 @c
1064 void *mp_open_file (MP mp, const char *fname, const char *fmode, int ftype) {
1065 char realmode[3];
1066 (void) mp;
1067 realmode[0] = *fmode;
1068 realmode[1] = 'b';
1069 realmode[2] = 0;
1070 if (ftype == mp_filetype_terminal) {
1071 return (fmode[0] == 'r' ? stdin : stdout);
1072 } else if (ftype == mp_filetype_error) {
1073 return stderr;
1074 } else if (fname != NULL && (fmode[0] != 'r' || (!access (fname, R_OK)))) {
1075 return (void *) fopen (fname, realmode);
1076 }
1077 return NULL;
1078 }
1079
1080
1081 @ (Almost) all file names pass through |name_of_file|.
1082
1083 @<Glob...@>=
1084 char *name_of_file; /* the name of a system file */
1085
1086 @ If this parameter is true, the terminal and log will report the found
1087 file names for input files instead of the requested ones.
1088 It is off by default because it creates an extra filename lookup.
1089
1090 @<Option variables@>=
1091 int print_found_names; /* configuration parameter */
1092
1093 @ @<Allocate or initialize ...@>=
1094 mp->print_found_names = (opt->print_found_names > 0 ? true : false);
1095
1096 @ The |file_line_error_style| parameter makes \MP\ use a more
1097 standard compiler error message format instead of the Knuthian
1098 exclamation mark. It needs the actual version of the current input
1099 file name, that will be saved by |open_in| in the |long_name|.
1100
1101 TODO: currently these long strings cause memory leaks, because they cannot
1102 be safely freed as they may appear in the |input_stack| multiple times.
1103 In fact, the current implementation is just a quick hack in response
1104 to a bug report for metapost 1.205.
1105
1106 @d long_name mp->cur_input.long_name_field /* long name of the current file */
1107
1108 @<Option variables@>=
1109 int file_line_error_style; /* configuration parameter */
1110
1111 @ @<Allocate or initialize ...@>=
1112 mp->file_line_error_style = (opt->file_line_error_style > 0 ? true : false);
1113
1114 @ \MP's file-opening procedures return |false| if no file identified by
1115 |name_of_file| could be opened.
1116
1117 The |do_open_file| function takes care of the |print_found_names| parameter.
1118
1119 @c
1120 static boolean mp_do_open_file (MP mp, void **f, int ftype, const char *mode) {
1121 if (mp->print_found_names || mp->file_line_error_style) {
1122 char *s = (mp->find_file)(mp,mp->name_of_file,mode,ftype);
1123 if (s!=NULL) {
1124 *f = (mp->open_file)(mp,mp->name_of_file,mode, ftype);
1125 if (mp->print_found_names) {
1126 xfree(mp->name_of_file);
1127 mp->name_of_file = xstrdup(s);
1128 }
1129 if ((*mode == 'r') && (ftype == mp_filetype_program)) {
1130 long_name = xstrdup(s);
1131 }
1132 xfree(s);
1133 } else {
1134 *f = NULL;
1135 }
1136 } else {
1137 *f = (mp->open_file)(mp,mp->name_of_file,mode, ftype);
1138 }
1139 return (*f ? true : false);
1140 }
1141 @#
1142 static boolean mp_open_in (MP mp, void **f, int ftype) {
1143 /* open a file for input */
1144 return mp_do_open_file (mp, f, ftype, "r");
1145 }
1146 @#
1147 static boolean mp_open_out (MP mp, void **f, int ftype) {
1148 /* open a file for output */
1149 return mp_do_open_file (mp, f, ftype, "w");
1150 }
1151
1152
1153 @ @c
1154 static char *mp_read_ascii_file (MP mp, void *ff, size_t * size) {
1155 int c;
1156 size_t len = 0, lim = 128;
1157 char *s = NULL;
1158 FILE *f = (FILE *) ff;
1159 *size = 0;
1160 (void) mp; /* for \.{-Wunused} */
1161 if (f == NULL)
1162 return NULL;
1163 c = fgetc (f);
1164 if (c == EOF)
1165 return NULL;
1166 s = malloc (lim);
1167 if (s == NULL)
1168 return NULL;
1169 while (c != EOF && c != '\n' && c != '\r') {
1170 if ((len + 1) == lim) {
1171 s = realloc (s, (lim + (lim >> 2)));
1172 if (s == NULL)
1173 return NULL;
1174 lim += (lim >> 2);
1175 }
1176 s[len++] = (char) c;
1177 c = fgetc (f);
1178 }
1179 if (c == '\r') {
1180 c = fgetc (f);
1181 if (c != EOF && c != '\n')
1182 ungetc (c, f);
1183 }
1184 s[len] = 0;
1185 *size = len;
1186 return s;
1187 }
1188
1189
1190 @ @c
1191 void mp_write_ascii_file (MP mp, void *f, const char *s) {
1192 (void) mp;
1193 if (f != NULL) {
1194 fputs (s, (FILE *) f);
1195 }
1196 }
1197
1198
1199 @ @c
1200 void mp_read_binary_file (MP mp, void *f, void **data, size_t * size) {
1201 size_t len = 0;
1202 (void) mp;
1203 if (f != NULL)
1204 len = fread (*data, 1, *size, (FILE *) f);
1205 *size = len;
1206 }
1207
1208
1209 @ @c
1210 void mp_write_binary_file (MP mp, void *f, void *s, size_t size) {
1211 (void) mp;
1212 if (f != NULL)
1213 (void) fwrite (s, size, 1, (FILE *) f);
1214 }
1215
1216
1217 @ @c
1218 void mp_close_file (MP mp, void *f) {
1219 (void) mp;
1220 if (f != NULL)
1221 fclose ((FILE *) f);
1222 }
1223
1224
1225 @ @c
1226 int mp_eof_file (MP mp, void *f) {
1227 (void) mp;
1228 if (f != NULL)
1229 return feof ((FILE *) f);
1230 else
1231 return 1;
1232 }
1233
1234
1235 @ @c
1236 void mp_flush_file (MP mp, void *f) {
1237 (void) mp;
1238 if (f != NULL)
1239 fflush ((FILE *) f);
1240 }
1241
1242
1243 @ Input from text files is read one line at a time, using a routine called
1244 |input_ln|. This function is defined in terms of global variables called
1245 |buffer|, |first|, and |last| that will be described in detail later; for
1246 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
1247 values, and that |first| and |last| are indices into this array
1248 representing the beginning and ending of a line of text.
1249
1250 @<Glob...@>=
1251 size_t buf_size; /* maximum number of characters simultaneously present in
1252 current lines of open files */
1253 ASCII_code *buffer; /* lines of characters being read */
1254 size_t first; /* the first unused position in |buffer| */
1255 size_t last; /* end of the line just input to |buffer| */
1256 size_t max_buf_stack; /* largest index used in |buffer| */
1257
1258 @ @<Allocate or initialize ...@>=
1259 mp->buf_size = 200;
1260 mp->buffer = xmalloc ((mp->buf_size + 1), sizeof (ASCII_code));
1261
1262 @ @<Dealloc variables@>=
1263 xfree (mp->buffer);
1264
1265 @ @c
1266 static void mp_reallocate_buffer (MP mp, size_t l) {
1267 ASCII_code *buffer;
1268 if (l > max_halfword) {
1269 mp_confusion (mp, "buffer size"); /* can't happen (I hope) */
1270 }
1271 buffer = xmalloc ((l + 1), sizeof (ASCII_code));
1272 (void) memcpy (buffer, mp->buffer, (mp->buf_size + 1));
1273 xfree (mp->buffer);
1274 mp->buffer = buffer;
1275 mp->buf_size = l;
1276 }
1277
1278
1279 @ The |input_ln| function brings the next line of input from the specified
1280 field into available positions of the buffer array and returns the value
1281 |true|, unless the file has already been entirely read, in which case it
1282 returns |false| and sets |last:=first|. In general, the |ASCII_code|
1283 numbers that represent the next line of the file are input into
1284 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
1285 global variable |last| is set equal to |first| plus the length of the
1286 line. Trailing blanks are removed from the line; thus, either |last=first|
1287 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
1288 @^inner loop@>
1289
1290 The variable |max_buf_stack|, which is used to keep track of how large
1291 the |buf_size| parameter must be to accommodate the present job, is
1292 also kept up to date by |input_ln|.
1293
1294 @c
1295 static boolean mp_input_ln (MP mp, void *f) {
1296 /* inputs the next line or returns |false| */
1297 char *s;
1298 size_t size = 0;
1299 mp->last = mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
1300 s = (mp->read_ascii_file) (mp, f, &size);
1301 if (s == NULL)
1302 return false;
1303 if (size > 0) {
1304 mp->last = mp->first + size;
1305 if (mp->last >= mp->max_buf_stack) {
1306 mp->max_buf_stack = mp->last + 1;
1307 while (mp->max_buf_stack > mp->buf_size) {
1308 mp_reallocate_buffer (mp, (mp->buf_size + (mp->buf_size >> 2)));
1309 }
1310 }
1311 (void) memcpy ((mp->buffer + mp->first), s, size);
1312 }
1313 free (s);
1314 return true;
1315 }
1316
1317
1318 @ The user's terminal acts essentially like other files of text, except
1319 that it is used both for input and for output. When the terminal is
1320 considered an input file, the file variable is called |term_in|, and when it
1321 is considered an output file the file variable is |term_out|.
1322 @^system dependencies@>
1323
1324 @<Glob...@>=
1325 void *term_in; /* the terminal as an input file */
1326 void *term_out; /* the terminal as an output file */
1327 void *err_out; /* the terminal as an output file */
1328
1329 @ Here is how to open the terminal files. In the default configuration,
1330 nothing happens except that the command line (if there is one) is copied
1331 to the input buffer. The variable |command_line| will be filled by the
1332 |main| procedure.
1333
1334 @d t_open_out() do {/* open the terminal for text output */
1335 mp->term_out = (mp->open_file)(mp,"terminal", "w", mp_filetype_terminal);
1336 mp->err_out = (mp->open_file)(mp,"error", "w", mp_filetype_error);
1337 } while (0)@;
1338 @d t_open_in() do { /* open the terminal for text input */
1339 mp->term_in = (mp->open_file)(mp,"terminal", "r", mp_filetype_terminal);
1340 if (mp->command_line!=NULL) {
1341 mp->last = strlen(mp->command_line);
1342 if (mp->last > (mp->buf_size+1)) {
1343 mp_reallocate_buffer(mp,mp->last);
1344 }
1345 (void)memcpy((void *)mp->buffer,(void *)mp->command_line,mp->last);
1346 xfree(mp->command_line);
1347 } else {
1348 mp->last = 0;
1349 }
1350 } while (0)@;
1351
1352 @<Option variables@>=
1353 char *command_line;
1354
1355 @ Sometimes it is necessary to synchronize the input/output mixture that
1356 happens on the user's terminal, and three system-dependent
1357 procedures are used for this
1358 purpose. The first of these, |update_terminal|, is called when we want
1359 to make sure that everything we have output to the terminal so far has
1360 actually left the computer's internal buffers and been sent.
1361 The second, |clear_terminal|, is called when we wish to cancel any
1362 input that the user may have typed ahead (since we are about to
1363 issue an unexpected error message). The third, |wake_up_terminal|,
1364 is supposed to revive the terminal if the user has disabled it by
1365 some instruction to the operating system. The following macros show how
1366 these operations can be specified:
1367 @^system dependencies@>
1368
1369 @<MPlib internal header stuff@>=
1370 #define update_terminal() @[(mp->flush_file)(mp,mp->term_out)@] /* empty the terminal output buffer */
1371 #define clear_terminal() @[@] /* clear the terminal input buffer */
1372 #define wake_up_terminal() @[(mp->flush_file)(mp,mp->term_out)@]
1373 /* cancel the user's cancellation of output */
1374
1375 @ We need a special routine to read the first line of \MP\ input from
1376 the user's terminal. This line is different because it is read before we
1377 have opened the transcript file; there is sort of a ``chicken and
1378 egg'' problem here. If the user types `\.{input cmr10}' on the first
1379 line, or if some macro invoked by that line does such an \.{input},
1380 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
1381 commands are performed during the first line of terminal input, the transcript
1382 file will acquire its default name `\.{mpout.log}'. (The transcript file
1383 will not contain error messages generated by the first line before the
1384 first \.{input} command.)
1385
1386 The first line is even more special. It's nice to let the user start
1387 running a \MP\ job by typing a command line like `\.{MP cmr10}'; in
1388 such a case, \MP\ will operate as if the first line of input were
1389 `\.{cmr10}', i.e., the first line will consist of the remainder of the
1390 command line, after the part that invoked \MP.
1391
1392 @ Different systems have different ways to get started. But regardless of
1393 what conventions are adopted, the routine that initializes the terminal
1394 should satisfy the following specifications:
1395
1396 \yskip\textindent{1)}It should open file |term_in| for input from the
1397 terminal. (The file |term_out| will already be open for output to the
1398 terminal.)
1399
1400 \textindent{2)}If the user has given a command line, this line should be
1401 considered the first line of terminal input. Otherwise the
1402 user should be prompted with `\.{**}', and the first line of input
1403 should be whatever is typed in response.
1404
1405 \textindent{3)}The first line of input, which might or might not be a
1406 command line, should appear in locations |first| to |last-1| of the
1407 |buffer| array.
1408
1409 \textindent{4)}The global variable |loc| should be set so that the
1410 character to be read next by \MP\ is in |buffer[loc]|. This
1411 character should not be blank, and we should have |loc<last|.
1412
1413 \yskip\noindent(It may be necessary to prompt the user several times
1414 before a non-blank line comes in. The prompt is `\.{**}' instead of the
1415 later `\.*' because the meaning is slightly different: `\.{input}' need
1416 not be typed immediately after~`\.{**}'.)
1417
1418 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
1419
1420 @c
1421 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
1422 t_open_in();
1423 if (mp->last != 0) {
1424 loc = 0;
1425 mp->first = 0;
1426 return true;
1427 }
1428 while (1) {
1429 if (!mp->noninteractive) {
1430 wake_up_terminal();
1431 mp_fputs ("**", mp->term_out);
1432 @.**@>
1433 update_terminal();
1434 }
1435 if (!mp_input_ln (mp, mp->term_in)) { /* this shouldn't happen */
1436 mp_fputs ("\n! End of file on the terminal... why?", mp->term_out);
1437 @.End of file on the terminal@>
1438 return false;
1439 }
1440 loc = (halfword) mp->first;
1441 while ((loc < (int) mp->last) && (mp->buffer[loc] == ' '))
1442 incr (loc);
1443 if (loc < (int) mp->last) {
1444 return true; /* return unless the line was all blank */
1445 }
1446 if (!mp->noninteractive) {
1447 mp_fputs ("Please type the name of your input file.\n", mp->term_out);
1448 }
1449 }
1450 }
1451
1452
1453 @ @<Declarations@>=
1454 static boolean mp_init_terminal (MP mp);
1455
1456 @* Globals for strings.
1457
1458 @ Symbolic token names and diagnostic messages are variable-length strings
1459 of eight-bit characters. Many strings \MP\ uses are simply literals
1460 in the compiled source, like the error messages and the names of the
1461 internal parameters. Other strings are used or defined from the \MP\ input
1462 language, and these have to be interned.
1463
1464 \MP\ uses strings more extensively than \MF\ does, but the necessary
1465 operations can still be handled with a fairly simple data structure.
1466 The avl tree |strings| contains all of the known string structures.
1467
1468 Each structure contains an |unsigned char| pointer containing the eight-bit
1469 data, a |size_t| that holds the length of that data, and an |int| that
1470 indicates how often this string is referenced (this will be explained below).
1471 Such strings are referred to by structure pointers called |mp_string|.
1472
1473 Besides the avl tree, there is a set of three variables called |cur_string|,
1474 |cur_length| and |cur_string_size| that are used for strings while they are
1475 being built.
1476
1477 @<Exported types...@>=
1478 typedef struct {
1479 unsigned char *str; /* the string value */
1480 size_t len; /* its length */
1481 int refs; /* number of references */
1482 } mp_lstring;
1483 typedef mp_lstring *mp_string; /* for pointers to string values */
1484
1485 @ The string handling functions are in \.{mpstrings.w}, but strings
1486 need a bunch of globals and those are defined here in the main file.
1487
1488 @<Glob...@>=
1489 avl_tree strings; /* string avl tree */
1490 unsigned char *cur_string; /* current string buffer */
1491 size_t cur_length; /* current index in that buffer */
1492 size_t cur_string_size; /* malloced size of |cur_string| */
1493
1494 @ @<Allocate or initialize ...@>=
1495 mp_initialize_strings(mp);
1496
1497 @ @<Dealloc variables@>=
1498 mp_dealloc_strings(mp);
1499
1500 @ The next four variables are for keeping track of string memory usage.
1501
1502 @<Glob...@>=
1503 integer pool_in_use; /* total number of string bytes actually in use */
1504 integer max_pl_used; /* maximum |pool_in_use| so far */
1505 integer strs_in_use; /* total number of strings actually in use */
1506 integer max_strs_used; /* maximum |strs_in_use| so far */
1507
1508
1509 @* On-line and off-line printing.
1510 Messages that are sent to a user's terminal and to the transcript-log file
1511 are produced by several `|print|' procedures. These procedures will
1512 direct their output to a variety of places, based on the setting of
1513 the global variable |selector|, which has the following possible
1514 values:
1515
1516 \yskip
1517 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1518 transcript file.
1519
1520 \hang |log_only|, prints only on the transcript file.
1521
1522 \hang |term_only|, prints only on the terminal.
1523
1524 \hang |no_print|, doesn't print at all. This is used only in rare cases
1525 before the transcript file is open.
1526
1527 \hang |pseudo|, puts output into a cyclic buffer that is used
1528 by the |show_context| routine; when we get to that routine we shall discuss
1529 the reasoning behind this curious mode.
1530
1531 \hang |new_string|, appends the output to the current string in the
1532 string pool.
1533
1534 \hang |>=write_file| prints on one of the files used for the \&{write}
1535 @:write_}{\&{write} primitive@>
1536 command.
1537
1538 \yskip
1539 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1540 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1541 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|. These
1542 relations are not used when |selector| could be |pseudo|, or |new_string|.
1543 We need not check for unprintable characters when |selector<pseudo|.
1544
1545 Three additional global variables, |tally|, |term_offset| and |file_offset|
1546 record the number of characters that have been printed
1547 since they were most recently cleared to zero. We use |tally| to record
1548 the length of (possibly very long) stretches of printing; |term_offset|,
1549 and |file_offset|, on the other hand, keep track of how many
1550 characters have appeared so far on the current line that has been output
1551 to the terminal, the transcript file, or the \ps\ output file, respectively.
1552
1553 @d new_string 0 /* printing is deflected to the string pool */
1554 @d pseudo 2 /* special |selector| setting for |show_context| */
1555 @d no_print 3 /* |selector| setting that makes data disappear */
1556 @d term_only 4 /* printing is destined for the terminal only */
1557 @d log_only 5 /* printing is destined for the transcript file only */
1558 @d term_and_log 6 /* normal |selector| setting */
1559 @d write_file 7 /* first write file selector */
1560
1561 @<Glob...@>=
1562 void *log_file; /* transcript of \MP\ session */
1563 void *output_file; /* the generic font output goes here */
1564 unsigned int selector; /* where to print a message */
1565 integer tally; /* the number of characters recently printed */
1566 unsigned int term_offset;
1567 /* the number of characters on the current terminal line */
1568 unsigned int file_offset;
1569 /* the number of characters on the current file line */
1570 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1571 integer trick_count; /* threshold for pseudoprinting, explained later */
1572 integer first_count; /* another variable for pseudoprinting */
1573
1574 @ The first 128 strings will contain 95 standard ASCII characters, and the
1575 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1576 unless a system-dependent change is made here. Installations that have
1577 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1578 would like string 032 to be printed as the single character 032 instead
1579 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1580 even people with an extended character set will want to represent string
1581 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1582 to produce visible strings instead of tabs or line-feeds or carriage-returns
1583 or bell-rings or characters that are treated anomalously in text files.
1584
1585 The boolean expression defined here should be |true| unless \MP\ internal
1586 code number~|k| corresponds to a non-troublesome visible symbol in the
1587 local character set.
1588 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1589 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1590 must be printable.
1591 @^character set dependencies@>
1592 @^system dependencies@>
1593
1594 @<Character |k| cannot be printed@>=
1595 (k < ' ') || (k == 127)
1596
1597 @ @<Allocate or initialize ...@>=
1598 mp->trick_buf = xmalloc ((mp->error_line + 1), sizeof (ASCII_code));
1599
1600 @ @<Dealloc variables@>=
1601 xfree (mp->trick_buf);
1602
1603 @ @<Initialize the output routines@>=
1604 mp->selector = term_only;
1605 mp->tally = 0;
1606 mp->term_offset = 0;
1607 mp->file_offset = 0;
1608
1609 @ Macro abbreviations for output to the terminal and to the log file are
1610 defined here for convenience. Some systems need special conventions
1611 for terminal output, and it is possible to adhere to those conventions
1612 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1613 @^system dependencies@>
1614
1615 @<MPlib internal header stuff@>=
1616 #define mp_fputs(b,f) @[(mp->write_ascii_file)(mp,f,b)@]
1617 #define wterm(A) @[mp_fputs((A), mp->term_out)@]
1618 #define wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]='\0'; wterm((char *)ss);}
1619 #define wterm_cr @[mp_fputs("\n", mp->term_out)@]
1620 #define wterm_ln(A) { wterm_cr; mp_fputs((A), mp->term_out); }
1621 #define wlog(A) @[mp_fputs((A), mp->log_file)@]
1622 #define wlog_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]='\0'; wlog((char *)ss);}
1623 #define wlog_cr @[mp_fputs("\n", mp->log_file)@]
1624 #define wlog_ln(A) { wlog_cr; mp_fputs((A), mp->log_file); }
1625
1626
1627 @ To end a line of text output, we call |print_ln|. Cases |0..max_write_files|
1628 use an array |wr_file| that will be declared later.
1629
1630 @d mp_print_text(A) mp_print_str(mp,text((A)))
1631
1632 @<Internal library ...@>=
1633 void mp_print (MP mp, const char *s);
1634 void mp_printf (MP mp, const char *ss, ...);
1635 void mp_print_ln (MP mp);
1636 void mp_print_char (MP mp, ASCII_code k);
1637 void mp_print_str (MP mp, mp_string s);
1638 void mp_print_nl (MP mp, const char *s);
1639 void mp_print_two (MP mp, mp_number x, mp_number y);
1640
1641 @ @<Declarations@>=
1642 static void mp_print_visible_char (MP mp, ASCII_code s);
1643
1644 @ @<Basic print...@>=
1645 void mp_print_ln (MP mp) { /* prints an end-of-line */
1646 switch (mp->selector) {
1647 case term_and_log:
1648 wterm_cr;
1649 wlog_cr;
1650 mp->term_offset = 0;
1651 mp->file_offset = 0;
1652 break;
1653 case log_only:
1654 wlog_cr;
1655 mp->file_offset = 0;
1656 break;
1657 case term_only:
1658 wterm_cr;
1659 mp->term_offset = 0;
1660 break;
1661 case no_print:
1662 case pseudo:
1663 case new_string:
1664 break;
1665 default:
1666 mp_fputs ("\n", mp->wr_file[(mp->selector - write_file)]);
1667 }
1668 } /* note that |tally| is not affected */
1669
1670
1671 @ The |print_visible_char| procedure sends one character to the desired
1672 destination, using the |xchr| array to map it into an external character
1673 compatible with |input_ln|. (It assumes that it is always called with
1674 a visible ASCII character.) All printing comes through |print_ln| or
1675 |print_char|, which ultimately calls |print_visible_char|, hence these
1676 routines are the ones that limit lines to at most |max_print_line| characters.
1677 But we must make an exception for the \ps\ output file since it is not safe
1678 to cut up lines arbitrarily in \ps.
1679
1680 @<Basic printing...@>=
1681 static void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1682 switch (mp->selector) {
1683 case term_and_log:
1684 wterm_chr (xchr (s));
1685 wlog_chr (xchr (s));
1686 incr (mp->term_offset);
1687 incr (mp->file_offset);
1688 if (mp->term_offset == (unsigned) mp->max_print_line) {
1689 wterm_cr;
1690 mp->term_offset = 0;
1691 }
1692 if (mp->file_offset == (unsigned) mp->max_print_line) {
1693 wlog_cr;
1694 mp->file_offset = 0;
1695 }
1696 break;
1697 case log_only:
1698 wlog_chr (xchr (s));
1699 incr (mp->file_offset);
1700 if (mp->file_offset == (unsigned) mp->max_print_line)
1701 mp_print_ln (mp);
1702 break;
1703 case term_only:
1704 wterm_chr (xchr (s));
1705 incr (mp->term_offset);
1706 if (mp->term_offset == (unsigned) mp->max_print_line)
1707 mp_print_ln (mp);
1708 break;
1709 case no_print:
1710 break;
1711 case pseudo:
1712 if (mp->tally < mp->trick_count)
1713 mp->trick_buf[mp->tally % mp->error_line] = s;
1714 break;
1715 case new_string:
1716 append_char (s);
1717 break;
1718 default:
1719 {
1720 text_char ss[2] = {0,0};
1721 ss[0] = xchr (s);
1722 mp_fputs ((char *) ss, mp->wr_file[(mp->selector - write_file)]);
1723 }
1724 }
1725 incr (mp->tally);
1726 }
1727
1728
1729 @ The |print_char| procedure sends one character to the desired destination.
1730 File names and string expressions might contain |ASCII_code| values that
1731 can't be printed using |print_visible_char|. These characters will be
1732 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1733 (This procedure assumes that it is safe to bypass all checks for unprintable
1734 characters when |selector| is in the range |0..max_write_files-1|.
1735 The user might want to write unprintable characters.
1736
1737 @<Basic printing...@>=
1738 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1739 if (mp->utf8_mode || mp->selector < pseudo || mp->selector >= write_file) {
1740 mp_print_visible_char (mp, k);
1741 } else if (@<Character |k| cannot be printed@>) {
1742 mp_print (mp, "^^");
1743 if (k < 0100) {
1744 mp_print_visible_char (mp, (ASCII_code) (k + 0100));
1745 } else if (k < 0200) {
1746 mp_print_visible_char (mp, (ASCII_code) (k - 0100));
1747 } else {
1748 int l; /* small index or counter */
1749 l = (k / 16);
1750 mp_print_visible_char (mp, xord (l < 10 ? l + '0' : l - 10 + 'a'));
1751 l = (k % 16);
1752 mp_print_visible_char (mp, xord (l < 10 ? l + '0' : l - 10 + 'a'));
1753 }
1754 } else {
1755 mp_print_visible_char (mp, k);
1756 }
1757 }
1758
1759
1760 @ An entire string is output by calling |print|. Note that if we are outputting
1761 the single standard ASCII character \.c, we could call |print("c")|, since
1762 |"c"=99| is the number of a single-character string, as explained above. But
1763 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1764 routine when it knows that this is safe. (The present implementation
1765 assumes that it is always safe to print a visible ASCII character.)
1766 @^system dependencies@>
1767
1768 @<Basic print...@>=
1769 static void mp_do_print (MP mp, const char *ss, size_t len) { /* prints string |s| */
1770 if (len==0)
1771 return;
1772 if (mp->selector == new_string) {
1773 str_room (len);
1774 memcpy((mp->cur_string+mp->cur_length), ss, len);
1775 mp->cur_length += len;
1776 } else {
1777 size_t j = 0;
1778 while (j < len) {
1779 /* this was |xord((int)ss[j])| but that doesn't work */
1780 mp_print_char (mp, (ASCII_code) ss[j]);
1781 j++;
1782 }
1783 }
1784 }
1785
1786
1787 @ @<Basic print...@>=
1788 void mp_print (MP mp, const char *ss) {
1789 assert (ss != NULL);
1790 mp_do_print (mp, ss, strlen (ss));
1791 }
1792 void mp_printf (MP mp, const char *ss, ...) {
1793 va_list ap;
1794 char pval[256];
1795 assert (ss != NULL);
1796 va_start(ap, ss);
1797 vsnprintf (pval, 256, ss, ap);
1798 mp_do_print (mp, pval, strlen (pval));
1799 va_end(ap);
1800 }
1801
1802 void mp_print_str (MP mp, mp_string s) {
1803 assert (s != NULL);
1804 mp_do_print (mp, (const char *) s->str, s->len);
1805 }
1806
1807
1808 @ Here is the very first thing that \MP\ prints: a headline that identifies
1809 the version number and base name. The |term_offset| variable is temporarily
1810 incorrect, but the discrepancy is not serious since we assume that the banner
1811 and mem identifier together will occupy at most |max_print_line|
1812 character positions.
1813
1814 @<Initialize the output...@>=
1815 wterm (mp->banner);
1816 mp_print_ln (mp);
1817 update_terminal();
1818
1819 @ The procedure |print_nl| is like |print|, but it makes sure that the
1820 string appears at the beginning of a new line.
1821
1822 @<Basic print...@>=
1823 void mp_print_nl (MP mp, const char *s) { /* prints string |s| at beginning of line */
1824 switch (mp->selector) {
1825 case term_and_log:
1826 if ((mp->term_offset > 0) || (mp->file_offset > 0))
1827 mp_print_ln (mp);
1828 break;
1829 case log_only:
1830 if (mp->file_offset > 0)
1831 mp_print_ln (mp);
1832 break;
1833 case term_only:
1834 if (mp->term_offset > 0)
1835 mp_print_ln (mp);
1836 break;
1837 case no_print:
1838 case pseudo:
1839 case new_string:
1840 break;
1841 } /* there are no other cases */
1842 mp_print (mp, s);
1843 }
1844
1845
1846 @ The following procedure, which prints out the decimal representation of a
1847 given integer |n|, assumes that all integers fit nicely into a |int|.
1848 @^system dependencies@>
1849
1850 @<Basic print...@>=
1851 void mp_print_int (MP mp, mpinteger64 n) { /* prints an integer in decimal form */
1852 char s[12];
1853 mp_snprintf (s, 12, "%" PRId64, n);
1854 mp_print (mp, s);
1855 }
1856 void mp_print_pointer (MP mp, void *n) { /* prints an pointer in hexadecimal form */
1857 char s[12];
1858 mp_snprintf (s, 12, "%p", n);
1859 mp_print (mp, s);
1860 }
1861
1862 @ @<Internal library ...@>=
1863 void mp_print_int (MP mp, mpinteger64 n);
1864 void mp_print_pointer (MP mp, void *n);
1865
1866 @ \MP\ also makes use of a trivial procedure to print two digits. The
1867 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1868
1869 @c
1870 static void mp_print_dd (MP mp, mpinteger64 n) { /* prints two least significant digits */
1871 n = MPOST_ABS (n) % 100;
1872 mp_print_char (mp, xord ('0' + (n / 10)));
1873 mp_print_char (mp, xord ('0' + (n % 10)));
1874 }
1875
1876
1877 @ @<Declarations@>=
1878 static void mp_print_dd (MP mp, mpinteger64 n);
1879
1880 @ Here is a procedure that asks the user to type a line of input,
1881 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1882 The input is placed into locations |first| through |last-1| of the
1883 |buffer| array, and echoed on the transcript file if appropriate.
1884
1885 This procedure is never called when |interaction<mp_scroll_mode|.
1886
1887 @d prompt_input(A) do {
1888 if (!mp->noninteractive) {
1889 wake_up_terminal();
1890 mp_print(mp, (A));
1891 }
1892 mp_term_input(mp);
1893 } while (0)@; /* prints a string and gets a line of input */
1894
1895 @c
1896 void mp_term_input (MP mp) { /* gets a line from the terminal */
1897 size_t k; /* index into |buffer| */
1898 if (mp->noninteractive) {
1899 if (!mp_input_ln (mp, mp->term_in))
1900 longjmp (*(mp->jump_buf), 1); /* chunk finished */
1901 mp->buffer[mp->last] = xord ('%');
1902 } else {
1903 update_terminal(); /* Now the user sees the prompt for sure */
1904 if (!mp_input_ln (mp, mp->term_in)) {
1905 mp_fatal_error (mp, "End of file on the terminal!");
1906 @.End of file on the terminal@>
1907 }
1908 mp->term_offset = 0; /* the user's line ended with \<\rm return> */
1909 decr (mp->selector); /* prepare to echo the input */
1910 if (mp->last != mp->first) {
1911 for (k = mp->first; k < mp->last; k++) {
1912 mp_print_char (mp, mp->buffer[k]);
1913 }
1914 }
1915 mp_print_ln (mp);
1916 mp->buffer[mp->last] = xord ('%');
1917 incr (mp->selector); /* restore previous status */
1918 }
1919 }
1920
1921
1922 @* Reporting errors.
1923
1924 The |print_err| procedure supplies a `\.!' before the official message,
1925 and makes sure that the terminal is awake if a stop is going to occur.
1926 The |error| procedure supplies a `\..' after the official message, then it
1927 shows the location of the error; and if |interaction=error_stop_mode|,
1928 it also enters into a dialog with the user, during which time the help
1929 message may be printed.
1930 @^system dependencies@>
1931
1932 @ The global variable |interaction| has four settings, representing increasing
1933 amounts of user interaction:
1934
1935 @<Exported types@>=
1936 enum mp_interaction_mode {
1937 mp_unspecified_mode = 0, /* extra value for command-line switch */
1938 mp_batch_mode, /* omits all stops and omits terminal output */
1939 mp_nonstop_mode, /* omits all stops */
1940 mp_scroll_mode, /* omits error stops */
1941 mp_error_stop_mode /* stops at every opportunity to interact */
1942 };
1943
1944 @ @<Option variables@>=
1945 integer64 interaction; /* current level of interaction */
1946 int noninteractive; /* do we have a terminal? */
1947 int extensions;
1948
1949 @ Set it here so it can be overwritten by the commandline
1950
1951 @<Allocate or initialize ...@>=
1952 mp->interaction = opt->interaction;
1953 if (mp->interaction == mp_unspecified_mode
1954 || mp->interaction > mp_error_stop_mode)
1955 mp->interaction = mp_error_stop_mode;
1956 if (mp->interaction < mp_unspecified_mode)
1957 mp->interaction = mp_batch_mode;
1958
1959 @ |print_err| is not merged in |error| because it is also used in |prompt_file_name|,
1960 where |error| is not called at all.
1961
1962 @<Declarations@>=
1963 static void mp_print_err (MP mp, const char *A);
1964
1965 @ @s line x @c
1966 static void mp_print_err (MP mp, const char *A) {
1967 if (mp->interaction == mp_error_stop_mode)
1968 wake_up_terminal();
1969 if (mp->file_line_error_style && file_state && !terminal_input) {
1970 mp_print_nl (mp, "");
1971 if (long_name != NULL) {
1972 mp_print (mp, long_name);
1973 } else {
1974 mp_print (mp, mp_str (mp, name));
1975 }
1976 mp_print (mp, ":");
1977 mp_print_int (mp, line);
1978 mp_print (mp, ": ");
1979 } else {
1980 mp_print_nl (mp, "! ");
1981 }
1982 mp_print (mp, A);
1983 @.!\relax@>
1984 }
1985
1986
1987 @ \MP\ is careful not to call |error| when the print |selector| setting
1988 might be unusual. The only possible values of |selector| at the time of
1989 error messages are
1990
1991 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1992 and |log_file| not yet open);
1993
1994 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1995
1996 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1997
1998 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1999
2000 @d initialize_print_selector() mp->selector = (mp->interaction == mp_batch_mode ? no_print : term_only);
2001
2002 @ The global variable |history| records the worst level of error that
2003 has been detected. It has four possible values: |spotless|, |warning_issued|,
2004 |error_message_issued|, and |fatal_error_stop|.
2005
2006 Another global variable, |error_count|, is increased by one when an
2007 |error| occurs without an interactive dialog, and it is reset to zero at
2008 the end of every statement. If |error_count| reaches 100, \MP\ decides
2009 that there is no point in continuing further.
2010
2011 @<Exported types@>=
2012 enum mp_history_state {
2013 mp_spotless = 0, /* |history| value when nothing has been amiss yet */
2014 mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
2015 mp_error_message_issued, /* |history| value when |error| has been called */
2016 mp_fatal_error_stop, /* |history| value when termination was premature */
2017 mp_system_error_stop /* |history| value when termination was due to disaster */
2018 };
2019
2020 @ @<Glob...@>=
2021 int history; /* has the source input been clean so far? */
2022 int error_count; /* the number of scrolled errors since the last statement ended */
2023
2024 @ The value of |history| is initially |fatal_error_stop|, but it will
2025 be changed to |spotless| if \MP\ survives the initialization process.
2026
2027 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2028 error procedures near the beginning of the program. But the error procedures
2029 in turn use some other procedures, which need to be declared |forward|
2030 before we get to |error| itself.
2031
2032 It is possible for |error| to be called recursively if some error arises
2033 when |get_next| is being used to delete a token, and/or if some fatal error
2034 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2035 @^recursion@>
2036 is never more than two levels deep.
2037
2038 @<Declarations@>=
2039 static void mp_get_next (MP mp);
2040 static void mp_term_input (MP mp);
2041 static void mp_show_context (MP mp);
2042 static void mp_begin_file_reading (MP mp);
2043 static void mp_open_log_file (MP mp);
2044 static void mp_clear_for_error_prompt (MP mp);
2045
2046 @ @<Internal ...@>=
2047 void mp_normalize_selector (MP mp);
2048
2049 @ @<Glob...@>=
2050 boolean use_err_help; /* should the |err_help| string be shown? */
2051 mp_string err_help; /* a string set up by \&{errhelp} */
2052
2053 @ @<Allocate or ...@>=
2054 mp->use_err_help = false;
2055
2056 @ The |jump_out| procedure just cuts across all active procedure levels and
2057 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2058 whole program. It is used when there is no recovery from a particular error.
2059
2060 The program uses a |jump_buf| to handle this, this is initialized at three
2061 spots: the start of |mp_new|, the start of |mp_initialize|, and the start
2062 of |mp_run|. Those are the only library entry points.
2063 @^system dependencies@>
2064
2065 @<Glob...@>=
2066 jmp_buf *jump_buf;
2067
2068 @ If the array of internals is still |NULL| when |jump_out| is called, a
2069 crash occurred during initialization, and it is not safe to run the normal
2070 cleanup routine.
2071
2072 @<Error hand...@>=
2073 void mp_jump_out (MP mp) {
2074 if (mp->internal != NULL && mp->history < mp_system_error_stop)
2075 mp_close_files_and_terminate (mp);
2076 longjmp (*(mp->jump_buf), 1);
2077 }
2078
2079 @ @<Internal ...@>=
2080 void mp_jump_out (MP mp);
2081
2082 @ @<Error hand...@>=
2083 void mp_warn (MP mp, const char *msg) {
2084 unsigned saved_selector = mp->selector;
2085 mp_normalize_selector (mp);
2086 mp_print_nl (mp, "Warning: ");
2087 mp_print (mp, msg);
2088 mp_print_ln (mp);
2089 mp->selector = saved_selector;
2090 }
2091
2092 @ Here now is the general |error| routine.
2093
2094 The argument |deletions_allowed| is set |false| if the |get_next|
2095 routine is active when |error| is called; this ensures that |get_next|
2096 will never be called recursively.
2097 @^recursion@>
2098
2099 Individual lines of help are recorded in the array |help_line|, which
2100 contains entries in positions |0..(help_ptr-1)|. They should be printed
2101 in reverse order, i.e., with |help_line[0]| appearing last.
2102
2103 @s mp_sym int
2104
2105 @c
2106 void mp_error (MP mp, const char *msg, const char **hlp, boolean deletions_allowed) {
2107 ASCII_code c; /* what the user types */
2108 //uint32_t s1;
2109 quarterword s1;
2110 mpinteger64 s2; /* used to save global variables when deleting tokens */
2111 mp_sym s3; /* likewise */
2112 int i = 0;
2113 const char *help_line[6]; /* helps for the next |error| */
2114 unsigned int help_ptr; /* the number of help lines present */
2115 const char **cnt = NULL;
2116 mp_print_err(mp, msg);
2117 if (hlp) {
2118 cnt = hlp;
2119 while (*cnt) {
2120 i++; cnt++;
2121 }
2122 cnt = hlp;
2123 }
2124 help_ptr=(unsigned int)i;
2125 while (i>0) {
2126 help_line[--i]= *cnt++;
2127 }
2128 if (mp->history < mp_error_message_issued)
2129 mp->history = mp_error_message_issued;
2130 mp_print_char (mp, xord ('.'));
2131 mp_show_context (mp);
2132 if (mp->halt_on_error) {
2133 mp->history = mp_fatal_error_stop;
2134 mp_jump_out (mp);
2135 }
2136 if ((!mp->noninteractive) && (mp->interaction == mp_error_stop_mode)) {
2137 @<Get user's advice and |return|@>;
2138 }
2139 incr (mp->error_count);
2140 if (mp->error_count == 100) {
2141 mp_print_nl (mp, "(That makes 100 errors; please try again.)");
2142 @.That makes 100 errors...@>
2143 mp->history = mp_fatal_error_stop;
2144 mp_jump_out (mp);
2145 }
2146 @<Put help message on the transcript file@>;
2147 }
2148
2149
2150 @ @<Exported function ...@>=
2151 extern void mp_error (MP mp, const char *msg, const char **hlp, boolean deletions_allowed);
2152 extern void mp_warn (MP mp, const char *msg);
2153
2154
2155 @ @<Get user's advice...@>=
2156 while (true) {
2157 CONTINUE:
2158 mp_clear_for_error_prompt (mp);
2159 prompt_input ("? ");
2160 @.?\relax@>
2161 if (mp->last == mp->first)
2162 return;
2163 c = mp->buffer[mp->first];
2164 if (c >= 'a')
2165 c = (ASCII_code) (c + 'A' - 'a'); /* convert to uppercase */
2166 @<Interpret code |c| and |return| if done@>;
2167 }
2168
2169
2170 @ It is desirable to provide an `\.E' option here that gives the user
2171 an easy way to return from \MP\ to the system editor, with the offending
2172 line ready to be edited. But such an extension requires some system
2173 wizardry, so the present implementation simply types out the name of the
2174 file that should be
2175 edited and the relevant line number.
2176 @^system dependencies@>
2177
2178 @<Exported types@>=
2179 typedef void @[@] (*mp_editor_cmd) (MP, char *, integer64);
2180
2181 @ @<Option variables@>=
2182 mp_editor_cmd run_editor;
2183
2184 @ @<Allocate or initialize ...@>=
2185 set_callback_option (run_editor);
2186
2187 @ @<Declarations@>=
2188 static void mp_run_editor (MP mp, char *fname, integer64 fline);
2189
2190 @ @c
2191 void mp_run_editor (MP mp, char *fname, integer64 fline) {
2192 char *s = xmalloc (256, 1);
2193 mp_snprintf (s, 256, "You want to edit file %s at line %" PRId64 "\n", fname, fline);
2194 wterm_ln (s);
2195 @.You want to edit file x@>
2196 }
2197
2198
2199 @ @<Interpret code |c| and |return| if done@>=
2200 switch (c) {
2201 case '0':
2202 case '1':
2203 case '2':
2204 case '3':
2205 case '4':
2206 case '5':
2207 case '6':
2208 case '7':
2209 case '8':
2210 case '9':
2211 if (deletions_allowed) {
2212 @<Delete tokens and |continue|@>;
2213 }
2214 break;
2215 case 'E':
2216 if (mp->file_ptr > 0) {
2217 mp->interaction = mp_scroll_mode;
2218 mp_close_files_and_terminate (mp);
2219 (mp->run_editor) (mp,
2220 mp_str (mp, mp->input_stack[mp->file_ptr].name_field),
2221 mp_true_line (mp));
2222 mp_jump_out (mp);
2223 }
2224 break;
2225 case 'H':
2226 @<Print the help information and |continue|@>;
2227 /* |break;| */
2228 case 'I':
2229 @<Introduce new material from the terminal and |return|@>;
2230 /* |break;| */
2231 case 'Q':
2232 case 'R':
2233 case 'S':
2234 @<Change the interaction level and |return|@>;
2235 /* |break;| */
2236 case 'X':
2237 mp->interaction = mp_scroll_mode;
2238 mp_jump_out (mp);
2239 break;
2240 default:
2241 break;
2242 }
2243 @<Print the menu of available options@>
2244
2245
2246 @ @<Print the menu...@>=
2247 {
2248 mp_print (mp, "Type <return> to proceed, S to scroll future error messages,");
2249 @.Type <return> to proceed...@>
2250 mp_print_nl (mp, "R to run without stopping, Q to run quietly,");
2251 mp_print_nl (mp, "I to insert something, ");
2252 if (mp->file_ptr > 0)
2253 mp_print (mp, "E to edit your file,");
2254 if (deletions_allowed)
2255 mp_print_nl (mp,
2256 "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2257 mp_print_nl (mp, "H for help, X to quit.");
2258 }
2259
2260
2261 @ @<Change the interaction...@>=
2262 {
2263 mp->error_count = 0;
2264 mp_print (mp, "OK, entering ");
2265 switch (c) {
2266 case 'Q':
2267 mp->interaction = mp_batch_mode;
2268 mp_print (mp, "batchmode");
2269 decr (mp->selector);
2270 break;
2271 case 'R':
2272 mp->interaction = mp_nonstop_mode;
2273 mp_print (mp, "nonstopmode");
2274 break;
2275 case 'S':
2276 mp->interaction = mp_scroll_mode;
2277 mp_print (mp, "scrollmode");
2278 break;
2279 } /* there are no other cases */
2280 mp_print (mp, "...");
2281 mp_print_ln (mp);
2282 update_terminal();
2283 return;
2284 }
2285
2286
2287 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2288 contain the material inserted by the user; otherwise another prompt will
2289 be given. In order to understand this part of the program fully, you need
2290 to be familiar with \MP's input stacks.
2291
2292 @<Introduce new material...@>=
2293 {
2294 mp_begin_file_reading (mp); /* enter a new syntactic level for terminal input */
2295 if (mp->last > mp->first + 1) {
2296 loc = (halfword) (mp->first + 1);
2297 mp->buffer[mp->first] = xord (' ');
2298 } else {
2299 prompt_input ("insert>");
2300 loc = (halfword) mp->first;
2301 @.insert>@>
2302 }
2303 mp->first = mp->last + 1;
2304 mp->cur_input.limit_field = (halfword) mp->last;
2305 return;
2306 }
2307
2308
2309 @ We allow deletion of up to 99 tokens at a time.
2310
2311 @<Delete tokens...@>=
2312 {
2313 s1 = cur_cmd();
2314 s2 = cur_mod();
2315 s3 = cur_sym();
2316 mp->OK_to_interrupt = false;
2317 if ((mp->last > mp->first + 1) && (mp->buffer[mp->first + 1] >= '0')
2318 && (mp->buffer[mp->first + 1] <= '9'))
2319 c = xord (c * 10 + mp->buffer[mp->first + 1] - '0' * 11);
2320 else
2321 c = (ASCII_code) (c - '0');
2322 while (c > 0) {
2323 mp_get_next (mp); /* one-level recursive call of |error| is possible */
2324 @<Decrease the string reference count, if the current token is a string@>;
2325 c--;
2326 }
2327 set_cur_cmd (s1);
2328 set_cur_mod (s2);
2329 set_cur_sym (s3);
2330 mp->OK_to_interrupt = true;
2331 help_ptr = 2;
2332 help_line[1] = "I have just deleted some text, as you asked.";
2333 help_line[0] = "You can now delete more, or insert, or whatever.";
2334 mp_show_context (mp);
2335 goto CONTINUE;
2336 }
2337
2338
2339 @ Some wriggling with |help_line| is done here to avoid giving no
2340 information whatsoever, or presenting the same information twice
2341 in a row.
2342
2343 @<Print the help info...@>=
2344 {
2345 if (mp->use_err_help) {
2346 @<Print the string |err_help|, possibly on several lines@>;
2347 mp->use_err_help = false;
2348 } else {
2349 if (help_ptr == 0) {
2350 help_ptr=2;
2351 help_line[1] = "Sorry, I don't know how to help in this situation.";
2352 help_line[0] = "Maybe you should try asking a human?";
2353 }
2354 do {
2355 decr (help_ptr);
2356 mp_print (mp, help_line[help_ptr]);
2357 mp_print_ln (mp);
2358 } while (help_ptr != 0);
2359 }
2360 help_ptr=4;
2361 help_line[3] = "Sorry, I already gave what help I could...";
2362 help_line[2] = "Maybe you should try asking a human?";
2363 help_line[1] = "An error might have occurred before I noticed any problems.";
2364 help_line[0] = "``If all else fails, read the instructions.''";
2365 goto CONTINUE;
2366 }
2367
2368
2369 @ @<Print the string |err_help|, possibly on several lines@>=
2370 {
2371 size_t j = 0;
2372 while (j < mp->err_help->len) {
2373 if (*(mp->err_help->str + j) != '%')
2374 mp_print (mp, (const char *) (mp->err_help->str + j));
2375 else if (j + 1 == mp->err_help->len)
2376 mp_print_ln (mp);
2377 else if (*(mp->err_help->str + j) != '%')
2378 mp_print_ln (mp);
2379 else {
2380 j++;
2381 mp_print_char (mp, xord ('%'));
2382 }
2383 j++;
2384 }
2385 }
2386
2387
2388 @ @<Put help message on the transcript file@>=
2389 if (! mp->noninteractive) {
2390 if (mp->interaction > mp_batch_mode) {
2391 decr (mp->selector); /* avoid terminal output */
2392 }
2393 }
2394 if (mp->use_err_help) {
2395 mp_print_nl (mp, "");
2396 @<Print the string |err_help|, possibly on several lines@>;
2397 } else {
2398 while (help_ptr > 0) {
2399 decr (help_ptr);
2400 mp_print_nl (mp, help_line[help_ptr]);
2401 }
2402 mp_print_ln (mp);
2403 if (! mp->noninteractive) {
2404 if (mp->interaction > mp_batch_mode)
2405 incr (mp->selector); /* re-enable terminal output */
2406 }
2407 mp_print_ln (mp);
2408 }
2409
2410
2411 @ In anomalous cases, the print selector might be in an unknown state;
2412 the following subroutine is called to fix things just enough to keep
2413 running a bit longer.
2414
2415 @c
2416 void mp_normalize_selector (MP mp) {
2417 if (mp->log_opened)
2418 mp->selector = term_and_log;
2419 else
2420 mp->selector = term_only;
2421 if (mp->job_name == NULL)
2422 mp_open_log_file (mp);
2423 if (mp->interaction == mp_batch_mode)
2424 decr (mp->selector);
2425 }
2426
2427
2428 @ The following procedure prints \MP's last words before dying.
2429
2430 @<Error hand...@>=
2431 void mp_fatal_error (MP mp, const char *s) { /* prints |s|, and that's it */
2432 const char *hlp[] = {s, NULL} ;
2433 mp_normalize_selector (mp);
2434 if ( mp->interaction==mp_error_stop_mode )
2435 mp->interaction=mp_scroll_mode; /* no more interaction */
2436 if ( mp->log_opened )
2437 mp_error(mp, "Emergency stop", hlp, true);
2438 mp->history=mp_fatal_error_stop;
2439 mp_jump_out(mp); /* irrecoverable error */
2440 @.Emergency stop@>
2441 }
2442
2443
2444 @ @<Exported function ...@>=
2445 extern void mp_fatal_error (MP mp, const char *s);
2446
2447
2448 @ @<Internal library declarations@>=
2449 void mp_overflow (MP mp, const char *s, integer n);
2450
2451
2452 @ @<Error hand...@>=
2453 void mp_overflow (MP mp, const char *s, integer n) { /* stop due to finiteness */
2454 char msg[256];
2455 const char *hlp[] = {
2456 "If you really absolutely need more capacity,",
2457 "you can ask a wizard to enlarge me.",
2458 NULL };
2459 mp_normalize_selector (mp);
2460 mp_snprintf (msg, 256, "MetaPost capacity exceeded, sorry [%s=%d]", s, (int) n);
2461 @.MetaPost capacity exceeded ...@>
2462 if ( mp->interaction==mp_error_stop_mode )
2463 mp->interaction=mp_scroll_mode; /* no more interaction */
2464 if ( mp->log_opened )
2465 mp_error(mp, msg, hlp, true);
2466 mp->history=mp_fatal_error_stop;
2467 mp_jump_out(mp); /* irrecoverable error */
2468 }
2469
2470
2471 @ The program might sometime run completely amok, at which point there is
2472 no choice but to stop. If no previous error has been detected, that's bad
2473 news; a message is printed that is really intended for the \MP\
2474 maintenance person instead of the user (unless the user has been
2475 particularly diabolical). The index entries for `this can't happen' may
2476 help to pinpoint the problem.
2477 @^dry rot@>
2478
2479 @<Internal library ...@>=
2480 void mp_confusion (MP mp, const char *s);
2481
2482 @ Consistency check violated; |s| tells where.
2483 @<Error hand...@>=
2484 void mp_confusion (MP mp, const char *s) {
2485 char msg[256];
2486 const char *hlp[] = {
2487 "One of your faux pas seems to have wounded me deeply...",
2488 "in fact, I'm barely conscious. Please fix it and try again.",
2489 NULL };
2490 mp_normalize_selector (mp);
2491 if (mp->history < mp_error_message_issued) {
2492 mp_snprintf (msg, 256, "This can't happen (%s)", s);
2493 @.This can't happen@>
2494 hlp[0] = "I'm broken. Please show this to someone who can fix can fix";
2495 hlp[1] = NULL;
2496 } else {
2497 mp_snprintf (msg, 256, "I can\'t go on meeting you like this");
2498 @.I can't go on...@>
2499 }
2500 if ( mp->interaction==mp_error_stop_mode )
2501 mp->interaction=mp_scroll_mode; /* no more interaction */
2502 if ( mp->log_opened )
2503 mp_error(mp, msg, hlp, true);
2504 mp->history=mp_fatal_error_stop;
2505 mp_jump_out(mp); /* irrecoverable error */
2506 }
2507
2508
2509 @ Users occasionally want to interrupt \MP\ while it's running.
2510 If the runtime system allows this, one can implement
2511 a routine that sets the global variable |interrupt| to some nonzero value
2512 when such an interrupt is signaled. Otherwise there is probably at least
2513 a way to make |interrupt| nonzero using the C debugger.
2514 @^system dependencies@>
2515 @^debugging@>
2516
2517 @d check_interrupt { if ( mp->interrupt!=0 )
2518 mp_pause_for_instructions(mp); }
2519
2520 @<Global...@>=
2521 integer interrupt; /* should \MP\ pause for instructions? */
2522 boolean OK_to_interrupt; /* should interrupts be observed? */
2523 integer run_state; /* are we processing input ? */
2524 boolean finished; /* set true by |close_files_and_terminate| */
2525 boolean reading_preload;
2526
2527 @ @<Allocate or ...@>=
2528 mp->OK_to_interrupt = true;
2529 mp->finished = false;
2530
2531 @ When an interrupt has been detected, the program goes into its
2532 highest interaction level and lets the user have the full flexibility of
2533 the |error| routine. \MP\ checks for interrupts only at times when it is
2534 safe to do this.
2535
2536 @c
2537 static void mp_pause_for_instructions (MP mp) {
2538 const char *hlp[] = { "You rang?",
2539 "Try to insert some instructions for me (e.g.,`I show x'),",
2540 "unless you just want to quit by typing `X'.",
2541 NULL } ;
2542 if (mp->OK_to_interrupt) {
2543 mp->interaction = mp_error_stop_mode;
2544 if ((mp->selector == log_only) || (mp->selector == no_print))
2545 incr (mp->selector);
2546 @.Interruption@>
2547 mp_error (mp, "Interruption", hlp, false);
2548 mp->interrupt = 0;
2549 }
2550 }
2551
2552
2553 @* Arithmetic with scaled numbers.
2554 The principal computations performed by \MP\ are done entirely in terms of
2555 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2556 program can be carried out in exactly the same way on a wide variety of
2557 computers, including some small ones.
2558 @^small computers@>
2559
2560 But C does not rigidly define the |/| operation in the case of negative
2561 dividends; for example, the result of |(-2*n-1) / 2| is |-(n+1)| on some
2562 computers and |-n| on others (is this true ?). There are two principal
2563 types of arithmetic: ``translation-preserving,'' in which the identity
2564 |(a+q*b)/b=(a/b)+q| is valid; and ``negation-preserving,'' in which
2565 |(-a)/b=-(a/b)|. This leads to two \MP s, which can produce
2566 different results, although the differences should be negligible when the
2567 language is being used properly. The \TeX\ processor has been defined
2568 carefully so that both varieties of arithmetic will produce identical
2569 output, but it would be too inefficient to constrain \MP\ in a similar way.
2570
2571 @d inf_t ((math_data *)mp->math)->inf_t
2572
2573 @ A single computation might use several subroutine calls, and it is
2574 desirable to avoid producing multiple error messages in case of arithmetic
2575 overflow. So the routines below set the global variable |arith_error| to |true|
2576 instead of reporting errors directly to the user.
2577 @^overflow in arithmetic@>
2578
2579 @<Glob...@>=
2580 boolean arith_error; /* has arithmetic overflow occurred recently? */
2581
2582 @ @<Allocate or ...@>=
2583 mp->arith_error = false;
2584
2585 @ At crucial points the program will say |check_arith|, to test if
2586 an arithmetic error has been detected.
2587
2588 @d check_arith() do {
2589 if ( mp->arith_error )
2590 mp_clear_arith(mp);
2591 } while (0)@;
2592
2593 @c
2594 static void mp_clear_arith (MP mp) {
2595 const char *hlp[] = {
2596 "Uh, oh. A little while ago one of the quantities that I was",
2597 "computing got too large, so I'm afraid your answers will be",
2598 "somewhat askew. You'll probably have to adopt different",
2599 "tactics next time. But I shall try to carry on anyway.",
2600 NULL };
2601 mp_error (mp, "Arithmetic overflow", hlp, true);
2602 @.Arithmetic overflow@>
2603 mp->arith_error = false;
2604 }
2605
2606
2607 @ The definitions of these are set up by the math initialization.
2608
2609 @d arc_tol_k ((math_data *)mp->math)->arc_tol_k
2610 @d coef_bound_k ((math_data *)mp->math)->coef_bound_k
2611 @d coef_bound_minus_1 ((math_data *)mp->math)->coef_bound_minus_1
2612 @d sqrt_8_e_k ((math_data *)mp->math)->sqrt_8_e_k
2613 @d twelve_ln_2_k ((math_data *)mp->math)->twelve_ln_2_k
2614 @d twelvebits_3 ((math_data *)mp->math)->twelvebits_3
2615 @d one_k ((math_data *)mp->math)->one_k
2616 @d epsilon_t ((math_data *)mp->math)->epsilon_t
2617 @d unity_t ((math_data *)mp->math)->unity_t
2618 @d zero_t ((math_data *)mp->math)->zero_t
2619 @d two_t ((math_data *)mp->math)->two_t
2620 @d three_t ((math_data *)mp->math)->three_t
2621 @d half_unit_t ((math_data *)mp->math)->half_unit_t
2622 @d three_quarter_unit_t ((math_data *)mp->math)->three_quarter_unit_t
2623 @d twentysixbits_sqrt2_t ((math_data *)mp->math)->twentysixbits_sqrt2_t
2624 @d twentyeightbits_d_t ((math_data *)mp->math)->twentyeightbits_d_t
2625 @d twentysevenbits_sqrt2_d_t ((math_data *)mp->math)->twentysevenbits_sqrt2_d_t
2626 @d warning_limit_t ((math_data *)mp->math)->warning_limit_t
2627 @d precision_default ((math_data *)mp->math)->precision_default
2628 @d precision_max ((math_data *)mp->math)->precision_max
2629 @d precision_min ((math_data *)mp->math)->precision_min
2630
2631 @ In fact, the two sorts of scaling discussed above aren't quite
2632 sufficient; \MP\ has yet another, used internally to keep track of angles.
2633
2634 @ We often want to print two scaled quantities in parentheses,
2635 separated by a comma.
2636
2637 @<Basic printing...@>=
2638 void mp_print_two (MP mp, mp_number x, mp_number y) { /* prints `|(x,y)|' */
2639 mp_print_char (mp, xord ('('));
2640 print_number (x);
2641 mp_print_char (mp, xord (','));
2642 print_number (y);
2643 mp_print_char (mp, xord (')'));
2644 }
2645
2646
2647 @
2648 @d fraction_one_t ((math_data *)mp->math)->fraction_one_t
2649 @d fraction_half_t ((math_data *)mp->math)->fraction_half_t
2650 @d fraction_three_t ((math_data *)mp->math)->fraction_three_t
2651 @d fraction_four_t ((math_data *)mp->math)->fraction_four_t
2652
2653 @d one_eighty_deg_t ((math_data *)mp->math)->one_eighty_deg_t
2654 @d three_sixty_deg_t ((math_data *)mp->math)->three_sixty_deg_t
2655
2656 @ @<Local variables for initialization@>=
2657 integer k; /* all-purpose loop index */
2658
2659 @ And now let's complete our collection of numeric utility routines
2660 by considering random number generation.
2661 \MP\ generates pseudo-random numbers with the additive scheme recommended
2662 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
2663 results are random fractions between 0 and |fraction_one-1|, inclusive.
2664
2665 There's an auxiliary array |randoms| that contains 55 pseudo-random
2666 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
2667 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
2668 The global variable |j_random| tells which element has most recently
2669 been consumed.
2670 The global variable |random_seed| was introduced in version 0.9,
2671 for the sole reason of stressing the fact that the initial value of the
2672 random seed is system-dependent. The initialization code below will initialize
2673 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this
2674 is not good enough on modern fast machines that are capable of running
2675 multiple MetaPost processes within the same second.
2676 @^system dependencies@>
2677
2678 @<Glob...@>=
2679 mp_number randoms[55]; /* the last 55 random values generated */
2680 int j_random; /* the number of unused |randoms| */
2681
2682 @ @<Option variables@>=
2683 int random_seed; /* the default random seed */
2684
2685 @ @<Allocate or initialize ...@>=
2686 mp->random_seed = opt->random_seed;
2687 {
2688 int i;
2689 for (i=0;i<55;i++) {
2690 new_fraction (mp->randoms[i]);
2691 }
2692 }
2693
2694 @ @<Dealloc...@>=
2695 {
2696 int i;
2697 for (i=0;i<55;i++) {
2698 free_number (mp->randoms[i]);
2699 }
2700 }
2701
2702 @ @<Internal library ...@>=
2703 void mp_new_randoms (MP mp);
2704
2705 @ @c
2706 void mp_new_randoms (MP mp) {
2707 int k; /* index into |randoms| */
2708 mp_number x; /* accumulator */
2709 new_number (x);
2710 for (k = 0; k <= 23; k++) {
2711 set_number_from_substraction(x, mp->randoms[k], mp->randoms[k + 31]);
2712 if (number_negative(x))
2713 number_add (x, fraction_one_t);
2714 number_clone (mp->randoms[k], x);
2715 }
2716 for (k = 24; k <= 54; k++) {
2717 set_number_from_substraction(x, mp->randoms[k], mp->randoms[k - 24]);
2718 if (number_negative(x))
2719 number_add (x, fraction_one_t);
2720 number_clone (mp->randoms[k], x);
2721 }
2722 free_number (x);
2723 mp->j_random = 54;
2724 }
2725
2726 @ To consume a random fraction, the program below will say `|next_random|'.
2727 Now each number system has its own implementation,
2728 true to the original as much as possible.
2729
2730 Unused.
2731
2732 @c
2733 #if 0
2734 static void mp_next_random (MP mp, mp_number *ret) {
2735 if ( mp->j_random==0 )
2736 mp_new_randoms(mp);
2737 else
2738 decr(mp->j_random);
2739 number_clone (*ret, mp->randoms[mp->j_random]);
2740 }
2741 #endif
2742
2743 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
2744 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
2745
2746 Note that the call of |take_fraction| will produce the values 0 and~|x|
2747 with about half the probability that it will produce any other particular
2748 values between 0 and~|x|, because it rounds its answers.
2749 This is the original one,
2750 that stays as reference:
2751 As said before, now each number system has its own implementation.
2752
2753 Unused.
2754
2755 @c
2756 #if 0
2757 static void mp_unif_rand (MP mp, mp_number *ret, mp_number x_orig) {
2758 mp_number y; // trial value
2759 mp_number x, abs_x;
2760 mp_number u;
2761 new_fraction (y);
2762 new_number (x);
2763 new_number (abs_x);
2764 new_number (u);
2765 number_clone (x, x_orig);
2766 number_clone (abs_x, x);
2767 number_abs (abs_x);
2768 mp_next_random(mp, &u);
2769 take_fraction (y, abs_x, u);
2770 free_number (u);
2771 if (number_equal(y, abs_x)) {
2772 set_number_to_zero(*ret);
2773 } else if (number_positive(x)) {
2774 number_clone (*ret, y);
2775 } else {
2776 number_clone (*ret, y);
2777 number_negate (*ret);
2778 }
2779 free_number (abs_x);
2780 free_number (x);
2781 free_number (y);
2782 }
2783 #endif
2784
2785 @ Finally, a normal deviate with mean zero and unit standard deviation
2786 can readily be obtained with the ratio method (Algorithm 3.4.1R in
2787 {\sl The Art of Computer Programming\/}). This is the original one,
2788 that stays as reference:
2789 Now each number system has its own implementation,
2790 true to the original as much as possible.
2791
2792 Unused.
2793
2794 @c
2795 #if 0
2796 static void mp_norm_rand (MP mp, mp_number *ret) {
2797 mp_number ab_vs_cd;
2798 mp_number abs_x;
2799 mp_number u;
2800 mp_number r;
2801 mp_number la, xa;
2802 new_number (ab_vs_cd);
2803 new_number (la);
2804 new_number (xa);
2805 new_number (abs_x);
2806 new_number (u);
2807 new_number (r);
2808 do {
2809 do {
2810 mp_number v;
2811 new_number (v);
2812 mp_next_random(mp, &v);
2813 number_substract (v, fraction_half_t);
2814 take_fraction (xa, sqrt_8_e_k, v);
2815 free_number (v);
2816 mp_next_random(mp, &u);
2817 number_clone (abs_x, xa);
2818 number_abs (abs_x);
2819 } while (number_greaterequal (abs_x, u));
2820 make_fraction (r, xa, u);
2821 number_clone (xa, r);
2822 m_log (la, u);
2823 set_number_from_substraction(la, twelve_ln_2_k, la);
2824 ab_vs_cd (ab_vs_cd, one_k, la, xa, xa);
2825 } while (number_negative(ab_vs_cd));
2826 number_clone (*ret, xa);
2827 free_number (ab_vs_cd);
2828 free_number (r);
2829 free_number (abs_x);
2830 free_number (la);
2831 free_number (xa);
2832 free_number (u);
2833 }
2834 #endif
2835
2836 @* Packed data.
2837
2838 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
2839 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
2840
2841 @ The macros |qi| and |qo| are used for input to and output
2842 from quarterwords. These are legacy macros.
2843 @^system dependencies@>
2844
2845 @d qo(A) (A) /* to read eight bits from a quarterword */
2846 @d qi(A) (quarterword)(A) /* to store eight bits in a quarterword */
2847
2848 @ The reader should study the following definitions closely:
2849 @^system dependencies@>
2850
2851 @s mp_knot int
2852 @s mp_variable_type int
2853
2854 @<Types...@>=
2855 typedef struct mp_value_node_data *mp_value_node;
2856 typedef struct mp_node_data *mp_node;
2857 typedef struct mp_symbol_entry *mp_sym;
2858 typedef int16_t quarterword; /* 1/4 of a word */
2859 typedef int32_t halfword; /* 1/2 of a word */
2860 typedef struct {
2861 integer scale; /* only for |indep_scale|, used together with |serial| */
2862 halfword serial; /* only for |indep_value|, used together with |scale| */
2863 } mp_independent_data;
2864 typedef struct {
2865 mp_independent_data indep;
2866 mp_number n;
2867 mp_string str;
2868 mp_sym sym;
2869 mp_node node;
2870 mp_knot p;
2871 } mp_value_data;
2872 typedef struct {
2873 mp_variable_type type;
2874 mp_value_data data;
2875 } mp_value;
2876 typedef struct {
2877 quarterword b0, b1, b2, b3;
2878 } four_quarters;
2879 typedef union {
2880 integer sc;
2881 four_quarters qqqq;
2882 } font_data;
2883
2884
2885 @ The global variable |math_mode| has four settings, representing the
2886 math value type that will be used in this run.
2887
2888 the typedef for |mp_number| is here because it has to come very early.
2889
2890 @<Exported types@>=
2891 typedef enum {
2892 mp_math_scaled_mode = 0,
2893 mp_math_double_mode = 1,
2894 mp_math_binary_mode = 2,
2895 mp_math_decimal_mode = 3,
2896 mp_math_interval_mode = 4
2897 } mp_math_mode;
2898
2899 @ @<Option variables@>=
2900 int math_mode; /* math mode */
2901
2902 @ @<Allocate or initialize ...@>=
2903 mp->math_mode = opt->math_mode;
2904
2905 @ @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)@;
2906 @d xrealloc(P,A,B) mp_xrealloc(mp,P,(size_t)A,B)
2907 @d xmalloc(A,B) mp_xmalloc(mp,(size_t)A,B)
2908 @d xstrdup(A) mp_xstrdup(mp,A)
2909 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
2910
2911 @<Declare helpers@>=
2912 extern void mp_xfree (void *x);
2913 extern void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size);
2914 extern void *mp_xmalloc (MP mp, size_t nmem, size_t size);
2915 extern void mp_do_snprintf (char *str, int size, const char *fmt, ...);
2916 extern void *do_alloc_node(MP mp, size_t size);
2917
2918 @ This is an attempt to spend less time in |malloc()|:
2919
2920 @d max_num_token_nodes 1000
2921 @d max_num_pair_nodes 1000
2922 @d max_num_knot_nodes 1000
2923 @d max_num_value_nodes 1000
2924 @d max_num_symbolic_nodes 1000
2925
2926 @<Global ...@>=
2927 mp_node token_nodes;
2928 int num_token_nodes;
2929 mp_node pair_nodes;
2930 int num_pair_nodes;
2931 mp_knot knot_nodes;
2932 int num_knot_nodes;
2933 mp_node value_nodes;
2934 int num_value_nodes;
2935 mp_node symbolic_nodes;
2936 int num_symbolic_nodes;
2937
2938 @ @<Allocate or initialize ...@>=
2939 mp->token_nodes = NULL;
2940 mp->num_token_nodes = 0;
2941 mp->pair_nodes = NULL;
2942 mp->num_pair_nodes = 0;
2943 mp->knot_nodes = NULL;
2944 mp->num_knot_nodes = 0;
2945 mp->value_nodes = NULL;
2946 mp->num_value_nodes = 0;
2947 mp->symbolic_nodes = NULL;
2948 mp->num_symbolic_nodes = 0;
2949
2950 @ @<Dealloc ...@>=
2951 while (mp->value_nodes) {
2952 mp_node p = mp->value_nodes;
2953 mp->value_nodes = p->link;
2954 mp_free_node(mp,p,value_node_size);
2955 }
2956 while (mp->symbolic_nodes) {
2957 mp_node p = mp->symbolic_nodes;
2958 mp->symbolic_nodes = p->link;
2959 mp_free_node(mp,p,symbolic_node_size);
2960 }
2961 while (mp->pair_nodes) {
2962 mp_node p = mp->pair_nodes;
2963 mp->pair_nodes = p->link;
2964 mp_free_node(mp,p,pair_node_size);
2965 }
2966 while (mp->token_nodes) {
2967 mp_node p = mp->token_nodes;
2968 mp->token_nodes = p->link;
2969 mp_free_node(mp,p,token_node_size);
2970 }
2971 while (mp->knot_nodes) {
2972 mp_knot p = mp->knot_nodes;
2973 mp->knot_nodes = p->next;
2974 mp_free_knot(mp,p);
2975 }
2976
2977 @ This is a nicer way of allocating nodes.
2978
2979 @d malloc_node(A) do_alloc_node(mp,(A))
2980
2981 @c
2982 void *do_alloc_node (MP mp, size_t size) {
2983 void *p;
2984 p = xmalloc(1,size);
2985 add_var_used (size);
2986 ((mp_node)p)->link = NULL;
2987 ((mp_node)p)->has_number = 0;
2988 return p;
2989 }
2990
2991
2992 @ The |max_size_test| guards against overflow, on the assumption that
2993 |size_t| is at least 31bits wide.
2994
2995 @d max_size_test 0x7FFFFFFF
2996
2997 @c
2998 void mp_xfree (void *x) {
2999 if (x != NULL)
3000 free (x);
3001 }
3002 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3003 void *w;
3004 if ((max_size_test / size) < nmem) {
3005 mp_fputs ("Memory size overflow!\n", mp->err_out);
3006 mp->history = mp_fatal_error_stop;
3007 mp_jump_out (mp);
3008 }
3009 w = realloc (p, (nmem * size));
3010 if (w == NULL) {
3011 mp_fputs ("Out of memory!\n", mp->err_out);
3012 mp->history = mp_system_error_stop;
3013 mp_jump_out (mp);
3014 }
3015 return w;
3016 }
3017 void *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3018 void *w;
3019 #if MPOST_DEBUG
3020 if ((max_size_test / size) < nmem) {
3021 mp_fputs ("Memory size overflow!\n", mp->err_out);
3022 mp->history = mp_fatal_error_stop;
3023 mp_jump_out (mp);
3024 }
3025 #endif
3026 w = calloc(nmem, size); /* TODO: check an un-initialized use of |w| and replace |calloc| with |malloc|. */
3027 if (w == NULL) {
3028 mp_fputs ("Out of memory!\n", mp->err_out);
3029 mp->history = mp_system_error_stop;
3030 mp_jump_out (mp);
3031 }
3032 return w;
3033 }
3034
3035 @ @<Internal library declarations@>=
3036 /* Avoid warning on format truncation */
3037 #define mp_snprintf(...) (snprintf(__VA_ARGS__) < 0 ? abort() : (void)0)
3038
3039 @* Dynamic memory allocation.
3040
3041 The \MP\ system does nearly all of its own memory allocation, so that it
3042 can readily be transported into environments that do not have automatic
3043 facilities for strings, garbage collection, etc., and so that it can be in
3044 control of what error messages the user receives.
3045
3046 @s mp_name_type_type int
3047 @s mp_node_data int
3048
3049 @d MP_VOID (mp_node)(1) /* |NULL+1|, a |NULL| pointer different from |NULL| */
3050
3051 @d mp_link(A) (A)->link /* the |link| field of a node */
3052 @d set_mp_link(A,B) do {
3053 mp_node d = (B);
3054 /* |printf("set link of %p to %p on line %d\n", (A), d, __LINE__);| */
3055 mp_link((A)) = d;
3056 } while (0)@;
3057 @d mp_type(A) (A)->type /* identifies what kind of value this is */
3058 @d mp_name_type(A) (A)->name_type /* a clue to the name of this value */
3059
3060 @<MPlib internal header stuff@>=
3061 #define NODE_BODY \
3062 mp_variable_type type; \
3063 mp_name_type_type name_type; \
3064 uint16_t has_number; \
3065 struct mp_node_data *link@;
3066 @#@t\2\2\4\4@>
3067 typedef struct mp_node_data {
3068 NODE_BODY;@+@t}\6{@>
3069 mp_value_data data;
3070 } mp_node_data;
3071 typedef struct mp_node_data *mp_symbolic_node;
3072
3073 @ Users who wish to study the memory requirements of particular applications can
3074 can use the special features that keep track of current and maximum memory usage.
3075 \MP\ will report these statistics when |mp_tracing_stats| is positive.
3076
3077 @d add_var_used(a) do {
3078 mp->var_used+=(a);
3079 if (mp->var_used>mp->var_used_max) mp->var_used_max=mp->var_used;
3080 } while (0)@;
3081
3082 @<Glob...@>=
3083 size_t var_used; /* how much memory is in use */
3084 size_t var_used_max; /* how much memory was in use max */
3085
3086 @ These redirect to function to aid in debugging.
3087
3088 @c
3089 #if MPOST_DEBUG
3090 #define mp_sym_info(A) @[get_mp_sym_info(mp,(A))@]
3091 #define set_mp_sym_info(A,B) @[do_set_mp_sym_info(mp,(A),(B))@]
3092 #define mp_sym_sym(A) @[get_mp_sym_sym(mp,(A))@]
3093 #define set_mp_sym_sym(A,B) @[do_set_mp_sym_sym(mp,(A),(mp_sym)(B))@]
3094 static void do_set_mp_sym_info (MP mp, mp_node p, halfword v) {
3095 FUNCTION_TRACE3 ("do_set_mp_sym_info(%p,%d)\n", p, v);
3096 assert (p->type == mp_symbol_node);
3097 set_indep_value(p, v);
3098 }
3099 static halfword get_mp_sym_info (MP mp, mp_node p) {
3100 FUNCTION_TRACE3 ("%d = get_mp_sym_info(%p)\n", indep_value (p), p);
3101 assert (p->type == mp_symbol_node);
3102 return indep_value(p);
3103 }
3104 static void do_set_mp_sym_sym (MP mp, mp_node p, mp_sym v) {
3105 mp_symbolic_node pp = (mp_symbolic_node) p;
3106 FUNCTION_TRACE3 ("do_set_mp_sym_sym(%p,%p)\n", pp, v);
3107 assert (pp->type == mp_symbol_node);
3108 pp->data.sym = v;
3109 }
3110 static mp_sym get_mp_sym_sym (MP mp, mp_node p) {
3111 mp_symbolic_node pp = (mp_symbolic_node) p;
3112 FUNCTION_TRACE3 ("%p = get_mp_sym_sym(%p)\n", pp->data.sym, pp);
3113 assert (pp->type == mp_symbol_node);
3114 return pp->data.sym;
3115 }
3116 #else
3117 #define mp_sym_info(A) @[indep_value(A)@]
3118 #define set_mp_sym_info(A,B) @[set_indep_value(A, (B))@]
3119 #define mp_sym_sym(A) @[(A)->data.sym@]
3120 #define set_mp_sym_sym(A,B) @[(A)->data.sym = (mp_sym)(B)@]
3121 #endif
3122
3123 @ @<Declarations@>=
3124 #if MPOST_DEBUG
3125 static void do_set_mp_sym_info (MP mp, mp_node A, halfword B);
3126 static halfword get_mp_sym_info (MP mp, mp_node p);
3127 static void do_set_mp_sym_sym (MP mp, mp_node A, mp_sym B);
3128 static mp_sym get_mp_sym_sym (MP mp, mp_node p);
3129 #endif
3130
3131 @ The function |get_symbolic_node| returns a pointer to a new symbolic node whose
3132 |link| field is null.
3133 @^inner loop@>
3134
3135 @d symbolic_node_size sizeof(mp_node_data)
3136 @c
3137 static mp_node mp_get_symbolic_node (MP mp) {
3138 mp_symbolic_node p;
3139 if (mp->symbolic_nodes) {
3140 p = (mp_symbolic_node)mp->symbolic_nodes;
3141 mp->symbolic_nodes = p->link;
3142 mp->num_symbolic_nodes--;
3143 p->link = NULL;
3144 } else {
3145 p = malloc_node (symbolic_node_size);
3146 new_number(p->data.n);
3147 p->has_number = 1;
3148 }
3149 p->type = mp_symbol_node;
3150 p->name_type = mp_normal_sym;
3151 FUNCTION_TRACE2 ("%p = mp_get_symbolic_node()\n", p);
3152 return (mp_node) p;
3153 }
3154
3155
3156 @ Conversely, when some node |p| of size |s| is no longer needed,
3157 the operation |free_node(p,s)| will make its words available, by inserting
3158 |p| as a new empty node just before where |rover| now points.
3159
3160 A symbolic node is recycled by calling |free_symbolic_node|.
3161
3162 @c
3163 void mp_free_node (MP mp, mp_node p, size_t siz) { /* node liberation */
3164 FUNCTION_TRACE3 ("mp_free_node(%p,%d)\n", p, (int)siz);
3165 if (!p) return;
3166 mp->var_used -= siz;
3167 if (mp->math_mode > mp_math_double_mode) {
3168 if (p->has_number >= 1 && is_number(((mp_symbolic_node)p)->data.n)) {
3169 free_number(((mp_symbolic_node)p)->data.n);
3170 }
3171 if (p->has_number == 2 && is_number(((mp_value_node)p)->subscript_)) {
3172 free_number(((mp_value_node)p)->subscript_);
3173 }
3174 /* There was a quite large |switch| here first, but the |mp_dash_node|
3175 case was the only one that did anything ... */
3176 if (mp_type (p) == mp_dash_node_type) {
3177 free_number(((mp_dash_node)p)->start_x);
3178 free_number(((mp_dash_node)p)->stop_x);
3179 free_number(((mp_dash_node)p)->dash_y);
3180 }
3181 }
3182 xfree (p);
3183 }
3184 void mp_free_symbolic_node (MP mp, mp_node p) { /* node liberation */
3185 FUNCTION_TRACE2 ("mp_free_symbolic_node(%p)\n", p);
3186 if (!p) return;
3187 if (mp->num_symbolic_nodes < max_num_symbolic_nodes) {
3188 p->link = mp->symbolic_nodes;
3189 mp->symbolic_nodes = p;
3190 mp->num_symbolic_nodes++;
3191 return;
3192 }
3193 mp->var_used -= symbolic_node_size;
3194 xfree (p);
3195 }
3196 void mp_free_value_node (MP mp, mp_node p) { /* node liberation */
3197 FUNCTION_TRACE2 ("mp_free_value_node(%p)\n", p);
3198 if (!p) return;
3199 if (mp->num_value_nodes < max_num_value_nodes) {
3200 p->link = mp->value_nodes;
3201 mp->value_nodes = p;
3202 mp->num_value_nodes++;
3203 return;
3204 }
3205 mp->var_used -= value_node_size;
3206 assert(p->has_number == 2);
3207 if (mp->math_mode > mp_math_double_mode) {
3208 free_number(((mp_value_node)p)->data.n);
3209 free_number(((mp_value_node)p)->subscript_);
3210 }
3211 xfree (p);
3212 }
3213
3214
3215 @ @<Internal library declarations@>=
3216 void mp_free_node (MP mp, mp_node p, size_t siz);
3217 void mp_free_symbolic_node (MP mp, mp_node p);
3218 void mp_free_value_node (MP mp, mp_node p);
3219
3220 @* Memory layout.
3221 Some nodes are created statically, since static allocation is
3222 more efficient than dynamic allocation when we can get away with it.
3223
3224 @s mp_dash_node int
3225
3226 @<Glob...@>=
3227 mp_dash_node null_dash;
3228 mp_value_node dep_head;
3229 mp_node inf_val;
3230 mp_node zero_val;
3231 mp_node temp_val;
3232 mp_node end_attr;
3233 mp_node bad_vardef;
3234 mp_node temp_head;
3235 mp_node hold_head;
3236 mp_node spec_head;
3237
3238 @ The following code gets the memory off to a good start.
3239
3240 @<Initialize table entries@>=
3241 mp->spec_head = mp_get_symbolic_node (mp);
3242 mp->last_pending = mp->spec_head;
3243 mp->temp_head = mp_get_symbolic_node (mp);
3244 mp->hold_head = mp_get_symbolic_node (mp);
3245
3246 @ @<Free table entries@>=
3247 mp_free_symbolic_node (mp, mp->spec_head);
3248 mp_free_symbolic_node (mp, mp->temp_head);
3249 mp_free_symbolic_node (mp, mp->hold_head);
3250
3251 @ The procedure |flush_node_list(p)| frees an entire linked list of
3252 nodes that starts at a given position, until coming to a |NULL| pointer.
3253 @^inner loop@>
3254
3255 @c
3256 static void mp_flush_node_list (MP mp, mp_node p) {
3257 mp_node q; /* the node being recycled */
3258 FUNCTION_TRACE2 ("mp_flush_node_list(%p)\n", p);
3259 while (p != NULL) {
3260 q = p;
3261 p = p->link;
3262 if (q->type != mp_symbol_node)
3263 mp_free_token_node (mp, q);
3264 else
3265 mp_free_symbolic_node (mp, q);
3266 }
3267 }
3268
3269
3270 @* The command codes.
3271 Before we can go much further, we need to define symbolic names for the internal
3272 code numbers that represent the various commands obeyed by \MP. These codes
3273 are somewhat arbitrary, but not completely so. For example,
3274 some codes have been made adjacent so that |case| statements in the
3275 program need not consider cases that are widely spaced, or so that |case|
3276 statements can be replaced by |if| statements. A command can begin an
3277 expression if and only if its code lies between |min_primary_command| and
3278 |max_primary_command|, inclusive. The first token of a statement that doesn't
3279 begin with an expression has a command code between |min_command| and
3280 |max_statement_command|, inclusive. Anything less than |min_command| is
3281 eliminated during macro expansions, and anything no more than |max_pre_command|
3282 is eliminated when expanding \TeX\ material. Ranges such as
3283 |min_secondary_command..max_secondary_command| are used when parsing
3284 expressions, but the relative ordering within such a range is generally not
3285 critical.
3286
3287 The ordering of the highest-numbered commands
3288 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
3289 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
3290 for the smallest two commands. The ordering is also important in the ranges
3291 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
3292
3293 At any rate, here is the list, for future reference.
3294
3295 @d mp_max_command_code mp_stop
3296 @d mp_max_pre_command mp_mpx_break
3297 @d mp_min_command (mp_defined_macro+1)
3298 @d mp_max_statement_command mp_type_name
3299 @d mp_min_primary_command mp_type_name
3300 @d mp_min_suffix_token mp_internal_quantity
3301 @d mp_max_suffix_token mp_numeric_token
3302 @d mp_max_primary_command mp_plus_or_minus /* should also be |numeric_token+1| */
3303 @d mp_min_tertiary_command mp_plus_or_minus
3304 @d mp_max_tertiary_command mp_tertiary_binary
3305 @d mp_min_expression_command mp_left_brace
3306 @d mp_max_expression_command mp_equals
3307 @d mp_min_secondary_command mp_and_command
3308 @d mp_max_secondary_command mp_secondary_binary
3309 @d mp_end_of_statement (cur_cmd()>mp_comma)
3310
3311
3312 @<Enumeration types@>=
3313 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >=202311L)
3314 typedef enum mp_command_code: QUARTERWORD {
3315 #else
3316 typedef enum {
3317 #endif
3318 mp_start_tex=1, /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
3319 mp_etex_marker, /* end \TeX\ material (\&{etex}) */
3320 mp_mpx_break, /* stop reading an \.{MPX} file (\&{mpxbreak}) */
3321 mp_if_test, /* conditional text (\&{if}) */
3322 mp_fi_or_else, /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi}) */
3323 mp_input, /* input a source file (\&{input}, \&{endinput}) */
3324 mp_iteration, /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
3325 mp_repeat_loop, /* special command substituted for \&{endfor} */
3326 mp_exit_test, /* premature exit from a loop (\&{exitif}) */
3327 mp_relax, /* do nothing (\.{\char`\\}) */
3328 mp_scan_tokens, /* put a string into the input buffer */
3329 mp_runscript, /* put a script result string into the input buffer */
3330 mp_maketext, /* put a script result string into the input buffer */
3331 mp_expand_after, /* look ahead one token */
3332 mp_defined_macro, /* a macro defined by the user */
3333 mp_save_command, /* save a list of tokens (\&{save}) */
3334 mp_interim_command, /* save an internal quantity (\&{interim}) */
3335 mp_let_command, /* redefine a symbolic token (\&{let}) */
3336 mp_new_internal, /* define a new internal quantity (\&{newinternal}) */
3337 mp_macro_def, /* define a macro (\&{def}, \&{vardef}, etc.) */
3338 mp_ship_out_command, /* output a character (\&{shipout}) */
3339 mp_add_to_command, /* add to edges (\&{addto}) */
3340 mp_bounds_command, /* add bounding path to edges (\&{setbounds}, \&{clip}) */
3341 mp_tfm_command, /* command for font metric info (\&{ligtable}, etc.) */
3342 mp_protection_command, /* set protection flag (\&{outer}, \&{inner}) */
3343 mp_show_command, /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
3344 mp_mode_command, /* set interaction level (\&{batchmode}, etc.) */
3345 mp_random_seed, /* initialize random number generator (\&{randomseed}) */
3346 mp_message_command, /* communicate to user (\&{message}, \&{errmessage}) */
3347 mp_every_job_command, /* designate a starting token (\&{everyjob}) */
3348 mp_delimiters, /* define a pair of delimiters (\&{delimiters}) */
3349 mp_special_command, /* output special info (\&{special}) or font map info (\&{fontmapfile}, \&{fontmapline}) */
3350 mp_write_command, /* write text to a file (\&{write}) */
3351 mp_type_name, /* declare a type (\&{numeric}, \&{pair}, etc.) */
3352 mp_left_delimiter, /* the left delimiter of a matching pair */
3353 mp_begin_group, /* beginning of a group (\&{begingroup}) */
3354 mp_nullary, /* an operator without arguments (e.g., \&{normaldeviate}) */
3355 mp_unary, /* an operator with one argument (e.g., \&{sqrt}) */
3356 mp_str_op, /* convert a suffix to a string (\&{str}) */
3357 mp_void_op, /* convert a suffix to a boolean (\&{void}) */
3358 mp_cycle, /* close a cyclic path (\&{cycle}) */
3359 mp_primary_binary, /* binary operation taking `\&{of}' (e.g., \&{point}) */
3360 mp_capsule_token, /* a value that has been put into a token list */
3361 mp_string_token, /* a string constant (e.g., |"hello"|) */
3362 mp_internal_quantity, /* internal numeric parameter (e.g., \&{pausing}) */
3363 mp_tag_token, /* a symbolic token without a primitive meaning */
3364 mp_numeric_token, /* a numeric constant (e.g., \.{3.14159}) */
3365 mp_plus_or_minus, /* either `\.+' or `\.-' */
3366 mp_tertiary_secondary_macro, /* a macro defined by \&{secondarydef} */
3367 mp_tertiary_binary, /* an operator at the tertiary level (e.g., `\.{++}') */
3368 mp_left_brace, /* the operator `\.{\char`\{}' */
3369 mp_path_join, /* the operator `\.{..}' */
3370 mp_ampersand, /* the operator `\.\&' */
3371 mp_expression_tertiary_macro, /* a macro defined by \&{tertiarydef} */
3372 mp_expression_binary, /* an operator at the expression level (e.g., `\.<') */
3373 mp_equals, /* the operator `\.=' */
3374 mp_and_command, /* the operator `\&{and}' */
3375 mp_secondary_primary_macro, /* a macro defined by \&{primarydef} */
3376 mp_slash, /* the operator `\./' */
3377 mp_secondary_binary, /* an operator at the binary level (e.g., \&{shifted}) */
3378 mp_param_type, /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
3379 mp_controls, /* specify control points explicitly (\&{controls}) */
3380 mp_tension, /* specify tension between knots (\&{tension}) */
3381 mp_at_least, /* bounded tension value (\&{atleast}) */
3382 mp_curl_command, /* specify curl at an end knot (\&{curl}) */
3383 mp_macro_special, /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
3384 mp_right_delimiter, /* the right delimiter of a matching pair */
3385 mp_left_bracket, /* the operator `\.[' */
3386 mp_right_bracket, /* the operator `\.]' */
3387 mp_right_brace, /* the operator `\.{\char`\}}' */
3388 mp_with_option, /* option for filling (\&{withpen}, \&{withweight}, etc.) */
3389 mp_thing_to_add, /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
3390 mp_of_token, /* the operator `\&{of}' */
3391 mp_to_token, /* the operator `\&{to}' */
3392 mp_step_token, /* the operator `\&{step}' */
3393 mp_until_token, /* the operator `\&{until}' */
3394 mp_within_token, /* the operator `\&{within}' */
3395 mp_lig_kern_token, /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}', etc. */
3396 mp_assignment, /* the operator `\.{:=}' */
3397 mp_skip_to, /* the operation `\&{skipto}' */
3398 mp_bchar_label, /* the operator `\.{\char'174\char'174:}' */
3399 mp_double_colon, /* the operator `\.{::}' */
3400 mp_colon, /* the operator `\.:' */
3401 @#
3402 mp_comma, /* the operator `\.,', must be |colon+1| */
3403 mp_semicolon, /* the operator `\.;', must be |comma+1| */
3404 mp_end_group, /* end a group (\&{endgroup}), must be |semicolon+1| */
3405 mp_stop, /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
3406 mp_outer_tag, /* protection code added to command code */
3407 mp_undefined_cs,@[@] /* protection code added to command code */
3408 } mp_command_code;
3409
3410 @ Variables and capsules in \MP\ have a variety of ``types,''
3411 distinguished by the code numbers defined here. These numbers are also
3412 not completely arbitrary. Things that get expanded must have types
3413 |>mp_independent|; a type remaining after expansion is numeric if and only if
3414 its code number is at least |numeric_type|; objects containing numeric
3415 parts must have types between |transform_type| and |pair_type|;
3416 all other types must be smaller than |transform_type|; and among the types
3417 that are not unknown or vacuous, the smallest two must be |boolean_type|
3418 and |string_type| in that order.
3419
3420 @d unknown_tag 1 /* this constant is added to certain type codes below */
3421 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
3422 case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
3423
3424 @<Enumeration types@>=
3425 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >=202311L)
3426 typedef enum mp_variable_type: QUARTERWORD {
3427 #else
3428 typedef enum {
3429 #endif
3430 mp_undefined = 0, /* no type has been declared */
3431 mp_vacuous, /* no expression was present */
3432 mp_boolean_type, /* \&{boolean} with a known value */
3433 mp_unknown_boolean,
3434 mp_string_type, /* \&{string} with a known value */
3435 mp_unknown_string,
3436 mp_pen_type, /* \&{pen} with a known value */
3437 mp_unknown_pen,
3438 mp_path_type, /* \&{path} with a known value */
3439 mp_unknown_path,
3440 mp_picture_type, /* \&{picture} with a known value */
3441 mp_unknown_picture,
3442 mp_transform_type, /* \&{transform} variable or capsule */
3443 mp_color_type, /* \&{color} variable or capsule */
3444 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
3445 mp_pair_type, /* \&{pair} variable or capsule */
3446 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
3447 mp_known, /* \&{numeric} with a known value */
3448 mp_dependent, /* a linear combination with |fraction| coefficients */
3449 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
3450 mp_independent, /* \&{numeric} with unknown value */
3451 mp_token_list, /* variable name or suffix argument or text argument */
3452 mp_structured, /* variable with subscripts and attributes */
3453 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
3454 mp_suffixed_macro, /* variable defined with \&{vardef} and \.{\AT!\#} */
3455 /* here are some generic node types */
3456 mp_symbol_node,
3457 mp_token_node_type,
3458 mp_value_node_type,
3459 mp_attr_node_type,
3460 mp_subscr_node_type,
3461 mp_pair_node_type,
3462 mp_transform_node_type,
3463 mp_color_node_type,
3464 mp_cmykcolor_node_type,
3465 /* it is important that the next 7 items remain in this order, for export */
3466 mp_fill_node_type,
3467 mp_stroked_node_type,
3468 mp_text_node_type,
3469 mp_start_clip_node_type,
3470 mp_start_bounds_node_type,
3471 mp_stop_clip_node_type,
3472 mp_stop_bounds_node_type,
3473 mp_dash_node_type,
3474 mp_dep_node_type,
3475 mp_if_node_type,
3476 mp_edge_header_node_type,@[@]
3477 } mp_variable_type;
3478
3479 @ @<Declarations@>=
3480 static void mp_print_type (MP mp, quarterword t);
3481
3482 @ @<Basic printing procedures@>=
3483 static const char *mp_type_string (quarterword t) {
3484 const char *s = NULL;
3485 switch (t) {
3486 case mp_undefined:
3487 s = "undefined";
3488 break;
3489 case mp_vacuous:
3490 s = "vacuous";
3491 break;
3492 case mp_boolean_type:
3493 s = "boolean";
3494 break;
3495 case mp_unknown_boolean:
3496 s = "unknown boolean";
3497 break;
3498 case mp_string_type:
3499 s = "string";
3500 break;
3501 case mp_unknown_string:
3502 s = "unknown string";
3503 break;
3504 case mp_pen_type:
3505 s = "pen";
3506 break;
3507 case mp_unknown_pen:
3508 s = "unknown pen";
3509 break;
3510 case mp_path_type:
3511 s = "path";
3512 break;
3513 case mp_unknown_path:
3514 s = "unknown path";
3515 break;
3516 case mp_picture_type:
3517 s = "picture";
3518 break;
3519 case mp_unknown_picture:
3520 s = "unknown picture";
3521 break;
3522 case mp_transform_type:
3523 s = "transform";
3524 break;
3525 case mp_color_type:
3526 s = "color";
3527 break;
3528 case mp_cmykcolor_type:
3529 s = "cmykcolor";
3530 break;
3531 case mp_pair_type:
3532 s = "pair";
3533 break;
3534 case mp_known:
3535 s = "known numeric";
3536 break;
3537 case mp_dependent:
3538 s = "dependent";
3539 break;
3540 case mp_proto_dependent:
3541 s = "proto-dependent";
3542 break;
3543 case mp_numeric_type:
3544 s = "numeric";
3545 break;
3546 case mp_independent:
3547 s = "independent";
3548 break;
3549 case mp_token_list:
3550 s = "token list";
3551 break;
3552 case mp_structured:
3553 s = "mp_structured";
3554 break;
3555 case mp_unsuffixed_macro:
3556 s = "unsuffixed macro";
3557 break;
3558 case mp_suffixed_macro:
3559 s = "suffixed macro";
3560 break;
3561 case mp_symbol_node:
3562 s = "symbol node";
3563 break;
3564 case mp_token_node_type:
3565 s = "token node";
3566 break;
3567 case mp_value_node_type:
3568 s = "value node";
3569 break;
3570 case mp_attr_node_type:
3571 s = "attribute node";
3572 break;
3573 case mp_subscr_node_type:
3574 s = "subscript node";
3575 break;
3576 case mp_pair_node_type:
3577 s = "pair node";
3578 break;
3579 case mp_transform_node_type:
3580 s = "transform node";
3581 break;
3582 case mp_color_node_type:
3583 s = "color node";
3584 break;
3585 case mp_cmykcolor_node_type:
3586 s = "cmykcolor node";
3587 break;
3588 case mp_fill_node_type:
3589 s = "fill node";
3590 break;
3591 case mp_stroked_node_type:
3592 s = "stroked node";
3593 break;
3594 case mp_text_node_type:
3595 s = "text node";
3596 break;
3597 case mp_start_clip_node_type:
3598 s = "start clip node";
3599 break;
3600 case mp_start_bounds_node_type:
3601 s = "start bounds node";
3602 break;
3603 case mp_stop_clip_node_type:
3604 s = "stop clip node";
3605 break;
3606 case mp_stop_bounds_node_type:
3607 s = "stop bounds node";
3608 break;
3609 case mp_dash_node_type:
3610 s = "dash node";
3611 break;
3612 case mp_dep_node_type:
3613 s = "dependency node";
3614 break;
3615 case mp_if_node_type:
3616 s = "if node";
3617 break;
3618 case mp_edge_header_node_type:
3619 s = "edge header node";
3620 break;
3621 default:
3622 {
3623 char ss[256];
3624 mp_snprintf (ss, 256, "<unknown type %d>", t);
3625 s = strdup(ss);
3626 }
3627 break;
3628 }
3629 return s;
3630 }
3631 void mp_print_type (MP mp, quarterword t) {
3632 if (t >= 0 && t <= mp_edge_header_node_type)
3633 mp_print (mp, mp_type_string (t));
3634 else
3635 mp_print (mp, "unknown");
3636 }
3637
3638
3639 @ Values inside \MP\ are stored in non-symbolic nodes that have a |name_type|
3640 as well as a |type|. The possibilities for |name_type| are defined
3641 here; they will be explained in more detail later.
3642
3643 @<Enumeration types...@>=
3644 typedef enum {
3645 mp_root = 0, /* |name_type| at the top level of a variable */
3646 mp_saved_root, /* same, when the variable has been saved */
3647 mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
3648 mp_subscr, /* |name_type| in a subscript node */
3649 mp_attr, /* |name_type| in an attribute node */
3650 mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
3651 mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
3652 mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
3653 mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
3654 mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
3655 mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
3656 mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
3657 mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
3658 mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
3659 mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
3660 mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
3661 mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
3662 mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
3663 mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
3664 mp_capsule, /* |name_type| in stashed-away subexpressions */
3665 mp_token, /* |name_type| in a numeric token or string token */
3666 /* Symbolic nodes also have |name_type|, which is a different enumeration */
3667 mp_normal_sym,
3668 mp_internal_sym, /* for values of internals */
3669 mp_macro_sym, /* for macro names */
3670 mp_expr_sym, /* for macro parameters if type |expr| */
3671 mp_suffix_sym, /* for macro parameters if type |suffix| */
3672 mp_text_sym, /* for macro parameters if type |text| */
3673 @<Operation codes@>
3674 } mp_name_type_type;
3675
3676 @ Primitive operations that produce values have a secondary identification
3677 code in addition to their command code; it's something like genera and species.
3678 For example, `\.*' has the command code |primary_binary|, and its
3679 secondary identification is |times|. The secondary codes start such that
3680 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
3681 are used as operators as well as type identifications. The relative values
3682 are not critical, except for |true_code..false_code|, |or_op..and_op|,
3683 and |filled_op..bounded_op|. The restrictions are that
3684 |and_op-false_code=or_op-true_code|, that the ordering of
3685 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
3686 and the ordering of |filled_op..bounded_op| must match that of the code
3687 values they test for.
3688
3689 @d mp_min_of mp_substring_of
3690
3691 @<Operation codes@>=
3692 mp_true_code, /* operation code for \.{true} */
3693 mp_false_code, /* operation code for \.{false} */
3694 mp_null_picture_code, /* operation code for \.{nullpicture} */
3695 mp_null_pen_code, /* operation code for \.{nullpen} */
3696 mp_read_string_op, /* operation code for \.{readstring} */
3697 mp_pen_circle, /* operation code for \.{pencircle} */
3698 mp_normal_deviate, /* operation code for \.{normaldeviate} */
3699 mp_read_from_op, /* operation code for \.{readfrom} */
3700 mp_close_from_op, /* operation code for \.{closefrom} */
3701 mp_odd_op, /* operation code for \.{odd} */
3702 mp_known_op, /* operation code for \.{known} */
3703 mp_unknown_op, /* operation code for \.{unknown} */
3704 mp_not_op, /* operation code for \.{not} */
3705 mp_decimal, /* operation code for \.{decimal} */
3706 mp_reverse, /* operation code for \.{reverse} */
3707 mp_make_path_op, /* operation code for \.{makepath} */
3708 mp_make_pen_op, /* operation code for \.{makepen} */
3709 mp_oct_op, /* operation code for \.{oct} */
3710 mp_hex_op, /* operation code for \.{hex} */
3711 mp_ASCII_op, /* operation code for \.{ASCII} */
3712 mp_char_op, /* operation code for \.{char} */
3713 mp_length_op, /* operation code for \.{length} */
3714 mp_turning_op, /* operation code for \.{turningnumber} */
3715 mp_color_model_part, /* operation code for \.{colormodel} */
3716 mp_x_part, /* operation code for \.{xpart} */
3717 mp_y_part, /* operation code for \.{ypart} */
3718 mp_xx_part, /* operation code for \.{xxpart} */
3719 mp_xy_part, /* operation code for \.{xypart} */
3720 mp_yx_part, /* operation code for \.{yxpart} */
3721 mp_yy_part, /* operation code for \.{yypart} */
3722 mp_red_part, /* operation code for \.{redpart} */
3723 mp_green_part, /* operation code for \.{greenpart} */
3724 mp_blue_part, /* operation code for \.{bluepart} */
3725 mp_cyan_part, /* operation code for \.{cyanpart} */
3726 mp_magenta_part, /* operation code for \.{magentapart} */
3727 mp_yellow_part, /* operation code for \.{yellowpart} */
3728 mp_black_part, /* operation code for \.{blackpart} */
3729 mp_grey_part, /* operation code for \.{greypart} */
3730 mp_font_part, /* operation code for \.{fontpart} */
3731 mp_text_part, /* operation code for \.{textpart} */
3732 mp_path_part, /* operation code for \.{pathpart} */
3733 mp_pen_part, /* operation code for \.{penpart} */
3734 mp_dash_part, /* operation code for \.{dashpart} */
3735 mp_prescript_part, /* operation code for \.{prescriptpart} */
3736 mp_postscript_part, /* operation code for \.{postscriptpart} */
3737 mp_sqrt_op, /* operation code for \.{sqrt} */
3738 mp_m_exp_op, /* operation code for \.{mexp} */
3739 mp_m_log_op, /* operation code for \.{mlog} */
3740 mp_sin_d_op, /* operation code for \.{sind} */
3741 mp_cos_d_op, /* operation code for \.{cosd} */
3742 mp_floor_op, /* operation code for \.{floor} */
3743 mp_uniform_deviate, /* operation code for \.{uniformdeviate} */
3744 mp_char_exists_op, /* operation code for \.{charexists} */
3745 mp_font_size, /* operation code for \.{fontsize} */
3746 mp_ll_corner_op, /* operation code for \.{llcorner} */
3747 mp_lr_corner_op, /* operation code for \.{lrcorner} */
3748 mp_ul_corner_op, /* operation code for \.{ulcorner} */
3749 mp_ur_corner_op, /* operation code for \.{urcorner} */
3750 mp_arc_length, /* operation code for \.{arclength} */
3751 mp_angle_op, /* operation code for \.{angle} */
3752 mp_cycle_op, /* operation code for \.{cycle} */
3753 mp_filled_op, /* operation code for \.{filled} */
3754 mp_stroked_op, /* operation code for \.{stroked} */
3755 mp_textual_op, /* operation code for \.{textual} */
3756 mp_clipped_op, /* operation code for \.{clipped} */
3757 mp_bounded_op, /* operation code for \.{bounded} */
3758 mp_plus, /* operation code for \.+ */
3759 mp_minus, /* operation code for \.- */
3760 mp_times, /* operation code for \.* */
3761 mp_over, /* operation code for \./ */
3762 mp_pythag_add, /* operation code for \.{++} */
3763 mp_pythag_sub, /* operation code for \.{+-+} */
3764 mp_or_op, /* operation code for \.{or} */
3765 mp_and_op, /* operation code for \.{and} */
3766 mp_less_than, /* operation code for \.< */
3767 mp_less_or_equal, /* operation code for \.{<=} */
3768 mp_greater_than, /* operation code for \.> */
3769 mp_greater_or_equal, /* operation code for \.{>=} */
3770 mp_equal_to, /* operation code for \.= */
3771 mp_unequal_to, /* operation code for \.{<>} */
3772 mp_concatenate, /* operation code for \.\& */
3773 mp_rotated_by, /* operation code for \.{rotated} */
3774 mp_slanted_by, /* operation code for \.{slanted} */
3775 mp_scaled_by, /* operation code for \.{scaled} */
3776 mp_shifted_by, /* operation code for \.{shifted} */
3777 mp_transformed_by, /* operation code for \.{transformed} */
3778 mp_x_scaled, /* operation code for \.{xscaled} */
3779 mp_y_scaled, /* operation code for \.{yscaled} */
3780 mp_z_scaled, /* operation code for \.{zscaled} */
3781 mp_in_font, /* operation code for \.{infont} */
3782 mp_intersect, /* operation code for \.{intersectiontimes} */
3783 mp_double_dot, /* operation code for improper \.{..} */
3784 mp_substring_of, /* operation code for \.{substring} */
3785 mp_subpath_of, /* operation code for \.{subpath} */
3786 mp_direction_time_of, /* operation code for \.{directiontime} */
3787 mp_point_of, /* operation code for \.{point} */
3788 mp_precontrol_of, /* operation code for \.{precontrol} */
3789 mp_postcontrol_of, /* operation code for \.{postcontrol} */
3790 mp_pen_offset_of, /* operation code for \.{penoffset} */
3791 mp_arc_time_of, /* operation code for \.{arctime} */
3792 mp_version, /* operation code for \.{mpversion} */
3793 mp_envelope_of, /* operation code for \.{envelope} */
3794 mp_boundingpath_of, /* operation code for \.{boundingpath} */
3795 mp_glyph_infont, /* operation code for \.{glyph} */
3796 mp_kern_flag, /* operation code for \.{kern} */
3797 mp_m_get_left_endpoint_op, /* math interval new primitives operation code for \.{interval\_get\_left\_endpoint} */
3798 mp_m_get_right_endpoint_op, /* math interval new primitives operation code for \.{interval\_get\_right\_endpoint} */
3799 mp_interval_set_op,@[@] /* math interval new primitives operation code for \.{interval\_set} */
3800
3801
3802 @ @c
3803 static void mp_print_op (MP mp, quarterword c) {
3804 if (c <= mp_numeric_type) {
3805 mp_print_type (mp, c);
3806 } else {
3807 switch (c) {
3808 case mp_true_code:
3809 mp_print (mp, "true");
3810 break;
3811 case mp_false_code:
3812 mp_print (mp, "false");
3813 break;
3814 case mp_null_picture_code:
3815 mp_print (mp, "nullpicture");
3816 break;
3817 case mp_null_pen_code:
3818 mp_print (mp, "nullpen");
3819 break;
3820 case mp_read_string_op:
3821 mp_print (mp, "readstring");
3822 break;
3823 case mp_pen_circle:
3824 mp_print (mp, "pencircle");
3825 break;
3826 case mp_normal_deviate:
3827 mp_print (mp, "normaldeviate");
3828 break;
3829 case mp_read_from_op:
3830 mp_print (mp, "readfrom");
3831 break;
3832 case mp_close_from_op:
3833 mp_print (mp, "closefrom");
3834 break;
3835 case mp_odd_op:
3836 mp_print (mp, "odd");
3837 break;
3838 case mp_known_op:
3839 mp_print (mp, "known");
3840 break;
3841 case mp_unknown_op:
3842 mp_print (mp, "unknown");
3843 break;
3844 case mp_not_op:
3845 mp_print (mp, "not");
3846 break;
3847 case mp_decimal:
3848 mp_print (mp, "decimal");
3849 break;
3850 case mp_reverse:
3851 mp_print (mp, "reverse");
3852 break;
3853 case mp_make_path_op:
3854 mp_print (mp, "makepath");
3855 break;
3856 case mp_make_pen_op:
3857 mp_print (mp, "makepen");
3858 break;
3859 case mp_oct_op:
3860 mp_print (mp, "oct");
3861 break;
3862 case mp_hex_op:
3863 mp_print (mp, "hex");
3864 break;
3865 case mp_ASCII_op:
3866 mp_print (mp, "ASCII");
3867 break;
3868 case mp_char_op:
3869 mp_print (mp, "char");
3870 break;
3871 case mp_length_op:
3872 mp_print (mp, "length");
3873 break;
3874 case mp_turning_op:
3875 mp_print (mp, "turningnumber");
3876 break;
3877 case mp_x_part:
3878 mp_print (mp, "xpart");
3879 break;
3880 case mp_y_part:
3881 mp_print (mp, "ypart");
3882 break;
3883 case mp_xx_part:
3884 mp_print (mp, "xxpart");
3885 break;
3886 case mp_xy_part:
3887 mp_print (mp, "xypart");
3888 break;
3889 case mp_yx_part:
3890 mp_print (mp, "yxpart");
3891 break;
3892 case mp_yy_part:
3893 mp_print (mp, "yypart");
3894 break;
3895 case mp_red_part:
3896 mp_print (mp, "redpart");
3897 break;
3898 case mp_green_part:
3899 mp_print (mp, "greenpart");
3900 break;
3901 case mp_blue_part:
3902 mp_print (mp, "bluepart");
3903 break;
3904 case mp_cyan_part:
3905 mp_print (mp, "cyanpart");
3906 break;
3907 case mp_magenta_part:
3908 mp_print (mp, "magentapart");
3909 break;
3910 case mp_yellow_part:
3911 mp_print (mp, "yellowpart");
3912 break;
3913 case mp_black_part:
3914 mp_print (mp, "blackpart");
3915 break;
3916 case mp_grey_part:
3917 mp_print (mp, "greypart");
3918 break;
3919 case mp_color_model_part:
3920 mp_print (mp, "colormodel");
3921 break;
3922 case mp_font_part:
3923 mp_print (mp, "fontpart");
3924 break;
3925 case mp_text_part:
3926 mp_print (mp, "textpart");
3927 break;
3928 case mp_prescript_part:
3929 mp_print (mp, "prescriptpart");
3930 break;
3931 case mp_postscript_part:
3932 mp_print (mp, "postscriptpart");
3933 break;
3934 case mp_path_part:
3935 mp_print (mp, "pathpart");
3936 break;
3937 case mp_pen_part:
3938 mp_print (mp, "penpart");
3939 break;
3940 case mp_dash_part:
3941 mp_print (mp, "dashpart");
3942 break;
3943 case mp_sqrt_op:
3944 mp_print (mp, "sqrt");
3945 break;
3946 case mp_m_exp_op:
3947 mp_print (mp, "mexp");
3948 break;
3949 case mp_m_log_op:
3950 mp_print (mp, "mlog");
3951 break;
3952 case mp_sin_d_op:
3953 mp_print (mp, "sind");
3954 break;
3955 case mp_cos_d_op:
3956 mp_print (mp, "cosd");
3957 break;
3958 case mp_floor_op:
3959 mp_print (mp, "floor");
3960 break;
3961 case mp_uniform_deviate:
3962 mp_print (mp, "uniformdeviate");
3963 break;
3964 case mp_char_exists_op:
3965 mp_print (mp, "charexists");
3966 break;
3967 case mp_font_size:
3968 mp_print (mp, "fontsize");
3969 break;
3970 case mp_ll_corner_op:
3971 mp_print (mp, "llcorner");
3972 break;
3973 case mp_lr_corner_op:
3974 mp_print (mp, "lrcorner");
3975 break;
3976 case mp_ul_corner_op:
3977 mp_print (mp, "ulcorner");
3978 break;
3979 case mp_ur_corner_op:
3980 mp_print (mp, "urcorner");
3981 break;
3982 case mp_arc_length:
3983 mp_print (mp, "arclength");
3984 break;
3985 case mp_angle_op:
3986 mp_print (mp, "angle");
3987 break;
3988 case mp_cycle_op:
3989 mp_print (mp, "cycle");
3990 break;
3991 case mp_filled_op:
3992 mp_print (mp, "filled");
3993 break;
3994 case mp_stroked_op:
3995 mp_print (mp, "stroked");
3996 break;
3997 case mp_textual_op:
3998 mp_print (mp, "textual");
3999 break;
4000 case mp_clipped_op:
4001 mp_print (mp, "clipped");
4002 break;
4003 case mp_bounded_op:
4004 mp_print (mp, "bounded");
4005 break;
4006 case mp_plus:
4007 mp_print_char (mp, xord ('+'));
4008 break;
4009 case mp_minus:
4010 mp_print_char (mp, xord ('-'));
4011 break;
4012 case mp_times:
4013 mp_print_char (mp, xord ('*'));
4014 break;
4015 case mp_over:
4016 mp_print_char (mp, xord ('/'));
4017 break;
4018 case mp_pythag_add:
4019 mp_print (mp, "++");
4020 break;
4021 case mp_pythag_sub:
4022 mp_print (mp, "+-+");
4023 break;
4024 case mp_or_op:
4025 mp_print (mp, "or");
4026 break;
4027 case mp_and_op:
4028 mp_print (mp, "and");
4029 break;
4030 case mp_less_than:
4031 mp_print_char (mp, xord ('<'));
4032 break;
4033 case mp_less_or_equal:
4034 mp_print (mp, "<=");
4035 break;
4036 case mp_greater_than:
4037 mp_print_char (mp, xord ('>'));
4038 break;
4039 case mp_greater_or_equal:
4040 mp_print (mp, ">=");
4041 break;
4042 case mp_equal_to:
4043 mp_print_char (mp, xord ('='));
4044 break;
4045 case mp_unequal_to:
4046 mp_print (mp, "<>");
4047 break;
4048 case mp_concatenate:
4049 mp_print (mp, "&");
4050 break;
4051 case mp_rotated_by:
4052 mp_print (mp, "rotated");
4053 break;
4054 case mp_slanted_by:
4055 mp_print (mp, "slanted");
4056 break;
4057 case mp_scaled_by:
4058 mp_print (mp, "scaled");
4059 break;
4060 case mp_shifted_by:
4061 mp_print (mp, "shifted");
4062 break;
4063 case mp_transformed_by:
4064 mp_print (mp, "transformed");
4065 break;
4066 case mp_x_scaled:
4067 mp_print (mp, "xscaled");
4068 break;
4069 case mp_y_scaled:
4070 mp_print (mp, "yscaled");
4071 break;
4072 case mp_z_scaled:
4073 mp_print (mp, "zscaled");
4074 break;
4075 case mp_in_font:
4076 mp_print (mp, "infont");
4077 break;
4078 case mp_intersect:
4079 mp_print (mp, "intersectiontimes");
4080 break;
4081 case mp_substring_of:
4082 mp_print (mp, "substring");
4083 break;
4084 case mp_subpath_of:
4085 mp_print (mp, "subpath");
4086 break;
4087 case mp_direction_time_of:
4088 mp_print (mp, "directiontime");
4089 break;
4090 case mp_point_of:
4091 mp_print (mp, "point");
4092 break;
4093 case mp_precontrol_of:
4094 mp_print (mp, "precontrol");
4095 break;
4096 case mp_postcontrol_of:
4097 mp_print (mp, "postcontrol");
4098 break;
4099 case mp_pen_offset_of:
4100 mp_print (mp, "penoffset");
4101 break;
4102 case mp_arc_time_of:
4103 mp_print (mp, "arctime");
4104 break;
4105 case mp_version:
4106 mp_print (mp, "mpversion");
4107 break;
4108 case mp_envelope_of:
4109 mp_print (mp, "envelope");
4110 break;
4111 case mp_boundingpath_of:
4112 mp_print (mp, "boundingpath");
4113 break;
4114 case mp_glyph_infont:
4115 mp_print (mp, "glyph");
4116 break;
4117 /* math interval new primitives */
4118 case mp_m_get_left_endpoint_op:
4119 mp_print (mp, "interval_get_left_endpoint");
4120 break;
4121 case mp_m_get_right_endpoint_op:
4122 mp_print (mp, "interval_get_right_endpoint");
4123 break;
4124 case mp_interval_set_op:
4125 mp_print (mp, "interval_set");
4126 break;
4127 default:
4128 mp_print (mp, "..");
4129 break;
4130 }
4131 }
4132 }
4133
4134
4135 @ \MP\ also has a bunch of internal parameters that a user might want to
4136 fuss with. Every such parameter has an identifying code number, defined here.
4137
4138 @<Types...@>=
4139 enum mp_given_internal {
4140 mp_output_template = 1, /* a string set up by \&{outputtemplate} */
4141 mp_output_filename, /* the output file name, accessible as \&{outputfilename} */
4142 mp_output_format, /* the output format set up by \&{outputformat} */
4143 mp_output_format_options, /* the output format options set up by \&{outputformatoptions} */
4144 mp_number_system, /* the number system as set up by \&{numbersystem} */
4145 mp_number_precision, /* the number system precision as set up by \&{numberprecision} */
4146 mp_job_name, /* the perceived jobname, as set up from the options structure,
4147 the name of the input file, or by \&{jobname} */
4148 mp_tracing_titles, /* show titles online when they appear */
4149 mp_tracing_equations, /* show each variable when it becomes known */
4150 mp_tracing_capsules, /* show capsules too */
4151 mp_tracing_choices, /* show the control points chosen for paths */
4152 mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
4153 mp_tracing_commands, /* show commands and operations before they are performed */
4154 mp_tracing_restores, /* show when a variable or internal is restored */
4155 mp_tracing_macros, /* show macros before they are expanded */
4156 mp_tracing_output, /* show digitized edges as they are output */
4157 mp_tracing_stats, /* show memory usage at end of job */
4158 mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
4159 mp_tracing_online, /* show long diagnostics on terminal and in the log file */
4160 mp_year, /* the current year (e.g., 1984) */
4161 mp_month, /* the current month (e.g., 3 $\equiv$ March) */
4162 mp_day, /* the current day of the month */
4163 mp_time, /* the number of minutes past midnight when this job started */
4164 mp_hour, /* the number of hours past midnight when this job started */
4165 mp_minute, /* the number of minutes in that hour when this job started */
4166 mp_char_code, /* the number of the next character to be output */
4167 mp_char_ext, /* the extension code of the next character to be output */
4168 mp_char_wd, /* the width of the next character to be output */
4169 mp_char_ht, /* the height of the next character to be output */
4170 mp_char_dp, /* the depth of the next character to be output */
4171 mp_char_ic, /* the italic correction of the next character to be output */
4172 mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
4173 mp_pausing, /* positive to display lines on the terminal before they are read */
4174 mp_showstopping, /* positive to stop after each \&{show} command */
4175 mp_fontmaking, /* positive if font metric output is to be produced */
4176 mp_texscriptmode, /* controls spacing in texmode */
4177 mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4178 mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
4179 mp_miterlimit, /* controls miter length as in \ps */
4180 mp_warning_check, /* controls error message when variable value is large */
4181 mp_boundary_char, /* the right boundary character for ligatures */
4182 mp_prologues, /* positive to output conforming PostScript using built-in fonts */
4183 mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4184 mp_default_color_model, /* the default color model for unspecified items */
4185 mp_restore_clip_color,
4186 mp_procset, /* whether or not create PostScript command shortcuts */
4187 mp_hppp, /* horizontal pixels per point (for png output) */
4188 mp_vppp, /* vertical pixels per point (for png output) */
4189 mp_gtroffmode,@[@] /* whether the user specified \.{-troff} on the command line */
4190 };
4191 typedef struct {
4192 mp_value v;
4193 char *intname;
4194 } mp_internal;
4195
4196
4197 @ @<MPlib internal header stuff@>=
4198 #define internal_value(A) @[mp->internal[(A)].v.data.n@]
4199 #define set_internal_from_number(A,B) do { \
4200 number_clone (internal_value ((A)),(B));\
4201 } while (0)@;
4202 #define internal_string(A) @[(mp_string)mp->internal[(A)].v.data.str@]
4203 #define set_internal_string(A,B) @[mp->internal[(A)].v.data.str=(B)@]
4204 #define internal_name(A) @[mp->internal[(A)].intname@]
4205 #define set_internal_name(A,B) @[mp->internal[(A)].intname=(B)@]
4206 #define internal_type(A) @[(mp_variable_type)mp->internal[(A)].v.type@]
4207 #define set_internal_type(A,B) @[mp->internal[(A)].v.type=(B)@]
4208 #define set_internal_from_cur_exp(A) do { \
4209 if (internal_type ((A)) == mp_string_type) { \
4210 add_str_ref (cur_exp_str ()); \
4211 set_internal_string ((A), cur_exp_str ()); \
4212 } else { \
4213 set_internal_from_number ((A), cur_exp_value_number ()); \
4214 } \
4215 } while (0)@;
4216
4217
4218
4219 @ @d max_given_internal mp_gtroffmode
4220
4221 @<Glob...@>=
4222 mp_internal *internal; /* the values of internal quantities */
4223 int int_ptr; /* the maximum internal quantity defined so far */
4224 int max_internal; /* current maximum number of internal quantities */
4225
4226 @ @<Option variables@>=
4227 int troff_mode;
4228
4229 @ @<Allocate or initialize ...@>=
4230 mp->max_internal = 2 * max_given_internal;
4231 mp->internal = xmalloc ((mp->max_internal + 1), sizeof (mp_internal));
4232 memset (mp->internal, 0,
4233 (size_t) (mp->max_internal + 1) * sizeof (mp_internal));
4234 {
4235 int i;
4236 for (i = 1; i <= mp->max_internal; i++) {
4237 new_number(mp->internal[i].v.data.n);
4238 }
4239 for (i = 1; i <= max_given_internal; i++) {
4240 set_internal_type (i, mp_known);
4241 }
4242 }
4243 set_internal_type (mp_output_format, mp_string_type);
4244 set_internal_type (mp_output_filename, mp_string_type);
4245 set_internal_type (mp_output_format_options, mp_string_type);
4246 set_internal_type (mp_output_template, mp_string_type);
4247 set_internal_type (mp_number_system, mp_string_type);
4248 set_internal_type (mp_job_name, mp_string_type);
4249 mp->troff_mode = (opt->troff_mode > 0 ? true : false);
4250
4251 @ @<Exported function ...@>=
4252 int mp_troff_mode (MP mp);
4253
4254 @ @c
4255 int mp_troff_mode (MP mp) {
4256 return mp->troff_mode;
4257 }
4258
4259
4260 @ @<Set initial ...@>=
4261 mp->int_ptr = max_given_internal;
4262
4263 @ The symbolic names for internal quantities are put into \MP's hash table
4264 by using a routine called |primitive|, which will be defined later. Let us
4265 enter them now, so that we don't have to list all those names again
4266 anywhere else.
4267
4268 @<Put each of \MP's primitives into the hash table@>=
4269 mp_primitive (mp, "tracingtitles", mp_internal_quantity, mp_tracing_titles);
4270 @:tracingtitles_}{\&{tracingtitles} primitive@>
4271 mp_primitive (mp, "tracingequations", mp_internal_quantity, mp_tracing_equations);
4272 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
4273 mp_primitive (mp, "tracingcapsules", mp_internal_quantity, mp_tracing_capsules);
4274 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
4275 mp_primitive (mp, "tracingchoices", mp_internal_quantity, mp_tracing_choices);
4276 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
4277 mp_primitive (mp, "tracingspecs", mp_internal_quantity, mp_tracing_specs);
4278 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
4279 mp_primitive (mp, "tracingcommands", mp_internal_quantity, mp_tracing_commands);
4280 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
4281 mp_primitive (mp, "tracingrestores", mp_internal_quantity, mp_tracing_restores);
4282 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
4283 mp_primitive (mp, "tracingmacros", mp_internal_quantity, mp_tracing_macros);
4284 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
4285 mp_primitive (mp, "tracingoutput", mp_internal_quantity, mp_tracing_output);
4286 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
4287 mp_primitive (mp, "tracingstats", mp_internal_quantity, mp_tracing_stats);
4288 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
4289 mp_primitive (mp, "tracinglostchars", mp_internal_quantity, mp_tracing_lost_chars);
4290 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
4291 mp_primitive (mp, "tracingonline", mp_internal_quantity, mp_tracing_online);
4292 @:mp_tracing_online_}{\&{tracingonline} primitive@>
4293 mp_primitive (mp, "year", mp_internal_quantity, mp_year);
4294 @:mp_year_}{\&{year} primitive@>
4295 mp_primitive (mp, "month", mp_internal_quantity, mp_month);
4296 @:mp_month_}{\&{month} primitive@>
4297 mp_primitive (mp, "day", mp_internal_quantity, mp_day);
4298 @:mp_day_}{\&{day} primitive@>
4299 mp_primitive (mp, "time", mp_internal_quantity, mp_time);
4300 @:time_}{\&{time} primitive@>
4301 mp_primitive (mp, "hour", mp_internal_quantity, mp_hour);
4302 @:hour_}{\&{hour} primitive@>
4303 mp_primitive (mp, "minute", mp_internal_quantity, mp_minute);
4304 @:minute_}{\&{minute} primitive@>
4305 mp_primitive (mp, "charcode", mp_internal_quantity, mp_char_code);
4306 @:mp_char_code_}{\&{charcode} primitive@>
4307 mp_primitive (mp, "charext", mp_internal_quantity, mp_char_ext);
4308 @:mp_char_ext_}{\&{charext} primitive@>
4309 mp_primitive (mp, "charwd", mp_internal_quantity, mp_char_wd);
4310 @:mp_char_wd_}{\&{charwd} primitive@>
4311 mp_primitive (mp, "charht", mp_internal_quantity, mp_char_ht);
4312 @:mp_char_ht_}{\&{charht} primitive@>
4313 mp_primitive (mp, "chardp", mp_internal_quantity, mp_char_dp);
4314 @:mp_char_dp_}{\&{chardp} primitive@>
4315 mp_primitive (mp, "charic", mp_internal_quantity, mp_char_ic);
4316 @:mp_char_ic_}{\&{charic} primitive@>
4317 mp_primitive (mp, "designsize", mp_internal_quantity, mp_design_size);
4318 @:mp_design_size_}{\&{designsize} primitive@>
4319 mp_primitive (mp, "pausing", mp_internal_quantity, mp_pausing);
4320 @:mp_pausing_}{\&{pausing} primitive@>
4321 mp_primitive (mp, "showstopping", mp_internal_quantity, mp_showstopping);
4322 @:mp_showstopping_}{\&{showstopping} primitive@>
4323 mp_primitive (mp, "fontmaking", mp_internal_quantity, mp_fontmaking);
4324 @:mp_fontmaking_}{\&{fontmaking} primitive@>
4325 mp_primitive (mp, "texscriptmode", mp_internal_quantity, mp_texscriptmode);
4326 @:mp_texscriptmode_}{\&{texscriptmode} primitive@>
4327 mp_primitive (mp, "linejoin", mp_internal_quantity, mp_linejoin);
4328 @:mp_linejoin_}{\&{linejoin} primitive@>
4329 mp_primitive (mp, "linecap", mp_internal_quantity, mp_linecap);
4330 @:mp_linecap_}{\&{linecap} primitive@>
4331 mp_primitive (mp, "miterlimit", mp_internal_quantity, mp_miterlimit);
4332 @:mp_miterlimit_}{\&{miterlimit} primitive@>
4333 mp_primitive (mp, "warningcheck", mp_internal_quantity, mp_warning_check);
4334 @:mp_warning_check_}{\&{warningcheck} primitive@>
4335 mp_primitive (mp, "boundarychar", mp_internal_quantity, mp_boundary_char);
4336 @:mp_boundary_char_}{\&{boundarychar} primitive@>
4337 mp_primitive (mp, "prologues", mp_internal_quantity, mp_prologues);
4338 @:mp_prologues_}{\&{prologues} primitive@>
4339 mp_primitive (mp, "truecorners", mp_internal_quantity, mp_true_corners);
4340 @:mp_true_corners_}{\&{truecorners} primitive@>
4341 mp_primitive (mp, "mpprocset", mp_internal_quantity, mp_procset);
4342 @:mp_procset_}{\&{mpprocset} primitive@>
4343 mp_primitive (mp, "troffmode", mp_internal_quantity, mp_gtroffmode);
4344 @:troffmode_}{\&{troffmode} primitive@>
4345 mp_primitive (mp, "defaultcolormodel", mp_internal_quantity, mp_default_color_model);
4346 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
4347 mp_primitive (mp, "restoreclipcolor", mp_internal_quantity, mp_restore_clip_color);
4348 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
4349 mp_primitive (mp, "outputtemplate", mp_internal_quantity, mp_output_template);
4350 @:mp_output_template_}{\&{outputtemplate} primitive@>
4351 mp_primitive (mp, "outputfilename", mp_internal_quantity, mp_output_filename);
4352 @:mp_output_filename_}{\&{outputfilename} primitive@>
4353 mp_primitive (mp, "numbersystem", mp_internal_quantity, mp_number_system);
4354 @:mp_number_system_}{\&{numbersystem} primitive@>
4355 mp_primitive (mp, "numberprecision", mp_internal_quantity, mp_number_precision);
4356 @:mp_number_precision_}{\&{numberprecision} primitive@>
4357 mp_primitive (mp, "outputformat", mp_internal_quantity, mp_output_format);
4358 @:mp_output_format_}{\&{outputformat} primitive@>
4359 mp_primitive (mp, "outputformatoptions", mp_internal_quantity, mp_output_format_options);
4360 @:mp_output_format_options_}{\&{outputformatoptions} primitive@>
4361 mp_primitive (mp, "jobname", mp_internal_quantity, mp_job_name);
4362 @:mp_job_name_}{\&{jobname} primitive@>
4363 mp_primitive (mp, "hppp", mp_internal_quantity, mp_hppp);
4364 @:mp_hppp_}{\&{hppp} primitive@>
4365 mp_primitive (mp, "vppp", mp_internal_quantity, mp_vppp);
4366 @:mp_vppp_}{\&{vppp} primitive@>
4367
4368
4369 @ Colors can be specified in four color models. In the special
4370 case of |no_model|, MetaPost does not output any color operator to
4371 the postscript output.
4372
4373 Note: these values are passed directly on to |with_option|. This only
4374 works because the other possible values passed to |with_option| are
4375 8 and 10 respectively (from |with_pen| and |with_picture|).
4376
4377 There is a first state, that is only used for |gs_colormodel|. It flags
4378 the fact that there has not been any kind of color specification by
4379 the user so far in the game.
4380
4381 @<MPlib header stuff@>=
4382 enum mp_color_model {
4383 mp_no_model = 1,
4384 mp_grey_model = 3,
4385 mp_rgb_model = 5,
4386 mp_cmyk_model = 7,
4387 mp_uninitialized_model = 9
4388 };
4389
4390
4391 @ @<Initialize table entries@>=
4392 set_internal_from_number (mp_default_color_model, unity_t);
4393 number_multiply_int (internal_value (mp_default_color_model), mp_rgb_model);
4394 number_clone (internal_value (mp_restore_clip_color), unity_t);
4395 number_clone (internal_value (mp_hppp), unity_t);
4396 number_clone (internal_value (mp_vppp), unity_t);
4397 set_internal_string (mp_output_template, mp_intern (mp, "%j.%c"));
4398 set_internal_string (mp_output_filename, mp_intern (mp, ""));
4399 set_internal_string (mp_output_format, mp_intern (mp, "eps"));
4400 set_internal_string (mp_output_format_options, mp_intern (mp, ""));
4401 set_internal_string (mp_number_system, mp_intern (mp, "scaled"));
4402 set_internal_from_number (mp_number_precision, precision_default);
4403 set_internal_from_number (mp_texscriptmode, unity_t);
4404 #if MPOST_DEBUG
4405 number_clone (internal_value (mp_tracing_titles), three_t);
4406 number_clone (internal_value (mp_tracing_equations), three_t);
4407 number_clone (internal_value (mp_tracing_capsules), three_t);
4408 number_clone (internal_value (mp_tracing_choices), three_t);
4409 number_clone (internal_value (mp_tracing_specs), three_t);
4410 number_clone (internal_value (mp_tracing_commands), three_t);
4411 number_clone (internal_value (mp_tracing_restores), three_t);
4412 number_clone (internal_value (mp_tracing_macros), three_t);
4413 number_clone (internal_value (mp_tracing_output), three_t);
4414 number_clone (internal_value (mp_tracing_stats), three_t);
4415 number_clone (internal_value (mp_tracing_lost_chars), three_t);
4416 number_clone (internal_value (mp_tracing_online), three_t);
4417 #endif
4418
4419 @ Well, we do have to list the names one more time, for use in symbolic
4420 printouts.
4421
4422 @<Initialize table...@>=
4423 set_internal_name (mp_tracing_titles, xstrdup ("tracingtitles"));
4424 set_internal_name (mp_tracing_equations, xstrdup ("tracingequations"));
4425 set_internal_name (mp_tracing_capsules, xstrdup ("tracingcapsules"));
4426 set_internal_name (mp_tracing_choices, xstrdup ("tracingchoices"));
4427 set_internal_name (mp_tracing_specs, xstrdup ("tracingspecs"));
4428 set_internal_name (mp_tracing_commands, xstrdup ("tracingcommands"));
4429 set_internal_name (mp_tracing_restores, xstrdup ("tracingrestores"));
4430 set_internal_name (mp_tracing_macros, xstrdup ("tracingmacros"));
4431 set_internal_name (mp_tracing_output, xstrdup ("tracingoutput"));
4432 set_internal_name (mp_tracing_stats, xstrdup ("tracingstats"));
4433 set_internal_name (mp_tracing_lost_chars, xstrdup ("tracinglostchars"));
4434 set_internal_name (mp_tracing_online, xstrdup ("tracingonline"));
4435 set_internal_name (mp_year, xstrdup ("year"));
4436 set_internal_name (mp_month, xstrdup ("month"));
4437 set_internal_name (mp_day, xstrdup ("day"));
4438 set_internal_name (mp_time, xstrdup ("time"));
4439 set_internal_name (mp_hour, xstrdup ("hour"));
4440 set_internal_name (mp_minute, xstrdup ("minute"));
4441 set_internal_name (mp_char_code, xstrdup ("charcode"));
4442 set_internal_name (mp_char_ext, xstrdup ("charext"));
4443 set_internal_name (mp_char_wd, xstrdup ("charwd"));
4444 set_internal_name (mp_char_ht, xstrdup ("charht"));
4445 set_internal_name (mp_char_dp, xstrdup ("chardp"));
4446 set_internal_name (mp_char_ic, xstrdup ("charic"));
4447 set_internal_name (mp_design_size, xstrdup ("designsize"));
4448 set_internal_name (mp_pausing, xstrdup ("pausing"));
4449 set_internal_name (mp_showstopping, xstrdup ("showstopping"));
4450 set_internal_name (mp_fontmaking, xstrdup ("fontmaking"));
4451 set_internal_name (mp_texscriptmode, xstrdup ("texscriptmode"));
4452 set_internal_name (mp_linejoin, xstrdup ("linejoin"));
4453 set_internal_name (mp_linecap, xstrdup ("linecap"));
4454 set_internal_name (mp_miterlimit, xstrdup ("miterlimit"));
4455 set_internal_name (mp_warning_check, xstrdup ("warningcheck"));
4456 set_internal_name (mp_boundary_char, xstrdup ("boundarychar"));
4457 set_internal_name (mp_prologues, xstrdup ("prologues"));
4458 set_internal_name (mp_true_corners, xstrdup ("truecorners"));
4459 set_internal_name (mp_default_color_model, xstrdup ("defaultcolormodel"));
4460 set_internal_name (mp_procset, xstrdup ("mpprocset"));
4461 set_internal_name (mp_gtroffmode, xstrdup ("troffmode"));
4462 set_internal_name (mp_restore_clip_color, xstrdup ("restoreclipcolor"));
4463 set_internal_name (mp_output_template, xstrdup ("outputtemplate"));
4464 set_internal_name (mp_output_filename, xstrdup ("outputfilename"));
4465 set_internal_name (mp_output_format, xstrdup ("outputformat"));
4466 set_internal_name (mp_output_format_options, xstrdup ("outputformatoptions"));
4467 set_internal_name (mp_job_name, xstrdup ("jobname"));
4468 set_internal_name (mp_number_system, xstrdup ("numbersystem"));
4469 set_internal_name (mp_number_precision, xstrdup ("numberprecision"));
4470 set_internal_name (mp_hppp, xstrdup ("hppp"));
4471 set_internal_name (mp_vppp, xstrdup ("vppp"));
4472
4473
4474 @ The following procedure, which is called just before \MP\ initializes its
4475 input and output, establishes the initial values of the date and time.
4476 @^system dependencies@>
4477
4478 Note that the values are |scaled| integers. Hence \MP\ can no longer
4479 be used after the year 32767.
4480
4481 @c
4482 #if defined(_MSC_VER)
4483 #define strtoull _strtoui64
4484 #endif
4485 static void mp_fix_date_and_time (MP mp) {
4486 char *source_date_epoch;
4487 time_t epoch;
4488 char *endptr;
4489 struct tm *tmptr;
4490 source_date_epoch = getenv("SOURCE_DATE_EPOCH");
4491 if (source_date_epoch) {
4492 errno = 0;
4493 epoch = (time_t)strtoull(source_date_epoch, &endptr, 10);
4494 if (*endptr != '\0' || errno != 0) {
4495 FATAL1("invalid epoch-seconds-timezone value for environment variable $SOURCE_DATE_EPOCH: %s",
4496 source_date_epoch);
4497 }
4498 /* there is a limit 3001.01.01:2059 for epoch in Microsoft C */
4499 #if defined(_MSC_VER)
4500 if (epoch > 32535291599ULL)
4501 epoch = 32535291599ULL;
4502 #endif
4503 tmptr = gmtime (&epoch);
4504 } else {
4505 epoch = time ((time_t *) 0);
4506 tmptr = localtime (&epoch);
4507 }
4508 set_internal_from_number (mp_time, unity_t);
4509 number_multiply_int (internal_value(mp_time), (tmptr->tm_hour * 60 + tmptr->tm_min));
4510 set_internal_from_number (mp_hour, unity_t);
4511 number_multiply_int (internal_value(mp_hour), (tmptr->tm_hour));
4512 set_internal_from_number (mp_minute, unity_t);
4513 number_multiply_int (internal_value(mp_minute), (tmptr->tm_min));
4514 set_internal_from_number (mp_day, unity_t);
4515 number_multiply_int (internal_value(mp_day), (tmptr->tm_mday));
4516 set_internal_from_number (mp_month, unity_t);
4517 number_multiply_int (internal_value(mp_month), (tmptr->tm_mon + 1));
4518 set_internal_from_number (mp_year, unity_t);
4519 number_multiply_int (internal_value(mp_year), (tmptr->tm_year + 1900));
4520 }
4521
4522
4523 @ @<Declarations@>=
4524 static void mp_fix_date_and_time (MP mp);
4525
4526 @ \MP\ is occasionally supposed to print diagnostic information that
4527 goes only into the transcript file, unless |mp_tracing_online| is positive.
4528 Now that we have defined |mp_tracing_online| we can define
4529 two routines that adjust the destination of print commands:
4530
4531 @<Declarations@>=
4532 static void mp_begin_diagnostic (MP mp);
4533 static void mp_end_diagnostic (MP mp, boolean blank_line);
4534 static void mp_print_diagnostic (MP mp, const char *s, const char *t,
4535 boolean nuline);
4536
4537 @ @<Basic printing...@>=
4538 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
4539 mp->old_setting = mp->selector;
4540 if (number_nonpositive(internal_value (mp_tracing_online))
4541 && (mp->selector == term_and_log)) {
4542 decr (mp->selector);
4543 if (mp->history == mp_spotless)
4544 mp->history = mp_warning_issued;
4545 }
4546 }
4547 @#
4548 void mp_end_diagnostic (MP mp, boolean blank_line) {
4549 /* restore proper conditions after tracing */
4550 mp_print_nl (mp, "");
4551 if (blank_line)
4552 mp_print_ln (mp);
4553 mp->selector = mp->old_setting;
4554 }
4555
4556
4557 @ @<Glob...@>=
4558 unsigned int old_setting;
4559
4560 @ We will occasionally use |begin_diagnostic| in connection with line-number
4561 printing, as follows. (The parameter |s| is typically |"Path"| or
4562 |"Cycle spec"|, etc.)
4563
4564 @<Basic printing...@>=
4565 void mp_print_diagnostic (MP mp, const char *s, const char *t, boolean nuline) {
4566 mp_begin_diagnostic (mp);
4567 if (nuline)
4568 mp_print_nl (mp, s);
4569 else
4570 mp_print (mp, s);
4571 mp_print (mp, " at line ");
4572 mp_print_int (mp, mp_true_line (mp));
4573 mp_print (mp, t);
4574 mp_print_char (mp, xord (':'));
4575 }
4576
4577
4578 @ The 256 |ASCII_code| characters are grouped into classes by means of
4579 the |char_class| table. Individual class numbers have no semantic
4580 or syntactic significance, except in a few instances defined here.
4581 There's also |max_class|, which can be used as a basis for additional
4582 class numbers in nonstandard extensions of \MP.
4583
4584 @d digit_class 0 /* the class number of \.{0123456789} */
4585 @d period_class 1 /* the class number of `\..' */
4586 @d space_class 2 /* the class number of spaces and nonstandard characters */
4587 @d percent_class 3 /* the class number of `\.\%' */
4588 @d string_class 4 /* the class number of `\."' */
4589 @d right_paren_class 8 /* the class number of `\.)' */
4590 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
4591 @d letter_class 9 /* letters and the underline character */
4592 @d mp_left_bracket_class 17 /* `\.[' */
4593 @d mp_right_bracket_class 18 /* `\.]' */
4594 @d invalid_class 20 /* bad character in the input */
4595 @d max_class 20 /* the largest class number */
4596
4597 @d semicolon_class 6 /* the class number of `\.;' */
4598
4599 @<Glob...@>=
4600 #define digit_class 0 /* the class number of \.{0123456789} */
4601 int char_class[256]; /* the class numbers */
4602
4603 @ If changes are made to accommodate non-ASCII character sets, they should
4604 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
4605 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
4606 @^system dependencies@>
4607
4608 @<Set initial ...@>=
4609 for (k = '0'; k <= '9'; k++)
4610 mp->char_class[k] = digit_class;
4611 mp->char_class['.'] = period_class;
4612 mp->char_class[' '] = space_class;
4613 mp->char_class['%'] = percent_class;
4614 mp->char_class['"'] = string_class;
4615 mp->char_class[','] = 5;
4616 mp->char_class[';'] = 6;
4617 mp->char_class['('] = 7;
4618 mp->char_class[')'] = right_paren_class;
4619 for (k = 'A'; k <= 'Z'; k++)
4620 mp->char_class[k] = letter_class;
4621 for (k = 'a'; k <= 'z'; k++)
4622 mp->char_class[k] = letter_class;
4623 mp->char_class['_'] = letter_class;
4624 mp->char_class['<'] = 10;
4625 mp->char_class['='] = 10;
4626 mp->char_class['>'] = 10;
4627 mp->char_class[':'] = 10;
4628 mp->char_class['|'] = 10;
4629 mp->char_class['`'] = 11;
4630 mp->char_class['\''] = 11;
4631 mp->char_class['+'] = 12;
4632 mp->char_class['-'] = 12;
4633 mp->char_class['/'] = 13;
4634 mp->char_class['*'] = 13;
4635 mp->char_class['\\'] = 13;
4636 mp->char_class['!'] = 14;
4637 mp->char_class['?'] = 14;
4638 mp->char_class['#'] = 15;
4639 mp->char_class['&'] = 15;
4640 mp->char_class['@@'] = 15;
4641 mp->char_class['$'] = 15;
4642 mp->char_class['^'] = 16;
4643 mp->char_class['~'] = 16;
4644 mp->char_class['['] = mp_left_bracket_class;
4645 mp->char_class[']'] = mp_right_bracket_class;
4646 mp->char_class['{'] = 19;
4647 mp->char_class['}'] = 19;
4648 for (k = 0; k < ' '; k++)
4649 mp->char_class[k] = invalid_class;
4650 mp->char_class['\t'] = space_class;
4651 mp->char_class['\f'] = space_class;
4652 for (i=127;i<=255;i++) {
4653 mp->char_class[i] = mp->utf8_mode ? letter_class : invalid_class;
4654 }
4655
4656 @* The hash table.
4657
4658 Symbolic tokens are stored in and retrieved from an AVL tree. This
4659 is not as fast as an actual hash table, but it is easily extensible.
4660
4661 A symbolic token contains a pointer to the |mp_string| that
4662 contains the string representation of the symbol, a |halfword|
4663 that holds the current command value of the token, and an
4664 |mp_value| for the associated equivalent.
4665
4666 @d set_text(A) do {
4667 FUNCTION_TRACE3 ("set_text(%p, %p)\n",(A),(B));
4668 (A)->text=(B) ;
4669 } while (0)@;
4670
4671 @d set_eq_type(A,B) do {
4672 FUNCTION_TRACE3 ("set_eq_type(%p, %d)\n",(A),(B));
4673 (A)->type=(B) ;
4674 } while (0)@;
4675
4676 @d set_equiv(A,B) do {
4677 FUNCTION_TRACE3 ("set_equiv(%p, %d)\n",(A),(B));
4678 (A)->v.data.node=NULL ;
4679 (A)->v.data.indep.serial=(B);
4680 } while (0)@;
4681
4682 @d set_equiv_node(A,B) do {
4683 FUNCTION_TRACE3 ("set_equiv_node(%p, %p)\n",(A),(B));
4684 (A)->v.data.node=(B) ;
4685 (A)->v.data.indep.serial=0;
4686 } while (0)@;
4687
4688 @d set_equiv_sym(A,B) do {
4689 FUNCTION_TRACE3 ("set_equiv_sym(%p, %p)\n",(A),(B));
4690 (A)->v.data.node=(mp_node)(B);
4691 (A)->v.data.indep.serial=0;
4692 } while (0)@;
4693
4694 @ @c
4695 #if MPOST_DEBUG
4696 #define text(A) @[do_get_text(mp, (A))@]
4697 #define eq_type(A) @[do_get_eq_type(mp, (A))@]
4698 #define equiv(A) @[do_get_equiv(mp, (A))@]
4699 #define equiv_node(A) @[do_get_equiv_node(mp, (A))@]
4700 #define equiv_sym(A) @[do_get_equiv_sym(mp, (A))@]
4701 static mp_string do_get_text (MP mp, mp_sym A) {
4702 FUNCTION_TRACE3 ("%d = do_get_text(%p)\n",A->text,A);
4703 return A->text;
4704 }
4705 static halfword do_get_eq_type (MP mp, mp_sym A) {
4706 FUNCTION_TRACE3 ("%d = do_get_eq_type(%p)\n",A->type,A);
4707 return A->type;
4708 }
4709 static halfword do_get_equiv (MP mp, mp_sym A) {
4710 FUNCTION_TRACE3 ("%d = do_get_equiv(%p)\n",A->v.data.indep.serial,A);
4711 return A->v.data.indep.serial;
4712 }
4713 static mp_node do_get_equiv_node (MP mp, mp_sym A) {
4714 FUNCTION_TRACE3 ("%p = do_get_equiv_node(%p)\n",A->v.data.node,A);
4715 return A->v.data.node;
4716 }
4717 static mp_sym do_get_equiv_sym (MP mp, mp_sym A) {
4718 FUNCTION_TRACE3 ("%p = do_get_equiv_sym(%p)\n",A->v.data.node,A);
4719 return (mp_sym)A->v.data.node;
4720 }
4721 #else
4722 #define text(A) @[(A)->text@]
4723 #define eq_type(A) @[(A)->type@]
4724 #define equiv(A) @[(A)->v.data.indep.serial@]
4725 #define equiv_node(A) @[(A)->v.data.node@]
4726 #define equiv_sym(A) @[(mp_sym)(A)->v.data.node@]
4727 #endif
4728
4729 @ @<Declarations...@>=
4730 #if MPOST_DEBUG
4731 static mp_string do_get_text (MP mp, mp_sym A);
4732 static halfword do_get_eq_type (MP mp, mp_sym A);
4733 static halfword do_get_equiv (MP mp, mp_sym A);
4734 static mp_node do_get_equiv_node (MP mp, mp_sym A);
4735 static mp_sym do_get_equiv_sym (MP mp, mp_sym A);
4736 #endif
4737
4738 @ @<Types...@>=
4739 typedef struct mp_symbol_entry {
4740 halfword type;
4741 mp_value v;
4742 mp_string text;
4743 void *parent;
4744 } mp_symbol_entry;
4745
4746 @ @s avl_tree int @<Glob...@>=
4747 integer st_count; /* total number of known identifiers */
4748 avl_tree symbols; /* avl tree of symbolic tokens */
4749 avl_tree frozen_symbols; /* avl tree of frozen symbolic tokens */
4750 mp_sym frozen_bad_vardef;
4751 mp_sym frozen_colon;
4752 mp_sym frozen_end_def;
4753 mp_sym frozen_end_for;
4754 mp_sym frozen_end_group;
4755 mp_sym frozen_etex;
4756 mp_sym frozen_fi;
4757 mp_sym frozen_inaccessible;
4758 mp_sym frozen_left_bracket;
4759 mp_sym frozen_mpx_break;
4760 mp_sym frozen_repeat_loop;
4761 mp_sym frozen_right_delimiter;
4762 mp_sym frozen_semicolon;
4763 mp_sym frozen_slash;
4764 mp_sym frozen_undefined;
4765 mp_sym frozen_dump;
4766
4767
4768 @ Here are the functions needed for the avl construction.
4769
4770 @<Declarations@>=
4771 static int comp_symbols_entry (void *p, const void *pa, const void *pb);
4772 static void *copy_symbols_entry (const void *p);
4773 static void *delete_symbols_entry (void *p);
4774
4775
4776 @ The avl comparison function is a straightword version of |strcmp|,
4777 except that checks for the string lengths first.
4778
4779 @c
4780 static int comp_symbols_entry (void *p, const void *pa, const void *pb) {
4781 const mp_symbol_entry *a = (const mp_symbol_entry *) pa;
4782 const mp_symbol_entry *b = (const mp_symbol_entry *) pb;
4783 (void) p;
4784 if (a->text->len != b->text->len) {
4785 return (a->text->len > b->text->len ? 1 : -1);
4786 }
4787 return strncmp ((const char *) a->text->str, (const char *) b->text->str,
4788 a->text->len);
4789 }
4790
4791
4792 @ Copying a symbol happens when an item is inserted into an AVL tree.
4793 The |text| and |mp_number| needs to be deep copied, every thing else
4794 can be reassigned.
4795
4796 @c
4797 static void *copy_symbols_entry (const void *p) {
4798 MP mp;
4799 mp_sym ff;
4800 const mp_symbol_entry *fp;
4801 fp = (const mp_symbol_entry *) p;
4802 mp = (MP)fp->parent;
4803 ff = malloc (sizeof (mp_symbol_entry));
4804 if (ff == NULL)
4805 return NULL;
4806 ff->text = copy_strings_entry (fp->text);
4807 if (ff->text == NULL)
4808 return NULL;
4809 ff->v = fp->v;
4810 ff->type = fp->type;
4811 ff->parent = mp;
4812 new_number(ff->v.data.n);
4813 number_clone(ff->v.data.n, fp->v.data.n);
4814 return ff;
4815 }
4816
4817
4818 @ In the current implementation, symbols are not freed until the
4819 end of the run.
4820
4821 @c
4822 static void *delete_symbols_entry (void *p) {
4823 MP mp;
4824 mp_sym ff = (mp_sym) p;
4825 mp = (MP)ff->parent;
4826 free_number(ff->v.data.n);
4827 mp_xfree (ff->text->str);
4828 mp_xfree (ff->text);
4829 mp_xfree (ff);
4830 return NULL;
4831 }
4832
4833
4834 @ @<Allocate or initialize ...@>=
4835 mp->symbols = avl_create (comp_symbols_entry,
4836 copy_symbols_entry,
4837 delete_symbols_entry, malloc, free, NULL);
4838 mp->frozen_symbols = avl_create (comp_symbols_entry,
4839 copy_symbols_entry,
4840 delete_symbols_entry, malloc, free, NULL);
4841
4842 @ @<Dealloc variables@>=
4843 if (mp->symbols != NULL)
4844 avl_destroy (mp->symbols);
4845 if (mp->frozen_symbols != NULL)
4846 avl_destroy (mp->frozen_symbols);
4847
4848 @ Actually creating symbols is done by |id_lookup|, but in order to
4849 do so it needs a way to create a new, empty symbol structure.
4850
4851 @<Declarations@>=
4852 static mp_sym new_symbols_entry (MP mp, unsigned char *nam, size_t len);
4853
4854 @ @c
4855 static mp_sym new_symbols_entry (MP mp, unsigned char *nam, size_t len) {
4856 mp_sym ff;
4857 ff = mp_xmalloc (mp, 1, sizeof (mp_symbol_entry));
4858 memset (ff, 0, sizeof (mp_symbol_entry));
4859 ff->parent = mp;
4860 ff->text = mp_xmalloc (mp, 1, sizeof (mp_lstring));
4861 ff->text->str = nam;
4862 ff->text->len = len;
4863 ff->type = mp_tag_token;
4864 ff->v.type = mp_known;
4865 new_number(ff->v.data.n);
4866 FUNCTION_TRACE4 ("%p = new_symbols_entry(\"%s\",%d)\n", ff, nam, (int)len);
4867 return ff;
4868 }
4869
4870
4871 @ There is one global variable so that |id_lookup| does not always have to
4872 create a new entry just for testing. This is not freed because it creates
4873 a double-free thanks to the |NULL| init.
4874
4875 @<Global ...@>=
4876 mp_sym id_lookup_test;
4877
4878 @ @<Initialize table entries@>=
4879 mp->id_lookup_test = new_symbols_entry (mp, NULL, 0);
4880
4881 @ Certain symbols are ``frozen'' and not redefinable, since they are
4882 used
4883 in error recovery.
4884
4885 @<Initialize table entries@>=
4886 mp->st_count = 0;
4887 mp->frozen_bad_vardef = mp_frozen_primitive (mp, "a bad variable", mp_tag_token, 0);
4888 mp->frozen_right_delimiter = mp_frozen_primitive (mp, ")", mp_right_delimiter, 0);
4889 mp->frozen_inaccessible = mp_frozen_primitive (mp, " INACCESSIBLE", mp_tag_token, 0);
4890 mp->frozen_undefined = mp_frozen_primitive (mp, " UNDEFINED", mp_tag_token, 0);
4891
4892 @ Here is the subroutine that searches the avl tree for an identifier
4893 that matches a given string of length~|l| appearing in |buffer[j..
4894 (j+l-1)]|. If the identifier is not found, it is inserted if
4895 |insert_new| is |true|, and the corresponding symbol will be returned.
4896
4897 There are two variations on the lookup function: one for the normal
4898 symbol table, and one for the table of error recovery symbols.
4899
4900 @d mp_id_lookup(A,B,C,D) mp_do_id_lookup ((A), mp->symbols, (B), (C), (D))
4901
4902 @c
4903 static mp_sym mp_do_id_lookup (MP mp, avl_tree symbols, char *j,
4904 size_t l, boolean insert_new) {
4905 /* search an avl tree */
4906 mp_sym str;
4907 mp->id_lookup_test->text->str = (unsigned char *)j;
4908 mp->id_lookup_test->text->len = l;
4909 str = (mp_sym) avl_find (mp->id_lookup_test, symbols);
4910 if (str == NULL && insert_new) {
4911 unsigned char *nam = (unsigned char *) mp_xstrldup (mp, j, l);
4912 mp_sym s = new_symbols_entry (mp, nam, l);
4913 mp->st_count++;
4914 assert (avl_ins (s, symbols, avl_false) > 0);
4915 str = (mp_sym) avl_find (s, symbols);
4916 delete_symbols_entry (s);
4917 }
4918 return str;
4919 }
4920 static mp_sym mp_frozen_id_lookup (MP mp, char *j, size_t l,
4921 boolean insert_new) {
4922 /* search the error recovery symbol table */
4923 return mp_do_id_lookup (mp, mp->frozen_symbols, j, l, insert_new);
4924 }
4925
4926 /* see |mp_print_sym (mp_sym sym)| */
4927 @ Get a numeric value from \MP\ is not easy. We have to consider
4928 the macro and the loops, as also the internal type (this is a
4929 first attempt, and more work is needed). If we are inside
4930 a \&{for} loop, then the global |loop_ptr| is not null and the other loops
4931 eventually nested are available by mean of |loop_ptr->link|.
4932 The current numeric value is stored in |old_value|.
4933
4934 @c
4935 double mp_get_numeric_value (MP mp, const char *s, size_t l) {
4936 char *ss = mp_xstrdup(mp,s);
4937 if (ss) {
4938 mp_sym sym = mp_id_lookup(mp,ss,l,false);
4939 if (sym != NULL) {
4940 if (mp->loop_ptr != NULL) {
4941 mp_loop_data *s;
4942 s = mp->loop_ptr;
4943 while (s != NULL && sym != s->var)
4944 s = s->link;
4945 if (s != NULL && sym == s->var ){
4946 mp_xfree (ss);
4947 return number_to_double(s->old_value) ;
4948 }
4949 }
4950 if (mp_type(sym) == mp_internal_quantity) {
4951 halfword qq = equiv(sym);
4952 mp_xfree (ss);
4953 if (internal_type (qq) != mp_string_type)
4954 return number_to_double(internal_value(qq));
4955 else
4956 return 0;
4957 }
4958 if (sym->v.data.node != NULL && mp_type(sym->v.data.node) == mp_known) {
4959 mp_xfree (ss);
4960 return number_to_double(sym->v.data.node->data.n) ;
4961 }
4962 }
4963 }
4964 mp_xfree (ss);
4965 return 0 ;
4966 }
4967
4968 int mp_get_boolean_value (MP mp, const char *s, size_t l) {
4969 char *ss = mp_xstrdup(mp,s);
4970 if (ss) {
4971 mp_sym sym = mp_id_lookup(mp,ss,l,false);
4972 if (sym != NULL) {
4973 if (mp_type(sym->v.data.node) == mp_boolean_type) {
4974 if (number_to_boolean (sym->v.data.node->data.n) == mp_true_code) {
4975 mp_xfree(ss);
4976 return 1 ;
4977 }
4978 }
4979 }
4980 }
4981 mp_xfree (ss);
4982 return 0;
4983 }
4984
4985 char *mp_get_string_value (MP mp, const char *s, size_t l) {
4986 char *ss = mp_xstrdup(mp,s);
4987 if (ss) {
4988 mp_sym sym = mp_id_lookup(mp,ss,l,false);
4989 if (sym != NULL) {
4990 if (mp_type(sym->v.data.node) == mp_string_type) {
4991 mp_xfree (ss);
4992 return (char *) sym->v.data.node->data.str->str;
4993 }
4994 }
4995 }
4996 mp_xfree (ss);
4997 return NULL;
4998 }
4999
5000 mp_knot mp_get_path_value (MP mp, const char *s, size_t l) {
5001 char *ss = mp_xstrdup(mp,s);
5002 if (ss) {
5003 mp_sym sym = mp_id_lookup(mp,ss,l,false);
5004 if (sym != NULL && sym->v.data.node != NULL) {
5005 if (mp_type(sym->v.data.node) == mp_path_type) {
5006 mp_xfree (ss);
5007 return (mp_knot) sym->v.data.node->data.p;
5008 }
5009 }
5010 }
5011 mp_xfree (ss);
5012 return NULL;
5013 }
5014
5015 @ @<Exported function headers@>=
5016 double mp_get_numeric_value(MP mp,const char *s,size_t l);
5017 int mp_get_boolean_value(MP mp,const char *s,size_t l);
5018 char *mp_get_string_value(MP mp,const char *s,size_t l);
5019 mp_knot mp_get_path_value(MP mp,const char *s,size_t l);
5020
5021 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5022 table, together with their command code (which will be the |eq_type|)
5023 and an operand (which will be the |equiv|). The |primitive| procedure
5024 does this, in a way that no \MP\ user can. The global value |cur_sym|
5025 contains the new |eqtb| pointer after |primitive| has acted.
5026
5027 @c
5028 static void mp_primitive (MP mp, const char *ss, halfword c, halfword o) {
5029 char *s = mp_xstrdup (mp, ss);
5030 set_cur_sym (mp_id_lookup (mp, s, strlen (s), true));
5031 mp_xfree (s);
5032 set_eq_type (cur_sym(), c);
5033 set_equiv (cur_sym(), o);
5034 }
5035
5036
5037 @ Some other symbolic tokens only exist for error recovery.
5038
5039 @c
5040 static mp_sym mp_frozen_primitive (MP mp, const char *ss, halfword c,
5041 halfword o) {
5042 char *s = mp_xstrdup (mp, ss);
5043 mp_sym str = mp_frozen_id_lookup (mp, s, strlen (ss), true);
5044 mp_xfree (s);
5045 str->type = c;
5046 str->v.data.indep.serial = o;
5047 return str;
5048 }
5049
5050
5051 @ This routine returns |true| if the argument is an un-redefinable symbol
5052 because it is one of the error recovery tokens (as explained elsewhere,
5053 |frozen_inaccessible| actually is redefinable).
5054
5055 @c
5056 static boolean mp_is_frozen (MP mp, mp_sym sym) {
5057 mp_sym temp = mp_frozen_id_lookup (mp, (char *) sym->text->str, sym->text->len, false);
5058 if (temp==mp->frozen_inaccessible)
5059 return false;
5060 return (temp == sym);
5061 }
5062
5063
5064 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5065 by their |eq_type| alone. These primitives are loaded into the hash table
5066 as follows:
5067
5068 @<Put each of \MP's primitives into the hash table@>=
5069 mp_primitive (mp, "..", mp_path_join, 0);
5070 @:.._}{\.{..} primitive@>
5071 mp_primitive (mp, "[", mp_left_bracket, 0);
5072 mp->frozen_left_bracket = mp_frozen_primitive (mp, "[", mp_left_bracket, 0);
5073 @:[ }{\.{[} primitive@>
5074 mp_primitive (mp, "]", mp_right_bracket, 0);
5075 @:] }{\.{]} primitive@>
5076 mp_primitive (mp, "}", mp_right_brace, 0);
5077 @:]]}{\.{\char`\}} primitive@>
5078 mp_primitive (mp, "{", mp_left_brace, 0);
5079 @:][}{\.{\char`\{} primitive@>
5080 mp_primitive (mp, ":", mp_colon, 0);
5081 mp->frozen_colon = mp_frozen_primitive (mp, ":", mp_colon, 0);
5082 @:: }{\.{:} primitive@>
5083 mp_primitive (mp, "::", mp_double_colon, 0);
5084 @::: }{\.{::} primitive@>
5085 mp_primitive (mp, "||:", mp_bchar_label, 0);
5086 @:::: }{\.{\char'174\char'174:} primitive@>
5087 mp_primitive (mp, ":=", mp_assignment, 0);
5088 @::=_}{\.{:=} primitive@>
5089 mp_primitive (mp, ",", mp_comma, 0);
5090 @:, }{\., primitive@>
5091 mp_primitive (mp, ";", mp_semicolon, 0);
5092 mp->frozen_semicolon = mp_frozen_primitive (mp, ";", mp_semicolon, 0);
5093 @:; }{\.; primitive@>
5094 mp_primitive (mp, "\\", mp_relax, 0);
5095 @:]]\\}{\.{\char`\\} primitive@>
5096 mp_primitive (mp, "addto", mp_add_to_command, 0);
5097 @:add_to_}{\&{addto} primitive@>
5098 mp_primitive (mp, "atleast", mp_at_least, 0);
5099 @:at_least_}{\&{atleast} primitive@>
5100 mp_primitive (mp, "begingroup", mp_begin_group, 0); @+
5101 mp->bg_loc = cur_sym();
5102 @:begin_group_}{\&{begingroup} primitive@>
5103 mp_primitive (mp, "controls", mp_controls, 0);
5104 @:controls_}{\&{controls} primitive@>
5105 mp_primitive (mp, "curl", mp_curl_command, 0);
5106 @:curl_}{\&{curl} primitive@>
5107 mp_primitive (mp, "delimiters", mp_delimiters, 0);
5108 @:delimiters_}{\&{delimiters} primitive@>
5109 mp_primitive (mp, "endgroup", mp_end_group, 0); @+
5110 mp->eg_loc = cur_sym();
5111 mp->frozen_end_group = mp_frozen_primitive (mp, "endgroup", mp_end_group, 0);
5112 @:endgroup_}{\&{endgroup} primitive@>
5113 mp_primitive (mp, "everyjob", mp_every_job_command, 0);
5114 @:every_job_}{\&{everyjob} primitive@>
5115 mp_primitive (mp, "exitif", mp_exit_test, 0);
5116 @:exit_if_}{\&{exitif} primitive@>
5117 mp_primitive (mp, "expandafter", mp_expand_after, 0);
5118 @:expand_after_}{\&{expandafter} primitive@>
5119 mp_primitive (mp, "interim", mp_interim_command, 0);
5120 @:interim_}{\&{interim} primitive@>
5121 mp_primitive (mp, "let", mp_let_command, 0);
5122 @:let_}{\&{let} primitive@>
5123 mp_primitive (mp, "newinternal", mp_new_internal, 0);
5124 @:new_internal_}{\&{newinternal} primitive@>
5125 mp_primitive (mp, "of", mp_of_token, 0);
5126 @:of_}{\&{of} primitive@>
5127 mp_primitive (mp, "randomseed", mp_random_seed, 0);
5128 @:mp_random_seed_}{\&{randomseed} primitive@>
5129 mp_primitive (mp, "save", mp_save_command, 0);
5130 @:save_}{\&{save} primitive@>
5131 mp_primitive (mp, "scantokens", mp_scan_tokens, 0);
5132 @:scan_tokens_}{\&{scantokens} primitive@>
5133 mp_primitive (mp, "runscript", mp_runscript, 0);
5134 @:run_script_}{\&{runscript} primitive@>
5135 mp_primitive (mp, "maketext", mp_maketext, 0);
5136 @:make_text_}{\&{maketext} primitive@>
5137 mp_primitive (mp, "shipout", mp_ship_out_command, 0);
5138 @:ship_out_}{\&{shipout} primitive@>
5139 mp_primitive (mp, "skipto", mp_skip_to, 0);
5140 @:skip_to_}{\&{skipto} primitive@>
5141 mp_primitive (mp, "special", mp_special_command, 0);
5142 @:special}{\&{special} primitive@>
5143 mp_primitive (mp, "fontmapfile", mp_special_command, 1);
5144 @:fontmapfile}{\&{fontmapfile} primitive@>
5145 mp_primitive (mp, "fontmapline", mp_special_command, 2);
5146 @:fontmapline}{\&{fontmapline} primitive@>
5147 mp_primitive (mp, "step", mp_step_token, 0);
5148 @:step_}{\&{step} primitive@>
5149 mp_primitive (mp, "str", mp_str_op, 0);
5150 @:str_}{\&{str} primitive@>
5151 mp_primitive (mp, "void", mp_void_op, 0);
5152 @:void_}{\&{void} primitive@>
5153 mp_primitive (mp, "tension", mp_tension, 0);
5154 @:tension_}{\&{tension} primitive@>
5155 mp_primitive (mp, "to", mp_to_token, 0);
5156 @:to_}{\&{to} primitive@>
5157 mp_primitive (mp, "until", mp_until_token, 0);
5158 @:until_}{\&{until} primitive@>
5159 mp_primitive (mp, "within", mp_within_token, 0);
5160 @:within_}{\&{within} primitive@>
5161 mp_primitive (mp, "write", mp_write_command, 0);
5162 @:write_}{\&{write} primitive@>
5163
5164
5165 @ Each primitive has a corresponding inverse, so that it is possible to
5166 display the cryptic numeric contents of |eqtb| in symbolic form.
5167 Every call of |primitive| in this program is therefore accompanied by some
5168 straightforward code that forms part of the |print_cmd_mod| routine
5169 explained below.
5170
5171 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5172 case mp_add_to_command:
5173 mp_print (mp, "addto");
5174 break;
5175 case mp_assignment:
5176 mp_print (mp, ":=");
5177 break;
5178 case mp_at_least:
5179 mp_print (mp, "atleast");
5180 break;
5181 case mp_bchar_label:
5182 mp_print (mp, "||:");
5183 break;
5184 case mp_begin_group:
5185 mp_print (mp, "begingroup");
5186 break;
5187 case mp_colon:
5188 mp_print (mp, ":");
5189 break;
5190 case mp_comma:
5191 mp_print (mp, ",");
5192 break;
5193 case mp_controls:
5194 mp_print (mp, "controls");
5195 break;
5196 case mp_curl_command:
5197 mp_print (mp, "curl");
5198 break;
5199 case mp_delimiters:
5200 mp_print (mp, "delimiters");
5201 break;
5202 case mp_double_colon:
5203 mp_print (mp, "::");
5204 break;
5205 case mp_end_group:
5206 mp_print (mp, "endgroup");
5207 break;
5208 case mp_every_job_command:
5209 mp_print (mp, "everyjob");
5210 break;
5211 case mp_exit_test:
5212 mp_print (mp, "exitif");
5213 break;
5214 case mp_expand_after:
5215 mp_print (mp, "expandafter");
5216 break;
5217 case mp_interim_command:
5218 mp_print (mp, "interim");
5219 break;
5220 case mp_left_brace:
5221 mp_print (mp, "{");
5222 break;
5223 case mp_left_bracket:
5224 mp_print (mp, "[");
5225 break;
5226 case mp_let_command:
5227 mp_print (mp, "let");
5228 break;
5229 case mp_new_internal:
5230 mp_print (mp, "newinternal");
5231 break;
5232 case mp_of_token:
5233 mp_print (mp, "of");
5234 break;
5235 case mp_path_join:
5236 mp_print (mp, "..");
5237 break;
5238 case mp_random_seed:
5239 mp_print (mp, "randomseed");
5240 break;
5241 case mp_relax:
5242 mp_print_char (mp, xord ('\\'));
5243 break;
5244 case mp_right_brace:
5245 mp_print_char (mp, xord ('}'));
5246 break;
5247 case mp_right_bracket:
5248 mp_print_char (mp, xord (']'));
5249 break;
5250 case mp_save_command:
5251 mp_print (mp, "save");
5252 break;
5253 case mp_scan_tokens:
5254 mp_print (mp, "scantokens");
5255 break;
5256 case mp_runscript:
5257 mp_print (mp, "runscript");
5258 break;
5259 case mp_maketext:
5260 mp_print (mp, "maketext");
5261 break;
5262 case mp_semicolon:
5263 mp_print_char (mp, xord (';'));
5264 break;
5265 case mp_ship_out_command:
5266 mp_print (mp, "shipout");
5267 break;
5268 case mp_skip_to:
5269 mp_print (mp, "skipto");
5270 break;
5271 case mp_special_command:
5272 if (m == 2)
5273 mp_print (mp, "fontmapline");
5274 else if (m == 1)
5275 mp_print (mp, "fontmapfile");
5276 else
5277 mp_print (mp, "special");
5278 break;
5279 case mp_step_token:
5280 mp_print (mp, "step");
5281 break;
5282 case mp_str_op:
5283 mp_print (mp, "str");
5284 break;
5285 case mp_void_op:
5286 mp_print (mp, "void");
5287 break;
5288 case mp_tension:
5289 mp_print (mp, "tension");
5290 break;
5291 case mp_to_token:
5292 mp_print (mp, "to");
5293 break;
5294 case mp_until_token:
5295 mp_print (mp, "until");
5296 break;
5297 case mp_within_token:
5298 mp_print (mp, "within");
5299 break;
5300 case mp_write_command:
5301 mp_print (mp, "write");
5302 break;
5303
5304 @ We will deal with the other primitives later, at some point in the program
5305 where their |eq_type| and |equiv| values are more meaningful. For example,
5306 the primitives for macro definitions will be loaded when we consider the
5307 routines that define macros. It is easy to find where each particular
5308 primitive was treated by looking in the index at the end; for example, the
5309 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5310
5311 @* Token lists.
5312
5313 A \MP\ token is either symbolic or numeric or a string, or it denotes a macro
5314 parameter or capsule or an internal; so there are six corresponding ways to
5315 encode it internally:
5316 @^token@>
5317
5318 (1)~A symbolic token for symbol |p| is represented by the pointer |p|,
5319 in the |sym_sym| field of a symbolic node in~|mem|. The |type| field is |symbol_node|;
5320 and it has a |name_type| to differentiate various subtypes of symbolic tokens,
5321 which is usually |normal_sym|, but |macro_sym| for macro names.
5322
5323 (2)~A numeric token whose |scaled| value is~|v| is
5324 represented in a non-symbolic node of~|mem|; the |type| field is |known|,
5325 the |name_type| field is |token|, and the |value| field holds~|v|.
5326
5327 (3)~A string token is also represented in a non-symbolic node; the |type|
5328 field is |mp_string_type|, the |name_type| field is |token|, and the
5329 |value| field holds the corresponding |mp_string|.
5330
5331 (4)~Capsules have |name_type=capsule|, and their |type| and |value| fields
5332 represent arbitrary values, with |type| different from |symbol_node|
5333 (in ways to be explained later).
5334
5335 (5)~Macro parameters appear in |sym_info| fields of symbolic nodes. The |type|
5336 field is |symbol_node|; the $k$th parameter is represented by |k| in |sym_info|;
5337 and |expr_sym| in |name_type|, if it is of type \&{expr}, or |suffix_sym| if it
5338 is of type \&{suffix}, or by |text_sym| if it is of type \&{text}.
5339
5340 (6)~The $k$th internal is also represented by |k| in |sym_info|; the |type| field is
5341 |symbol_node| as for the other symbolic tokens; and |internal_sym| is its |name_type|;
5342
5343 Actual values of the parameters and internals are kept in a separate
5344 stack, as we will see later.
5345
5346 Note that the `\\{type}' field of a node has nothing to do with ``type'' in a
5347 printer's sense. It's curious that the same word is used in such different ways.
5348
5349 @d token_node_size sizeof(mp_node_data) /* the number of words in a large token node */
5350
5351 @d set_value_sym(A,B) do_set_value_sym(mp, (mp_token_node)(A), (B))
5352 @d set_value_number(A,B) do_set_value_number(mp, (mp_token_node)(A), (B))
5353 @d set_value_node(A,B) do_set_value_node(mp, (mp_token_node)(A), (B))
5354 @d set_value_str(A,B) do_set_value_str(mp, (mp_token_node)(A), (B))
5355 @d set_value_knot(A,B) do_set_value_knot(mp, (mp_token_node)A, (B))
5356
5357 @d value_sym_NEW(A) (mp_sym)mp_link(A)
5358 @d set_value_sym_NEW(A,B) set_mp_link(A,(mp_node)B)
5359
5360 @<MPlib internal header stuff@>=
5361 typedef struct mp_node_data *mp_token_node;
5362
5363 @ @c
5364 #if MPOST_DEBUG
5365 #define value_sym(A) @[do_get_value_sym(mp,(mp_token_node)(A))@]
5366 @[@]/*|
5367 #define value_number(A) @[do_get_value_number(mp,(mp_token_node)(A))@]
5368 | */
5369 #define value_number(A) @[((mp_token_node)(A))->data.n@]
5370 #define value_node(A) @[do_get_value_node(mp,(mp_token_node)(A))@]
5371 #define value_str(A) @[do_get_value_str(mp,(mp_token_node)(A))@]
5372 #define value_knot(A) @[do_get_value_knot(mp,(mp_token_node)(A))@]
5373 #else
5374 #define value_sym(A) @[((mp_token_node)(A))->data.sym@]
5375 #define value_number(A) @[((mp_token_node)(A))->data.n@]
5376 #define value_node(A) @[((mp_token_node)(A))->data.node@]
5377 #define value_str(A) @[((mp_token_node)(A))->data.str@]
5378 #define value_knot(A) @[((mp_token_node)(A))->data.p@]
5379 #endif
5380 @/@t\2\2\4\4@>
5381 static void do_set_value_sym(MP mp, mp_token_node A, mp_sym B) {
5382 FUNCTION_TRACE3 ("set_value_sym(%p,%p)\n", (A),(B));
5383 A->data.sym=(B);
5384 }
5385 static void do_set_value_number(MP mp, mp_token_node A, mp_number B) {
5386 FUNCTION_TRACE3 ("set_value(%p,%s)\n", (A), number_tostring(B));
5387 A->data.p = NULL;
5388 A->data.str = NULL;
5389 A->data.node = NULL;
5390 number_clone (A->data.n, B);
5391 }
5392 static void do_set_value_str(MP mp, mp_token_node A, mp_string B) {
5393 FUNCTION_TRACE3 ("set_value_str(%p,%p)\n", (A),(B));
5394 assert (A->type != mp_structured);
5395 A->data.p = NULL;
5396 A->data.str = (B);
5397 add_str_ref((B));
5398 A->data.node = NULL;
5399 number_clone (A->data.n, zero_t);
5400 }
5401 static void do_set_value_node(MP mp, mp_token_node A, mp_node B) {
5402 /* store the value in a large token node */
5403 FUNCTION_TRACE3 ("set_value_node(%p,%p)\n", A,B);
5404 assert (A->type != mp_structured);
5405 A->data.p = NULL;
5406 A->data.str = NULL;
5407 A->data.node = B;
5408 number_clone (A->data.n, zero_t);
5409 }
5410 static void do_set_value_knot(MP mp, mp_token_node A, mp_knot B) {
5411 FUNCTION_TRACE3 ("set_value_knot(%p,%p)\n", (A),(B));
5412 assert (A->type != mp_structured);
5413 A->data.p = (B);
5414 A->data.str = NULL;
5415 A->data.node = NULL;
5416 number_clone (A->data.n, zero_t);
5417 }
5418
5419
5420 @ @c
5421 #if MPOST_DEBUG
5422 static mp_sym do_get_value_sym (MP mp, mp_token_node A) {
5423 /* |A->type| can be structured in this case */
5424 FUNCTION_TRACE3 ("%p = get_value_sym(%p)\n", A->data.sym, A);
5425 return A->data.sym ;
5426 }
5427 static mp_node do_get_value_node (MP mp, mp_token_node A) {
5428 assert (A->type != mp_structured);
5429 FUNCTION_TRACE3 ("%p = get_value_node(%p)\n", A->data.node, A);
5430 return A->data.node ;
5431 }
5432 static mp_string do_get_value_str (MP mp, mp_token_node A) {
5433 assert (A->type != mp_structured);
5434 FUNCTION_TRACE3 ("%p = get_value_str(%p)\n", A->data.str, A);
5435 return A->data.str ;
5436 }
5437 static mp_knot do_get_value_knot (MP mp, mp_token_node A) {
5438 assert (A->type != mp_structured);
5439 FUNCTION_TRACE3 ("%p = get_value_knot(%p)\n", A->data.p, A);
5440 return A->data.p ;
5441 }
5442 /* static mp_number do_get_value_number (MP mp, mp_token_node A) \{ */
5443 /* assert (A->type != mp_structured); */
5444 /* FUNCTION_TRACE3 ("%d = get_value_number(%p)\n", A->data.n.type, A); */
5445 /* return A->data.n ; */
5446 /* \} */
5447 #endif
5448
5449 @ @<Declarations@>=
5450 #if MPOST_DEBUG
5451 /* static mp_number do_get_value_number (MP mp, mp_token_node A); */
5452 static mp_sym do_get_value_sym (MP mp, mp_token_node A);
5453 static mp_node do_get_value_node (MP mp, mp_token_node A);
5454 static mp_string do_get_value_str (MP mp, mp_token_node A) ;
5455 static mp_knot do_get_value_knot (MP mp, mp_token_node A) ;
5456 #endif
5457 static void do_set_value_sym (MP mp, mp_token_node A, mp_sym B);
5458 static void do_set_value_number (MP mp, mp_token_node A, mp_number B);
5459 static void do_set_value_node (MP mp, mp_token_node A, mp_node B);
5460 static void do_set_value_str (MP mp, mp_token_node A, mp_string B);
5461 static void do_set_value_knot (MP mp, mp_token_node A, mp_knot B);
5462
5463 @ @c
5464 static mp_node mp_get_token_node (MP mp) {
5465 mp_node p;
5466 if (mp->token_nodes) {
5467 p = mp->token_nodes;
5468 mp->token_nodes = p->link;
5469 mp->num_token_nodes--;
5470 p->link = NULL;
5471 } else {
5472 p = malloc_node (token_node_size);
5473 new_number(p->data.n);
5474 p->has_number = 1;
5475 }
5476 p->type = mp_token_node_type;
5477 FUNCTION_TRACE2 ("%p = mp_get_token_node()\n", p);
5478 return (mp_node) p;
5479 }
5480
5481 @ @c
5482 static void mp_free_token_node (MP mp, mp_node p) {
5483 FUNCTION_TRACE2 ("mp_free_token_node(%p)\n", p);
5484 if (!p) return;
5485 if (mp->num_token_nodes < max_num_token_nodes) {
5486 p->link = mp->token_nodes;
5487 mp->token_nodes = p;
5488 mp->num_token_nodes++;
5489 return;
5490 }
5491 mp->var_used -= token_node_size;
5492 if (mp->math_mode > mp_math_double_mode) {
5493 free_number(((mp_value_node)p)->data.n);
5494 }
5495 xfree (p);
5496 }
5497
5498 @ @<Declarations@>=
5499 static void mp_free_token_node (MP mp, mp_node p);
5500
5501 @ A numeric token is created by the following trivial routine.
5502
5503 @c
5504 static mp_node mp_new_num_tok (MP mp, mp_number v) {
5505 mp_node p; /* the new node */
5506 p = mp_get_token_node (mp);
5507 set_value_number (p, v);
5508 p->type = mp_known;
5509 p->name_type = mp_token;
5510 FUNCTION_TRACE3 ("%p = mp_new_num_tok(%p)\n", p, v);
5511 return p;
5512 }
5513
5514
5515 @ A token list is a singly linked list of nodes in |mem|, where
5516 each node contains a token and a link. Here's a subroutine that gets rid
5517 of a token list when it is no longer needed.
5518
5519 @c
5520 static void mp_flush_token_list (MP mp, mp_node p) {
5521 mp_node q; /* the node being recycled */
5522 FUNCTION_TRACE2 ("mp_flush_token_list(%p)\n", p);
5523 while (p != NULL) {
5524 q = p;
5525 p = mp_link (p);
5526 if (mp_type (q) == mp_symbol_node) {
5527 mp_free_symbolic_node (mp, q);
5528 } else {
5529 switch (mp_type (q)) {
5530 case mp_vacuous:
5531 case mp_boolean_type:
5532 case mp_known:
5533 break;
5534 case mp_string_type:
5535 delete_str_ref (value_str (q));
5536 break;
5537 case unknown_types:
5538 case mp_pen_type:
5539 case mp_path_type:
5540 case mp_picture_type:
5541 case mp_pair_type:
5542 case mp_color_type:
5543 case mp_cmykcolor_type:
5544 case mp_transform_type:
5545 case mp_dependent:
5546 case mp_proto_dependent:
5547 case mp_independent:
5548 mp_recycle_value (mp, q);
5549 break;
5550 default:
5551 mp_confusion (mp, "token");
5552 @:this can't happen token}{\quad token@>
5553 }
5554 mp_free_token_node (mp, q);
5555 }
5556 }
5557 }
5558
5559
5560 @ The procedure |show_token_list|, which prints a symbolic form of
5561 the token list that starts at a given node |p|, illustrates these
5562 conventions. The token list being displayed should not begin with a reference
5563 count.
5564
5565 An additional parameter |q| is also given; this parameter is either NULL
5566 or it points to a node in the token list where a certain magic computation
5567 takes place that will be explained later. (Basically, |q| is non-NULL when
5568 we are printing the two-line context information at the time of an error
5569 message; |q| marks the place corresponding to where the second line
5570 should begin.)
5571
5572 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5573 of printing exceeds a given limit~|l|; the length of printing upon entry is
5574 assumed to be a given amount called |null_tally|. (Note that
5575 |show_token_list| sometimes uses itself recursively to print
5576 variable names within a capsule.)
5577 @^recursion@>
5578
5579 Unusual entries are printed in the form of all-caps tokens
5580 preceded by a space, e.g., `\.{\char`\ BAD}'.
5581
5582 @<Declarations@>=
5583 static void mp_show_token_list (MP mp, mp_node p, mp_node q, integer l,
5584 integer null_tally);
5585
5586 @ @c
5587 void mp_show_token_list (MP mp, mp_node p, mp_node q, integer l,
5588 integer null_tally) {
5589 quarterword cclass, c; /* the |char_class| of previous and new tokens */
5590 cclass = percent_class;
5591 mp->tally = null_tally;
5592 while ((p != NULL) && (mp->tally < l)) {
5593 if (p == q) {
5594 set_trick_count();
5595 }
5596 /* Display token |p| and set |c| to its class; but |return| if there are problems */
5597 c = letter_class; /* the default */
5598 if (mp_type (p) != mp_symbol_node) {
5599 /* Display non-symbolic token */
5600 if (mp_name_type (p) == mp_token) {
5601 if (mp_type (p) == mp_known) {
5602 /* Display a numeric token */
5603 if (cclass == digit_class)
5604 mp_print_char (mp, xord (' '));
5605 if (number_negative (value_number (p))) {
5606 if (cclass == mp_left_bracket_class)
5607 mp_print_char (mp, xord (' '));
5608 mp_print_char (mp, xord ('['));
5609 print_number (value_number (p));
5610 mp_print_char (mp, xord (']'));
5611 c = mp_right_bracket_class;
5612 } else {
5613 print_number (value_number (p));
5614 c = digit_class;
5615 }
5616
5617 } else if (mp_type (p) != mp_string_type) {
5618 mp_print (mp, " BAD");
5619 } else {
5620 mp_print_char (mp, xord ('"'));
5621 mp_print_str (mp, value_str (p));
5622 mp_print_char (mp, xord ('"'));
5623 c = string_class;
5624 }
5625 } else if ((mp_name_type (p) != mp_capsule) || (mp_type (p) < mp_vacuous)
5626 || (mp_type (p) > mp_independent)) {
5627 mp_print (mp, " BAD");
5628 } else {
5629 mp_print_capsule (mp, p);
5630 c = right_paren_class;
5631 }
5632
5633 } else {
5634 if (mp_name_type (p) == mp_expr_sym ||
5635 mp_name_type (p) == mp_suffix_sym || mp_name_type (p) == mp_text_sym) {
5636 integer r; /* temporary register */
5637 r = mp_sym_info (p);
5638 if (mp_name_type (p) == mp_expr_sym) {
5639 mp_print (mp, "(EXPR");
5640 } else if (mp_name_type (p) == mp_suffix_sym) {
5641 mp_print (mp, "(SUFFIX");
5642 } else {
5643 mp_print (mp, "(TEXT");
5644 }
5645 mp_print_int (mp, r);
5646 mp_print_char (mp, xord (')'));
5647 c = right_paren_class;
5648 } else {
5649 mp_sym sr = mp_sym_sym (p);
5650 if (sr == collective_subscript) {
5651 /* Display a collective subscript */
5652 if (cclass == mp_left_bracket_class)
5653 mp_print_char (mp, xord (' '));
5654 mp_print (mp, "[]");
5655 c = mp_right_bracket_class;
5656
5657 } else {
5658 mp_string rr = text (sr);
5659 if (rr == NULL || rr->str == NULL) {
5660 mp_print (mp, " NONEXISTENT");
5661 } else {
5662 /* Print string |r| as a symbolic token and set |c| to its class */
5663 c = (quarterword) mp->char_class[(rr->str[0])];
5664 if (c == cclass) {
5665 switch (c) {
5666 case letter_class:
5667 mp_print_char (mp, xord ('.'));
5668 break;
5669 case isolated_classes:
5670 break;
5671 default:
5672 mp_print_char (mp, xord (' '));
5673 break;
5674 }
5675 }
5676 mp_print_str (mp, rr);
5677
5678 }
5679 }
5680 }
5681 }
5682
5683 cclass = c;
5684 p = mp_link (p);
5685 }
5686 if (p != NULL)
5687 mp_print (mp, " ETC.");
5688 return;
5689 }
5690
5691
5692 @ @<Declarations@>=
5693 static void mp_print_capsule (MP mp, mp_node p);
5694
5695 @ @<Declare miscellaneous procedures that were declared |forward|@>=
5696 void mp_print_capsule (MP mp, mp_node p) {
5697 mp_print_char (mp, xord ('('));
5698 mp_print_exp (mp, p, 0);
5699 mp_print_char (mp, xord (')'));
5700 }
5701
5702
5703 @ Macro definitions are kept in \MP's memory in the form of token lists
5704 that have a few extra symbolic nodes at the beginning.
5705
5706 The first node contains a reference count that is used to tell when the
5707 list is no longer needed. To emphasize the fact that a reference count is
5708 present, we shall refer to the |sym_info| field of this special node as the
5709 |ref_count| field.
5710 @^reference counts@>
5711
5712 The next node or nodes after the reference count serve to describe the
5713 formal parameters. They consist of zero or more parameter tokens followed
5714 by a code for the type of macro.
5715
5716 /* reference count preceding a macro definition or picture header */
5717 @d ref_count(A) indep_value(A)
5718 @d set_ref_count(A,B) set_indep_value(A,B)
5719 @d add_mac_ref(A) set_ref_count((A),ref_count((A))+1) /* make a new reference to a macro list */
5720 @d decr_mac_ref(A) set_ref_count((A),ref_count((A))-1) /* remove a reference to a macro list */
5721
5722 @<Types...@>=
5723 typedef enum {
5724 mp_general_macro, /* preface to a macro defined with a parameter list */
5725 mp_primary_macro, /* preface to a macro with a \&{primary} parameter */
5726 mp_secondary_macro, /* preface to a macro with a \&{secondary} parameter */
5727 mp_tertiary_macro, /* preface to a macro with a \&{tertiary} parameter */
5728 mp_expr_macro, /* preface to a macro with an undelimited \&{expr} parameter */
5729 mp_of_macro, /* preface to a macro with undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5730 mp_suffix_macro, /* preface to a macro with an undelimited \&{suffix} parameter */
5731 mp_text_macro, /* preface to a macro with an undelimited \&{text} parameter */
5732 mp_expr_param, /* used by \.{expr} primitive */
5733 mp_suffix_param, /* used by \.{suffix} primitive */
5734 mp_text_param /* used by \.{text} primitive */
5735 } mp_macro_info;
5736
5737 @ @c
5738 static void mp_delete_mac_ref (MP mp, mp_node p) {
5739 /* |p| points to the reference count of a macro list that is
5740 losing one reference */
5741 if (ref_count (p) == 0)
5742 mp_flush_token_list (mp, p);
5743 else
5744 decr_mac_ref (p);
5745 }
5746
5747
5748 @ The following subroutine displays a macro, given a pointer to its
5749 reference count.
5750
5751 @c
5752 static void mp_show_macro (MP mp, mp_node p, mp_node q, integer l) {
5753 mp_node r; /* temporary storage */
5754 p = mp_link (p); /* bypass the reference count */
5755 while (mp_name_type (p) != mp_macro_sym) {
5756 r = mp_link (p);
5757 mp_link (p) = NULL;
5758 mp_show_token_list (mp, p, NULL, l, 0);
5759 mp_link (p) = r;
5760 p = r;
5761 if (l > 0)
5762 l = l - mp->tally;
5763 else
5764 return;
5765 } /* control printing of `\.{ETC.}' */
5766 @.ETC@>
5767 mp->tally = 0;
5768 switch (mp_sym_info (p)) {
5769 case mp_general_macro:
5770 mp_print (mp, "->");
5771 break;
5772 @.->@>
5773 case mp_primary_macro:
5774 case mp_secondary_macro:
5775 case mp_tertiary_macro:
5776 mp_print_char (mp, xord ('<'));
5777 mp_print_cmd_mod (mp, mp_param_type, mp_sym_info (p));
5778 mp_print (mp, ">->");
5779 break;
5780 case mp_expr_macro:
5781 mp_print (mp, "<expr>->");
5782 break;
5783 case mp_of_macro:
5784 mp_print (mp, "<expr>of<primary>->");
5785 break;
5786 case mp_suffix_macro:
5787 mp_print (mp, "<suffix>->");
5788 break;
5789 case mp_text_macro:
5790 mp_print (mp, "<text>->");
5791 break;
5792 } /* there are no other cases */
5793 mp_show_token_list (mp, mp_link (p), q, l - mp->tally, 0);
5794 }
5795
5796
5797 @* Data structures for variables.
5798 The variables of \MP\ programs can be simple, like `\.x', or they can
5799 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5800 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5801 example, `\.{boolean} \.{x[]a.b}'. It's time for us to study how such
5802 things are represented inside of the computer.
5803
5804 Each variable value occupies two consecutive words, either in a non-symbolic
5805 node called a value node, or as a non-symbolic subfield of a larger node. One
5806 of those two words is called the |value| field; it is an integer,
5807 containing either a |scaled| numeric value or the representation of some
5808 other type of quantity. (It might also be subdivided into halfwords, in
5809 which case it is referred to by other names instead of |value|.) The other
5810 word is broken into subfields called |type|, |name_type|, and |link|. The
5811 |type| field is a quarterword that specifies the variable's type, and
5812 |name_type| is a quarterword from which \MP\ can reconstruct the
5813 variable's name (sometimes by using the |link| field as well). Thus, only
5814 1.25 words are actually devoted to the value itself; the other
5815 three-quarters of a word are overhead, but they aren't wasted because they
5816 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
5817
5818 In this section we shall be concerned only with the structural aspects of
5819 variables, not their values. Later parts of the program will change the
5820 |type| and |value| fields, but we shall treat those fields as black boxes
5821 whose contents should not be touched.
5822
5823 However, if the |type| field is |mp_structured|, there is no |value| field,
5824 and the second word is broken into two pointer fields called |attr_head|
5825 and |subscr_head|. Those fields point to additional nodes that
5826 contain structural information, as we shall see.
5827
5828 TH Note: DEK and JDH had a nice theoretical split between |value|,
5829 |attr| and |subscr| nodes, as documented above and further
5830 below. However, all three types had a bad habit of transmuting into
5831 each other in practice while pointers to them still lived on
5832 elsewhere, so using three different C structures is simply not
5833 workable. All three are now represented as a single C structure called
5834 |mp_value_node|.
5835
5836 There is a potential union in this structure in the interest of space
5837 saving: |subscript_| and |hashloc_| are mutually exclusive.
5838
5839 Actually, so are |attr_head_| + |subscr_head_| on one side and and
5840 |value_| on the other, but because of all the access macros that are
5841 used in the code base to get at values, those cannot be folded into a
5842 union (yet); this would have required creating a similar union in
5843 |mp_token_node| where it would only serve to confuse things.
5844
5845 Finally, |parent_| only applies in |attr| nodes (the ones that have
5846 |hashloc_|), but creating an extra substructure inside the union just
5847 for that does not save space and the extra complication in the
5848 structure is not worth the minimal extra code clarification.
5849
5850 @d attr_head(A) do_get_attr_head(mp,(mp_value_node)(A))
5851 @d set_attr_head(A,B) do_set_attr_head(mp,(mp_value_node)(A),(mp_node)(B))
5852
5853 @d subscr_head(A) do_get_subscr_head(mp,(mp_value_node)(A))
5854 @d set_subscr_head(A,B) do_set_subscr_head(mp,(mp_value_node)(A),(mp_node)(B))
5855
5856 @<MPlib internal header stuff@>=
5857 typedef struct mp_value_node_data {
5858 NODE_BODY;@+@t}\6{@>
5859 mp_value_data data;
5860 mp_number subscript_;
5861 mp_sym hashloc_;
5862 mp_node parent_;
5863 mp_node attr_head_;
5864 mp_node subscr_head_;
5865 } mp_value_node_data;
5866
5867 @ @c
5868 static mp_node do_get_attr_head (MP mp, mp_value_node A) {
5869 assert (A->type == mp_structured);
5870 FUNCTION_TRACE3 ("%p = get_attr_head(%p)\n", A->attr_head_, A);
5871 return A->attr_head_;
5872 }
5873 static mp_node do_get_subscr_head (MP mp, mp_value_node A) {
5874 assert (A->type == mp_structured);
5875 FUNCTION_TRACE3 ("%p = get_subscr_head(%p)\n", A->subscr_head_, A);
5876 return A->subscr_head_;
5877 }
5878 static void do_set_attr_head (MP mp, mp_value_node A, mp_node d) {
5879 FUNCTION_TRACE4 ("set_attr_head(%p,%p) on line %d\n", (A), d, __LINE__);
5880 assert (A->type == mp_structured);
5881 A->attr_head_ = d;
5882 }
5883 static void do_set_subscr_head (MP mp, mp_value_node A, mp_node d) {
5884 FUNCTION_TRACE4 ("set_subscr_head(%p,%p) on line %d\n", (A), d, __LINE__);
5885 assert (A->type == mp_structured);
5886 A->subscr_head_ = d;
5887 }
5888
5889 @ @<Declarations@>=
5890 static mp_node do_get_subscr_head (MP mp, mp_value_node A);
5891 static mp_node do_get_attr_head (MP mp, mp_value_node A);
5892 static void do_set_attr_head (MP mp, mp_value_node A, mp_node d);
5893 static void do_set_subscr_head (MP mp, mp_value_node A, mp_node d);
5894
5895 @ It would have been nicer to make |mp_get_value_node| return
5896 |mp_value_node| variables, but with |eqtb| as it stands that
5897 became messy: lots of typecasts. So, it returns a simple
5898 |mp_node| for now.
5899
5900 @d value_node_size sizeof(struct mp_value_node_data)
5901
5902 @c
5903 static mp_node mp_get_value_node (MP mp) {
5904 mp_value_node p;
5905 if (mp->value_nodes) {
5906 p = (mp_value_node)mp->value_nodes;
5907 mp->value_nodes = p->link;
5908 mp->num_value_nodes--;
5909 p->link = NULL;
5910 } else {
5911 p = malloc_node (value_node_size);
5912 new_number(p->data.n);
5913 new_number(p->subscript_);
5914 p->has_number = 2;
5915 }
5916 mp_type (p) = mp_value_node_type;
5917 FUNCTION_TRACE2 ("%p = mp_get_value_node()\n", p);
5918 return (mp_node)p;
5919 }
5920 #if MPOST_DEBUG > 1
5921 static void debug_dump_value_node (mp_node x) __attribute__((unused)) ;
5922 static void debug_dump_value_node (mp_node x) {
5923 mp_value_node qq = (mp_value_node)x;
5924 fprintf (stdout, "\nnode %p:\n", (void*)qq);
5925 fprintf (stdout, " type=%s\n", mp_type_string(qq->type));
5926 fprintf (stdout, " name_type=%d\n", qq->name_type);
5927 fprintf (stdout, " link=%p\n", (void*)qq->link);
5928 fprintf (stdout, " data.n=%d\n", qq->data.n.type);
5929 if (is_number(qq->data.n)) {
5930 fprintf (stdout, " data.n.data.val=%d\n", qq->data.n.data.val);
5931 fprintf (stdout, " data.n.data.dval=%f\n", qq->data.n.data.dval);
5932 }
5933 fprintf (stdout, " data.str=%p\n", (void*)qq->data.str);
5934 if (qq->data.str != NULL) {
5935 fprintf (stdout, " data.str->len=%d\n", (int)qq->data.str->len);
5936 fprintf (stdout, " data.str->str=%s\n", qq->data.str->str);
5937 }
5938 fprintf (stdout, " data.indep.serial=%d\n data.indep.scale=%d\n", qq->data.indep.serial,
5939 qq->data.indep.scale);
5940 fprintf (stdout, " data.sym=%p\n", (void*)qq->data.sym);
5941 fprintf (stdout, " data.p=%p\n", (void*)qq->data.p);
5942 fprintf (stdout, " data.node=%p\n", (void*)qq->data.node);
5943 fprintf (stdout, " subscript=%d\n", qq->subscript_.type);
5944 if (is_number(qq->subscript_)) {
5945 fprintf (stdout, " subscript_.data.val=%d\n", qq->subscript_.data.val);
5946 fprintf (stdout, " subscript_.data.dval=%f\n", qq->subscript_.data.dval);
5947 }
5948 fprintf (stdout, " hashloc=%p\n", (void*)qq->hashloc_);
5949 fprintf (stdout, " parent=%p\n", (void*)qq->parent_);
5950 fprintf (stdout, " attr_head=%p\n", (void*)qq->attr_head_);
5951 fprintf (stdout, " subscr_head=%p\n\n", (void*)qq->subscr_head_);
5952 }
5953 #endif
5954
5955 @ @<Declarations@>=
5956 static mp_node mp_get_value_node (MP mp);
5957 #if MPOST_DEBUG > 1
5958 static void debug_dump_value_node (mp_node x);
5959 #endif
5960
5961 @ An attribute node is three words long. Two of these words contain |type|
5962 and |value| fields as described above, and the third word contains
5963 additional information: There is an |hashloc| field, which contains the
5964 hash address of the token that names this attribute; and there's also a
5965 |parent| field, which points to the value node of |mp_structured| type at the
5966 next higher level (i.e., at the level to which this attribute is
5967 subsidiary). The |name_type| in an attribute node is `|attr|'. The
5968 |link| field points to the next attribute with the same parent; these are
5969 arranged in increasing order, so that |hashloc(mp_link(p))>hashloc(p)|. The
5970 final attribute node links to the constant |end_attr|, whose |hashloc|
5971 field is greater than any legal hash address. The |attr_head| in the
5972 parent points to a node whose |name_type| is |mp_structured_root|; this
5973 node represents the NULL attribute, i.e., the variable that is relevant
5974 when no attributes are attached to the parent. The |attr_head| node
5975 has the fields of either
5976 a value node, a subscript node, or an attribute node, depending on what
5977 the parent would be if it were not structured; but the subscript and
5978 attribute fields are ignored, so it effectively contains only the data of
5979 a value node. The |link| field in this special node points to an attribute
5980 node whose |hashloc| field is zero; the latter node represents a collective
5981 subscript `\.{[]}' attached to the parent, and its |link| field points to
5982 the first non-special attribute node (or to |end_attr| if there are none).
5983
5984 A subscript node likewise occupies three words, with |type| and |value| fields
5985 plus extra information; its |name_type| is |subscr|. In this case the
5986 third word is called the |subscript| field, which is a |scaled| integer.
5987 The |link| field points to the subscript node with the next larger
5988 subscript, if any; otherwise the |link| points to the attribute node
5989 for collective subscripts at this level. We have seen that the latter node
5990 contains an upward pointer, so that the parent can be deduced.
5991
5992 The |name_type| in a parent-less value node is |root|, and the |link|
5993 is the hash address of the token that names this value.
5994
5995 In other words, variables have a hierarchical structure that includes
5996 enough threads running around so that the program is able to move easily
5997 between siblings, parents, and children. An example should be helpful:
5998 (The reader is advised to draw a picture while reading the following
5999 description, since that will help to firm up the ideas.)
6000 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6001 and `\.{x20b}' have been mentioned in a user's program, where
6002 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6003 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6004 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a non-symbolic value
6005 node with |mp_name_type(p)=root| and |mp_link(p)=h(x)|. We have |type(p)=mp_structured|,
6006 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6007 node and |r| to a subscript node. (Are you still following this? Use
6008 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6009 |type(q)| and |value(q)|; furthermore
6010 |mp_name_type(q)=mp_structured_root| and |mp_link(q)=q1|, where |q1| points
6011 to an attribute node representing `\.{x[]}'. Thus |mp_name_type(q1)=attr|,
6012 |hashloc(q1)=collective_subscript=0|, |parent(q1)=p|,
6013 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6014 |qq| is a three-word ``attribute-as-value'' node with |type(qq)=numeric_type|
6015 (assuming that \.{x5} is numeric, because |qq| represents `\.{x[]}'
6016 with no further attributes), |mp_name_type(qq)=structured_root|,
6017 |hashloc(qq)=0|, |parent(qq)=p|, and
6018 |mp_link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6019 an attribute node representing `\.{x[][]}', which has never yet
6020 occurred; its |type| field is |undefined|, and its |value| field is
6021 undefined. We have |mp_name_type(qq1)=attr|, |hashloc(qq1)=collective_subscript|,
6022 |parent(qq1)=q1|, and |mp_link(qq1)=qq2|. Since |qq2| represents
6023 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |hashloc(qq2)=h(b)|,
6024 |parent(qq2)=q1|, |mp_name_type(qq2)=attr|, |mp_link(qq2)=end_attr|.
6025 (Maybe colored lines will help untangle your picture.)
6026 Node |r| is a subscript node with |type| and |value|
6027 representing `\.{x5}'; |mp_name_type(r)=subscr|, |subscript(r)=5.0|,
6028 and |mp_link(r)=r1| is another subscript node. To complete the picture,
6029 see if you can guess what |mp_link(r1)| is; give up? It's~|q1|.
6030 Furthermore |subscript(r1)=20.0|, |mp_name_type(r1)=subscr|,
6031 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6032 and we finish things off with three more nodes
6033 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6034 with a larger sheet of paper.) The value of variable \.{x20b}
6035 appears in node~|qqq2|, as you can well imagine.
6036
6037 If the example in the previous paragraph doesn't make things crystal
6038 clear, a glance at some of the simpler subroutines below will reveal how
6039 things work out in practice.
6040
6041 The only really unusual thing about these conventions is the use of
6042 collective subscript attributes. The idea is to avoid repeating a lot of
6043 type information when many elements of an array are identical macros
6044 (for which distinct values need not be stored) or when they don't have
6045 all of the possible attributes. Branches of the structure below collective
6046 subscript attributes do not carry actual values except for macro identifiers;
6047 branches of the structure below subscript nodes do not carry significant
6048 information in their collective subscript attributes.
6049
6050
6051 @c
6052 #if MPOST_DEBUG
6053 #define hashloc(A) @[do_get_hashloc(mp,(mp_value_node)(A))@]
6054 #define set_hashloc(A,B) @[do_set_hashloc (mp,(mp_value_node)A, B)@]
6055 #define parent(A) @[do_get_parent(mp, A)@]
6056 #define set_parent(A,B) @[do_set_parent (mp,(mp_value_node)A, B)@]
6057 static mp_sym do_get_hashloc (MP mp, mp_value_node A) {
6058 assert((A)->type == mp_attr_node_type || (A)->name_type == mp_attr);
6059 return (A)->hashloc_;
6060 }
6061 static void do_set_hashloc (MP mp, mp_value_node A, mp_sym B) {
6062 FUNCTION_TRACE4 ("set_hashloc(%p,%p) on line %d\n", (A), (B), __LINE__);
6063 assert((A)->type == mp_attr_node_type || (A)->name_type == mp_attr);
6064 A->hashloc_ = B;
6065 }
6066 static mp_node do_get_parent (MP mp, mp_value_node A) {
6067 assert((A)->type == mp_attr_node_type || (A)->name_type == mp_attr);
6068 return (A)->parent_; /* pointer to |mp_structured| variable */
6069 }
6070 static void do_set_parent (MP mp, mp_value_node A, mp_node d) {
6071 assert((A)->type == mp_attr_node_type || (A)->name_type == mp_attr);
6072 FUNCTION_TRACE4 ("set_parent(%p,%p) on line %d\n", (A), d, __LINE__);
6073 A->parent_ = d;
6074 }
6075 #else
6076 #define hashloc(A) @[((mp_value_node)(A))->hashloc_@]
6077 #define set_hashloc(A,B) @[((mp_value_node)(A))->hashloc_ = B@]
6078 #define parent(A) @[((mp_value_node)(A))->parent_@]
6079 #define set_parent(A,B) @[((mp_value_node)(A))->parent_ = B@]
6080 #endif
6081
6082 @ @d mp_free_attr_node(a,b) do {
6083 assert((b)->type == mp_attr_node_type || (b)->name_type == mp_attr);
6084 mp_free_value_node(a,b);
6085 } while (0)@;
6086
6087 @c
6088 static mp_value_node mp_get_attr_node (MP mp) {
6089 mp_value_node p = (mp_value_node) mp_get_value_node (mp);
6090 mp_type (p) = mp_attr_node_type;
6091 return p;
6092 }
6093
6094
6095 @ Setting the |hashloc| field of |end_attr| to a value greater than
6096 any legal hash address is done by assigning $-1$ typecasted to
6097 |mp_sym|, hopefully resulting in all bits being set. On systems that
6098 support negative pointer values or where typecasting $-1$ does not
6099 result in all bits in a pointer being set, something else needs to be done.
6100 @^system dependencies@>
6101
6102 @<Initialize table...@>=
6103 mp->end_attr = (mp_node) mp_get_attr_node (mp);
6104 set_hashloc (mp->end_attr, (mp_sym)-1);
6105 set_parent ((mp_value_node) mp->end_attr, NULL);
6106
6107 @ @<Free table...@>=
6108 mp_free_attr_node (mp, mp->end_attr);
6109
6110 @ @d collective_subscript (void *)0 /* code for the attribute `\.{[]}' */
6111 @d subscript(A) ((mp_value_node)(A))->subscript_
6112 @d set_subscript(A,B) do_set_subscript (mp, (mp_value_node)(A), B)
6113
6114 @c
6115 static void do_set_subscript (MP mp, mp_value_node A, mp_number B) {
6116 FUNCTION_TRACE3("set_subscript(%p,%p)\n", (A), (B));
6117 assert((A)->type == mp_subscr_node_type || (A)->name_type == mp_subscr);
6118 number_clone(A->subscript_,B); /* subscript of this variable */
6119 }
6120
6121 @ @c
6122 static mp_value_node mp_get_subscr_node (MP mp) {
6123 mp_value_node p = (mp_value_node) mp_get_value_node (mp);
6124 mp_type (p) = mp_subscr_node_type;
6125 return p;
6126 }
6127
6128
6129 @ Variables of type \&{pair} will have values that point to four-word
6130 nodes containing two numeric values. The first of these values has
6131 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6132 the |link| in the first points back to the node whose |value| points
6133 to this four-word node.
6134
6135 @d x_part(A) ((mp_pair_node)(A))->x_part_ /* where the \&{xpart} is found in a pair node */
6136 @d y_part(A) ((mp_pair_node)(A))->y_part_ /* where the \&{ypart} is found in a pair node */
6137
6138 @<MPlib internal header stuff@>=
6139 typedef struct mp_pair_node_data {
6140 NODE_BODY;@+@t}\6{@>
6141 mp_node x_part_;
6142 mp_node y_part_;
6143 } mp_pair_node_data;
6144 typedef struct mp_pair_node_data *mp_pair_node;
6145
6146 @ @d pair_node_size sizeof(struct mp_pair_node_data) /* the number of words in a subscript node */
6147
6148 @c
6149 static mp_node mp_get_pair_node (MP mp) {
6150 mp_node p;
6151 if (mp->pair_nodes) {
6152 p = mp->pair_nodes;
6153 mp->pair_nodes = p->link;
6154 mp->num_pair_nodes--;
6155 p->link = NULL;
6156 } else {
6157 p = malloc_node (pair_node_size);
6158 }
6159 mp_type (p) = mp_pair_node_type;
6160 FUNCTION_TRACE2("get_pair_node(): %p\n", p);
6161 return (mp_node) p;
6162 }
6163
6164 @ @<Declarations@>=
6165 void mp_free_pair_node (MP mp, mp_node p);
6166
6167 @ @c
6168 void mp_free_pair_node (MP mp, mp_node p) {
6169 FUNCTION_TRACE2 ("mp_free_pair_node(%p)\n", p);
6170 if (!p) return;
6171 if (mp->num_pair_nodes < max_num_pair_nodes) {
6172 p->link = mp->pair_nodes;
6173 mp->pair_nodes = p;
6174 mp->num_pair_nodes++;
6175 return;
6176 }
6177 mp->var_used -= pair_node_size;
6178 xfree (p);
6179 }
6180
6181
6182 @ If |type(p)=mp_pair_type| or if |value(p)=NULL|, the procedure call |init_pair_node(p)| will
6183 allocate a pair node for~|p|. The individual parts of such nodes are initially of type
6184 |mp_independent|.
6185
6186 @c
6187 static void mp_init_pair_node (MP mp, mp_node p) {
6188 mp_node q; /* the new node */
6189 mp_type (p) = mp_pair_type;
6190 q = mp_get_pair_node (mp);
6191 y_part (q) = mp_get_value_node (mp);
6192 mp_new_indep (mp, y_part (q)); /* sets |type(q)| and |value(q)| */
6193 mp_name_type (y_part (q)) = (quarterword) (mp_y_part_sector);
6194 mp_link (y_part (q)) = p;
6195 x_part (q) = mp_get_value_node (mp);
6196 mp_new_indep (mp, x_part (q)); /* sets |type(q)| and |value(q)| */
6197 mp_name_type (x_part (q)) = (quarterword) (mp_x_part_sector);
6198 mp_link (x_part (q)) = p;
6199 set_value_node (p, q);
6200 }
6201
6202
6203 @ Variables of type \&{transform} are similar, but in this case their
6204 |value| points to a 12-word node containing six values, identified by
6205 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6206 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6207
6208 @d tx_part(A) ((mp_transform_node)(A))->tx_part_ /* where the \&{xpart} is found in a transform node */
6209 @d ty_part(A) ((mp_transform_node)(A))->ty_part_ /* where the \&{ypart} is found in a transform node */
6210 @d xx_part(A) ((mp_transform_node)(A))->xx_part_ /* where the \&{xxpart} is found in a transform node */
6211 @d xy_part(A) ((mp_transform_node)(A))->xy_part_ /* where the \&{xypart} is found in a transform node */
6212 @d yx_part(A) ((mp_transform_node)(A))->yx_part_ /* where the \&{yxpart} is found in a transform node */
6213 @d yy_part(A) ((mp_transform_node)(A))->yy_part_ /* where the \&{yypart} is found in a transform node */
6214
6215 @<MPlib internal header stuff@>=
6216 typedef struct mp_transform_node_data {
6217 NODE_BODY;@+@t}\6{@>
6218 mp_node tx_part_;
6219 mp_node ty_part_;
6220 mp_node xx_part_;
6221 mp_node yx_part_;
6222 mp_node xy_part_;
6223 mp_node yy_part_;
6224 } mp_transform_node_data;
6225 typedef struct mp_transform_node_data *mp_transform_node;
6226
6227 @ @d transform_node_size sizeof(struct mp_transform_node_data) /* the number of words in a subscript node */
6228
6229 @c
6230 static mp_node mp_get_transform_node (MP mp) {
6231 mp_transform_node p = (mp_transform_node) malloc_node (transform_node_size);
6232 mp_type (p) = mp_transform_node_type;
6233 return (mp_node) p;
6234 }
6235
6236
6237 @ @c
6238 static void mp_init_transform_node (MP mp, mp_node p) {
6239 mp_node q; /* the new node */
6240 mp_type (p) = mp_transform_type;
6241 q = mp_get_transform_node (mp); /* big node */
6242 yy_part (q) = mp_get_value_node (mp);
6243 mp_new_indep (mp, yy_part (q)); /* sets |type(q)| and |value(q)| */
6244 mp_name_type (yy_part (q)) = (quarterword) (mp_yy_part_sector);
6245 mp_link (yy_part (q)) = p;
6246 yx_part (q) = mp_get_value_node (mp);
6247 mp_new_indep (mp, yx_part (q)); /* sets |type(q)| and |value(q)| */
6248 mp_name_type (yx_part (q)) = (quarterword) (mp_yx_part_sector);
6249 mp_link (yx_part (q)) = p;
6250 xy_part (q) = mp_get_value_node (mp);
6251 mp_new_indep (mp, xy_part (q)); /* sets |type(q)| and |value(q)| */
6252 mp_name_type (xy_part (q)) = (quarterword) (mp_xy_part_sector);
6253 mp_link (xy_part (q)) = p;
6254 xx_part (q) = mp_get_value_node (mp);
6255 mp_new_indep (mp, xx_part (q)); /* sets |type(q)| and |value(q)| */
6256 mp_name_type (xx_part (q)) = (quarterword) (mp_xx_part_sector);
6257 mp_link (xx_part (q)) = p;
6258 ty_part (q) = mp_get_value_node (mp);
6259 mp_new_indep (mp, ty_part (q)); /* sets |type(q)| and |value(q)| */
6260 mp_name_type (ty_part (q)) = (quarterword) (mp_y_part_sector);
6261 mp_link (ty_part (q)) = p;
6262 tx_part (q) = mp_get_value_node (mp);
6263 mp_new_indep (mp, tx_part (q)); /* sets |type(q)| and |value(q)| */
6264 mp_name_type (tx_part (q)) = (quarterword) (mp_x_part_sector);
6265 mp_link (tx_part (q)) = p;
6266 set_value_node (p, q);
6267 }
6268
6269
6270 @ Variables of type \&{color} have 3~values in 6~words identified by |mp_red_part_sector|,
6271 |mp_green_part_sector|, and |mp_blue_part_sector|.
6272
6273 @d red_part(A) ((mp_color_node)(A))->red_part_ /* where the \&{redpart} is found in a color node */
6274 @d green_part(A) ((mp_color_node)(A))->green_part_ /* where the \&{greenpart} is found in a color node */
6275 @d blue_part(A) ((mp_color_node)(A))->blue_part_ /* where the \&{bluepart} is found in a color node */
6276
6277 @d grey_part(A) red_part(A) /* where the \&{greypart} is found in a color node */
6278
6279 @<MPlib internal header stuff@>=
6280 typedef struct mp_color_node_data {
6281 NODE_BODY;@+@t}\6{@>
6282 mp_node red_part_;
6283 mp_node green_part_;
6284 mp_node blue_part_;
6285 } mp_color_node_data;
6286 typedef struct mp_color_node_data *mp_color_node;
6287
6288 @ @d color_node_size sizeof(struct mp_color_node_data) /* the number of words in a subscript node */
6289
6290 @c
6291 static mp_node mp_get_color_node (MP mp) {
6292 mp_color_node p = (mp_color_node) malloc_node (color_node_size);
6293 mp_type (p) = mp_color_node_type;
6294 p->link = NULL;
6295 return (mp_node) p;
6296 }
6297
6298
6299 @ @c
6300 static void mp_init_color_node (MP mp, mp_node p) {
6301 mp_node q; /* the new node */
6302 mp_type (p) = mp_color_type;
6303 q = mp_get_color_node (mp); /* big node */
6304 blue_part (q) = mp_get_value_node (mp);
6305 mp_new_indep (mp, blue_part (q)); /* sets |type(q)| and |value(q)| */
6306 mp_name_type (blue_part (q)) = (quarterword) (mp_blue_part_sector);
6307 mp_link (blue_part (q)) = p;
6308 green_part (q) = mp_get_value_node (mp);
6309 mp_new_indep (mp, green_part (q)); /* sets |type(q)| and |value(q)| */
6310 mp_name_type (y_part (q)) = (quarterword) (mp_green_part_sector);
6311 mp_link (green_part (q)) = p;
6312 red_part (q) = mp_get_value_node (mp);
6313 mp_new_indep (mp, red_part (q)); /* sets |type(q)| and |value(q)| */
6314 mp_name_type (red_part (q)) = (quarterword) (mp_red_part_sector);
6315 mp_link (red_part (q)) = p;
6316 set_value_node (p, q);
6317 }
6318
6319
6320 @ Finally, variables of type |cmykcolor|.
6321
6322 @d cyan_part(A) ((mp_cmykcolor_node)(A))->cyan_part_ /* where the \&{cyanpart} is found in a color node */
6323 @d magenta_part(A) ((mp_cmykcolor_node)(A))->magenta_part_ /* where the \&{magentapart} is found in a color node */
6324 @d yellow_part(A) ((mp_cmykcolor_node)(A))->yellow_part_ /* where the \&{yellowpart} is found in a color node */
6325 @d black_part(A) ((mp_cmykcolor_node)(A))->black_part_ /* where the \&{blackpart} is found in a color node */
6326
6327 @<MPlib internal header stuff@>=
6328 typedef struct mp_cmykcolor_node_data {
6329 NODE_BODY;@+@t}\6{@>
6330 mp_node cyan_part_;
6331 mp_node magenta_part_;
6332 mp_node yellow_part_;
6333 mp_node black_part_;
6334 } mp_cmykcolor_node_data;
6335 typedef struct mp_cmykcolor_node_data *mp_cmykcolor_node;
6336
6337 @ @d cmykcolor_node_size sizeof(struct mp_cmykcolor_node_data) /* the number of words in a subscript node */
6338
6339 @c
6340 static mp_node mp_get_cmykcolor_node (MP mp) {
6341 mp_cmykcolor_node p = (mp_cmykcolor_node) malloc_node (cmykcolor_node_size);
6342 mp_type (p) = mp_cmykcolor_node_type;
6343 p->link = NULL;
6344 return (mp_node) p;
6345 }
6346
6347
6348 @ @c
6349 static void mp_init_cmykcolor_node (MP mp, mp_node p) {
6350 mp_node q; /* the new node */
6351 mp_type (p) = mp_cmykcolor_type;
6352 q = mp_get_cmykcolor_node (mp); /* big node */
6353 black_part (q) = mp_get_value_node (mp);
6354 mp_new_indep (mp, black_part (q)); /* sets |type(q)| and |value(q)| */
6355 mp_name_type (black_part (q)) = (quarterword) (mp_black_part_sector);
6356 mp_link (black_part (q)) = p;
6357 yellow_part (q) = mp_get_value_node (mp);
6358 mp_new_indep (mp, yellow_part (q)); /* sets |type(q)| and |value(q)| */
6359 mp_name_type (yellow_part (q)) = (quarterword) (mp_yellow_part_sector);
6360 mp_link (yellow_part (q)) = p;
6361 magenta_part (q) = mp_get_value_node (mp);
6362 mp_new_indep (mp, magenta_part (q)); /* sets |type(q)| and |value(q)| */
6363 mp_name_type (magenta_part (q)) = (quarterword) (mp_magenta_part_sector);
6364 mp_link (magenta_part (q)) = p;
6365 cyan_part (q) = mp_get_value_node (mp);
6366 mp_new_indep (mp, cyan_part (q)); /* sets |type(q)| and |value(q)| */
6367 mp_name_type (cyan_part (q)) = (quarterword) (mp_cyan_part_sector);
6368 mp_link (cyan_part (q)) = p;
6369 set_value_node (p, q);
6370 }
6371
6372
6373 @ When an entire structured variable is saved, the |root| indication
6374 is temporarily replaced by |saved_root|.
6375
6376 Some variables have no name; they just are used for temporary storage
6377 while expressions are being evaluated. We call them {\sl capsules}.
6378
6379 @ The |id_transform| function creates a capsule for the
6380 identity transformation.
6381
6382 @c
6383 static mp_node mp_id_transform (MP mp) {
6384 mp_node p, q; /* list manipulation registers */
6385 p = mp_get_value_node (mp);
6386 mp_name_type (p) = mp_capsule;
6387 set_value_number (p, zero_t); /* TODO: this was |NULL| */
6388 mp_init_transform_node (mp, p);
6389 q = value_node (p);
6390 mp_type (tx_part (q)) = mp_known;
6391 set_value_number (tx_part (q), zero_t);
6392 mp_type (ty_part (q)) = mp_known;
6393 set_value_number (ty_part (q), zero_t);
6394 mp_type (xy_part (q)) = mp_known;
6395 set_value_number (xy_part (q), zero_t);
6396 mp_type (yx_part (q)) = mp_known;
6397 set_value_number (yx_part (q), zero_t);
6398 mp_type (xx_part (q)) = mp_known;
6399 set_value_number (xx_part (q), unity_t);
6400 mp_type (yy_part (q)) = mp_known;
6401 set_value_number (yy_part (q), unity_t);
6402 return p;
6403 }
6404
6405
6406 @ Tokens are of type |tag_token| when they first appear, but they point
6407 to |NULL| until they are first used as the root of a variable.
6408 The following subroutine establishes the root node on such grand occasions.
6409
6410 @c
6411 static void mp_new_root (MP mp, mp_sym x) {
6412 mp_node p; /* the new node */
6413 p = mp_get_value_node (mp);
6414 mp_type (p) = mp_undefined;
6415 mp_name_type (p) = mp_root;
6416 set_value_sym (p, x);
6417 set_equiv_node (x, p);
6418 }
6419
6420
6421 @ These conventions for variable representation are illustrated by the
6422 |print_variable_name| routine, which displays the full name of a
6423 variable given only a pointer to its value.
6424
6425 @<Declarations@>=
6426 static void mp_print_variable_name (MP mp, mp_node p);
6427
6428 @ @c
6429 void mp_print_variable_name (MP mp, mp_node p) {
6430 mp_node q; /* a token list that will name the variable's suffix */
6431 mp_node r; /* temporary for token list creation */
6432 while (mp_name_type (p) >= mp_x_part_sector) {
6433 switch (mp_name_type (p)) {
6434 case mp_x_part_sector: mp_print (mp, "xpart "); break;
6435 case mp_y_part_sector: mp_print (mp, "ypart "); break;
6436 case mp_xx_part_sector: mp_print (mp, "xxpart "); break;
6437 case mp_xy_part_sector: mp_print (mp, "xypart "); break;
6438 case mp_yx_part_sector: mp_print (mp, "yxpart "); break;
6439 case mp_yy_part_sector: mp_print (mp, "yypart "); break;
6440 case mp_red_part_sector: mp_print (mp, "redpart "); break;
6441 case mp_green_part_sector: mp_print (mp, "greenpart "); break;
6442 case mp_blue_part_sector: mp_print (mp, "bluepart "); break;
6443 case mp_cyan_part_sector: mp_print (mp, "cyanpart "); break;
6444 case mp_magenta_part_sector:mp_print (mp, "magentapart ");break;
6445 case mp_yellow_part_sector: mp_print (mp, "yellowpart "); break;
6446 case mp_black_part_sector: mp_print (mp, "blackpart "); break;
6447 case mp_grey_part_sector: mp_print (mp, "greypart "); break;
6448 case mp_capsule: mp_printf (mp, "%%CAPSULE%p",p); return; break;
6449 default: /* this is to please the compiler: the remaining cases are operation codes */
6450 break;
6451 }
6452 p = mp_link (p);
6453 }
6454 q = NULL;
6455 while (mp_name_type (p) > mp_saved_root) {
6456 /* Ascend one level, pushing a token onto list |q|
6457 and replacing |p| by its parent */
6458 if (mp_name_type (p) == mp_subscr) {
6459 r = mp_new_num_tok (mp, subscript (p));
6460 do {
6461 p = mp_link (p);
6462 } while (mp_name_type (p) != mp_attr);
6463 } else if (mp_name_type (p) == mp_structured_root) {
6464 p = mp_link (p);
6465 goto FOUND;
6466 } else {
6467 if (mp_name_type (p) != mp_attr)
6468 mp_confusion (mp, "var");
6469 r = mp_get_symbolic_node (mp);
6470 set_mp_sym_sym (r, hashloc (p)); /* the hash address */
6471 }
6472 set_mp_link (r, q);
6473 q = r;
6474 FOUND:
6475 p = parent ((mp_value_node) p);
6476
6477 }
6478 /* now |link(p)| is the hash address of |p|, and
6479 |name_type(p)| is either |root| or |saved_root|.
6480 Have to prepend a token to |q| for |show_token_list|. */
6481 r = mp_get_symbolic_node (mp);
6482 set_mp_sym_sym (r, value_sym (p));
6483 mp_link (r) = q;
6484 if (mp_name_type (p) == mp_saved_root)
6485 mp_print (mp, "(SAVED)");
6486 mp_show_token_list (mp, r, NULL, max_integer, mp->tally);
6487 mp_flush_token_list (mp, r);
6488 }
6489
6490 @ The |interesting| function returns |true| if a given variable is not
6491 in a capsule, or if the user wants to trace capsules.
6492
6493 @c
6494 static boolean mp_interesting (MP mp, mp_node p) {
6495 mp_name_type_type t; /* a |name_type| */
6496 if (number_positive(internal_value (mp_tracing_capsules))) {
6497 return true;
6498 } else {
6499 t = mp_name_type (p);
6500 if (t >= mp_x_part_sector && t != mp_capsule) {
6501 mp_node tt = value_node(mp_link(p));
6502 switch (t) {
6503 case mp_x_part_sector:
6504 t = mp_name_type (x_part (tt));
6505 break;
6506 case mp_y_part_sector:
6507 t = mp_name_type (y_part (tt));
6508 break;
6509 case mp_xx_part_sector:
6510 t = mp_name_type (xx_part (tt));
6511 break;
6512 case mp_xy_part_sector:
6513 t = mp_name_type (xy_part (tt));
6514 break;
6515 case mp_yx_part_sector:
6516 t = mp_name_type (yx_part (tt));
6517 break;
6518 case mp_yy_part_sector:
6519 t = mp_name_type (yy_part (tt));
6520 break;
6521 case mp_red_part_sector:
6522 t = mp_name_type (red_part (tt));
6523 break;
6524 case mp_green_part_sector:
6525 t = mp_name_type (green_part (tt));
6526 break;
6527 case mp_blue_part_sector:
6528 t = mp_name_type (blue_part (tt));
6529 break;
6530 case mp_cyan_part_sector:
6531 t = mp_name_type (cyan_part (tt));
6532 break;
6533 case mp_magenta_part_sector:
6534 t = mp_name_type (magenta_part (tt));
6535 break;
6536 case mp_yellow_part_sector:
6537 t = mp_name_type (yellow_part (tt));
6538 break;
6539 case mp_black_part_sector:
6540 t = mp_name_type (black_part (tt));
6541 break;
6542 case mp_grey_part_sector:
6543 t = mp_name_type (grey_part (tt));
6544 break;
6545 default:
6546 break;
6547 }
6548 }
6549 }
6550 return (t != mp_capsule);
6551 }
6552
6553
6554 @ Now here is a subroutine that converts an unstructured type into an
6555 equivalent structured type, by inserting a |mp_structured| node that is
6556 capable of growing. This operation is done only when |mp_name_type(p)=root|,
6557 |subscr|, or |attr|.
6558
6559 The procedure returns a pointer to the new node that has taken node~|p|'s
6560 place in the structure. Node~|p| itself does not move, nor are its
6561 |value| or |type| fields changed in any way.
6562
6563 @c
6564 static mp_node mp_new_structure (MP mp, mp_node p) {
6565 mp_node q, r = NULL; /* list manipulation registers */
6566 mp_sym qq = NULL;
6567 switch (mp_name_type (p)) {
6568 case mp_root:
6569 {
6570 qq = value_sym (p);
6571 r = mp_get_value_node (mp);
6572 set_equiv_node (qq, r);
6573 }
6574 break;
6575 case mp_subscr:
6576 /* Link a new subscript node |r| in place of node |p| */
6577 {
6578 mp_node q_new;
6579 q = p;
6580 do {
6581 q = mp_link (q);
6582 } while (mp_name_type (q) != mp_attr);
6583 q = parent ((mp_value_node) q);
6584 r = mp->temp_head;
6585 set_mp_link (r, subscr_head (q));
6586 do {
6587 q_new = r;
6588 r = mp_link (r);
6589 } while (r != p);
6590 r = (mp_node) mp_get_subscr_node (mp);
6591 if (q_new == mp->temp_head) {
6592 set_subscr_head (q, r);
6593 } else {
6594 set_mp_link (q_new, r);
6595 }
6596 set_subscript (r, subscript (p));
6597 }
6598
6599 break;
6600 case mp_attr:
6601 /* Link a new attribute node |r| in place of node |p| */
6602 /* If the attribute is |collective_subscript|, there are two pointers to
6603 node~|p|, so we must change both of them. */
6604 {
6605 mp_value_node rr;
6606 q = parent ((mp_value_node) p);
6607 r = attr_head (q);
6608 do {
6609 q = r;
6610 r = mp_link (r);
6611 } while (r != p);
6612 rr = mp_get_attr_node (mp);
6613 r = (mp_node) rr;
6614 set_mp_link (q, (mp_node) rr);
6615 set_hashloc (rr, hashloc (p));
6616 set_parent (rr, parent ((mp_value_node) p));
6617 if (hashloc (p) == collective_subscript) {
6618 q = mp->temp_head;
6619 set_mp_link (q, subscr_head (parent ((mp_value_node) p)));
6620 while (mp_link (q) != p)
6621 q = mp_link (q);
6622 if (q == mp->temp_head)
6623 set_subscr_head (parent ((mp_value_node) p), (mp_node) rr);
6624 else
6625 set_mp_link (q, (mp_node) rr);
6626 }
6627 }
6628
6629 break;
6630 default:
6631 mp_confusion (mp, "struct");
6632 break;
6633 }
6634 set_mp_link (r, mp_link (p));
6635 set_value_sym (r, value_sym (p));
6636 mp_type (r) = mp_structured;
6637 mp_name_type (r) = mp_name_type (p);
6638 set_attr_head (r, p);
6639 mp_name_type (p) = mp_structured_root;
6640 {
6641 mp_value_node qqr = mp_get_attr_node (mp);
6642 set_mp_link (p, (mp_node) qqr);
6643 set_subscr_head (r, (mp_node) qqr);
6644 set_parent (qqr, r);
6645 mp_type (qqr) = mp_undefined;
6646 mp_name_type (qqr) = mp_attr;
6647 set_mp_link (qqr, mp->end_attr);
6648 set_hashloc (qqr, collective_subscript);
6649 }
6650 return r;
6651 }
6652
6653 @ The |mp_find_variable| routine is given a pointer~|t| to a nonempty token
6654 list of suffixes; it returns a pointer to the corresponding non-symbolic
6655 value. For example, if |t| points to token \.x followed by a numeric
6656 token containing the value~7, |find_variable| finds where the value of
6657 \.{x7} is stored in memory. This may seem a simple task, and it
6658 usually is, except when \.{x7} has never been referenced before.
6659 Indeed, \.x may never have even been subscripted before; complexities
6660 arise with respect to updating the collective subscript information.
6661
6662 If a macro type is detected anywhere along path~|t|, or if the first
6663 item on |t| isn't a |tag_token|, the value |NULL| is returned.
6664 Otherwise |p| will be a non-NULL pointer to a node such that
6665 |undefined<type(p)<mp_structured|.
6666
6667 @c
6668 static mp_node mp_find_variable (MP mp, mp_node t) {
6669 mp_node p, q, r, s; /* nodes in the ``value'' line */
6670 mp_sym p_sym;
6671 mp_node pp, qq, rr, ss; /* nodes in the ``collective'' line */
6672 @^inner loop@>
6673 p_sym = mp_sym_sym (t);
6674 t = mp_link (t);
6675 if ((eq_type (p_sym) % mp_outer_tag) != mp_tag_token)
6676 return NULL;
6677 if (equiv_node (p_sym) == NULL)
6678 mp_new_root (mp, p_sym);
6679 p = equiv_node (p_sym);
6680 pp = p;
6681 while (t != NULL) {
6682 /* Make sure that both nodes |p| and |pp| are of |mp_structured| type */
6683 /* Although |pp| and |p| begin together, they diverge when a subscript occurs;
6684 |pp|~stays in the collective line while |p|~goes through actual subscript
6685 values. */
6686 if (mp_type (pp) != mp_structured) {
6687 if (mp_type (pp) > mp_structured)
6688 return NULL;
6689 ss = mp_new_structure (mp, pp);
6690 if (p == pp)
6691 p = ss;
6692 pp = ss;
6693 } /* now |type(pp)=mp_structured| */
6694 if (mp_type (p) != mp_structured) { /* it cannot be |>mp_structured| */
6695 p = mp_new_structure (mp, p); /* now |type(p)=mp_structured| */
6696 }
6697
6698 if (mp_type (t) != mp_symbol_node) {
6699 /* Descend one level for the subscript |value(t)| */
6700 /* We want this part of the program to be reasonably fast, in case there are
6701 lots of subscripts at the same level of the data structure. Therefore
6702 we store an ``infinite'' value in the word that appears at the end of the
6703 subscript list, even though that word isn't part of a subscript node. */
6704 mp_number nn, save_subscript; /* temporary storage */
6705 new_number (nn);
6706 new_number (save_subscript);
6707 number_clone (nn, value_number (t));
6708 pp = mp_link (attr_head (pp)); /* now |hashloc(pp)=collective_subscript| */
6709 q = mp_link (attr_head (p));
6710 number_clone (save_subscript, subscript (q));
6711 set_number_to_inf(subscript (q));
6712 s = mp->temp_head;
6713 set_mp_link (s, subscr_head (p));
6714 do {
6715 r = s;
6716 s = mp_link (s);
6717 } while (number_greater (nn, subscript (s)));
6718 if (number_equal(nn, subscript (s))) {
6719 p = s;
6720 } else {
6721 mp_value_node p1 = mp_get_subscr_node (mp);
6722 if (r == mp->temp_head)
6723 set_subscr_head (p, (mp_node) p1);
6724 else
6725 set_mp_link (r, (mp_node) p1);
6726 set_mp_link (p1, s);
6727 number_clone (subscript (p1), nn);
6728 mp_name_type (p1) = mp_subscr;
6729 mp_type (p1) = mp_undefined;
6730 p = (mp_node) p1;
6731 }
6732 number_clone (subscript (q), save_subscript);
6733 free_number (save_subscript);
6734 free_number (nn);
6735 } else {
6736 /* Descend one level for the attribute |mp_sym_info(t)| */
6737 mp_sym nn1 = mp_sym_sym (t);
6738 ss = attr_head (pp);
6739 do {
6740 rr = ss;
6741 ss = mp_link (ss);
6742 } while (nn1 > hashloc (ss));
6743 if (nn1 < hashloc (ss)) {
6744 qq = (mp_node) mp_get_attr_node (mp);
6745 set_mp_link (rr, qq);
6746 set_mp_link (qq, ss);
6747 set_hashloc (qq, nn1);
6748 mp_name_type (qq) = mp_attr;
6749 mp_type (qq) = mp_undefined;
6750 set_parent ((mp_value_node) qq, pp);
6751 ss = qq;
6752 }
6753 if (p == pp) {
6754 p = ss;
6755 pp = ss;
6756 } else {
6757 pp = ss;
6758 s = attr_head (p);
6759 do {
6760 r = s;
6761 s = mp_link (s);
6762 } while (nn1 > hashloc (s));
6763 if (nn1 == hashloc (s)) {
6764 p = s;
6765 } else {
6766 q = (mp_node) mp_get_attr_node (mp);
6767 set_mp_link (r, q);
6768 set_mp_link (q, s);
6769 set_hashloc (q, nn1);
6770 mp_name_type (q) = mp_attr;
6771 mp_type (q) = mp_undefined;
6772 set_parent ((mp_value_node) q, p);
6773 p = q;
6774 }
6775 }
6776 }
6777 t = mp_link (t);
6778 }
6779 if (mp_type (pp) >= mp_structured) {
6780 if (mp_type (pp) == mp_structured)
6781 pp = attr_head (pp);
6782 else
6783 return NULL;
6784 }
6785 if (mp_type (p) == mp_structured)
6786 p = attr_head (p);
6787 if (mp_type (p) == mp_undefined) {
6788 if (mp_type (pp) == mp_undefined) {
6789 mp_type (pp) = mp_numeric_type;
6790 set_value_number (pp, zero_t);
6791 }
6792 mp_type (p) = mp_type (pp);
6793 set_value_number (p, zero_t);
6794 }
6795 return p;
6796 }
6797
6798
6799 @ Variables lose their former values when they appear in a type declaration,
6800 or when they are defined to be macros or \&{let} equal to something else.
6801 A subroutine will be defined later that recycles the storage associated
6802 with any particular |type| or |value|; our goal now is to study a higher
6803 level process called |flush_variable|, which selectively frees parts of a
6804 variable structure.
6805
6806 This routine has some complexity because of examples such as
6807 `\hbox{\tt numeric x[]a[]b}'
6808 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6809 `\hbox{\tt vardef x[]a[]=...}'
6810 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6811 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6812 to handle such examples is to use recursion; so that's what we~do.
6813 @^recursion@>
6814
6815 Parameter |p| points to the root information of the variable;
6816 parameter |t| points to a list of symbolic nodes that represent
6817 suffixes, with |info=collective_subscript| for subscripts.
6818
6819 @<Declarations@>=
6820 void mp_flush_cur_exp (MP mp, mp_value v);
6821
6822 @ @c
6823 static void mp_flush_variable (MP mp, mp_node p, mp_node t,
6824 boolean discard_suffixes) {
6825 mp_node q, r = NULL; /* list manipulation */
6826 mp_sym n; /* attribute to match */
6827 while (t != NULL) {
6828 if (mp_type (p) != mp_structured) {
6829 return;
6830 }
6831 n = mp_sym_sym (t);
6832 t = mp_link (t);
6833 if (n == collective_subscript) {
6834 q = subscr_head (p);
6835 while (mp_name_type (q) == mp_subscr) {
6836 mp_flush_variable (mp, q, t, discard_suffixes);
6837 if (t == NULL) {
6838 if (mp_type (q) == mp_structured) {
6839 r = q;
6840 } else {
6841 if (r==NULL)
6842 set_subscr_head (p, mp_link (q));
6843 else
6844 set_mp_link (r, mp_link (q));
6845 mp_free_value_node (mp, q);
6846 }
6847 } else {
6848 r = q;
6849 }
6850 q = (r==NULL ? subscr_head (p) : mp_link (r));
6851 }
6852 }
6853 p = attr_head (p);
6854 do {
6855 p = mp_link (p);
6856 } while (hashloc (p) < n);
6857 if (hashloc (p) != n) {
6858 return;
6859 }
6860 }
6861 if (discard_suffixes) {
6862 mp_flush_below_variable (mp, p);
6863 } else {
6864 if (mp_type (p) == mp_structured) {
6865 p = attr_head (p);
6866 }
6867 mp_recycle_value (mp, p);
6868 }
6869 }
6870
6871
6872 @ The next procedure is simpler; it wipes out everything but |p| itself,
6873 which becomes undefined.
6874
6875 @<Declarations@>=
6876 static void mp_flush_below_variable (MP mp, mp_node p);
6877
6878 @ @c
6879 void mp_flush_below_variable (MP mp, mp_node p) {
6880 mp_node q, r; /* list manipulation registers */
6881 FUNCTION_TRACE2 ("mp_flush_below_variable(%p)\n", p);
6882 if (mp_type (p) != mp_structured) {
6883 mp_recycle_value (mp, p); /* this sets |type(p)=undefined| */
6884 } else {
6885 q = subscr_head (p);
6886 while (q && mp_name_type (q) == mp_subscr) {
6887 mp_flush_below_variable (mp, q);
6888 r = q;
6889 q = mp_link (q);
6890 mp_free_value_node (mp, r);
6891 }
6892 r = attr_head (p);
6893 q = mp_link (r);
6894 mp_recycle_value (mp, r);
6895 mp_free_value_node (mp, r);
6896 do {
6897 mp_flush_below_variable (mp, q);
6898 r = q;
6899 q = mp_link (q);
6900 mp_free_value_node (mp, r);
6901 } while (q != mp->end_attr);
6902 mp_type (p) = mp_undefined;
6903 }
6904 }
6905
6906
6907 @ Just before assigning a new value to a variable, we will recycle the
6908 old value and make the old value undefined. The |und_type| routine
6909 determines what type of undefined value should be given, based on
6910 the current type before recycling.
6911
6912 @c
6913 static quarterword mp_und_type (MP mp, mp_node p) {
6914 (void) mp;
6915 switch (mp_type (p)) {
6916 case mp_vacuous:
6917 return mp_undefined;
6918 case mp_boolean_type:
6919 case mp_unknown_boolean:
6920 return mp_unknown_boolean;
6921 case mp_string_type:
6922 case mp_unknown_string:
6923 return mp_unknown_string;
6924 case mp_pen_type:
6925 case mp_unknown_pen:
6926 return mp_unknown_pen;
6927 case mp_path_type:
6928 case mp_unknown_path:
6929 return mp_unknown_path;
6930 case mp_picture_type:
6931 case mp_unknown_picture:
6932 return mp_unknown_picture;
6933 case mp_transform_type:
6934 case mp_color_type:
6935 case mp_cmykcolor_type:
6936 case mp_pair_type:
6937 case mp_numeric_type:
6938 return mp_type (p);
6939 case mp_known:
6940 case mp_dependent:
6941 case mp_proto_dependent:
6942 case mp_independent:
6943 return mp_numeric_type;
6944 default: /* there are no other valid cases, but please the compiler */
6945 return 0;
6946 }
6947 return 0;
6948 }
6949
6950
6951 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6952 of a symbolic token. It must remove any variable structure or macro
6953 definition that is currently attached to that symbol. If the |saving|
6954 parameter is true, a subsidiary structure is saved instead of destroyed.
6955
6956 @c
6957 static void mp_clear_symbol (MP mp, mp_sym p, boolean saving) {
6958 mp_node q; /* |equiv(p)| */
6959 FUNCTION_TRACE3 ("mp_clear_symbol(%p,%d)\n", p, saving);
6960 q = equiv_node (p);
6961 switch (eq_type (p) % mp_outer_tag) {
6962 case mp_defined_macro:
6963 case mp_secondary_primary_macro:
6964 case mp_tertiary_secondary_macro:
6965 case mp_expression_tertiary_macro:
6966 if (!saving)
6967 mp_delete_mac_ref (mp, q);
6968 break;
6969 case mp_tag_token:
6970 if (q != NULL) {
6971 if (saving) {
6972 mp_name_type (q) = mp_saved_root;
6973 } else {
6974 mp_flush_below_variable (mp, q);
6975 mp_free_value_node (mp, q);
6976 }
6977 }
6978 break;
6979 default:
6980 break;
6981 }
6982 set_equiv (p, mp->frozen_undefined->v.data.indep.serial);
6983 set_eq_type (p, mp->frozen_undefined->type);
6984 }
6985
6986
6987 @* Saving and restoring equivalents.
6988 The nested structure given by \&{begingroup} and \&{endgroup}
6989 allows |eqtb| entries to be saved and restored, so that temporary changes
6990 can be made without difficulty. When the user requests a current value to
6991 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6992 \&{endgroup} ultimately causes the old values to be removed from the save
6993 stack and put back in their former places.
6994
6995 The save stack is a linked list containing three kinds of entries,
6996 distinguished by their |type| fields. If |p| points to a saved item,
6997 then
6998
6999 \smallskip\hang
7000 |p->type=0| stands for a group boundary; each \&{begingroup} contributes
7001 such an item to the save stack and each \&{endgroup} cuts back the stack
7002 until the most recent such entry has been removed.
7003
7004 \smallskip\hang
7005 |p->type=mp_normal_sym| means that |p->value| holds the former
7006 contents of |eqtb[q]| (saved in the |knot| field of the value, which
7007 is otherwise unused for variables). Such save stack entries are generated by \&{save}
7008 commands.
7009
7010 \smallskip\hang
7011 |p->type=mp_internal_sym| means that |p->value| is a |mp_internal|
7012 to be restored to internal parameter number~|q| (saved in the |serial| field of the value, which
7013 is otherwise unused for internals). Such entries are generated by \&{interim} commands.
7014
7015 \smallskip\noindent
7016 The global variable |save_ptr| points to the top item on the save stack.
7017
7018 @<Types...@>=
7019 typedef struct mp_save_data {
7020 quarterword type;
7021 mp_internal value;
7022 struct mp_save_data *link;
7023 } mp_save_data;
7024
7025 @ @<Glob...@>=
7026 mp_save_data *save_ptr; /* the most recently saved item */
7027
7028 @ @<Set init...@>=
7029 mp->save_ptr = NULL;
7030
7031 @ Saving a boundary item
7032 @c
7033 static void mp_save_boundary (MP mp) {
7034 mp_save_data *p; /* temporary register */
7035 FUNCTION_TRACE1 ("mp_save_boundary ()\n");
7036 p = xmalloc (1, sizeof (mp_save_data));
7037 p->type = 0;
7038 p->link = mp->save_ptr;
7039 mp->save_ptr = p;
7040 }
7041
7042
7043 @ The |save_variable| routine is given a hash address |q|; it salts this
7044 address in the save stack, together with its current equivalent,
7045 then makes token~|q| behave as though it were brand new.
7046
7047 Nothing is stacked when |save_ptr=NULL|, however; there's no way to remove
7048 things from the stack when the program is not inside a group, so there's
7049 no point in wasting the space.
7050
7051 @c
7052 static void mp_save_variable (MP mp, mp_sym q) {
7053 mp_save_data *p; /* temporary register */
7054 FUNCTION_TRACE2 ("mp_save_variable (%p)\n", q);
7055 if (mp->save_ptr != NULL) {
7056 p = xmalloc (1, sizeof (mp_save_data));
7057 p->type = mp_normal_sym;
7058 p->link = mp->save_ptr;
7059 p->value.v.data.indep.scale = eq_type (q);
7060 p->value.v.data.indep.serial = equiv(q);
7061 p->value.v.data.node = equiv_node(q);
7062 p->value.v.data.p = (mp_knot)q;
7063 mp->save_ptr = p;
7064 }
7065 mp_clear_symbol (mp, q, (mp->save_ptr != NULL));
7066 }
7067 static void mp_unsave_variable (MP mp) {
7068 mp_sym q = (mp_sym)mp->save_ptr->value.v.data.p;
7069 if (number_positive(internal_value (mp_tracing_restores))) {
7070 mp_begin_diagnostic (mp);
7071 mp_print_nl (mp, "{restoring ");
7072 mp_print_text (q);
7073 mp_print_char (mp, xord ('}'));
7074 mp_end_diagnostic (mp, false);
7075 }
7076 mp_clear_symbol (mp, q, false);
7077 set_eq_type(q, mp->save_ptr->value.v.data.indep.scale);
7078 set_equiv (q,mp->save_ptr->value.v.data.indep.serial);
7079 q->v.data.node = mp->save_ptr->value.v.data.node;
7080 if (eq_type (q) % mp_outer_tag == mp_tag_token) {
7081 mp_node pp = q->v.data.node;
7082 if (pp != NULL)
7083 mp_name_type (pp) = mp_root;
7084 }
7085 }
7086
7087 @ Similarly, |save_internal| is given the location |q| of an internal
7088 quantity like |mp_tracing_pens|. It creates a save stack entry of the
7089 third kind.
7090
7091 @c
7092 static void mp_save_internal (MP mp, halfword q) {
7093 mp_save_data *p; /* new item for the save stack */
7094 FUNCTION_TRACE2 ("mp_save_internal (%d)\n", q);
7095 if (mp->save_ptr != NULL) {
7096 p = xmalloc (1, sizeof (mp_save_data));
7097 p->type = mp_internal_sym;
7098 p->link = mp->save_ptr;
7099 p->value = mp->internal[q];
7100 p->value.v.data.indep.serial = q;
7101 new_number(p->value.v.data.n);
7102 number_clone(p->value.v.data.n, mp->internal[q].v.data.n);
7103 mp->save_ptr = p;
7104 }
7105 }
7106
7107 static void mp_unsave_internal (MP mp) {
7108 halfword q = mp->save_ptr->value.v.data.indep.serial;
7109 mp_internal saved = mp->save_ptr->value;
7110 if (number_positive(internal_value (mp_tracing_restores))) {
7111 mp_begin_diagnostic (mp);
7112 mp_print_nl (mp, "{restoring ");
7113 mp_print (mp, internal_name (q));
7114 mp_print_char (mp, xord ('='));
7115 if (internal_type (q) == mp_known) {
7116 print_number (saved.v.data.n);
7117 } else if (internal_type (q) == mp_string_type) {
7118 char *s = mp_str (mp, saved.v.data.str);
7119 mp_print (mp, s);
7120 } else {
7121 mp_confusion (mp, "internal_restore");
7122 }
7123 mp_print_char (mp, xord ('}'));
7124 mp_end_diagnostic (mp, false);
7125 }
7126 free_number (mp->internal[q].v.data.n);
7127 mp->internal[q] = saved;
7128 }
7129
7130 @ At the end of a group, the |unsave| routine restores all of the saved
7131 equivalents in reverse order. This routine will be called only when there
7132 is at least one boundary item on the save stack.
7133
7134 @c
7135 static void mp_unsave (MP mp) {
7136 mp_save_data *p; /* saved item */
7137 FUNCTION_TRACE1 ("mp_unsave ()\n");
7138 while (mp->save_ptr->type != 0) {
7139 if (mp->save_ptr->type == mp_internal_sym) {
7140 mp_unsave_internal(mp);
7141 } else {
7142 mp_unsave_variable(mp);
7143 }
7144 p = mp->save_ptr->link;
7145 xfree (mp->save_ptr);
7146 mp->save_ptr = p;
7147 }
7148 p = mp->save_ptr->link;
7149 xfree (mp->save_ptr);
7150 mp->save_ptr = p;
7151 }
7152
7153
7154 @* Data structures for paths.
7155 When a \MP\ user specifies a path, \MP\ will create a list of knots
7156 and control points for the associated cubic spline curves. If the
7157 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
7158 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
7159 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
7160 @:Bezier}{B\'ezier, Pierre Etienne@>
7161 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
7162 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
7163 for |0<=t<=1|.
7164
7165 There is a 8-word node for each knot $z_k$, containing one word of
7166 control information and six words for the |x| and |y| coordinates of
7167 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
7168 |mp_left_type| and |mp_right_type| fields, which each occupy a quarter of
7169 the first word in the node; they specify properties of the curve as it
7170 enters and leaves the knot. There's also a halfword |link| field,
7171 which points to the following knot, and a final supplementary word (of
7172 which only a quarter is used).
7173
7174 If the path is a closed contour, knots 0 and |n| are identical;
7175 i.e., the |link| in knot |n-1| points to knot~0. But if the path
7176 is not closed, the |mp_left_type| of knot~0 and the |mp_right_type| of knot~|n|
7177 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
7178 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
7179
7180 @d mp_next_knot(A) (A)->next /* the next knot in this list */
7181 @d mp_left_type(A) (A)->data.types.left_type /* characterizes the path entering this knot */
7182 @d mp_right_type(A) (A)->data.types.right_type /* characterizes the path leaving this knot */
7183 @d mp_prev_knot(A) (A)->data.prev /* the previous knot in this list (only for pens) */
7184 @d mp_knot_info(A) (A)->data.info /* temporary info, used during splitting */
7185
7186 @<Exported types...@>=
7187 typedef struct mp_knot_data *mp_knot;
7188 typedef struct mp_knot_data {
7189 mp_number x_coord; /* the |x| coordinate of this knot */
7190 mp_number y_coord; /* the |y| coordinate of this knot */
7191 mp_number left_x; /* the |x| coordinate of previous control point */
7192 mp_number left_y; /* the |y| coordinate of previous control point */
7193 mp_number right_x; /* the |x| coordinate of next control point */
7194 mp_number right_y; /* the |y| coordinate of next control point */
7195 mp_knot next;
7196 union {
7197 struct {
7198 unsigned short left_type;
7199 unsigned short right_type;
7200 } types;
7201 mp_knot prev;
7202 signed int info;
7203 } data;
7204 unsigned char originator;
7205 } mp_knot_data;
7206
7207
7208 @ @d mp_gr_next_knot(A) (A)->next /* the next knot in this list */
7209
7210 @<Exported types...@>=
7211 typedef struct mp_gr_knot_data *mp_gr_knot;
7212 typedef struct mp_gr_knot_data {
7213 double x_coord;
7214 double y_coord;
7215 double left_x;
7216 double left_y;
7217 double right_x;
7218 double right_y;
7219 mp_gr_knot next;
7220 union {
7221 struct {
7222 unsigned short left_type;
7223 unsigned short right_type;
7224 } types;
7225 mp_gr_knot prev;
7226 signed int info;
7227 } data;
7228 unsigned char originator;
7229 } mp_gr_knot_data;
7230
7231
7232 @ @<MPlib header stuff@>=
7233 enum mp_knot_type {
7234 mp_endpoint = 0, /* |mp_left_type| at path beginning and |mp_right_type| at path end */
7235 mp_explicit, /* |mp_left_type| or |mp_right_type| when control points are known */
7236 mp_given, /* |mp_left_type| or |mp_right_type| when a direction is given */
7237 mp_curl, /* |mp_left_type| or |mp_right_type| when a curl is desired */
7238 mp_open, /* |mp_left_type| or |mp_right_type| when \MP\ should choose the direction */
7239 mp_end_cycle
7240 };
7241
7242 @ Before the B\'ezier control points have been calculated, the memory
7243 space they will ultimately occupy is taken up by information that can be
7244 used to compute them. There are four cases:
7245
7246 \yskip
7247 \textindent{$\bullet$} If |mp_right_type=mp_open|, the curve should leave
7248 the knot in the same direction it entered; \MP\ will figure out a
7249 suitable direction.
7250
7251 \yskip
7252 \textindent{$\bullet$} If |mp_right_type=mp_curl|, the curve should leave the
7253 knot in a direction depending on the angle at which it enters the next
7254 knot and on the curl parameter stored in |right_curl|.
7255
7256 \yskip
7257 \textindent{$\bullet$} If |mp_right_type=mp_given|, the curve should leave the
7258 knot in a nonzero direction stored as an |angle| in |right_given|.
7259
7260 \yskip
7261 \textindent{$\bullet$} If |mp_right_type=mp_explicit|, the B\'ezier control
7262 point for leaving this knot has already been computed; it is in the
7263 |mp_right_x| and |mp_right_y| fields.
7264
7265 \yskip\noindent
7266 The rules for |mp_left_type| are similar, but they refer to the curve entering
7267 the knot, and to \\{left} fields instead of \\{right} fields.
7268
7269 Non-|explicit| control points will be chosen based on ``tension'' parameters
7270 in the |left_tension|/|right_tension| fields. The
7271 `\&{atleast}' option is represented by negative tension values.
7272 @:at_least_}{\&{atleast} primitive@>
7273
7274 For example, the \MP\ path specification
7275 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
7276 3 and 4..p},$$
7277 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
7278 by the six knots
7279 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
7280 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
7281 |mp_left_type|&\\{left} info&|x_coord,y_coord|&|mp_right_type|&\\{right} info\cr
7282 \noalign{\yskip}
7283 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
7284 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
7285 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
7286 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
7287 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
7288 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
7289 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
7290 Of course, this example is more complicated than anything a normal user
7291 would ever write.
7292
7293 These types must satisfy certain restrictions because of the form of \MP's
7294 path syntax:
7295 (i)~|open| type never appears in the same node together with |endpoint|,
7296 |given|, or |curl|.
7297 (ii)~The |mp_right_type| of a node is |explicit| if and only if the
7298 |mp_left_type| of the following node is |explicit|.
7299 (iii)~|endpoint| types occur only at the ends, as mentioned above.
7300
7301 @s explicit x @q Undefine C++ keyword @>
7302
7303 @d left_curl left_x /* curl information when entering this knot */
7304 @d left_given left_x /* given direction when entering this knot */
7305 @d left_tension left_y /* tension information when entering this knot */
7306 @d right_curl right_x /* curl information when leaving this knot */
7307 @d right_given right_x /* given direction when leaving this knot */
7308 @d right_tension right_y /* tension information when leaving this knot */
7309
7310 @ Knots can be user-supplied, or they can be created by program code,
7311 like the |split_cubic| function, or |copy_path|. The distinction is
7312 needed for the cleanup routine that runs after |split_cubic|, because
7313 it should only delete knots it has previously inserted, and never
7314 anything that was user-supplied. In order to be able to differentiate
7315 one knot from another, we will set |originator(p):=mp_metapost_user| when
7316 it appeared in the actual metapost program, and
7317 |originator(p):=mp_program_code| in all other cases.
7318
7319 @d mp_originator(A) (A)->originator /* the creator of this knot */
7320
7321 @<Exported types@>=
7322 enum mp_knot_originator {
7323 mp_program_code = 0, /* not created by a user */
7324 mp_metapost_user /* created by a user */
7325 };
7326
7327 @ Here is a routine that prints a given knot list
7328 in symbolic form. It illustrates the conventions discussed above,
7329 and checks for anomalies that might arise while \MP\ is being debugged.
7330
7331 @<Declarations@>=
7332 static void mp_pr_path (MP mp, mp_knot h);
7333
7334 @ @c
7335 void mp_pr_path (MP mp, mp_knot h) {
7336 mp_knot p, q; /* for list traversal */
7337 p = h;
7338 do {
7339 q = mp_next_knot (p);
7340 if ((p == NULL) || (q == NULL)) {
7341 mp_print_nl (mp, "???");
7342 return; /* this won't happen */
7343 @.???@>
7344 }
7345 @<Print information for adjacent knots |p| and |q|@>;
7346 DONE1:
7347 p = q;
7348 if (p && ((p != h) || (mp_left_type (h) != mp_endpoint)))
7349 @<Print two dots, followed by |given| or |curl| if present@>@;
7350 } while (p != h);
7351 if (mp_left_type (h) != mp_endpoint)
7352 mp_print (mp, "cycle");
7353 }
7354
7355
7356 @ @<Print information for adjacent knots...@>=
7357 mp_print_two (mp, p->x_coord, p->y_coord);
7358 switch (mp_right_type (p)) {
7359 case mp_endpoint:
7360 if (mp_left_type (p) == mp_open)
7361 mp_print (mp, "{open?}"); /* can't happen */
7362 @.open?@>
7363 if ((mp_left_type (q) != mp_endpoint) || (q != h))
7364 q = NULL; /* force an error */
7365 goto DONE1;
7366 break;
7367 case mp_explicit:
7368 @<Print control points between |p| and |q|, then |goto done1|@>;
7369 break;
7370 case mp_open:
7371 @<Print information for a curve that begins |open|@>;
7372 break;
7373 case mp_curl:
7374 case mp_given:
7375 @<Print information for a curve that begins |curl| or |given|@>;
7376 break;
7377 default:
7378 mp_print (mp, "???"); /* can't happen */
7379 @.???@>
7380 break;
7381 }
7382 if (mp_left_type (q) <= mp_explicit) {
7383 mp_print (mp, "..control?"); /* can't happen */
7384 @.control?@>
7385 } else if ((!number_equal(p->right_tension, unity_t)) || (!number_equal(q->left_tension, unity_t)))
7386 @<Print tension between |p| and |q|@>@;
7387
7388 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
7389 were |scaled|, the magnitude of a |given| direction vector will be~4096.
7390
7391 @<Print two dots...@>=
7392 {
7393 mp_number n_sin, n_cos;
7394 new_fraction (n_sin);
7395 new_fraction (n_cos);
7396 mp_print_nl (mp, " ..");
7397 if (mp_left_type (p) == mp_given) {
7398 n_sin_cos (p->left_given, n_cos, n_sin);
7399 mp_print_char (mp, xord ('{'));
7400 print_number (n_cos);
7401 mp_print_char (mp, xord (','));
7402 print_number (n_sin);
7403 mp_print_char (mp, xord ('}'));
7404 } else if (mp_left_type (p) == mp_curl) {
7405 mp_print (mp, "{curl ");
7406 print_number (p->left_curl);
7407 mp_print_char (mp, xord ('}'));
7408 }
7409 free_number (n_sin);
7410 free_number (n_cos);
7411 }
7412
7413
7414 @ @<Print tension between |p| and |q|@>=
7415 {
7416 mp_number v1;
7417 new_number (v1);
7418 mp_print (mp, "..tension ");
7419 if (number_negative(p->right_tension))
7420 mp_print (mp, "atleast");
7421 number_clone (v1, p->right_tension);
7422 number_abs (v1);
7423 print_number (v1);
7424 if (!number_equal(p->right_tension, q->left_tension)) {
7425 mp_print (mp, " and ");
7426 if (number_negative(q->left_tension))
7427 mp_print (mp, "atleast");
7428 number_clone (v1, p->left_tension);
7429 number_abs (v1);
7430 print_number (v1);
7431 }
7432 free_number (v1);
7433 }
7434
7435
7436 @ @<Print control points between |p| and |q|, then |goto done1|@>=
7437 {
7438 mp_print (mp, "..controls ");
7439 mp_print_two (mp, p->right_x, p->right_y);
7440 mp_print (mp, " and ");
7441 if (mp_left_type (q) != mp_explicit) {
7442 mp_print (mp, "??"); /* can't happen */
7443 @.??@>
7444 } else {
7445 mp_print_two (mp, q->left_x, q->left_y);
7446 }
7447 goto DONE1;
7448 }
7449
7450
7451 @ @<Print information for a curve that begins |open|@>=
7452 if ((mp_left_type (p) != mp_explicit) && (mp_left_type (p) != mp_open)) {
7453 mp_print (mp, "{open?}"); /* can't happen */
7454 @.open?@>
7455 }
7456
7457 @ A curl of 1 is shown explicitly, so that the user sees clearly that
7458 \MP's default curl is present.
7459
7460 @<Print information for a curve that begins |curl|...@>=
7461 {
7462 if (mp_left_type (p) == mp_open)
7463 mp_print (mp, "??"); /* can't happen */
7464 @.??@>
7465 if (mp_right_type (p) == mp_curl) {
7466 mp_print (mp, "{curl ");
7467 print_number (p->right_curl);
7468 } else {
7469 mp_number n_sin, n_cos;
7470 new_fraction (n_sin);
7471 new_fraction (n_cos);
7472 n_sin_cos (p->right_given, n_cos, n_sin);
7473 mp_print_char (mp, xord ('{'));
7474 print_number (n_cos);
7475 mp_print_char (mp, xord (','));
7476 print_number (n_sin);
7477 free_number (n_sin);
7478 free_number (n_cos);
7479 }
7480 mp_print_char (mp, xord ('}'));
7481 }
7482
7483
7484 @ It is convenient to have another version of |pr_path| that prints the path
7485 as a diagnostic message.
7486
7487 @<Declarations@>=
7488 static void mp_print_path (MP mp, mp_knot h, const char *s, boolean nuline);
7489
7490 @ @c
7491 void mp_print_path (MP mp, mp_knot h, const char *s, boolean nuline) {
7492 mp_print_diagnostic (mp, "Path", s, nuline);
7493 mp_print_ln (mp);
7494 @.Path at line...@>
7495 mp_pr_path (mp, h);
7496 mp_end_diagnostic (mp, true);
7497 }
7498
7499
7500 @ @<Declarations@>=
7501 static mp_knot mp_new_knot (MP mp);
7502
7503 @ @c
7504 static mp_knot mp_new_knot (MP mp) {
7505 mp_knot q;
7506 if (mp->knot_nodes) {
7507 q = mp->knot_nodes;
7508 mp->knot_nodes = q->next;
7509 mp->num_knot_nodes--;
7510 } else {
7511 q = mp_xmalloc (mp, 1, sizeof (struct mp_knot_data));
7512 }
7513 memset(q,0,sizeof (struct mp_knot_data));
7514 new_number(q->x_coord);
7515 new_number(q->y_coord);
7516 new_number(q->left_x);
7517 new_number(q->left_y);
7518 new_number(q->right_x);
7519 new_number(q->right_y);
7520 return q;
7521 }
7522
7523
7524 @ @<Declarations@>=
7525 static mp_gr_knot mp_gr_new_knot (MP mp);
7526
7527 @ @c
7528 static mp_gr_knot mp_gr_new_knot (MP mp) {
7529 mp_gr_knot q = mp_xmalloc (mp, 1, sizeof (struct mp_gr_knot_data));
7530 return q;
7531 }
7532
7533
7534 @ If we want to duplicate a knot node, we can say |copy_knot|:
7535
7536 @c
7537 static mp_knot mp_copy_knot (MP mp, mp_knot p) {
7538 mp_knot q;
7539 if (mp->knot_nodes) {
7540 q = mp->knot_nodes;
7541 mp->knot_nodes = q->next;
7542 mp->num_knot_nodes--;
7543 } else {
7544 q = mp_xmalloc (mp, 1, sizeof (struct mp_knot_data));
7545 }
7546 memcpy (q, p, sizeof (struct mp_knot_data));
7547 if (mp->math_mode > mp_math_double_mode) {
7548 new_number(q->x_coord);
7549 new_number(q->y_coord);
7550 new_number(q->left_x);
7551 new_number(q->left_y);
7552 new_number(q->right_x);
7553 new_number(q->right_y);
7554 number_clone(q->x_coord, p->x_coord);
7555 number_clone(q->y_coord, p->y_coord);
7556 number_clone(q->left_x, p->left_x);
7557 number_clone(q->left_y, p->left_y);
7558 number_clone(q->right_x, p->right_x);
7559 number_clone(q->right_y, p->right_y);
7560 }
7561 mp_next_knot (q) = NULL;
7562 return q;
7563 }
7564
7565 @ If we want to export a knot node, we can say |export_knot|:
7566
7567 @c
7568 static mp_gr_knot mp_export_knot (MP mp, mp_knot p) {
7569 mp_gr_knot q; /* the copy */
7570 q = mp_gr_new_knot (mp);
7571 q->x_coord = number_to_double(p->x_coord);
7572 q->y_coord = number_to_double(p->y_coord);
7573 q->left_x = number_to_double(p->left_x);
7574 q->left_y = number_to_double(p->left_y);
7575 q->right_x = number_to_double(p->right_x);
7576 q->right_y = number_to_double(p->right_y);
7577 q->data.types.left_type = mp_left_type(p);
7578 q->data.types.right_type = mp_left_type(p);
7579 q->data.info = mp_knot_info(p);
7580 mp_gr_next_knot (q) = NULL;
7581 return q;
7582 }
7583
7584
7585 @ The |copy_path| routine makes a clone of a given path.
7586
7587 @c
7588 static mp_knot mp_copy_path (MP mp, mp_knot p) {
7589 mp_knot q, pp, qq; /* for list manipulation */
7590 if (p == NULL)
7591 return NULL;
7592 q = mp_copy_knot (mp, p);
7593 qq = q;
7594 pp = mp_next_knot (p);
7595 while (pp != p) {
7596 mp_next_knot (qq) = mp_copy_knot (mp, pp);
7597 qq = mp_next_knot (qq);
7598 pp = mp_next_knot (pp);
7599 }
7600 mp_next_knot (qq) = q;
7601 return q;
7602 }
7603
7604 @ The |export_path| routine makes a clone of a given path
7605 and converts the |value|s therein to |double|s.
7606
7607 @c
7608 static mp_gr_knot mp_export_path (MP mp, mp_knot p) {
7609 mp_knot pp; /* for list manipulation */
7610 mp_gr_knot q, qq;
7611 if (p == NULL)
7612 return NULL;
7613 q = mp_export_knot (mp, p);
7614 qq = q;
7615 pp = mp_next_knot (p);
7616 while (pp != p) {
7617 mp_gr_next_knot (qq) = mp_export_knot (mp, pp);
7618 qq = mp_gr_next_knot (qq);
7619 pp = mp_next_knot (pp);
7620 }
7621 mp_gr_next_knot (qq) = q;
7622 return q;
7623 }
7624
7625 @ If we want to import a knot node, we can say |import_knot|:
7626
7627 @c
7628 static mp_knot mp_import_knot (MP mp, mp_gr_knot p) {
7629 mp_knot q; /* the copy */
7630 q = mp_new_knot (mp);
7631 set_number_from_double(q->x_coord, p->x_coord);
7632 set_number_from_double(q->y_coord, p->y_coord);
7633 set_number_from_double(q->left_x, p->left_x);
7634 set_number_from_double(q->left_y, p->left_y);
7635 set_number_from_double(q->right_x, p->right_x);
7636 set_number_from_double(q->right_y, p->right_y);
7637 mp_left_type(q) = p->data.types.left_type;
7638 mp_left_type(q) = p->data.types.right_type;
7639 mp_knot_info(q) = p->data.info;
7640 mp_next_knot (q) = NULL;
7641 return q;
7642 }
7643
7644
7645 @ The |import_path| routine makes a clone of a given path
7646 and converts the |value|s therein to |scaled|s.
7647
7648 @c
7649 static mp_knot mp_import_path (MP mp, mp_gr_knot p) {
7650 mp_gr_knot pp; /* for list manipulation */
7651 mp_knot q, qq;
7652 if (p == NULL)
7653 return NULL;
7654 q = mp_import_knot (mp, p);
7655 qq = q;
7656 pp = mp_gr_next_knot (p);
7657 while (pp != p) {
7658 mp_next_knot (qq) = mp_import_knot (mp, pp);
7659 qq = mp_next_knot (qq);
7660 pp = mp_gr_next_knot (pp);
7661 }
7662 mp_next_knot (qq) = q;
7663 return q;
7664 }
7665
7666
7667 @ Just before |ship_out|, knot lists are exported for printing.
7668
7669 @ The |export_knot_list| routine therefore also makes a clone
7670 of a given path.
7671
7672 @c
7673 static mp_gr_knot mp_export_knot_list (MP mp, mp_knot p) {
7674 mp_gr_knot q; /* the exported copy */
7675 if (p == NULL)
7676 return NULL;
7677 q = mp_export_path (mp, p);
7678 return q;
7679 }
7680 static mp_knot mp_import_knot_list (MP mp, mp_gr_knot q) {
7681 mp_knot p; /* the imported copy */
7682 if (q == NULL)
7683 return NULL;
7684 p = mp_import_path (mp, q);
7685 return p;
7686 }
7687
7688 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7689 returns a pointer to the first node of the copy, if the path is a cycle,
7690 but to the final node of a non-cyclic copy. The global
7691 variable |path_tail| will point to the final node of the original path;
7692 this trick makes it easier to implement `\&{doublepath}'.
7693
7694 All node types are assumed to be |endpoint| or |explicit| only.
7695
7696 @c
7697 static mp_knot mp_htap_ypoc (MP mp, mp_knot p) {
7698 mp_knot q, pp, qq, rr; /* for list manipulation */
7699 q = mp_new_knot (mp); /* this will correspond to |p| */
7700 qq = q;
7701 pp = p;
7702 while (1) {
7703 mp_right_type (qq) = mp_left_type (pp);
7704 mp_left_type (qq) = mp_right_type (pp);
7705 number_clone (qq->x_coord, pp->x_coord);
7706 number_clone (qq->y_coord, pp->y_coord);
7707 number_clone (qq->right_x, pp->left_x);
7708 number_clone (qq->right_y, pp->left_y);
7709 number_clone (qq->left_x, pp->right_x);
7710 number_clone (qq->left_y, pp->right_y);
7711 mp_originator (qq) = mp_originator (pp);
7712 if (mp_next_knot (pp) == p) {
7713 mp_next_knot (q) = qq;
7714 mp->path_tail = pp;
7715 return q;
7716 }
7717 rr = mp_new_knot (mp);
7718 mp_next_knot (rr) = qq;
7719 qq = rr;
7720 pp = mp_next_knot (pp);
7721 }
7722 }
7723
7724
7725 @ @<Glob...@>=
7726 mp_knot path_tail; /* the node that links to the beginning of a path */
7727
7728 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7729 calling the following subroutine.
7730
7731 @<Declarations@>=
7732 static void mp_toss_knot_list (MP mp, mp_knot p);
7733 static void mp_toss_knot (MP mp, mp_knot p);
7734 static void mp_free_knot (MP mp, mp_knot p);
7735
7736 @ @c
7737 void mp_free_knot (MP mp, mp_knot q) {
7738 free_number (q->x_coord);
7739 free_number (q->y_coord);
7740 free_number (q->left_x);
7741 free_number (q->left_y);
7742 free_number (q->right_x);
7743 free_number (q->right_y);
7744 mp_xfree (q);
7745 }
7746 void mp_toss_knot (MP mp, mp_knot q) {
7747 if (mp->num_knot_nodes < max_num_knot_nodes) {
7748 q->next = mp->knot_nodes;
7749 mp->knot_nodes = q;
7750 mp->num_knot_nodes++;
7751 if (mp->math_mode > mp_math_double_mode) {
7752 free_number (q->x_coord);
7753 free_number (q->y_coord);
7754 free_number (q->left_x);
7755 free_number (q->left_y);
7756 free_number (q->right_x);
7757 free_number (q->right_y);
7758 }
7759 return;
7760 }
7761 if (mp->math_mode > mp_math_double_mode) {
7762 mp_free_knot(mp,q);
7763 } else {
7764 mp_xfree (q);
7765 }
7766 }
7767
7768
7769 void mp_toss_knot_list (MP mp, mp_knot p) {
7770 mp_knot q; /* the node being freed */
7771 mp_knot r; /* the next node */
7772 if (p == NULL)
7773 return;
7774 q = p;
7775 if (mp->math_mode > mp_math_double_mode) {
7776 do {
7777 r = mp_next_knot (q);
7778 mp_toss_knot(mp, q);
7779 q = r;
7780 } while (q != p);
7781 } else {
7782 do {
7783 r = mp_next_knot (q);
7784 if (mp->num_knot_nodes < max_num_knot_nodes) {
7785 q->next = mp->knot_nodes;
7786 mp->knot_nodes = q;
7787 mp->num_knot_nodes++;
7788 } else {
7789 mp_xfree (q);
7790 }
7791 q = r;
7792 } while (q != p);
7793 }
7794 }
7795
7796
7797 @* Choosing control points.
7798 Now we must actually delve into one of \MP's more difficult routines,
7799 the |make_choices| procedure that chooses angles and control points for
7800 the splines of a curve when the user has not specified them explicitly.
7801 The parameter to |make_choices| points to a list of knots and
7802 path information, as described above.
7803
7804 A path decomposes into independent segments at ``breakpoint'' knots,
7805 which are knots whose left and right angles are both prespecified in
7806 some way (i.e., their |mp_left_type| and |mp_right_type| aren't both open).
7807
7808 @c
7809 void mp_make_choices (MP mp, mp_knot knots) {
7810 mp_knot h; /* the first breakpoint */
7811 mp_knot p, q; /* consecutive breakpoints being processed */
7812 @<Other local variables for |make_choices|@>;
7813 FUNCTION_TRACE1 ("make_choices()\n");
7814 check_arith(); /* make sure that |arith_error==false| */
7815 if (number_positive(internal_value (mp_tracing_choices)))
7816 mp_print_path (mp, knots, ", before choices", true);
7817 @<If consecutive knots are equal, join them explicitly@>;
7818 @<Find the first breakpoint, |h|, on the path;
7819 insert an artificial breakpoint if the path is an unbroken cycle@>;
7820 p = h;
7821 do {
7822 @<Fill in the control points between |p| and the next breakpoint,
7823 then advance |p| to that breakpoint@>;
7824 } while (p != h);
7825 if (number_positive(internal_value (mp_tracing_choices)))
7826 mp_print_path (mp, knots, ", after choices", true);
7827 if (mp->arith_error)
7828 @<Report an unexpected problem during the choice-making@>@;
7829 }
7830
7831 @ @<Internal ...@>=
7832 void mp_make_choices (MP mp, mp_knot knots);
7833
7834 @ @<Report an unexpected problem during the choice...@>=
7835 {
7836 const char *hlp[] = {
7837 "The path that I just computed is out of range.",
7838 "So it will probably look funny. Proceed, for a laugh.",
7839 NULL };
7840 mp_back_error (mp, "Some number got too big", hlp, true);
7841 @.Some number got too big@>
7842 mp_get_x_next (mp);
7843 mp->arith_error = false;
7844 }
7845
7846
7847 @ Two knots in a row with the same coordinates will always be joined
7848 by an explicit ``curve'' whose control points are identical with the
7849 knots.
7850
7851 @<If consecutive knots are equal, join them explicitly@>=
7852 p = knots;
7853 do {
7854 q = mp_next_knot (p);
7855 if (number_equal (p->x_coord, q->x_coord) &&
7856 number_equal (p->y_coord, q->y_coord) &&
7857 mp_right_type (p) > mp_explicit) {
7858 mp_right_type (p) = mp_explicit;
7859 if (mp_left_type (p) == mp_open) {
7860 mp_left_type (p) = mp_curl;
7861 set_number_to_unity(p->left_curl);
7862 }
7863 mp_left_type (q) = mp_explicit;
7864 if (mp_right_type (q) == mp_open) {
7865 mp_right_type (q) = mp_curl;
7866 set_number_to_unity(q->right_curl);
7867 }
7868 number_clone (p->right_x, p->x_coord);
7869 number_clone (q->left_x, p->x_coord);
7870 number_clone (p->right_y, p->y_coord);
7871 number_clone (q->left_y, p->y_coord);
7872 }
7873 p = q;
7874 } while (p != knots)@;
7875
7876 @ If there are no breakpoints, it is necessary to compute the direction
7877 angles around an entire cycle. In this case the |mp_left_type| of the first
7878 node is temporarily changed to |end_cycle|.
7879
7880 @<Find the first breakpoint, |h|, on the path...@>=
7881 h = knots;
7882 while (1) {
7883 if (mp_left_type (h) != mp_open)
7884 break;
7885 if (mp_right_type (h) != mp_open)
7886 break;
7887 h = mp_next_knot (h);
7888 if (h == knots) {
7889 mp_left_type (h) = mp_end_cycle;
7890 break;
7891 }
7892 }
7893
7894
7895 @ If |mp_right_type(p)<given| and |q=mp_link(p)|, we must have
7896 |mp_right_type(p)=mp_left_type(q)=mp_explicit| or |endpoint|.
7897
7898 @<Fill in the control points between |p| and the next breakpoint...@>=
7899 q = mp_next_knot (p);
7900 if (mp_right_type (p) >= mp_given) {
7901 while ((mp_left_type (q) == mp_open) && (mp_right_type (q) == mp_open)) {
7902 q = mp_next_knot (q);
7903 }
7904 @<Fill in the control information between consecutive breakpoints |p| and |q|@>;
7905 } else if (mp_right_type (p) == mp_endpoint)
7906 @<Give reasonable values for the unused control points between |p| and~|q|@>@;
7907 p = q
7908
7909 @ This step makes it possible to transform an explicitly computed path without
7910 checking the |mp_left_type| and |mp_right_type| fields.
7911
7912 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7913 {
7914 number_clone (p->right_x, p->x_coord);
7915 number_clone (p->right_y, p->y_coord);
7916 number_clone (q->left_x, q->x_coord);
7917 number_clone (q->left_y, q->y_coord);
7918 }
7919
7920
7921 @ Before we can go further into the way choices are made, we need to
7922 consider the underlying theory. The basic ideas implemented in |make_choices|
7923 are due to John Hobby, who introduced the notion of ``mock curvature''
7924 @^Hobby, John Douglas@>
7925 at a knot. Angles are chosen so that they preserve mock curvature when
7926 a knot is passed, and this has been found to produce excellent results.
7927
7928 It is convenient to introduce some notations that simplify the necessary
7929 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7930 between knots |k| and |k+1|; and let
7931 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7932 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7933 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7934 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7935 $$\eqalign{z_k^+&=z_k+
7936 \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7937 z\k^-&=z\k-
7938 \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7939 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7940 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7941 corresponding ``offset angles.'' These angles satisfy the condition
7942 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7943 whenever the curve leaves an intermediate knot~|k| in the direction that
7944 it enters.
7945
7946 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7947 the curve at its beginning and ending points. This means that
7948 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7949 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7950 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7951 z\k^-,z\k^{\phantom+};t)$
7952 has curvature
7953 @^curvature@>
7954 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7955 \qquad{\rm and}\qquad
7956 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7957 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7958 @^mock curvature@>
7959 approximation to this true curvature that arises in the limit for
7960 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7961 The standard velocity function satisfies
7962 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7963 hence the mock curvatures are respectively
7964 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7965 \qquad{\rm and}\qquad
7966 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7967
7968 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7969 determines $\phi_k$ when $\theta_k$ is known, so the task of
7970 angle selection is essentially to choose appropriate values for each
7971 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7972 from $(**)$, we obtain a system of linear equations of the form
7973 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7974 where
7975 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7976 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7977 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7978 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7979 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7980 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7981 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7982 hence they have a unique solution. Moreover, in most cases the tensions
7983 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7984 solution numerically stable, and there is an exponential damping
7985 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7986 a factor of~$O(2^{-j})$.
7987
7988 @ However, we still must consider the angles at the starting and ending
7989 knots of a non-cyclic path. These angles might be given explicitly, or
7990 they might be specified implicitly in terms of an amount of ``curl.''
7991
7992 Let's assume that angles need to be determined for a non-cyclic path
7993 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7994 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7995 have been given for $0<k<n$, and it will be convenient to introduce
7996 equations of the same form for $k=0$ and $k=n$, where
7997 $$A_0=B_0=C_n=D_n=0.$$
7998 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7999 define $C_0=1$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
8000 parameter, $\gamma_0$, has been specified at~$z_0$; this means
8001 that the mock curvature at $z_0$ should be $\gamma_0$ times the
8002 mock curvature at $z_1$; i.e.,
8003 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
8004 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
8005 This equation simplifies to
8006 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
8007 \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
8008 -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
8009 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
8010 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
8011 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
8012 hence the linear equations remain nonsingular.
8013
8014 Similar considerations apply at the right end, when the final angle $\phi_n$
8015 may or may not need to be determined. It is convenient to let $\psi_n=0$,
8016 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
8017 or we have
8018 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
8019 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
8020 \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
8021
8022 When |make_choices| chooses angles, it must compute the coefficients of
8023 these linear equations, then solve the equations. To compute the coefficients,
8024 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
8025 When the equations are solved, the chosen directions $\theta_k$ are put
8026 back into the form of control points by essentially computing sines and
8027 cosines.
8028
8029 @ OK, we are ready to make the hard choices of |make_choices|.
8030 Most of the work is relegated to an auxiliary procedure
8031 called |solve_choices|, which has been introduced to keep
8032 |make_choices| from being extremely long.
8033
8034 @<Fill in the control information between...@>=
8035 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
8036 set $n$ to the length of the path@>;
8037 @<Remove |open| types at the breakpoints@>
8038 mp_solve_choices (mp, p, q, n)
8039
8040
8041 @ It's convenient to precompute quantities that will be needed several
8042 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
8043 coordinates of $z\k-z_k$, and the magnitude of this vector will be
8044 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
8045 and $z\k-z_k$ will be stored in |psi[k]|.
8046
8047 @<Glob...@>=
8048 integer path_size; /* maximum number of knots between breakpoints of a path */
8049 mp_number *delta_x;
8050 mp_number *delta_y;
8051 mp_number *delta; /* knot differences */
8052 mp_number *psi; /* turning angles */
8053
8054 @ @<Dealloc variables@>=
8055 {
8056 int k;
8057 for (k = 0; k<mp->path_size; k++) {
8058 free_number (mp->delta_x[k]);
8059 free_number (mp->delta_y[k]);
8060 free_number (mp->delta[k]);
8061 free_number (mp->psi[k]);
8062 }
8063 xfree (mp->delta_x);
8064 xfree (mp->delta_y);
8065 xfree (mp->delta);
8066 xfree (mp->psi);
8067 }
8068
8069 @ @<Other local variables for |make_choices|@>=
8070 int k, n; /* current and final knot numbers */
8071 mp_knot s, t; /* registers for list traversal */
8072
8073 @ @<Calculate the turning angles...@>=
8074 {
8075 mp_number sine, cosine; /* trig functions of various angles */
8076 new_fraction (sine);
8077 new_fraction (cosine);
8078 RESTART:
8079 k = 0;
8080 s = p;
8081 n = mp->path_size;
8082 do {
8083 t = mp_next_knot (s);
8084 set_number_from_substraction(mp->delta_x[k], t->x_coord, s->x_coord);
8085 set_number_from_substraction(mp->delta_y[k], t->y_coord, s->y_coord);
8086 pyth_add (mp->delta[k], mp->delta_x[k], mp->delta_y[k]);
8087 if (k > 0) {
8088 mp_number arg1, arg2, r1, r2;
8089 new_number (arg1);
8090 new_number (arg2);
8091 new_fraction (r1);
8092 new_fraction (r2);
8093 make_fraction (r1, mp->delta_y[k - 1], mp->delta[k - 1]);
8094 number_clone (sine, r1);
8095 make_fraction (r2, mp->delta_x[k - 1], mp->delta[k - 1]);
8096 number_clone (cosine, r2);
8097 take_fraction (r1, mp->delta_x[k], cosine);
8098 take_fraction (r2, mp->delta_y[k], sine);
8099 set_number_from_addition (arg1, r1, r2);
8100 take_fraction (r1, mp->delta_y[k], cosine);
8101 take_fraction (r2, mp->delta_x[k], sine);
8102 set_number_from_substraction (arg2, r1, r2);
8103 n_arg (mp->psi[k], arg1, arg2 );
8104 free_number (r1);
8105 free_number (r2);
8106 free_number (arg1);
8107 free_number (arg2);
8108 }
8109 incr (k);
8110 s = t;
8111 if (k == mp->path_size) {
8112 mp_reallocate_paths (mp, mp->path_size + (mp->path_size / 4));
8113 goto RESTART; /* retry, loop size has changed */
8114 }
8115 if (s == q)
8116 n = k;
8117 } while (!((k >= n) && (mp_left_type (s) != mp_end_cycle)));
8118 if (k == n)
8119 set_number_to_zero(mp->psi[k]);
8120 else
8121 number_clone(mp->psi[k], mp->psi[1]);
8122 free_number (sine);
8123 free_number (cosine);
8124 }
8125
8126
8127 @ When we get to this point of the code, |mp_right_type(p)| is either
8128 |given| or |curl| or |open|. If it is |open|, we must have
8129 |mp_left_type(p)=mp_end_cycle| or |mp_left_type(p)=mp_explicit|. In the latter
8130 case, the |open| type is converted to |given|; however, if the
8131 velocity coming into this knot is zero, the |open| type is
8132 converted to a |curl|, since we don't know the incoming direction.
8133
8134 Similarly, |mp_left_type(q)| is either |given| or |curl| or |open| or
8135 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
8136
8137 @<Remove |open| types at the breakpoints@>=
8138 {
8139 mp_number delx, dely; /* directions where |open| meets |explicit| */
8140 new_number(delx);
8141 new_number(dely);
8142 if (mp_left_type (q) == mp_open) {
8143 set_number_from_substraction(delx, q->right_x, q->x_coord);
8144 set_number_from_substraction(dely, q->right_y, q->y_coord);
8145 if (number_zero(delx) && number_zero(dely)) {
8146 mp_left_type (q) = mp_curl;
8147 set_number_to_unity(q->left_curl);
8148 } else {
8149 mp_left_type (q) = mp_given;
8150 n_arg (q->left_given, delx, dely);
8151 }
8152 }
8153 if ((mp_right_type (p) == mp_open) && (mp_left_type (p) == mp_explicit)) {
8154 set_number_from_substraction(delx, p->x_coord, p->left_x);
8155 set_number_from_substraction(dely, p->y_coord, p->left_y);
8156 if (number_zero(delx) && number_zero(dely)) {
8157 mp_right_type (p) = mp_curl;
8158 set_number_to_unity(p->right_curl);
8159 } else {
8160 mp_right_type (p) = mp_given;
8161 n_arg (p->right_given, delx, dely);
8162 }
8163 }
8164 free_number (delx);
8165 free_number (dely);
8166 }
8167
8168 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
8169 and exactly one of the breakpoints involves a curl. The simplest case occurs
8170 when |n=1| and there is a curl at both breakpoints; then we simply draw
8171 a straight line.
8172
8173 But before coding up the simple cases, we might as well face the general case,
8174 since we must deal with it sooner or later, and since the general case
8175 is likely to give some insight into the way simple cases can be handled best.
8176
8177 When there is no cycle, the linear equations to be solved form a tridiagonal
8178 system, and we can apply the standard technique of Gaussian elimination
8179 to convert that system to a sequence of equations of the form
8180 $$\theta_0+u_0\theta_1=v_0,\quad
8181 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
8182 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
8183 \theta_n=v_n.$$
8184 It is possible to do this diagonalization while generating the equations.
8185 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
8186 $\theta_1$, $\theta_0$; thus, the equations will be solved.
8187
8188 The procedure is slightly more complex when there is a cycle, but the
8189 basic idea will be nearly the same. In the cyclic case the right-hand
8190 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
8191 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
8192 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
8193 ending routine will take account of the fact that $\theta_n=\theta_0$ and
8194 eliminate the $w$'s from the system, after which the solution can be
8195 obtained as before.
8196
8197 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
8198 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
8199 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
8200 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
8201
8202 @<Glob...@>=
8203 mp_number *theta; /* values of $\theta_k$ */
8204 mp_number *uu; /* values of $u_k$ */
8205 mp_number *vv; /* values of $v_k$ */
8206 mp_number *ww; /* values of $w_k$ */
8207
8208 @ @<Dealloc variables@>=
8209 {
8210 int k;
8211 for (k = 0; k<mp->path_size; k++) {
8212 free_number (mp->theta[k]);
8213 free_number (mp->uu[k]);
8214 free_number (mp->vv[k]);
8215 free_number (mp->ww[k]);
8216 }
8217 xfree (mp->theta);
8218 xfree (mp->uu);
8219 xfree (mp->vv);
8220 xfree (mp->ww);
8221 }
8222
8223 @ @<Declarations@>=
8224 static void mp_reallocate_paths (MP mp, int l);
8225
8226 @ @c
8227 void mp_reallocate_paths (MP mp, int l) {
8228 int k;
8229 XREALLOC (mp->delta_x, l, mp_number);
8230 XREALLOC (mp->delta_y, l, mp_number);
8231 XREALLOC (mp->delta, l, mp_number);
8232 XREALLOC (mp->psi, l, mp_number);
8233 XREALLOC (mp->theta, l, mp_number);
8234 XREALLOC (mp->uu, l, mp_number);
8235 XREALLOC (mp->vv, l, mp_number);
8236 XREALLOC (mp->ww, l, mp_number);
8237 for (k = mp->path_size; k<l; k++) {
8238 new_number (mp->delta_x[k]);
8239 new_number (mp->delta_y[k]);
8240 new_number (mp->delta[k]);
8241 new_angle (mp->psi[k]);
8242 new_angle (mp->theta[k]);
8243 new_fraction (mp->uu[k]);
8244 new_angle (mp->vv[k]);
8245 new_fraction (mp->ww[k]);
8246 }
8247 mp->path_size = l;
8248 }
8249
8250
8251 @ Our immediate problem is to get the ball rolling by setting up the
8252 first equation or by realizing that no equations are needed, and to fit
8253 this initialization into a framework suitable for the overall computation.
8254
8255 @<Declarations@>=
8256 static void mp_solve_choices (MP mp, mp_knot p, mp_knot q, halfword n);
8257
8258 @ @c
8259 void mp_solve_choices (MP mp, mp_knot p, mp_knot q, halfword n) {
8260 int k; /* current knot number */
8261 mp_knot r, s, t; /* registers for list traversal */
8262 mp_number ff;
8263 new_fraction (ff);
8264 FUNCTION_TRACE2 ("solve_choices(%d)\n", n);
8265 k = 0;
8266 s = p;
8267 r = 0;
8268 while (1) {
8269 t = mp_next_knot (s);
8270 if (k == 0)
8271 @<Get the linear equations started; or |return|
8272 with the control points in place, if linear equations
8273 needn't be solved@>@;
8274 else {
8275 switch (mp_left_type (s)) {
8276 case mp_end_cycle:
8277 case mp_open:
8278 @<Set up equation to match mock curvatures
8279 at $z_k$; then |goto found| with $\theta_n$
8280 adjusted to equal $\theta_0$, if a cycle has ended@>;
8281 break;
8282 case mp_curl:
8283 @<Set up equation for a curl at $\theta_n$
8284 and |goto found|@>;
8285 break;
8286 case mp_given:
8287 @<Calculate the given value of $\theta_n$
8288 and |goto found|@>;
8289 break;
8290 } /* there are no other cases */
8291 }
8292 r = s;
8293 s = t;
8294 incr (k);
8295 }
8296 FOUND:
8297 @<Finish choosing angles and assigning control points@>;
8298 free_number (ff);
8299 }
8300
8301
8302 @ On the first time through the loop, we have |k=0| and |r| is not yet
8303 defined. The first linear equation, if any, will have $A_0=B_0=0$.
8304
8305 @<Get the linear equations started...@>=
8306 {
8307 switch (mp_right_type (s)) {
8308 case mp_given:
8309 if (mp_left_type (t) == mp_given)
8310 @<Reduce to simple case of two givens and |return|@>@;
8311 else
8312 @<Set up the equation for a given value of $\theta_0$@>@;
8313 break;
8314 case mp_curl:
8315 if (mp_left_type (t) == mp_curl)
8316 @<Reduce to simple case of straight line and |return|@>@;
8317 else
8318 @<Set up the equation for a curl at $\theta_0$@>@;
8319 break;
8320 case mp_open:
8321 set_number_to_zero(mp->uu[0]);
8322 set_number_to_zero(mp->vv[0]);
8323 number_clone(mp->ww[0], fraction_one_t);
8324 /* this begins a cycle */
8325 break;
8326 } /* there are no other cases */
8327 }
8328
8329 @ The general equation that specifies equality of mock curvature at $z_k$ is
8330 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
8331 as derived above. We want to combine this with the already-derived equation
8332 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
8333 a new equation
8334 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
8335 equation
8336 $$(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}
8337 -A_kw_{k-1}\theta_0$$
8338 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
8339 fixed-point arithmetic, avoiding the chance of overflow while retaining
8340 suitable precision.
8341
8342 The calculations will be performed in several registers that
8343 provide temporary storage for intermediate quantities.
8344
8345 @<Set up equation to match mock curvatures...@>=
8346 {
8347 mp_number aa, bb, cc, acc; /* temporary registers */
8348 mp_number dd, ee; /* likewise, but |scaled| */
8349 new_fraction (aa);
8350 new_fraction (bb);
8351 new_fraction (cc);
8352 new_fraction (acc);
8353 new_number (dd);
8354 new_number (ee);
8355 @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
8356 $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
8357 and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
8358 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
8359 take_fraction (mp->uu[k], ff, bb);
8360 @<Calculate the values of $v_k$ and $w_k$@>;
8361 if (mp_left_type (s) == mp_end_cycle)
8362 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>@;
8363 free_number(aa);
8364 free_number(bb);
8365 free_number(cc);
8366 free_number(acc);
8367 free_number(dd);
8368 free_number(ee);
8369 }
8370
8371
8372 @ Since tension values are never less than 3/4, the values |aa| and
8373 |bb| computed here are never more than 4/5.
8374
8375 @<Calculate the values $\\{aa}=...@>=
8376 {
8377 mp_number absval;
8378 new_number (absval);
8379 number_clone (absval, r->right_tension);
8380 number_abs (absval);
8381 if (number_equal (absval, unity_t)) {
8382 number_clone (aa, fraction_half_t);
8383 number_clone (dd, mp->delta[k]);
8384 number_double (dd);
8385 } else {
8386 mp_number arg1, arg2, ret;
8387 new_number (arg2);
8388 new_number (arg1);
8389 number_clone (arg2, r->right_tension);
8390 number_abs (arg2);
8391 number_multiply_int (arg2, 3);
8392 number_substract (arg2, unity_t);
8393 make_fraction (aa, unity_t, arg2);
8394 number_clone (arg2, r->right_tension);
8395 number_abs (arg2);
8396 new_fraction (ret);
8397 make_fraction (ret, unity_t, arg2);
8398 set_number_from_substraction (arg1, fraction_three_t, ret);
8399 take_fraction (arg2, mp->delta[k], arg1);
8400 number_clone (dd, arg2);
8401 free_number (ret);
8402 free_number (arg1);
8403 free_number (arg2);
8404 }
8405 number_clone (absval, t->left_tension);
8406 number_abs (absval);
8407 if (number_equal (absval, unity_t)) {
8408 number_clone (bb, fraction_half_t);
8409 number_clone (ee, mp->delta[k - 1]);
8410 number_double (ee);
8411 } else {
8412 mp_number arg1, arg2, ret;
8413 new_number (arg1);
8414 new_number (arg2);
8415 number_clone (arg2, t->left_tension);
8416 number_abs (arg2);
8417 number_multiply_int (arg2, 3);
8418 number_substract (arg2, unity_t);
8419 make_fraction (bb, unity_t, arg2);
8420 number_clone (arg2, t->left_tension);
8421 number_abs (arg2);
8422 new_fraction(ret);
8423 make_fraction (ret, unity_t, arg2);
8424 set_number_from_substraction (arg1,fraction_three_t, ret);
8425 take_fraction (ee, mp->delta[k - 1], arg1);
8426 free_number (ret);
8427 free_number (arg1);
8428 free_number (arg2);
8429 }
8430 free_number (absval);
8431 }
8432 {
8433 mp_number r1;
8434 new_number (r1);
8435 take_fraction (r1, mp->uu[k - 1], aa);
8436 set_number_from_substraction (cc, fraction_one_t, r1);
8437 free_number (r1);
8438 }
8439
8440 @ The ratio to be calculated in this step can be written in the form
8441 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
8442 \\{cc}\cdot\\{dd},$$
8443 because of the quantities just calculated. The values of |dd| and |ee|
8444 will not be needed after this step has been performed.
8445
8446 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
8447 {
8448 mp_number rt, lt;
8449 mp_number arg2;
8450 new_number (arg2);
8451 number_clone (arg2, dd);
8452 take_fraction (dd, arg2, cc);
8453 new_number (lt);
8454 new_number (rt);
8455 number_clone (lt, s->left_tension);
8456 number_abs (lt);
8457 number_clone (rt, s->right_tension);
8458 number_abs (rt);
8459 if (!number_equal(lt, rt)) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
8460 mp_number r1;
8461 new_number (r1);
8462 if (number_less(lt, rt)) {
8463 make_fraction (r1, lt, rt); /* $\alpha_k^2/\beta_k^2$ */
8464 take_fraction (ff, r1, r1);
8465 number_clone (r1, dd);
8466 take_fraction (dd, r1, ff);
8467 } else {
8468 make_fraction (r1, rt, lt); /* $\beta_k^2/\alpha_k^2$ */
8469 take_fraction (ff, r1, r1);
8470 number_clone (r1, ee);
8471 take_fraction (ee, r1, ff);
8472 }
8473 free_number (r1);
8474 }
8475 free_number (rt);
8476 free_number (lt);
8477 set_number_from_addition (arg2, dd, ee);
8478 make_fraction (ff, ee, arg2);
8479 free_number (arg2);
8480 }
8481
8482
8483 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
8484 equation was specified by a curl. In that case we must use a special
8485 method of computation to prevent overflow.
8486
8487 Fortunately, the calculations turn out to be even simpler in this ``hard''
8488 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
8489 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
8490
8491 @<Calculate the values of $v_k$ and $w_k$@>=
8492 take_fraction (acc, mp->psi[k + 1], mp->uu[k]);
8493 number_negate (acc);
8494 if (mp_right_type (r) == mp_curl) {
8495 mp_number r1, arg2;
8496 new_fraction (r1);
8497 new_number (arg2);
8498 set_number_from_substraction (arg2, fraction_one_t, ff);
8499 take_fraction (r1, mp->psi[1], arg2);
8500 set_number_to_zero(mp->ww[k]);
8501 set_number_from_substraction(mp->vv[k], acc, r1);
8502 free_number (r1);
8503 free_number (arg2);
8504 } else {
8505 mp_number arg1, r1;
8506 new_fraction (r1);
8507 new_number (arg1);
8508 set_number_from_substraction (arg1, fraction_one_t, ff);
8509 make_fraction (ff, arg1, cc); /* this is $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
8510 free_number (arg1);
8511 take_fraction (r1, mp->psi[k], ff);
8512 number_substract (acc, r1);
8513 number_clone (r1, ff);
8514 take_fraction (ff, r1, aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
8515 take_fraction (r1, mp->vv[k - 1], ff);
8516 set_number_from_substraction(mp->vv[k], acc, r1 );
8517 if (number_zero(mp->ww[k - 1])) {
8518 set_number_to_zero(mp->ww[k]);
8519 } else {
8520 take_fraction (mp->ww[k], mp->ww[k - 1], ff);
8521 number_negate(mp->ww[k]);
8522 }
8523 free_number (r1);
8524 }
8525
8526
8527 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
8528 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
8529 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
8530 for |0<=k<n|, so that the cyclic case can be finished up just as if there
8531 were no cycle.
8532
8533 The idea in the following code is to observe that
8534 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
8535 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
8536 -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
8537 so we can solve for $\theta_n=\theta_0$.
8538
8539 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
8540 {
8541 mp_number arg2, r1;
8542 new_number (arg2);
8543 new_number (r1);
8544 set_number_to_zero (aa);
8545 number_clone (bb, fraction_one_t); /* we have |k==n| */
8546 do {
8547 decr (k);
8548 if (k == 0)
8549 k = n;
8550 take_fraction (r1, aa, mp->uu[k]);
8551 set_number_from_substraction (aa, mp->vv[k], r1);
8552 take_fraction (r1, bb, mp->uu[k]);
8553 set_number_from_substraction (bb, mp->ww[k], r1);
8554 } while (k != n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
8555 set_number_from_substraction (arg2, fraction_one_t, bb);
8556 make_fraction (r1, aa, arg2);
8557 number_clone (aa, r1);
8558 number_clone(mp->theta[n], aa);
8559 number_clone(mp->vv[0], aa);
8560 for (k = 1; k < n; k++) {
8561 take_fraction (r1, aa, mp->ww[k]);
8562 number_add(mp->vv[k], r1);
8563 }
8564 free_number(arg2);
8565 free_number(r1);
8566 free_number(aa);
8567 free_number(bb);
8568 free_number(cc);
8569 free_number(acc);
8570 free_number(dd);
8571 free_number(ee);
8572 goto FOUND;
8573 }
8574
8575
8576 @ @c
8577 void mp_reduce_angle (MP mp, mp_number *a) {
8578 mp_number abs_a;
8579 FUNCTION_TRACE2 ("reduce_angle(%f)\n", number_to_double(*a));
8580 new_number(abs_a);
8581 number_clone(abs_a, *a);
8582 number_abs(abs_a);
8583 if ( number_greater(abs_a, one_eighty_deg_t)) {
8584 if (number_positive(*a)) {
8585 number_substract(*a, three_sixty_deg_t);
8586 } else {
8587 number_add(*a, three_sixty_deg_t);
8588 }
8589 }
8590 free_number(abs_a);
8591 }
8592
8593 @ @<Declarations@>=
8594 void mp_reduce_angle (MP mp, mp_number *a);
8595
8596
8597 @ @<Calculate the given value of $\theta_n$...@>=
8598 {
8599 mp_number narg;
8600 new_angle (narg);
8601 n_arg (narg, mp->delta_x[n - 1], mp->delta_y[n - 1]);
8602 set_number_from_substraction(mp->theta[n], s->left_given, narg);
8603 free_number (narg);
8604 mp_reduce_angle (mp, &mp->theta[n]);
8605 goto FOUND;
8606 }
8607
8608
8609 @ @<Set up the equation for a given value of $\theta_0$@>=
8610 {
8611 mp_number narg;
8612 new_angle (narg);
8613 n_arg (narg, mp->delta_x[0], mp->delta_y[0]);
8614 set_number_from_substraction(mp->vv[0], s->right_given, narg);
8615 free_number (narg);
8616 mp_reduce_angle (mp, &mp->vv[0]);
8617 set_number_to_zero(mp->uu[0]);
8618 set_number_to_zero(mp->ww[0]);
8619 }
8620
8621
8622 @ @<Set up the equation for a curl at $\theta_0$@>=
8623 {
8624 mp_number lt, rt, cc; /* tension values */
8625 new_number (lt);
8626 new_number (rt);
8627 new_number (cc);
8628 number_clone (cc, s->right_curl);
8629 number_clone (lt, t->left_tension);
8630 number_abs(lt);
8631 number_clone (rt, s->right_tension);
8632 number_abs(rt);
8633 if (number_unity(rt) && number_unity(lt)) {
8634 mp_number arg1, arg2;
8635 new_number (arg1);
8636 new_number (arg2);
8637 number_clone (arg1, cc);
8638 number_double (arg1);
8639 number_add (arg1, unity_t);
8640 number_clone (arg2, cc);
8641 number_add (arg2, two_t);
8642 make_fraction (mp->uu[0], arg1, arg2);
8643 free_number (arg1);
8644 free_number (arg2);
8645 } else {
8646 mp_curl_ratio (mp, &mp->uu[0], cc, rt, lt);
8647 }
8648 take_fraction (mp->vv[0], mp->psi[1], mp->uu[0]);
8649 number_negate(mp->vv[0]);
8650 set_number_to_zero(mp->ww[0]);
8651 free_number (rt);
8652 free_number (lt);
8653 free_number (cc);
8654 }
8655
8656
8657 @ @<Set up equation for a curl at $\theta_n$...@>=
8658 {
8659 mp_number lt, rt, cc; /* tension values */
8660 new_number (lt);
8661 new_number (rt);
8662 new_number (cc);
8663 number_clone (cc, s->left_curl);
8664 number_clone (lt, s->left_tension);
8665 number_abs(lt);
8666 number_clone (rt, r->right_tension);
8667 number_abs(rt);
8668 if (number_unity(rt) && number_unity(lt)) {
8669 mp_number arg1, arg2;
8670 new_number (arg1);
8671 new_number (arg2);
8672 number_clone (arg1, cc);
8673 number_double (arg1);
8674 number_add (arg1, unity_t);
8675 number_clone (arg2, cc);
8676 number_add (arg2, two_t);
8677 make_fraction (ff, arg1, arg2);
8678 free_number (arg1);
8679 free_number (arg2);
8680 } else {
8681 mp_curl_ratio (mp, &ff, cc, lt, rt);
8682 }
8683 {
8684 mp_number arg1, arg2, r1;
8685 new_fraction (r1);
8686 new_fraction (arg1);
8687 new_number (arg2);
8688 take_fraction (arg1, mp->vv[n - 1], ff);
8689 take_fraction (r1, ff, mp->uu[n - 1]);
8690 set_number_from_substraction (arg2, fraction_one_t, r1);
8691 make_fraction (mp->theta[n], arg1, arg2);
8692 number_negate(mp->theta[n]);
8693 free_number (r1);
8694 free_number (arg1);
8695 free_number (arg2);
8696 }
8697 free_number (rt);
8698 free_number (lt);
8699 free_number (cc);
8700 goto FOUND;
8701 }
8702
8703
8704 @ The |curl_ratio| subroutine has three arguments, which our previous notation
8705 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
8706 a somewhat tedious program to calculate
8707 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
8708 \alpha^3\gamma+(3-\beta)\beta^2},$$
8709 with the result reduced to 4 if it exceeds 4. (This reduction of curl
8710 is necessary only if the curl and tension are both large.)
8711 The values of $\alpha$ and $\beta$ will be at most~4/3.
8712
8713 @<Declarations@>=
8714 static void mp_curl_ratio (MP mp, mp_number *ret, mp_number gamma, mp_number a_tension,
8715 mp_number b_tension);
8716
8717 @ @c
8718 void mp_curl_ratio (MP mp, mp_number *ret, mp_number gamma_orig, mp_number a_tension, mp_number b_tension) {
8719 mp_number alpha, beta, gamma, num, denom, ff; /* registers */
8720 mp_number arg1;
8721 new_number (arg1);
8722 new_fraction (alpha);
8723 new_fraction (beta);
8724 new_fraction (gamma);
8725 new_fraction (ff);
8726 new_fraction (denom);
8727 new_fraction (num);
8728 make_fraction (alpha, unity_t, a_tension);
8729 make_fraction (beta, unity_t, b_tension);
8730 number_clone (gamma, gamma_orig);
8731 if (number_lessequal(alpha, beta)) {
8732 make_fraction (ff, alpha, beta);
8733 number_clone (arg1, ff);
8734 take_fraction (ff, arg1, arg1);
8735 number_clone (arg1, gamma);
8736 take_fraction (gamma, arg1, ff);
8737 convert_fraction_to_scaled (beta);
8738 take_fraction (denom, gamma, alpha);
8739 number_add (denom, three_t);
8740 } else {
8741 make_fraction (ff, beta, alpha);
8742 number_clone (arg1, ff);
8743 take_fraction (ff, arg1, arg1);
8744 take_fraction (arg1, beta, ff);
8745 convert_fraction_to_scaled (arg1);
8746 number_clone (beta, arg1);
8747 take_fraction (denom, gamma, alpha);
8748 set_number_from_div (arg1, ff, twelvebits_3);
8749 number_add (denom, arg1);
8750 }
8751 number_substract (denom, beta);
8752 set_number_from_substraction (arg1, fraction_three_t, alpha);
8753 take_fraction (num, gamma, arg1);
8754 number_add (num, beta);
8755 number_clone (arg1, denom);
8756 number_double (arg1);
8757 number_double (arg1); /* arg1 = 4*denom */
8758 if (number_greaterequal(num, arg1)) {
8759 number_clone(*ret, fraction_four_t);
8760 } else {
8761 make_fraction (*ret, num, denom);
8762 }
8763 free_number (alpha);
8764 free_number (beta);
8765 free_number (gamma);
8766 free_number (num);
8767 free_number (denom);
8768 free_number (ff);
8769 free_number (arg1);
8770 }
8771
8772
8773 @ We're in the home stretch now.
8774
8775 @<Finish choosing angles and assigning control points@>=
8776 {
8777 mp_number r1;
8778 new_number (r1);
8779 for (k = n - 1; k >= 0; k--) {
8780 take_fraction (r1, mp->theta[k + 1], mp->uu[k]);
8781 set_number_from_substraction(mp->theta[k], mp->vv[k], r1);
8782 }
8783 free_number (r1);
8784 }
8785 s = p;
8786 k = 0;
8787 {
8788 mp_number arg;
8789 new_number (arg);
8790 do {
8791 t = mp_next_knot (s);
8792 n_sin_cos (mp->theta[k], mp->ct, mp->st);
8793 number_clone (arg, mp->psi[k + 1]);
8794 number_negate (arg);
8795 number_substract (arg, mp->theta[k + 1]);
8796 n_sin_cos (arg, mp->cf, mp->sf);
8797 mp_set_controls (mp, s, t, k);
8798 incr (k);
8799 s = t;
8800 } while (k != n);
8801 free_number (arg);
8802 }
8803
8804
8805 @ The |set_controls| routine actually puts the control points into
8806 a pair of consecutive nodes |p| and~|q|. Global variables are used to
8807 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
8808 $\cos\phi$ needed in this calculation.
8809
8810 @<Glob...@>=
8811 mp_number st;
8812 mp_number ct;
8813 mp_number sf;
8814 mp_number cf; /* sines and cosines */
8815
8816 @ @<Initialize table...@>=
8817 new_fraction (mp->st);
8818 new_fraction (mp->ct);
8819 new_fraction (mp->sf);
8820 new_fraction (mp->cf);
8821
8822 @ @<Dealloc ...@>=
8823 free_number (mp->st);
8824 free_number (mp->ct);
8825 free_number (mp->sf);
8826 free_number (mp->cf);
8827
8828
8829 @ @<Declarations@>=
8830 static void mp_set_controls (MP mp, mp_knot p, mp_knot q, integer k);
8831
8832 @ @c
8833 void mp_set_controls (MP mp, mp_knot p, mp_knot q, integer k) {
8834 mp_number rr, ss; /* velocities, divided by thrice the tension */
8835 mp_number lt, rt; /* tensions */
8836 mp_number sine; /* $\sin(\theta+\phi)$ */
8837 mp_number tmp;
8838 mp_number r1, r2;
8839 new_number(tmp);
8840 new_number (lt);
8841 new_number (rt);
8842 new_number (r1);
8843 new_number (r2);
8844 number_clone(lt, q->left_tension);
8845 number_abs(lt);
8846 number_clone(rt, p->right_tension);
8847 number_abs(rt);
8848 new_fraction (sine);
8849 new_fraction (rr);
8850 new_fraction (ss);
8851 velocity (rr, mp->st, mp->ct, mp->sf, mp->cf, rt);
8852 velocity (ss, mp->sf, mp->cf, mp->st, mp->ct, lt);
8853 if (number_negative(p->right_tension) || number_negative(q->left_tension))
8854 @<Decrease the velocities,
8855 if necessary, to stay inside the bounding triangle@>@;
8856 take_fraction (r1, mp->delta_x [k], mp->ct);
8857 take_fraction (r2, mp->delta_y [k], mp->st);
8858 number_substract (r1, r2);
8859 take_fraction (tmp, r1, rr);
8860 set_number_from_addition (p->right_x, p->x_coord, tmp);
8861 take_fraction (r1, mp->delta_y[k], mp->ct);
8862 take_fraction (r2, mp->delta_x[k], mp->st);
8863 number_add (r1, r2);
8864 take_fraction (tmp, r1, rr);
8865 set_number_from_addition (p->right_y, p->y_coord, tmp);
8866 take_fraction (r1, mp->delta_x[k], mp->cf);
8867 take_fraction (r2, mp->delta_y[k], mp->sf);
8868 number_add (r1, r2);
8869 take_fraction (tmp, r1, ss);
8870 set_number_from_substraction (q->left_x, q->x_coord, tmp);
8871 take_fraction (r1, mp->delta_y[k], mp->cf);
8872 take_fraction (r2, mp->delta_x[k], mp->sf);
8873 number_substract (r1, r2);
8874 take_fraction (tmp, r1, ss);
8875 set_number_from_substraction(q->left_y, q->y_coord, tmp);
8876 mp_right_type (p) = mp_explicit;
8877 mp_left_type (q) = mp_explicit;
8878 free_number (tmp);
8879 free_number (r1);
8880 free_number (r2);
8881 free_number (lt);
8882 free_number (rt);
8883 free_number (rr);
8884 free_number (ss);
8885 free_number (sine);
8886 }
8887
8888
8889 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
8890 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
8891 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
8892 there is no ``bounding triangle.''
8893
8894 @<Decrease the velocities, if necessary...@>=
8895 if ((number_nonnegative(mp->st) && number_nonnegative(mp->sf)) || (number_nonpositive(mp->st) && number_nonpositive(mp->sf))) {
8896 mp_number r1, r2, arg1;
8897 mp_number ab_vs_cd;
8898 new_number (ab_vs_cd);
8899 new_fraction (r1);
8900 new_fraction (r2);
8901 new_number (arg1);
8902 number_clone (arg1, mp->st);
8903 number_abs (arg1);
8904 take_fraction (r1, arg1, mp->cf);
8905 number_clone (arg1, mp->sf);
8906 number_abs (arg1);
8907 take_fraction (r2, arg1, mp->ct);
8908 set_number_from_addition (sine, r1, r2);
8909 if (number_positive(sine)) {
8910 set_number_from_addition (arg1, fraction_one_t, unity_t); /* safety factor */
8911 number_clone (r1, sine);
8912 take_fraction (sine, r1, arg1);
8913 if (number_negative(p->right_tension)) {
8914 number_clone (arg1, mp->sf);
8915 number_abs (arg1);
8916 ab_vs_cd (ab_vs_cd, arg1, fraction_one_t, rr, sine);
8917 if (number_negative(ab_vs_cd)) {
8918 number_clone (arg1, mp->sf);
8919 number_abs (arg1);
8920 make_fraction (rr, arg1, sine);
8921 }
8922 }
8923 if (number_negative(q->left_tension)) {
8924 number_clone (arg1, mp->st);
8925 number_abs (arg1);
8926 ab_vs_cd (ab_vs_cd, arg1, fraction_one_t, ss, sine);
8927 if (number_negative(ab_vs_cd)) {
8928 number_clone (arg1, mp->st);
8929 number_abs (arg1);
8930 make_fraction (ss, arg1, sine);
8931 }
8932 }
8933 }
8934 free_number (arg1);
8935 free_number (r1);
8936 free_number (r2);
8937 free_number (ab_vs_cd);
8938 }
8939
8940 @ Only the simple cases remain to be handled.
8941
8942 @<Reduce to simple case of two givens and |return|@>=
8943 {
8944 mp_number arg1;
8945 mp_number narg;
8946 new_angle (narg);
8947 n_arg (narg, mp->delta_x[0], mp->delta_y[0]);
8948 new_number (arg1);
8949 set_number_from_substraction (arg1, p->right_given, narg);
8950 n_sin_cos (arg1, mp->ct, mp->st);
8951 set_number_from_substraction (arg1, q->left_given, narg);
8952 n_sin_cos (arg1, mp->cf, mp->sf);
8953 number_negate (mp->sf);
8954 mp_set_controls (mp, p, q, 0);
8955 free_number (narg);
8956 free_number (arg1);
8957 free_number (ff);
8958 return;
8959 }
8960
8961
8962 @ @<Reduce to simple case of straight line and |return|@>=
8963 {
8964 mp_number lt, rt; /* tension values */
8965 mp_right_type (p) = mp_explicit;
8966 mp_left_type (q) = mp_explicit;
8967 new_number (lt);
8968 new_number (rt);
8969 number_clone (lt, q->left_tension);
8970 number_abs(lt);
8971 number_clone (rt, p->right_tension);
8972 number_abs(rt);
8973 if (number_unity(rt)) {
8974 mp_number arg2;
8975 new_number (arg2);
8976 if (number_nonnegative(mp->delta_x[0])) {
8977 set_number_from_addition (arg2, mp->delta_x[0], epsilon_t);
8978 } else {
8979 set_number_from_substraction (arg2, mp->delta_x[0], epsilon_t);
8980 }
8981 number_int_div (arg2, 3);
8982 set_number_from_addition (p->right_x, p->x_coord, arg2);
8983 if (number_nonnegative(mp->delta_y[0])) {
8984 set_number_from_addition (arg2, mp->delta_y[0], epsilon_t);
8985 } else {
8986 set_number_from_substraction (arg2, mp->delta_y[0], epsilon_t);
8987 }
8988 number_int_div (arg2, 3);
8989 set_number_from_addition (p->right_y, p->y_coord, arg2);
8990 free_number (arg2);
8991 } else {
8992 mp_number arg2, r1;
8993 new_fraction (r1);
8994 new_number (arg2);
8995 number_clone (arg2, rt);
8996 number_multiply_int (arg2, 3);
8997 make_fraction (ff, unity_t, arg2); /* $\alpha/3$ */
8998 free_number (arg2);
8999 take_fraction (r1, mp->delta_x[0], ff);
9000 set_number_from_addition (p->right_x, p->x_coord, r1);
9001 take_fraction (r1, mp->delta_y[0], ff);
9002 set_number_from_addition (p->right_y, p->y_coord, r1);
9003 }
9004 if (number_unity(lt)) {
9005 mp_number arg2;
9006 new_number (arg2);
9007 if (number_nonnegative(mp->delta_x[0])) {
9008 set_number_from_addition (arg2, mp->delta_x[0], epsilon_t);
9009 } else {
9010 set_number_from_substraction (arg2, mp->delta_x[0], epsilon_t);
9011 }
9012 number_int_div (arg2, 3);
9013 set_number_from_substraction (q->left_x, q->x_coord, arg2);
9014 if (number_nonnegative(mp->delta_y[0])) {
9015 set_number_from_addition (arg2, mp->delta_y[0], epsilon_t);
9016 } else {
9017 set_number_from_substraction (arg2, mp->delta_y[0], epsilon_t);
9018 }
9019 number_int_div (arg2, 3);
9020 set_number_from_substraction (q->left_y, q->y_coord, arg2);
9021 free_number (arg2);
9022 } else {
9023 mp_number arg2, r1;
9024 new_fraction (r1);
9025 new_number (arg2);
9026 number_clone (arg2, lt);
9027 number_multiply_int (arg2, 3);
9028 make_fraction (ff, unity_t, arg2); /* $\beta/3$ */
9029 free_number (arg2);
9030 take_fraction (r1, mp->delta_x[0], ff);
9031 set_number_from_substraction(q->left_x, q->x_coord, r1);
9032 take_fraction (r1, mp->delta_y[0], ff);
9033 set_number_from_substraction(q->left_y, q->y_coord, r1);
9034 free_number (r1);
9035 }
9036 free_number (ff);
9037 free_number (lt);
9038 free_number (rt);
9039 return;
9040 }
9041
9042 @ Various subroutines that are useful for the new (1.770) exported
9043 api for solving path choices
9044
9045 @c
9046 #define TOO_LARGE(a) (fabs((a))>4096.0)
9047 #define PI 3.1415926535897932384626433832795028841971
9048
9049 static int out_of_range(MP mp, double a)
9050 {
9051 mp_number t;
9052 new_number (t);
9053 set_number_from_double(t,fabs(a));
9054 if (number_greaterequal(t,inf_t)) {
9055 free_number (t);
9056 return 1;
9057 }
9058 free_number (t);
9059 return 0;
9060 }
9061
9062 static int mp_link_knotpair (MP mp, mp_knot p, mp_knot q)
9063 {
9064 if (p==NULL ||q==NULL) return 0;
9065 p->next = q;
9066 set_number_from_double(p->right_tension, 1.0);
9067 if (mp_right_type(p)==mp_endpoint) {
9068 mp_right_type(p) = mp_open;
9069 }
9070 set_number_from_double(q->left_tension, 1.0);
9071 if (mp_left_type(q) == mp_endpoint) {
9072 mp_left_type(q) = mp_open;
9073 }
9074 return 1;
9075 }
9076
9077 int mp_close_path_cycle (MP mp, mp_knot p, mp_knot q)
9078 {
9079 return mp_link_knotpair(mp,p,q);
9080 }
9081
9082 int mp_close_path (MP mp, mp_knot q, mp_knot first)
9083 {
9084 if (q==NULL || first==NULL) return 0;
9085 q->next = first;
9086 mp_right_type(q) = mp_endpoint;
9087 set_number_from_double(q->right_tension, 1.0);
9088 mp_left_type(first) = mp_endpoint;
9089 set_number_from_double(first->left_tension, 1.0);
9090 return 1;
9091 }
9092
9093 mp_knot mp_create_knot (MP mp)
9094 {
9095 mp_knot q = mp_new_knot(mp);
9096 mp_left_type(q) = mp_endpoint;
9097 mp_right_type(q) = mp_endpoint;
9098 return q;
9099 }
9100
9101 int mp_set_knot (MP mp, mp_knot p, double x, double y)
9102 {
9103 if (out_of_range(mp, x)) return 0;
9104 if (out_of_range(mp, y)) return 0;
9105 if (p==NULL) return 0;
9106 set_number_from_double(p->x_coord, x);
9107 set_number_from_double(p->y_coord, y);
9108 return 1;
9109 }
9110
9111 mp_knot mp_append_knot (MP mp, mp_knot p, double x, double y)
9112 {
9113 mp_knot q = mp_create_knot(mp);
9114 if (q==NULL) return NULL;
9115 if (!mp_set_knot(mp, q, x, y)) {
9116 free(q);
9117 return NULL;
9118 }
9119 if (p == NULL) return q;
9120 if (!mp_link_knotpair(mp, p,q)) {
9121 free(q);
9122 return NULL;
9123 }
9124 return q;
9125 }
9126
9127 int mp_set_knot_curl (MP mp, mp_knot q, double value) {
9128 if (q==NULL) return 0;
9129 if (TOO_LARGE(value)) return 0;
9130 mp_right_type(q)=mp_curl;
9131 set_number_from_double(q->right_curl, value);
9132 if (mp_left_type(q)==mp_open) {
9133 mp_left_type(q)=mp_curl;
9134 set_number_from_double(q->left_curl, value);
9135 }
9136 return 1;
9137 }
9138
9139 int mp_set_knot_left_curl (MP mp, mp_knot q, double value) {
9140 if (q==NULL) return 0;
9141 if (TOO_LARGE(value)) return 0;
9142 mp_left_type(q)=mp_curl;
9143 set_number_from_double(q->left_curl, value);
9144 if (mp_right_type(q)==mp_open) {
9145 mp_right_type(q)=mp_curl;
9146 set_number_from_double(q->right_curl, value);
9147 }
9148 return 1;
9149 }
9150
9151 int mp_set_knot_right_curl (MP mp, mp_knot q, double value) {
9152 if (q==NULL) return 0;
9153 if (TOO_LARGE(value)) return 0;
9154 mp_right_type(q)=mp_curl;
9155 set_number_from_double(q->right_curl, value);
9156 if (mp_left_type(q)==mp_open) {
9157 mp_left_type(q)=mp_curl;
9158 set_number_from_double(q->left_curl, value);
9159 }
9160 return 1;
9161 }
9162
9163 int mp_set_knotpair_curls (MP mp, mp_knot p, mp_knot q, double t1, double t2) {
9164 if (p==NULL || q==NULL) return 0;
9165 if (mp_set_knot_curl(mp, p, t1))
9166 return mp_set_knot_curl(mp, q, t2);
9167 return 0;
9168 }
9169
9170 int mp_set_knotpair_tensions (MP mp, mp_knot p, mp_knot q, double t1, double t2) {
9171 if (p==NULL || q==NULL) return 0;
9172 if (TOO_LARGE(t1)) return 0;
9173 if (TOO_LARGE(t2)) return 0;
9174 if ((fabs(t1)<0.75)) return 0;
9175 if ((fabs(t2)<0.75)) return 0;
9176 set_number_from_double(p->right_tension, t1);
9177 set_number_from_double(q->left_tension, t2);
9178 return 1;
9179 }
9180
9181 int mp_set_knot_left_tension (MP mp, mp_knot p, double t1) {
9182 if (p==NULL) return 0;
9183 if (TOO_LARGE(t1)) return 0;
9184 if ((fabs(t1)<0.75)) return 0;
9185 set_number_from_double(p->left_tension, t1);
9186 return 1;
9187 }
9188
9189 int mp_set_knot_right_tension (MP mp, mp_knot p, double t1) {
9190 if (p==NULL) return 0;
9191 if (TOO_LARGE(t1)) return 0;
9192 if ((fabs(t1)<0.75)) return 0;
9193 set_number_from_double(p->right_tension, t1);
9194 return 1;
9195 }
9196
9197 int mp_set_knotpair_controls (MP mp, mp_knot p, mp_knot q, double x1, double y1, double x2, double y2) {
9198 if (p==NULL || q==NULL) return 0;
9199 if (out_of_range(mp, x1)) return 0;
9200 if (out_of_range(mp, y1)) return 0;
9201 if (out_of_range(mp, x2)) return 0;
9202 if (out_of_range(mp, y2)) return 0;
9203 mp_right_type(p)=mp_explicit;
9204 set_number_from_double(p->right_x, x1);
9205 set_number_from_double(p->right_y, y1);
9206 mp_left_type(q)=mp_explicit;
9207 set_number_from_double(q->left_x, x2);
9208 set_number_from_double(q->left_y, y2);
9209 return 1;
9210 }
9211
9212 int mp_set_knot_left_control (MP mp, mp_knot p, double x1, double y1) {
9213 if (p==NULL) return 0;
9214 if (out_of_range(mp, x1)) return 0;
9215 if (out_of_range(mp, y1)) return 0;
9216 mp_left_type(p)=mp_explicit;
9217 set_number_from_double(p->left_x, x1);
9218 set_number_from_double(p->left_y, y1);
9219 return 1;
9220 }
9221
9222 int mp_set_knot_right_control (MP mp, mp_knot p, double x1, double y1) {
9223 if (p==NULL) return 0;
9224 if (out_of_range(mp, x1)) return 0;
9225 if (out_of_range(mp, y1)) return 0;
9226 mp_right_type(p)=mp_explicit;
9227 set_number_from_double(p->right_x, x1);
9228 set_number_from_double(p->right_y, y1);
9229 return 1;
9230 }
9231
9232 int mp_set_knot_direction (MP mp, mp_knot q, double x, double y) {
9233 double value = 0;
9234 if (q==NULL) return 0;
9235 if (TOO_LARGE(x)) return 0;
9236 if (TOO_LARGE(y)) return 0;
9237 if (!(x==0 && y == 0))
9238 value = atan2 (y, x) * (180.0 / PI) * 16.0;
9239 mp_right_type(q)=mp_given;
9240 set_number_from_double(q->right_curl, value);
9241 if (mp_left_type(q)==mp_open) {
9242 mp_left_type(q)=mp_given;
9243 set_number_from_double(q->left_curl, value);
9244 }
9245 return 1;
9246 }
9247
9248 int mp_set_knotpair_directions (MP mp, mp_knot p, mp_knot q, double x1, double y1, double x2, double y2) {
9249 if (p==NULL || q==NULL) return 0;
9250 if (mp_set_knot_direction(mp,p, x1, y1))
9251 return mp_set_knot_direction(mp,q, x2, y2);
9252 return 0;
9253 }
9254
9255 @ @c
9256 static int path_needs_fixing (mp_knot source) {
9257 mp_knot sourcehead = source;
9258 do {
9259 source = source->next;
9260 } while (source && source != sourcehead);
9261 if (!source) {
9262 return 1;
9263 }
9264 return 0;
9265 }
9266
9267 int mp_solve_path (MP mp, mp_knot first)
9268 {
9269 int saved_arith_error = mp->arith_error;
9270 jmp_buf *saved_jump_buf = mp->jump_buf;
9271 int retval = 1;
9272 if (first==NULL) return 0;
9273 if (path_needs_fixing(first)) return 0;
9274 mp->jump_buf = malloc(sizeof(jmp_buf));
9275 if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0) {
9276 return 0;
9277 }
9278 mp->arith_error = 0;
9279 mp_make_choices(mp, first);
9280 if (mp->arith_error)
9281 retval = 0;
9282 mp->arith_error = saved_arith_error;
9283 free(mp->jump_buf);
9284 mp->jump_buf = saved_jump_buf;
9285 return retval;
9286 }
9287
9288 void mp_free_path (MP mp, mp_knot p) {
9289 mp_toss_knot_list(mp, p);
9290 }
9291
9292 @ @<Exported function headers@>=
9293 int mp_close_path_cycle (MP mp, mp_knot p, mp_knot q);
9294 int mp_close_path (MP mp, mp_knot q, mp_knot first);
9295 mp_knot mp_create_knot (MP mp);
9296 int mp_set_knot (MP mp, mp_knot p, double x, double y);
9297 mp_knot mp_append_knot (MP mp, mp_knot p, double x, double y);
9298 int mp_set_knot_curl (MP mp, mp_knot q, double value);
9299 int mp_set_knot_left_curl (MP mp, mp_knot q, double value);
9300 int mp_set_knot_right_curl (MP mp, mp_knot q, double value);
9301 int mp_set_knotpair_curls (MP mp, mp_knot p, mp_knot q, double t1, double t2) ;
9302 int mp_set_knotpair_tensions (MP mp, mp_knot p, mp_knot q, double t1, double t2) ;
9303 int mp_set_knot_left_tension (MP mp, mp_knot p, double t1);
9304 int mp_set_knot_right_tension (MP mp, mp_knot p, double t1);
9305 int mp_set_knot_left_control (MP mp, mp_knot p, double t1, double t2);
9306 int mp_set_knot_right_control (MP mp, mp_knot p, double t1, double t2);
9307 int mp_set_knotpair_controls (MP mp, mp_knot p, mp_knot q, double x1, double y1, double x2, double y2) ;
9308 int mp_set_knot_direction (MP mp, mp_knot q, double x, double y) ;
9309 int mp_set_knotpair_directions (MP mp, mp_knot p, mp_knot q, double x1, double y1, double x2, double y2) ;
9310 int mp_solve_path (MP mp, mp_knot first);
9311 void mp_free_path (MP mp, mp_knot p);
9312
9313 @ Simple accessors for |mp_knot|.
9314
9315 @c
9316 mp_number mp_knot_x_coord(MP mp, mp_knot p) { (void)mp; return p->x_coord; }
9317 mp_number mp_knot_y_coord(MP mp, mp_knot p) { (void)mp; return p->y_coord; }
9318 mp_number mp_knot_left_x (MP mp, mp_knot p) { (void)mp; return p->left_x; }
9319 mp_number mp_knot_left_y (MP mp, mp_knot p) { (void)mp; return p->left_y; }
9320 mp_number mp_knot_right_x(MP mp, mp_knot p) { (void)mp; return p->right_x; }
9321 mp_number mp_knot_right_y(MP mp, mp_knot p) { (void)mp; return p->right_y; }
9322 int mp_knot_right_type(MP mp, mp_knot p) { (void)mp; return mp_right_type(p);}
9323 int mp_knot_left_type (MP mp, mp_knot p) { (void)mp; return mp_left_type(p);}
9324 mp_knot mp_knot_next (MP mp, mp_knot p) { (void)mp; return p->next; }
9325 double mp_number_as_double(MP mp, mp_number n) {
9326 (void)mp;
9327 return number_to_double(n);
9328 }
9329
9330 @ @<Exported function headers@>=
9331 #define mp_knot_left_curl mp_knot_left_x
9332 #define mp_knot_left_given mp_knot_left_x
9333 #define mp_knot_left_tension mp_knot_left_y
9334 #define mp_knot_right_curl mp_knot_right_x
9335 #define mp_knot_right_given mp_knot_right_x
9336 #define mp_knot_right_tension mp_knot_right_y
9337 mp_number mp_knot_x_coord(MP mp, mp_knot p);
9338 mp_number mp_knot_y_coord(MP mp, mp_knot p);
9339 mp_number mp_knot_left_x(MP mp, mp_knot p);
9340 mp_number mp_knot_left_y(MP mp, mp_knot p);
9341 mp_number mp_knot_right_x(MP mp, mp_knot p);
9342 mp_number mp_knot_right_y(MP mp, mp_knot p);
9343 int mp_knot_right_type(MP mp, mp_knot p);
9344 int mp_knot_left_type(MP mp, mp_knot p);
9345 mp_knot mp_knot_next(MP mp, mp_knot p);
9346 double mp_number_as_double(MP mp, mp_number n);
9347
9348
9349 @* Measuring paths.
9350 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
9351 allow the user to measure the bounding box of anything that can go into a
9352 picture. It's easy to get rough bounds on the $x$ and $y$ extent of a path
9353 by just finding the bounding box of the knots and the control points. We
9354 need a more accurate version of the bounding box, but we can still use the
9355 easy estimate to save time by focusing on the interesting parts of the path.
9356
9357 @ Computing an accurate bounding box involves a theme that will come up again
9358 and again. Given a Bernshte{\u\i}n polynomial
9359 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
9360 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
9361 we can conveniently bisect its range as follows:
9362
9363 \smallskip
9364 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
9365
9366 \smallskip
9367 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
9368 |0<=k<n-j|, for |0<=j<n|.
9369
9370 \smallskip\noindent
9371 Then
9372 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
9373 =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
9374 This formula gives us the coefficients of polynomials to use over the ranges
9375 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
9376
9377 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
9378 a cubic corresponding to the |fraction| value~|t|.
9379
9380 @c
9381 static void mp_eval_cubic (MP mp, mp_number *r, mp_knot p, mp_knot q, quarterword c,
9382 mp_number t) {
9383 mp_number x1, x2, x3; /* intermediate values */
9384 new_number(x1);
9385 new_number(x2);
9386 new_number(x3);
9387 if (c == mp_x_code) {
9388 set_number_from_of_the_way(x1, t, p->x_coord, p->right_x);
9389 set_number_from_of_the_way(x2, t, p->right_x, q->left_x);
9390 set_number_from_of_the_way(x3, t, q->left_x, q->x_coord);
9391 } else {
9392 set_number_from_of_the_way(x1, t, p->y_coord, p->right_y);
9393 set_number_from_of_the_way(x2, t, p->right_y, q->left_y);
9394 set_number_from_of_the_way(x3, t, q->left_y, q->y_coord);
9395 }
9396 set_number_from_of_the_way(x1, t, x1, x2);
9397 set_number_from_of_the_way(x2, t, x2, x3);
9398 set_number_from_of_the_way(*r, t, x1, x2);
9399 free_number (x1);
9400 free_number (x2);
9401 free_number (x3);
9402 }
9403
9404
9405 @ The actual bounding box information is stored in global variables.
9406 Since it is convenient to address the $x$ and $y$ information
9407 separately, we define arrays indexed by |x_code..y_code| and use
9408 macros to give them more convenient names.
9409
9410 @<Types...@>=
9411 enum mp_bb_code {
9412 mp_x_code = 0, /* index for |minx| and |maxx| */
9413 mp_y_code /* index for |miny| and |maxy| */
9414 };
9415
9416 @
9417 @d mp_minx mp->bbmin[mp_x_code]
9418 @d mp_maxx mp->bbmax[mp_x_code]
9419 @d mp_miny mp->bbmin[mp_y_code]
9420 @d mp_maxy mp->bbmax[mp_y_code]
9421
9422 @<Glob...@>=
9423 mp_number bbmin[mp_y_code + 1];
9424 mp_number bbmax[mp_y_code + 1];
9425 /* the result of procedures that compute bounding box information */
9426
9427 @ @<Initialize table ...@>=
9428 {
9429 int i;
9430 for (i=0;i<=mp_y_code;i++) {
9431 new_number(mp->bbmin[i]);
9432 new_number(mp->bbmax[i]);
9433 }
9434 }
9435
9436 @ @<Dealloc...@>=
9437 {
9438 int i;
9439 for (i=0;i<=mp_y_code;i++) {
9440 free_number(mp->bbmin[i]);
9441 free_number(mp->bbmax[i]);
9442 }
9443 }
9444
9445
9446 @ Now we're ready for the key part of the bounding box computation.
9447 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
9448 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
9449 \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
9450 $$
9451 for $0<t\le1$. In other words, the procedure adjusts the bounds to
9452 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
9453 The |c| parameter is |x_code| or |y_code|.
9454
9455 @c
9456 static void mp_bound_cubic (MP mp, mp_knot p, mp_knot q, quarterword c) {
9457 boolean wavy; /* whether we need to look for extremes */
9458 mp_number del1, del2, del3, del, dmax; /* proportional to the control
9459 points of a quadratic derived from a cubic */
9460 mp_number t, tt; /* where a quadratic crosses zero */
9461 mp_number x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
9462 new_number (x);
9463 new_fraction (t);
9464 new_fraction (tt);
9465 if (c == mp_x_code) {
9466 number_clone(x, q->x_coord);
9467 } else {
9468 number_clone(x, q->y_coord);
9469 }
9470 new_number(del1);
9471 new_number(del2);
9472 new_number(del3);
9473 new_number(del);
9474 new_number(dmax);
9475 @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
9476 @<Check the control points against the bounding box and set |wavy:=true|
9477 if any of them lie outside@>;
9478 if (wavy) {
9479 if (c == mp_x_code) {
9480 set_number_from_substraction(del1, p->right_x, p->x_coord);
9481 set_number_from_substraction(del2, q->left_x, p->right_x);
9482 set_number_from_substraction(del3, q->x_coord, q->left_x);
9483 } else {
9484 set_number_from_substraction(del1, p->right_y, p->y_coord);
9485 set_number_from_substraction(del2, q->left_y, p->right_y);
9486 set_number_from_substraction(del3, q->y_coord, q->left_y);
9487 }
9488 @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
9489 also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
9490 if (number_negative(del)) {
9491 number_negate (del1);
9492 number_negate (del2);
9493 number_negate (del3);
9494 }
9495 crossing_point (t, del1, del2, del3);
9496 if (number_less(t, fraction_one_t))
9497 @<Test the extremes of the cubic against the bounding box@>@;
9498 }
9499 free_number (del3);
9500 free_number (del2);
9501 free_number (del1);
9502 free_number (del);
9503 free_number (dmax);
9504 free_number (x);
9505 free_number (t);
9506 free_number (tt);
9507 }
9508
9509
9510 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
9511 if (number_less(x, mp->bbmin[c]))
9512 number_clone(mp->bbmin[c], x);
9513 if (number_greater(x, mp->bbmax[c]))
9514 number_clone(mp->bbmax[c], x)
9515
9516 @ @<Check the control points against the bounding box and set...@>=
9517 wavy = true;
9518 if (c == mp_x_code) {
9519 if (number_lessequal(mp->bbmin[c], p->right_x))
9520 if (number_lessequal (p->right_x, mp->bbmax[c]))
9521 if (number_lessequal(mp->bbmin[c], q->left_x))
9522 if (number_lessequal (q->left_x, mp->bbmax[c]))
9523 wavy = false;
9524 } else {
9525 if (number_lessequal(mp->bbmin[c], p->right_y))
9526 if (number_lessequal (p->right_y, mp->bbmax[c]))
9527 if (number_lessequal(mp->bbmin[c], q->left_y))
9528 if (number_lessequal (q->left_y, mp->bbmax[c]))
9529 wavy = false;
9530 }
9531
9532
9533 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
9534 section. We just set |del=0| in that case.
9535
9536 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
9537 if (number_nonzero(del1)) {
9538 number_clone (del, del1);
9539 } else if (number_nonzero(del2)) {
9540 number_clone (del, del2);
9541 } else {
9542 number_clone (del, del3);
9543 }
9544 if (number_nonzero(del)) {
9545 mp_number absval1;
9546 new_number(absval1);
9547 number_clone (dmax, del1);
9548 number_abs (dmax);
9549 number_clone (absval1, del2);
9550 number_abs(absval1);
9551 if (number_greater(absval1, dmax)) {
9552 number_clone(dmax, absval1);
9553 }
9554 number_clone (absval1, del3);
9555 number_abs(absval1);
9556 if (number_greater(absval1, dmax)) {
9557 number_clone(dmax, absval1);
9558 }
9559 while (number_less(dmax, fraction_half_t)) {
9560 number_double(dmax);
9561 number_double(del1);
9562 number_double(del2);
9563 number_double(del3);
9564 }
9565 free_number (absval1);
9566 }
9567
9568 @ Since |crossing_point| has tried to choose |t| so that
9569 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
9570 slope, the value of |del2| computed below should not be positive.
9571 But rounding error could make it slightly positive in which case we
9572 must cut it to zero to avoid confusion.
9573
9574 @<Test the extremes of the cubic against the bounding box@>=
9575 {
9576 mp_eval_cubic (mp, &x, p, q, c, t);
9577 @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
9578 set_number_from_of_the_way(del2, t, del2, del3);
9579 /* now |0,del2,del3| represent the derivative on the remaining interval */
9580 if (number_positive(del2))
9581 set_number_to_zero(del2);
9582 {
9583 mp_number arg2, arg3;
9584 new_number(arg2);
9585 new_number(arg3);
9586 number_clone(arg2, del2);
9587 number_negate(arg2);
9588 number_clone(arg3, del3);
9589 number_negate(arg3);
9590 crossing_point (tt, zero_t, arg2, arg3);
9591 free_number (arg2);
9592 free_number (arg3);
9593 }
9594 if (number_less(tt, fraction_one_t))
9595 @<Test the second extreme against the bounding box@>@;
9596 }
9597
9598
9599 @ @<Test the second extreme against the bounding box@>=
9600 {
9601 mp_number arg;
9602 new_number (arg);
9603 set_number_from_of_the_way (arg, t, tt, fraction_one_t);
9604 mp_eval_cubic (mp, &x, p, q, c, arg);
9605 free_number (arg);
9606 @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
9607 }
9608
9609
9610 @ Finding the bounding box of a path is basically a matter of applying
9611 |bound_cubic| twice for each pair of adjacent knots.
9612
9613 @c
9614 static void mp_path_bbox (MP mp, mp_knot h) {
9615 mp_knot p, q; /* a pair of adjacent knots */
9616 number_clone(mp_minx, h->x_coord);
9617 number_clone(mp_miny, h->y_coord);
9618 number_clone (mp_maxx, mp_minx);
9619 number_clone (mp_maxy, mp_miny);
9620 p = h;
9621 do {
9622 if (mp_right_type (p) == mp_endpoint)
9623 return;
9624 q = mp_next_knot (p);
9625 mp_bound_cubic (mp, p, q, mp_x_code);
9626 mp_bound_cubic (mp, p, q, mp_y_code);
9627 p = q;
9628 } while (p != h);
9629 }
9630
9631
9632 @ Another important way to measure a path is to find its arc length. This
9633 is best done by using the general bisection algorithm to subdivide the path
9634 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
9635 by simple means.
9636
9637 Since the arc length is the integral with respect to time of the magnitude of
9638 the velocity, it is natural to use Simpson's rule for the approximation.
9639 @^Simpson's rule@>
9640 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
9641 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
9642 for the arc length of a path of length~1. For a cubic spline
9643 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
9644 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$. Hence the arc length
9645 approximation is
9646 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
9647 where
9648 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
9649 is the result of the bisection algorithm.
9650
9651 @ The remaining problem is how to decide when a subpath is ``well behaved.''
9652 This could be done via the theoretical error bound for Simpson's rule,
9653 @^Simpson's rule@>
9654 but this is impractical because it requires an estimate of the fourth
9655 derivative of the quantity being integrated. It is much easier to just perform
9656 a bisection step and see how much the arc length estimate changes. Since the
9657 error for Simpson's rule is proportional to the fourth power of the sample
9658 spacing, the remaining error is typically about $1\over16$ of the amount of
9659 the change. We say ``typically'' because the error has a pseudo-random behavior
9660 that could cause the two estimates to agree when each contain large errors.
9661
9662 To protect against disasters such as undetected cusps, the bisection process
9663 should always continue until all the $dz_i$ vectors belong to a single
9664 $90^\circ$ sector. This ensures that no point on the spline can have velocity
9665 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
9666 If such a spline happens to produce an erroneous arc length estimate that
9667 is little changed by bisection, the amount of the error is likely to be fairly
9668 small. We will try to arrange things so that freak accidents of this type do
9669 not destroy the inverse relationship between the \&{arclength} and
9670 \&{arctime} operations.
9671 @:arclength_}{\&{arclength} primitive@>
9672 @:arctime_}{\&{arctime} primitive@>
9673
9674 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
9675 @^recursion@>
9676 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
9677 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
9678 returns the time when the arc length reaches |a_goal| if there is such a time.
9679 Thus the return value is either an arc length less than |a_goal| or, if the
9680 arc length would be at least |a_goal|, it returns a time value decreased by
9681 |two|. This allows the caller to use the sign of the result to distinguish
9682 between arc lengths and time values. On certain types of overflow, it is
9683 possible for |a_goal| and the result of |arc_test| both to be |EL_GORDO|.
9684 Otherwise, the result is always less than |a_goal|.
9685
9686 Rather than halving the control point coordinates on each recursive call to
9687 |arc_test|, it is better to keep them proportional to velocity on the original
9688 curve and halve the results instead. This means that recursive calls can
9689 potentially use larger error tolerances in their arc length estimates. How
9690 much larger depends on to what extent the errors behave as though they are
9691 independent of each other. To save computing time, we use optimistic assumptions
9692 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
9693 call.
9694
9695 In addition to the tolerance parameter, |arc_test| should also have parameters
9696 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
9697 ${1\over3}\vb\dot B(1)\vb$. These quantities are relatively expensive to compute
9698 and they are needed in different instances of |arc_test|.
9699
9700 @c
9701 static void mp_arc_test (MP mp, mp_number *ret, mp_number dx0, mp_number dy0, mp_number dx1,
9702 mp_number dy1, mp_number dx2, mp_number dy2, mp_number v0,
9703 mp_number v02, mp_number v2, mp_number a_goal, mp_number tol_orig) {
9704 boolean simple; /* are the control points confined to a $90^\circ$ sector? */
9705 mp_number dx01, dy01, dx12, dy12, dx02, dy02; /* bisection results */
9706 mp_number v002, v022; /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
9707 mp_number arc; /* best arc length estimate before recursion */
9708 mp_number arc1; /* arc length estimate for the first half */
9709 mp_number simply;
9710 mp_number tol;
9711 new_number (arc );
9712 new_number (arc1);
9713 new_number (dx01);
9714 new_number (dy01);
9715 new_number (dx12);
9716 new_number (dy12);
9717 new_number (dx02);
9718 new_number (dy02);
9719 new_number (v002);
9720 new_number (v022);
9721 new_number (simply);
9722 new_number (tol);
9723 number_clone(tol, tol_orig);
9724 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
9725 |dx2|, |dy2|@>;
9726 @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
9727 set |arc_test| and |return|@>;
9728 @<Test if the control points are confined to one quadrant or rotating them
9729 $45^\circ$ would put them in one quadrant. Then set |simple| appropriately@>;
9730
9731 set_number_from_addition(simply, v0, v2);
9732 number_halfp (simply);
9733 number_negate (simply);
9734 number_add (simply, arc);
9735 number_substract (simply, v02);
9736 number_abs (simply);
9737
9738 if (simple && number_lessequal(simply, tol)) {
9739 if (number_less(arc, a_goal)){
9740 number_clone(*ret, arc);
9741 } else
9742 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
9743 that time minus |two|@>@;
9744 } else
9745 @<Use one or two recursive calls to compute the |arc_test| function@>@;
9746 DONE:
9747 free_number (arc);
9748 free_number (arc1);
9749 free_number (dx01);
9750 free_number (dy01);
9751 free_number (dx12);
9752 free_number (dy12);
9753 free_number (dx02);
9754 free_number (dy02);
9755 free_number (v002);
9756 free_number (v022);
9757 free_number (simply);
9758 free_number (tol);
9759 }
9760
9761
9762 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
9763 calls, but $1.5$ is an adequate approximation. It is best to avoid using
9764 |make_fraction| in this inner loop.
9765 @^inner loop@>
9766
9767 @<Use one or two recursive calls to compute the |arc_test| function@>=
9768 {
9769 mp_number a_new, a_aux; /* the sum of these gives the |a_goal| */
9770 mp_number a, b; /* results of recursive calls */
9771 mp_number half_v02; /* |halfp(v02)|, a recursion argument */
9772 new_number(a_new);
9773 new_number(a_aux);
9774 new_number(half_v02);
9775 @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
9776 large as possible@>;
9777 {
9778 mp_number halfp_tol;
9779 new_number(halfp_tol);
9780 number_clone (halfp_tol, tol);
9781 number_halfp (halfp_tol);
9782 number_add(tol, halfp_tol);
9783 free_number (halfp_tol);
9784 }
9785 number_clone(half_v02, v02);
9786 number_halfp(half_v02);
9787 new_number (a);
9788 mp_arc_test (mp, &a, dx0, dy0, dx01, dy01, dx02, dy02,
9789 v0, v002, half_v02, a_new, tol);
9790 if (number_negative(a)) {
9791 set_number_to_unity(*ret); /* |1| */
9792 number_double(*ret); /* |2| */
9793 number_substract(*ret, a); /* |2 - a| */
9794 number_halfp(*ret);
9795 number_negate(*ret); /* |-halfp(2 - a)| */
9796 } else {
9797 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
9798 new_number (b);
9799 mp_arc_test (mp, &b, dx02, dy02, dx12, dy12, dx2, dy2,
9800 half_v02, v022, v2, a_new, tol);
9801 if (number_negative(b)) {
9802 mp_number tmp ;
9803 new_number (tmp);
9804 number_clone(tmp, b);
9805 number_negate(tmp);
9806 number_halfp(tmp);
9807 number_negate(tmp);
9808 number_clone(*ret, tmp);
9809 set_number_to_unity(tmp);
9810 number_halfp(tmp);
9811 number_substract(*ret, tmp); /* |-(halfp(-b)) - 1/2| */
9812 free_number (tmp);
9813 } else {
9814 set_number_from_substraction(*ret, b, a);
9815 number_half(*ret);
9816 set_number_from_addition(*ret, a, *ret); /* |a + half(b - a)| */
9817 }
9818 free_number (b);
9819 }
9820 free_number (half_v02);
9821 free_number (a_aux);
9822 free_number (a_new);
9823 free_number (a);
9824 goto DONE;
9825 }
9826
9827
9828 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
9829 set_number_to_inf(a_aux);
9830 number_substract(a_aux, a_goal);
9831 if (number_greater(a_goal, a_aux)) {
9832 set_number_from_substraction(a_aux, a_goal, a_aux);
9833 set_number_to_inf(a_new);
9834 } else {
9835 set_number_from_addition(a_new, a_goal, a_goal);
9836 set_number_to_zero(a_aux);
9837 }
9838
9839
9840 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
9841 to force the additions and subtractions to be done in an order that avoids
9842 overflow.
9843
9844 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
9845 if (number_greater(a, a_aux)) {
9846 number_substract(a_aux, a);
9847 number_add(a_new, a_aux);
9848 }
9849
9850 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
9851 |fraction_four|. To simplify the rest of the |arc_test| routine, we strengthen
9852 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
9853 this bound. Note that recursive calls will maintain this invariant.
9854
9855 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
9856 set_number_from_addition(dx01, dx0, dx1);
9857 number_half(dx01);
9858 set_number_from_addition(dx12, dx1, dx2);
9859 number_half(dx12);
9860 set_number_from_addition(dx02, dx01, dx12);
9861 number_half(dx02);
9862 set_number_from_addition(dy01, dy0, dy1);
9863 number_half(dy01);
9864 set_number_from_addition(dy12, dy1, dy2);
9865 number_half(dy12);
9866 set_number_from_addition(dy02, dy01, dy12);
9867 number_half(dy02);
9868
9869 @ We should be careful to keep |arc<EL_GORDO| so that calling |arc_test| with
9870 |a_goal=EL_GORDO| is guaranteed to yield the arc length.
9871
9872 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
9873 {
9874 mp_number tmp, arg1, arg2 ;
9875 new_number (tmp);
9876 new_number (arg1);
9877 new_number (arg2);
9878 set_number_from_addition(arg1, dx0, dx02);
9879 number_half(arg1);
9880 number_add(arg1, dx01);
9881 set_number_from_addition(arg2, dy0, dy02);
9882 number_half(arg2);
9883 number_add(arg2, dy01);
9884 pyth_add (v002, arg1, arg2);
9885
9886 set_number_from_addition(arg1, dx02, dx2);
9887 number_half(arg1);
9888 number_add(arg1, dx12);
9889 set_number_from_addition(arg2, dy02, dy2);
9890 number_half(arg2);
9891 number_add(arg2, dy12);
9892 pyth_add (v022, arg1, arg2);
9893 free_number(arg1);
9894 free_number(arg2);
9895
9896 number_clone (tmp, v02);
9897 number_add_scaled (tmp, 2);
9898 number_halfp (tmp);
9899
9900 set_number_from_addition(arc1, v0, tmp);
9901 number_halfp (arc1);
9902 number_substract (arc1, v002);
9903 number_half (arc1);
9904 set_number_from_addition(arc1, v002, arc1);
9905
9906 set_number_from_addition(arc, v2, tmp);
9907 number_halfp (arc);
9908 number_substract (arc, v022);
9909 number_half (arc);
9910 set_number_from_addition(arc, v022, arc);
9911
9912 set_number_to_inf(tmp); /* reuse |tmp| for the next |if| test */
9913 number_substract(tmp,arc1);
9914 if (number_less(arc, tmp)) {
9915 free_number (tmp);
9916 number_add(arc, arc1);
9917 } else {
9918 free_number (tmp);
9919 mp->arith_error = true;
9920 if (number_infinite(a_goal)) {
9921 set_number_to_inf(*ret);
9922 } else {
9923 set_number_to_unity(*ret);
9924 number_double(*ret);
9925 number_negate(*ret); /* |-2| */
9926 }
9927 goto DONE;
9928 }
9929 }
9930
9931
9932 @ @<Test if the control points are confined to one quadrant or rotating...@>=
9933 simple = ((number_nonnegative(dx0) && number_nonnegative(dx1) && number_nonnegative(dx2)) ||
9934 (number_nonpositive(dx0) && number_nonpositive(dx1) && number_nonpositive(dx2)));
9935 if (simple) {
9936 simple = (number_nonnegative(dy0) && number_nonnegative(dy1) && number_nonnegative(dy2)) ||
9937 (number_nonpositive(dy0) && number_nonpositive(dy1) && number_nonpositive(dy2));
9938 }
9939 if (!simple) {
9940 simple = (number_greaterequal(dx0, dy0) && number_greaterequal(dx1, dy1) && number_greaterequal(dx2, dy2)) ||
9941 (number_lessequal(dx0, dy0) && number_lessequal(dx1, dy1) && number_lessequal(dx2, dy2));
9942 if (simple) {
9943 mp_number neg_dx0, neg_dx1, neg_dx2;
9944 new_number(neg_dx0);
9945 new_number(neg_dx1);
9946 new_number(neg_dx2);
9947 number_clone(neg_dx0, dx0);
9948 number_clone(neg_dx1, dx1);
9949 number_clone(neg_dx2, dx2);
9950 number_negate(neg_dx0);
9951 number_negate(neg_dx1);
9952 number_negate(neg_dx2);
9953 simple =
9954 (number_greaterequal(neg_dx0, dy0) && number_greaterequal(neg_dx1, dy1) && number_greaterequal(neg_dx2, dy2)) ||
9955 (number_lessequal(neg_dx0, dy0) && number_lessequal(neg_dx1, dy1) && number_lessequal(neg_dx2, dy2));
9956 free_number (neg_dx0);
9957 free_number (neg_dx1);
9958 free_number (neg_dx2);
9959 }
9960 }
9961
9962 @ Since Simpson's rule is based on approximating the integrand by a parabola,
9963 @^Simpson's rule@>
9964 it is appropriate to use the same approximation to decide when the integral
9965 reaches the intermediate value |a_goal|. At this point
9966 $$\eqalign{
9967 {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
9968 {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
9969 {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
9970 {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
9971 {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
9972 }
9973 $$
9974 and
9975 $$ {\vb\dot B(t)\vb\over 3} \approx
9976 \cases{B\left(\hbox{|v0|},
9977 \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
9978 {1\over 2}\hbox{|v02|}; 2t \right)&
9979 if $t\le{1\over 2}$\cr
9980 B\left({1\over 2}\hbox{|v02|},
9981 \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
9982 \hbox{|v2|}; 2t-1 \right)&
9983 if $t\ge{1\over 2}$.\cr}
9984 \eqno (*)
9985 $$
9986 We can integrate $\vb\dot B(t)\vb$ by using
9987 $$\int 3B(a,b,c;\tau)\,dt =
9988 {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
9989 $$
9990
9991 This construction allows us to find the time when the arc length reaches
9992 |a_goal| by solving a cubic equation of the form
9993 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
9994 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
9995 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
9996 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
9997 $d\tau\over dt$. We shall define a function |solve_rising_cubic| that finds
9998 $\tau$ given $a$, $b$, $c$, and $x$.
9999
10000 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
10001 {
10002 mp_number tmp;
10003 mp_number tmp2;
10004 mp_number tmp3;
10005 mp_number tmp4;
10006 mp_number tmp5;
10007 new_number (tmp);
10008 new_number (tmp2);
10009 new_number (tmp3);
10010 new_number (tmp4);
10011 new_number (tmp5);
10012 number_clone(tmp, v02);
10013 number_add_scaled(tmp, 2);
10014 number_half(tmp);
10015 number_half(tmp); /* |(v02+2) / 4| */
10016 if (number_lessequal(a_goal, arc1)) {
10017 number_clone(tmp2, v0);
10018 number_halfp(tmp2);
10019 set_number_from_substraction(tmp3, arc1, tmp2);
10020 number_substract(tmp3, tmp);
10021 mp_solve_rising_cubic (mp, &tmp5, tmp2, tmp3, tmp, a_goal);
10022 number_halfp (tmp5);
10023 set_number_to_unity(tmp3);
10024 number_substract(tmp5, tmp3);
10025 number_substract(tmp5, tmp3);
10026 number_clone(*ret, tmp5);
10027 } else {
10028 number_clone(tmp2, v2);
10029 number_halfp(tmp2);
10030 set_number_from_substraction(tmp3, arc, arc1);
10031 number_substract(tmp3, tmp);
10032 number_substract(tmp3, tmp2);
10033 set_number_from_substraction(tmp4, a_goal, arc1);
10034 mp_solve_rising_cubic (mp, &tmp5, tmp, tmp3, tmp2, tmp4);
10035 number_halfp(tmp5);
10036 set_number_to_unity(tmp2);
10037 set_number_to_unity(tmp3);
10038 number_half(tmp2);
10039 number_substract(tmp2, tmp3);
10040 number_substract(tmp2, tmp3);
10041 set_number_from_addition(*ret, tmp2, tmp5);
10042 }
10043 free_number (tmp);
10044 free_number (tmp2);
10045 free_number (tmp3);
10046 free_number (tmp4);
10047 free_number (tmp5);
10048 goto DONE;
10049 }
10050
10051
10052 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
10053 $$ B(0, a, a+b, a+b+c; t) = x. $$
10054 This routine is based on |crossing_point| but is simplified by the
10055 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
10056 If rounding error causes this condition to be violated slightly, we just ignore
10057 it and proceed with binary search. This finds a time when the function value
10058 reaches |x| and the slope is positive.
10059
10060 @<Declarations@>=
10061 static void mp_solve_rising_cubic (MP mp, mp_number *ret, mp_number a, mp_number b, mp_number c, mp_number x);
10062
10063 @ @c
10064 void mp_solve_rising_cubic (MP mp, mp_number *ret, mp_number a_orig, mp_number b_orig, mp_number c_orig, mp_number x_orig) {
10065 mp_number abc;
10066 mp_number a, b, c, x; /* local versions of arguments */
10067 mp_number ab, bc, ac; /* bisection results */
10068 mp_number t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
10069 mp_number xx; /* temporary for updating |x| */
10070 mp_number neg_x; /* temporary for an |if| */
10071 if (number_negative(a_orig) || number_negative(c_orig))
10072 mp_confusion (mp, "rising?");
10073 @:this can't happen rising?}{\quad rising?@>
10074 new_number (t);
10075 new_number (abc);
10076 new_number (a);
10077 new_number (b);
10078 new_number (c);
10079 new_number (x);
10080 number_clone(a, a_orig);
10081 number_clone(b, b_orig);
10082 number_clone(c, c_orig);
10083 number_clone(x, x_orig);
10084 new_number (ab);
10085 new_number (bc);
10086 new_number (ac);
10087 new_number (xx);
10088 new_number (neg_x);
10089 set_number_from_addition(abc, a, b);
10090 number_add(abc, c);
10091 if (number_nonpositive(x)) {
10092 set_number_to_zero(*ret);
10093 } else if (number_greaterequal(x, abc)) {
10094 set_number_to_unity(*ret);
10095 } else {
10096 number_clone (t, epsilon_t);
10097 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
10098 |EL_GORDO div 3|@>;
10099 do {
10100 number_add (t, t);
10101 @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
10102 number_clone(xx,x);
10103 number_substract(xx, a);
10104 number_substract(xx, ab);
10105 number_substract(xx, ac);
10106 number_clone(neg_x, x);
10107 number_negate(neg_x);
10108 if (number_less(xx, neg_x)) {
10109 number_double(x);
10110 number_clone(b, ab);
10111 number_clone(c, ac);
10112 } else {
10113 number_add(x, xx);
10114 number_clone(a, ac);
10115 number_clone(b, bc);
10116 number_add (t, epsilon_t);
10117 }
10118 } while (number_less (t, unity_t));
10119 set_number_from_substraction(*ret, t, unity_t);
10120 }
10121 free_number (abc);
10122 free_number (t);
10123 free_number (a);
10124 free_number (b);
10125 free_number (c);
10126 free_number (ab);
10127 free_number (bc);
10128 free_number (ac);
10129 free_number (xx);
10130 free_number (x);
10131 free_number (neg_x);
10132 }
10133
10134
10135 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
10136 set_number_from_addition(ab, a, b);
10137 number_half(ab);
10138 set_number_from_addition(bc, b, c);
10139 number_half(bc);
10140 set_number_from_addition(ac, ab, bc);
10141 number_half(ac);
10142
10143 @ The upper bound on |a|, |b|, and |c|:
10144
10145 @d one_third_inf_t ((math_data *)mp->math)->one_third_inf_t
10146
10147 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
10148 while (number_greater(a, one_third_inf_t) ||
10149 number_greater(b, one_third_inf_t) ||
10150 number_greater(c, one_third_inf_t)) {
10151 number_halfp(a);
10152 number_half(b);
10153 number_halfp(c);
10154 number_halfp(x);
10155 }
10156
10157
10158 @ It is convenient to have a simpler interface to |arc_test| that requires no
10159 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
10160 length less than |fraction_four|.
10161
10162 @c
10163 static void mp_do_arc_test (MP mp, mp_number *ret, mp_number dx0, mp_number dy0, mp_number dx1,
10164 mp_number dy1, mp_number dx2, mp_number dy2, mp_number a_goal) {
10165 mp_number v0, v1, v2; /* length of each $({\it dx},{\it dy})$ pair */
10166 mp_number v02; /* twice the norm of the quadratic at $t={1\over2}$ */
10167 new_number (v0);
10168 new_number (v1);
10169 new_number (v2);
10170 pyth_add (v0, dx0, dy0);
10171 pyth_add (v1, dx1, dy1);
10172 pyth_add (v2, dx2, dy2);
10173 if ((number_greaterequal(v0, fraction_four_t)) ||
10174 (number_greaterequal(v1, fraction_four_t)) ||
10175 (number_greaterequal(v2, fraction_four_t))) {
10176 mp->arith_error = true;
10177 if (number_infinite(a_goal)) {
10178 set_number_to_inf(*ret);
10179 } else {
10180 set_number_to_unity(*ret);
10181 number_double(*ret);
10182 number_negate(*ret);
10183 }
10184 } else {
10185 mp_number arg1, arg2;
10186 new_number (v02);
10187 new_number (arg1);
10188 new_number (arg2);
10189 set_number_from_addition(arg1, dx0, dx2);
10190 number_half(arg1);
10191 number_add(arg1, dx1);
10192 set_number_from_addition(arg2, dy0, dy2);
10193 number_half(arg2);
10194 number_add(arg2, dy1);
10195 pyth_add (v02, arg1, arg2);
10196 free_number(arg1);
10197 free_number(arg2);
10198 mp_arc_test (mp, ret, dx0, dy0, dx1, dy1, dx2, dy2, v0, v02, v2, a_goal, arc_tol_k);
10199 free_number (v02);
10200 }
10201 free_number (v0);
10202 free_number (v1);
10203 free_number (v2);
10204 }
10205
10206
10207 @ Now it is easy to find the arc length of an entire path.
10208
10209 @c
10210 static void mp_get_arc_length (MP mp, mp_number *ret, mp_knot h) {
10211 mp_knot p, q; /* for traversing the path */
10212 mp_number a; /* current arc length */
10213 mp_number a_tot; /* total arc length */
10214 mp_number arg1, arg2, arg3, arg4, arg5, arg6;
10215 mp_number arcgoal;
10216 p = h;
10217 new_number (a_tot);
10218 new_number (arg1);
10219 new_number (arg2);
10220 new_number (arg3);
10221 new_number (arg4);
10222 new_number (arg5);
10223 new_number (arg6);
10224 new_number (a);
10225 new_number(arcgoal);
10226 set_number_to_inf(arcgoal);
10227 while (mp_right_type (p) != mp_endpoint) {
10228 q = mp_next_knot (p);
10229 set_number_from_substraction(arg1, p->right_x, p->x_coord);
10230 set_number_from_substraction(arg2, p->right_y, p->y_coord);
10231 set_number_from_substraction(arg3, q->left_x, p->right_x);
10232 set_number_from_substraction(arg4, q->left_y, p->right_y);
10233 set_number_from_substraction(arg5, q->x_coord, q->left_x);
10234 set_number_from_substraction(arg6, q->y_coord, q->left_y);
10235 mp_do_arc_test (mp, &a, arg1, arg2, arg3, arg4, arg5, arg6, arcgoal);
10236 slow_add (a_tot, a, a_tot);
10237 if (q == h)
10238 break;
10239 else
10240 p = q;
10241 }
10242 free_number (arcgoal);
10243 free_number (a);
10244 free_number (arg1);
10245 free_number (arg2);
10246 free_number (arg3);
10247 free_number (arg4);
10248 free_number (arg5);
10249 free_number (arg6);
10250 check_arith();
10251 number_clone (*ret, a_tot);
10252 free_number (a_tot);
10253 }
10254
10255
10256 @ The inverse operation of finding the time on a path~|h| when the arc length
10257 reaches some value |arc0| can also be accomplished via |do_arc_test|. Some care
10258 is required to handle very large times or negative times on cyclic paths. For
10259 non-cyclic paths, |arc0| values that are negative or too large cause
10260 |get_arc_time| to return 0 or the length of path~|h|.
10261
10262 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
10263 time value greater than the length of the path. Since it could be much greater,
10264 we must be prepared to compute the arc length of path~|h| and divide this into
10265 |arc0| to find how many multiples of the length of path~|h| to add.
10266
10267 @c
10268 static void mp_get_arc_time (MP mp, mp_number *ret, mp_knot h, mp_number arc0_orig) {
10269 mp_knot p, q; /* for traversing the path */
10270 mp_number t_tot; /* accumulator for the result */
10271 mp_number t; /* the result of |do_arc_test| */
10272 mp_number arc, arc0; /* portion of |arc0| not used up so far */
10273 mp_number arg1, arg2, arg3, arg4, arg5, arg6; /* |do_arc_test| arguments */
10274 if (number_negative(arc0_orig)) {
10275 @<Deal with a negative |arc0_orig| value and |return|@>;
10276 }
10277 new_number (t_tot);
10278 new_number (arc0);
10279 number_clone(arc0, arc0_orig);
10280 if (number_infinite(arc0)) {
10281 number_add_scaled (arc0, -1);
10282 }
10283 new_number (arc);
10284 number_clone(arc, arc0);
10285 p = h;
10286 new_number (arg1);
10287 new_number (arg2);
10288 new_number (arg3);
10289 new_number (arg4);
10290 new_number (arg5);
10291 new_number (arg6);
10292 new_number (t);
10293 while ((mp_right_type (p) != mp_endpoint) && number_positive(arc)) {
10294 q = mp_next_knot (p);
10295 set_number_from_substraction(arg1, p->right_x, p->x_coord);
10296 set_number_from_substraction(arg2, p->right_y, p->y_coord);
10297 set_number_from_substraction(arg3, q->left_x, p->right_x);
10298 set_number_from_substraction(arg4, q->left_y, p->right_y);
10299 set_number_from_substraction(arg5, q->x_coord, q->left_x);
10300 set_number_from_substraction(arg6, q->y_coord, q->left_y);
10301 mp_do_arc_test (mp, &t, arg1, arg2, arg3, arg4, arg5, arg6, arc);
10302 @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
10303 if (q == h)
10304 @<Update |t_tot| and |arc| to avoid going around the cyclic
10305 path too many times but set |arith_error=true| and |goto done| on
10306 overflow@>@;
10307 p = q;
10308 }
10309 check_arith();
10310 number_clone (*ret, t_tot);
10311 RETURN:
10312 free_number (t_tot);
10313 free_number (t);
10314 free_number (arc);
10315 free_number (arc0);
10316 free_number (arg1);
10317 free_number (arg2);
10318 free_number (arg3);
10319 free_number (arg4);
10320 free_number (arg5);
10321 free_number (arg6);
10322 }
10323
10324
10325 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
10326 if (number_negative(t)) {
10327 number_add (t_tot, t);
10328 number_add (t_tot, two_t);
10329 set_number_to_zero(arc);
10330 } else {
10331 number_add (t_tot, unity_t);
10332 number_substract(arc, t);
10333 }
10334
10335
10336 @ @<Deal with a negative |arc0_orig| value and |return|@>=
10337 {
10338 if (mp_left_type (h) == mp_endpoint) {
10339 set_number_to_zero (*ret);
10340 } else {
10341 mp_number neg_arc0;
10342 p = mp_htap_ypoc (mp, h);
10343 new_number(neg_arc0);
10344 number_clone(neg_arc0, arc0_orig);
10345 number_negate(neg_arc0);
10346 mp_get_arc_time (mp, ret, p, neg_arc0);
10347 number_negate(*ret);
10348 mp_toss_knot_list (mp, p);
10349 free_number (neg_arc0);
10350 }
10351 check_arith();
10352 return;
10353 }
10354
10355
10356 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
10357 if (number_positive(arc)) {
10358 mp_number n, n1, d1, v1;
10359 new_number (n);
10360 new_number (n1);
10361 new_number (d1);
10362 new_number (v1);
10363
10364 set_number_from_substraction (d1, arc0, arc); /* |d1 = arc0 - arc| */
10365 if (number_greater (d1,arc)) {
10366 set_number_to_zero(n1); /* |n1 = 0| */
10367 } else {
10368 set_number_from_div (n1, arc, d1); /* |n1 = (arc / d1)| */
10369 floor_scaled(n1);
10370 }
10371 number_clone (n, n1);
10372 set_number_from_mul (n1, n1, d1); /* |n1 = (n1 * d1)| */
10373 number_substract (arc, n1); /* |arc = arc - n1| */
10374
10375 number_clone (d1, inf_t); /* reuse |d1| */
10376 number_clone (v1, n); /* |v1 = n| */
10377
10378 set_number_from_int(v1, number_to_int(v1)+1); /* |v1 = n1+1| */
10379 set_number_from_div (d1, d1, v1); /* |d1 = EL_GORDO / v1| */
10380 if (number_greater (t_tot, d1)) {
10381 mp->arith_error = true;
10382 check_arith();
10383 set_number_to_inf(*ret);
10384 free_number (n);
10385 free_number (n1);
10386 free_number (d1);
10387 free_number (v1);
10388 goto RETURN;
10389 }
10390 set_number_from_mul (t_tot, t_tot, v1);
10391 free_number (n);
10392 free_number (n1);
10393 free_number (d1);
10394 free_number (v1);
10395 }
10396
10397 @* Data structures for pens.
10398 A Pen in \MP\ can be either elliptical or polygonal. Elliptical pens result
10399 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
10400 @:stroke}{\&{stroke} command@>
10401 converted into an area fill as described in the next part of this program.
10402 The mathematics behind this process is based on simple aspects of the theory
10403 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
10404 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
10405 Foundations of Computer Science {\bf 24} (1983), 100--111].
10406
10407 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
10408 @:makepen_}{\&{makepen} primitive@>
10409 This path representation is almost sufficient for our purposes except that
10410 a pen path should always be a convex polygon with the vertices in
10411 counter-clockwise order.
10412 Since we will need to scan pen polygons both forward and backward, a pen
10413 should be represented as a doubly linked ring of knot nodes. There is
10414 room for the extra back pointer because we do not need the
10415 |mp_left_type| or |mp_right_type| fields. In fact, we don't need the |left_x|,
10416 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
10417 so that certain procedures can operate on both pens and paths. In particular,
10418 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
10419
10420 @ The |make_pen| procedure turns a path into a pen by initializing
10421 the |prev_knot| pointers and making sure the knots form a convex polygon.
10422 Thus each cubic in the given path becomes a straight line and the control
10423 points are ignored. If the path is not cyclic, the ends are connected by a
10424 straight line.
10425
10426 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
10427
10428 @c
10429 static mp_knot mp_make_pen (MP mp, mp_knot h, boolean need_hull) {
10430 mp_knot p, q; /* two consecutive knots */
10431 q = h;
10432 do {
10433 p = q;
10434 q = mp_next_knot (q);
10435 mp_prev_knot (q) = p;
10436 } while (q != h);
10437 if (need_hull) {
10438 h = mp_convex_hull (mp, h);
10439 @<Make sure |h| isn't confused with an elliptical pen@>;
10440 }
10441 return h;
10442 }
10443
10444
10445 @ The only information required about an elliptical pen is the overall
10446 transformation that has been applied to the original \&{pencircle}.
10447 @:pencircle_}{\&{pencircle} primitive@>
10448 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
10449 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
10450 knot node and transformed as if it were a path.
10451
10452 @d pen_is_elliptical(A) ((A)==mp_next_knot((A)))
10453
10454 @c
10455 static mp_knot mp_get_pen_circle (MP mp, mp_number diam) {
10456 mp_knot h; /* the knot node to return */
10457 h = mp_new_knot (mp);
10458 mp_next_knot (h) = h;
10459 mp_prev_knot (h) = h;
10460 mp_originator (h) = mp_program_code;
10461 set_number_to_zero(h->x_coord);
10462 set_number_to_zero(h->y_coord);
10463 number_clone(h->left_x, diam);
10464 set_number_to_zero(h->left_y);
10465 set_number_to_zero(h->right_x);
10466 number_clone(h->right_y, diam);
10467 return h;
10468 }
10469
10470
10471 @ If the polygon being returned by |make_pen| has only one vertex, it will
10472 be interpreted as an elliptical pen. This is no problem since a degenerate
10473 polygon can equally well be thought of as a degenerate ellipse. We need only
10474 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
10475
10476 @<Make sure |h| isn't confused with an elliptical pen@>=
10477 if (pen_is_elliptical (h)) {
10478 number_clone(h->left_x, h->x_coord);
10479 number_clone(h->left_y, h->y_coord);
10480 number_clone(h->right_x, h->x_coord);
10481 number_clone(h->right_y, h->y_coord);
10482 }
10483
10484 @ Printing a polygonal pen is very much like printing a path
10485
10486 @<Declarations@>=
10487 static void mp_pr_pen (MP mp, mp_knot h);
10488
10489 @ @c
10490 void mp_pr_pen (MP mp, mp_knot h) {
10491 mp_knot p, q; /* for list traversal */
10492 if (pen_is_elliptical (h))
10493 @<Print the elliptical pen |h|@>@;
10494 else {
10495 p = h;
10496 do {
10497 mp_print_two (mp, p->x_coord, p->y_coord);
10498 mp_print_nl (mp, " .. ");
10499 @<Advance |p| making sure the links are OK and |return| if there is
10500 a problem@>;
10501 } while (p != h);
10502 mp_print (mp, "cycle");
10503 }
10504 }
10505
10506
10507 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
10508 q = mp_next_knot (p);
10509 if ((q == NULL) || (mp_prev_knot (q) != p)) {
10510 mp_print_nl (mp, "???");
10511 return; /* this won't happen */
10512 @.???@>
10513 }
10514 p = q
10515
10516 @ @<Print the elliptical pen |h|@>=
10517 {
10518 mp_number v1;
10519 new_number (v1);
10520 mp_print (mp, "pencircle transformed (");
10521 print_number (h->x_coord);
10522 mp_print_char (mp, xord (','));
10523 print_number (h->y_coord);
10524 mp_print_char (mp, xord (','));
10525 set_number_from_substraction (v1, h->left_x, h->x_coord);
10526 print_number (v1);
10527 mp_print_char (mp, xord (','));
10528 set_number_from_substraction (v1, h->right_x, h->x_coord);
10529 print_number (v1);
10530 mp_print_char (mp, xord (','));
10531 set_number_from_substraction (v1, h->left_y, h->y_coord);
10532 print_number (v1);
10533 mp_print_char (mp, xord (','));
10534 set_number_from_substraction (v1, h->right_y, h->y_coord);
10535 print_number (v1);
10536 mp_print_char (mp, xord (')'));
10537 free_number (v1);
10538 }
10539
10540
10541 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
10542 message.
10543
10544 @<Declarations@>=
10545 static void mp_print_pen (MP mp, mp_knot h, const char *s, boolean nuline);
10546
10547 @ @c
10548 void mp_print_pen (MP mp, mp_knot h, const char *s, boolean nuline) {
10549 mp_print_diagnostic (mp, "Pen", s, nuline);
10550 mp_print_ln (mp);
10551 @.Pen at line...@>
10552 mp_pr_pen (mp, h);
10553 mp_end_diagnostic (mp, true);
10554 }
10555
10556
10557 @ Making a polygonal pen into a path involves restoring the |mp_left_type| and
10558 |mp_right_type| fields and setting the control points so as to make a polygonal
10559 path.
10560
10561 @c
10562 static void mp_make_path (MP mp, mp_knot h) {
10563 mp_knot p; /* for traversing the knot list */
10564 quarterword k; /* a loop counter */
10565 @<Other local variables in |make_path|@>;
10566 FUNCTION_TRACE1 ("make_path()\n");
10567 if (pen_is_elliptical (h)) {
10568 FUNCTION_TRACE1 ("make_path(elliptical)\n");
10569 @<Make the elliptical pen |h| into a path@>;
10570 } else {
10571 p = h;
10572 do {
10573 mp_left_type (p) = mp_explicit;
10574 mp_right_type (p) = mp_explicit;
10575 @<Copy the coordinates of knot |p| into its control points@>;
10576 p = mp_next_knot (p);
10577 } while (p != h);
10578 }
10579 }
10580
10581
10582 @ @<Copy the coordinates of knot |p| into its control points@>=
10583 number_clone (p->left_x, p->x_coord);
10584 number_clone (p->left_y, p->y_coord);
10585 number_clone (p->right_x, p->x_coord);
10586 number_clone (p->right_y, p->y_coord)@;
10587
10588
10589 @ We need an eight knot path to get a good approximation to an ellipse.
10590
10591 @<Make the elliptical pen |h| into a path@>=
10592 {
10593 mp_number center_x, center_y; /* translation parameters for an elliptical pen */
10594 mp_number width_x, width_y; /* the effect of a unit change in $x$ */
10595 mp_number height_x, height_y; /* the effect of a unit change in $y$ */
10596 mp_number dx, dy; /* the vector from knot |p| to its right control point */
10597 new_number (center_x);
10598 new_number (center_y);
10599 new_number (width_x);
10600 new_number (width_y);
10601 new_number (height_x);
10602 new_number (height_y);
10603 new_number (dx);
10604 new_number (dy);
10605 @<Extract the transformation parameters from the elliptical pen~|h|@>;
10606 p = h;
10607 for (k = 0; k <= 7; k++) {
10608 @<Initialize |p| as the |k|th knot of a circle of unit diameter,
10609 transforming it appropriately@>;
10610 if (k == 7)
10611 mp_next_knot (p) = h;
10612 else
10613 mp_next_knot (p) = mp_new_knot (mp);
10614 p = mp_next_knot (p);
10615 }
10616 free_number (dx);
10617 free_number (dy);
10618 free_number (center_x);
10619 free_number (center_y);
10620 free_number (width_x);
10621 free_number (width_y);
10622 free_number (height_x);
10623 free_number (height_y);
10624 }
10625
10626
10627 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
10628 number_clone (center_x, h->x_coord);
10629 number_clone (center_y, h->y_coord);
10630 set_number_from_substraction (width_x, h->left_x, center_x);
10631 set_number_from_substraction (width_y, h->left_y, center_y);
10632 set_number_from_substraction (height_x, h->right_x, center_x);
10633 set_number_from_substraction (height_y, h->right_y, center_y);
10634
10635 @ @<Other local variables in |make_path|@>=
10636 integer kk;
10637 /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
10638
10639 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
10640 find the point $k/8$ of the way around the circle and the direction vector
10641 to use there.
10642
10643 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
10644 kk = (k + 6) % 8;
10645 {
10646 mp_number r1, r2;
10647 new_fraction (r1);
10648 new_fraction (r2);
10649 take_fraction (r1, mp->half_cos[k], width_x);
10650 take_fraction (r2, mp->half_cos[kk], height_x);
10651 number_add (r1, r2);
10652 set_number_from_addition (p->x_coord, center_x, r1);
10653 take_fraction (r1, mp->half_cos[k], width_y);
10654 take_fraction (r2, mp->half_cos[kk], height_y);
10655 number_add (r1, r2);
10656 set_number_from_addition (p->y_coord, center_y, r1);
10657 take_fraction (r1, mp->d_cos[kk], width_x);
10658 take_fraction (r2, mp->d_cos[k], height_x);
10659 number_clone (dx, r1);
10660 number_negate (dx);
10661 number_add (dx, r2);
10662 take_fraction (r1, mp->d_cos[kk], width_y);
10663 take_fraction (r2, mp->d_cos[k], height_y);
10664 number_clone (dy, r1);
10665 number_negate (dy);
10666 number_add (dy, r2);
10667 set_number_from_addition (p->right_x, p->x_coord, dx);
10668 set_number_from_addition (p->right_y, p->y_coord, dy);
10669 set_number_from_substraction (p->left_x, p->x_coord, dx);
10670 set_number_from_substraction (p->left_y, p->y_coord, dy);
10671 free_number (r1);
10672 free_number (r2);
10673 }
10674 mp_left_type (p) = mp_explicit;
10675 mp_right_type (p) = mp_explicit;
10676 mp_originator (p) = mp_program_code@;
10677
10678 @ @<Glob...@>=
10679 mp_number half_cos[8]; /* ${1\over2}\cos(45k)$ */
10680 mp_number d_cos[8]; /* a magic constant times $\cos(45k)$ */
10681
10682 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
10683 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
10684 function for $\theta=\phi=22.5^\circ$. This comes out to be
10685 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
10686 \approx 0.132608244919772.
10687 $$
10688
10689 @<Set init...@>=
10690 for (k = 0; k <= 7; k++) {
10691 new_fraction (mp->half_cos[k]);
10692 new_fraction (mp->d_cos[k]);
10693 }
10694 number_clone (mp->half_cos[0], fraction_half_t);
10695 number_clone (mp->half_cos[1], twentysixbits_sqrt2_t);
10696 number_clone (mp->half_cos[2], zero_t);
10697 number_clone (mp->d_cos[0], twentyeightbits_d_t);
10698 number_clone (mp->d_cos[1], twentysevenbits_sqrt2_d_t);
10699 number_clone (mp->d_cos[2], zero_t);
10700 for (k = 3; k <= 4; k++) {
10701 number_clone (mp->half_cos[k], mp->half_cos[4 - k]);
10702 number_negate (mp->half_cos[k]);
10703 number_clone (mp->d_cos[k], mp->d_cos[4 - k]);
10704 number_negate (mp->d_cos[k]);
10705 }
10706 for (k = 5; k <= 7; k++) {
10707 number_clone (mp->half_cos[k], mp->half_cos[8 - k]);
10708 number_clone (mp->d_cos[k], mp->d_cos[8 - k]);
10709 }
10710
10711 @ @<Dealloc...@>=
10712 for (k = 0; k <= 7; k++) {
10713 free_number (mp->half_cos[k]);
10714 free_number (mp->d_cos[k]);
10715 }
10716
10717
10718 @ The |convex_hull| function forces a pen polygon to be convex when it is
10719 returned by |make_pen| and after any subsequent transformation where rounding
10720 error might allow the convexity to be lost.
10721 The convex hull algorithm used here is described by F.~P. Preparata and
10722 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
10723
10724 @<Declarations@>=
10725 static mp_knot mp_convex_hull (MP mp, mp_knot h);
10726
10727 @ @c
10728 mp_knot mp_convex_hull (MP mp, mp_knot h) { /* Make a polygonal pen convex */
10729 mp_knot l, r; /* the leftmost and rightmost knots */
10730 mp_knot p, q; /* knots being scanned */
10731 mp_knot s; /* the starting point for an upcoming scan */
10732 mp_number dx, dy; /* a temporary pointer */
10733 mp_knot ret;
10734 new_number (dx);
10735 new_number (dy);
10736 if (pen_is_elliptical (h)) {
10737 ret = h;
10738 } else {
10739 @<Set |l| to the leftmost knot in polygon~|h|@>;
10740 @<Set |r| to the rightmost knot in polygon~|h|@>;
10741 if (l != r) {
10742 s = mp_next_knot (r);
10743 @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
10744 move them past~|r|@>;
10745 @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
10746 move them past~|l|@>;
10747 @<Sort the path from |l| to |r| by increasing $x$@>;
10748 @<Sort the path from |r| to |l| by decreasing $x$@>;
10749 }
10750 if (l != mp_next_knot (l))
10751 @<Do a Gramm scan and remove vertices where there is no left turn@>@;
10752 ret = l;
10753 }
10754 free_number (dx);
10755 free_number (dy);
10756 return ret;
10757 }
10758
10759
10760 @ All comparisons are done primarily on $x$ and secondarily on $y$.
10761
10762 @<Set |l| to the leftmost knot in polygon~|h|@>=
10763 l = h;
10764 p = mp_next_knot (h);
10765 while (p != h) {
10766 if (number_lessequal (p->x_coord, l->x_coord))
10767 if ((number_less (p->x_coord, l->x_coord)) ||
10768 (number_less (p->y_coord, l->y_coord)))
10769 l = p;
10770 p = mp_next_knot (p);
10771 }
10772
10773
10774 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
10775 r = h;
10776 p = mp_next_knot (h);
10777 while (p != h) {
10778 if (number_greaterequal(p->x_coord, r->x_coord))
10779 if (number_greater (p->x_coord, r->x_coord) ||
10780 number_greater (p->y_coord, r->y_coord))
10781 r = p;
10782 p = mp_next_knot (p);
10783 }
10784
10785
10786 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
10787 {
10788 mp_number ab_vs_cd;
10789 mp_number arg1, arg2;
10790 new_number (arg1);
10791 new_number (arg2);
10792 new_number (ab_vs_cd);
10793 set_number_from_substraction (dx, r->x_coord, l->x_coord);
10794 set_number_from_substraction (dy, r->y_coord, l->y_coord);
10795 p = mp_next_knot (l);
10796 while (p != r) {
10797 q = mp_next_knot (p);
10798 set_number_from_substraction (arg1, p->y_coord, l->y_coord);
10799 set_number_from_substraction (arg2, p->x_coord, l->x_coord);
10800 ab_vs_cd (ab_vs_cd, dx, arg1, dy, arg2);
10801 if (number_positive(ab_vs_cd))
10802 mp_move_knot (mp, p, r);
10803 p = q;
10804 }
10805 free_number (ab_vs_cd);
10806 free_number (arg1);
10807 free_number (arg2);
10808 }
10809
10810
10811 @ The |mp_move_knot| procedure removes |p| from a doubly linked list and inserts
10812 it after |q|.
10813
10814 @<Declarations@>=
10815 static void mp_move_knot (MP mp, mp_knot p, mp_knot q);
10816
10817 @ @c
10818 void mp_move_knot (MP mp, mp_knot p, mp_knot q) {
10819 (void) mp;
10820 mp_next_knot (mp_prev_knot (p)) = mp_next_knot (p);
10821 mp_prev_knot (mp_next_knot (p)) = mp_prev_knot (p);
10822 mp_prev_knot (p) = q;
10823 mp_next_knot (p) = mp_next_knot (q);
10824 mp_next_knot (q) = p;
10825 mp_prev_knot (mp_next_knot (p)) = p;
10826 }
10827
10828
10829 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
10830 {
10831 mp_number ab_vs_cd;
10832 mp_number arg1, arg2;
10833 new_number (ab_vs_cd);
10834 new_number (arg1);
10835 new_number (arg2);
10836 p = s;
10837 while (p != l) {
10838 q = mp_next_knot (p);
10839 set_number_from_substraction (arg1, p->y_coord, l->y_coord);
10840 set_number_from_substraction (arg2, p->x_coord, l->x_coord);
10841 ab_vs_cd (ab_vs_cd, dx, arg1, dy, arg2);
10842 if (number_negative(ab_vs_cd))
10843 mp_move_knot (mp, p, l);
10844 p = q;
10845 }
10846 free_number (ab_vs_cd);
10847 free_number (arg1);
10848 free_number (arg2);
10849 }
10850
10851
10852 @ The list is likely to be in order already so we just do linear insertions.
10853 Secondary comparisons on $y$ ensure that the sort is consistent with the
10854 choice of |l| and |r|.
10855
10856 @<Sort the path from |l| to |r| by increasing $x$@>=
10857 p = mp_next_knot (l);
10858 while (p != r) {
10859 q = mp_prev_knot (p);
10860 while (number_greater(q->x_coord, p->x_coord))
10861 q = mp_prev_knot (q);
10862 while (number_equal(q->x_coord, p->x_coord)) {
10863 if (number_greater(q->y_coord, p->y_coord))
10864 q = mp_prev_knot (q);
10865 else
10866 break;
10867 }
10868 if (q == mp_prev_knot (p)) {
10869 p = mp_next_knot (p);
10870 } else {
10871 p = mp_next_knot (p);
10872 mp_move_knot (mp, mp_prev_knot (p), q);
10873 }
10874 }
10875
10876
10877 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
10878 p = mp_next_knot (r);
10879 while (p != l) {
10880 q = mp_prev_knot (p);
10881 while (number_less(q->x_coord, p->x_coord))
10882 q = mp_prev_knot (q);
10883 while (number_equal(q->x_coord, p->x_coord)) {
10884 if (number_less (q->y_coord, p->y_coord))
10885 q = mp_prev_knot (q);
10886 else
10887 break;
10888 }
10889 if (q == mp_prev_knot (p)) {
10890 p = mp_next_knot (p);
10891 } else {
10892 p = mp_next_knot (p);
10893 mp_move_knot (mp, mp_prev_knot (p), q);
10894 }
10895 }
10896
10897
10898 @ The condition involving |ab_vs_cd| tests if there is not a left turn
10899 at knot |q|. There usually will be a left turn so we streamline the case
10900 where the |then| clause is not executed.
10901
10902 @<Do a Gramm scan and remove vertices where there...@>=
10903 {
10904 mp_number ab_vs_cd;
10905 mp_number arg1, arg2;
10906 new_number (arg1);
10907 new_number (arg2);
10908 new_number (ab_vs_cd);
10909 p = l;
10910 q = mp_next_knot (l);
10911 while (1) {
10912 set_number_from_substraction (dx, q->x_coord, p->x_coord);
10913 set_number_from_substraction (dy, q->y_coord, p->y_coord);
10914 p = q;
10915 q = mp_next_knot (q);
10916 if (p == l)
10917 break;
10918 if (p != r) {
10919 set_number_from_substraction (arg1, q->y_coord, p->y_coord);
10920 set_number_from_substraction (arg2, q->x_coord, p->x_coord);
10921 ab_vs_cd (ab_vs_cd, dx, arg1, dy, arg2);
10922 if (number_nonpositive(ab_vs_cd))
10923 @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>@;
10924 }
10925 }
10926 free_number (ab_vs_cd);
10927 free_number (arg1);
10928 free_number (arg2);
10929 }
10930
10931
10932 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
10933 {
10934 s = mp_prev_knot (p);
10935 mp_xfree (p);
10936 mp_next_knot (s) = q;
10937 mp_prev_knot (q) = s;
10938 if (s == l) {
10939 p = s;
10940 } else {
10941 p = mp_prev_knot (s);
10942 q = s;
10943 }
10944 }
10945
10946
10947 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
10948 offset associated with the given direction |(x,y)|. If two different offsets
10949 apply, it chooses one of them.
10950
10951 @c
10952 static void mp_find_offset (MP mp, mp_number x_orig, mp_number y_orig, mp_knot h) {
10953 mp_knot p, q; /* consecutive knots */
10954 if (pen_is_elliptical (h)) {
10955 mp_fraction xx, yy; /* untransformed offset for an elliptical pen */
10956 mp_number wx, wy, hx, hy; /* the transformation matrix for an elliptical pen */
10957 mp_fraction d; /* a temporary register */
10958 new_fraction(xx);
10959 new_fraction(yy);
10960 new_number(wx);
10961 new_number(wy);
10962 new_number(hx);
10963 new_number(hy);
10964 new_fraction(d);
10965 @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
10966 free_number (xx);
10967 free_number (yy);
10968 free_number (wx);
10969 free_number (wy);
10970 free_number (hx);
10971 free_number (hy);
10972 free_number (d);
10973 } else {
10974 mp_number ab_vs_cd;
10975 mp_number arg1, arg2;
10976 new_number (arg1);
10977 new_number (arg2);
10978 new_number (ab_vs_cd);
10979 q = h;
10980 do {
10981 p = q;
10982 q = mp_next_knot (q);
10983 set_number_from_substraction (arg1, q->x_coord, p->x_coord);
10984 set_number_from_substraction (arg2, q->y_coord, p->y_coord);
10985 ab_vs_cd (ab_vs_cd, arg1, y_orig, arg2, x_orig);
10986 } while (number_negative(ab_vs_cd));
10987 do {
10988 p = q;
10989 q = mp_next_knot (q);
10990 set_number_from_substraction (arg1, q->x_coord, p->x_coord);
10991 set_number_from_substraction (arg2, q->y_coord, p->y_coord);
10992 ab_vs_cd (ab_vs_cd, arg1, y_orig, arg2, x_orig);
10993 } while (number_positive(ab_vs_cd));
10994 number_clone (mp->cur_x, p->x_coord);
10995 number_clone (mp->cur_y, p->y_coord);
10996 free_number (ab_vs_cd);
10997 free_number (arg1);
10998 free_number (arg2);
10999 }
11000 }
11001
11002
11003 @ @<Glob...@>=
11004 mp_number cur_x;
11005 mp_number cur_y; /* all-purpose return value registers */
11006
11007 @ @<Initialize table entries@>=
11008 new_number (mp->cur_x);
11009 new_number (mp->cur_y);
11010
11011 @ @<Dealloc...@>=
11012 free_number (mp->cur_x);
11013 free_number (mp->cur_y);
11014
11015 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
11016 if (number_zero(x_orig) && number_zero(y_orig)) {
11017 number_clone(mp->cur_x, h->x_coord);
11018 number_clone(mp->cur_y, h->y_coord);
11019 } else {
11020 mp_number x, y, abs_x, abs_y;
11021 new_number(x);
11022 new_number(y);
11023 new_number(abs_x);
11024 new_number(abs_y);
11025 number_clone(x, x_orig);
11026 number_clone(y, y_orig);
11027 @<Find the non-constant part of the transformation for |h|@>;
11028 number_clone(abs_x, x);
11029 number_clone(abs_y, y);
11030 number_abs(abs_x);
11031 number_abs(abs_y);
11032 while (number_less(abs_x, fraction_half_t) && number_less(abs_y, fraction_half_t)) {
11033 number_double(x);
11034 number_double(y);
11035 number_clone(abs_x, x);
11036 number_clone(abs_y, y);
11037 number_abs(abs_x);
11038 number_abs(abs_y);
11039 }
11040 @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
11041 untransformed version of |(x,y)|@>;
11042 {
11043 mp_number r1, r2;
11044 new_fraction (r1);
11045 new_fraction (r2);
11046 take_fraction (r1, xx, wx);
11047 take_fraction (r2, yy, hx);
11048 number_add(r1, r2);
11049 set_number_from_addition(mp->cur_x, h->x_coord, r1);
11050 take_fraction (r1, xx, wy);
11051 take_fraction (r2, yy, hy);
11052 number_add(r1, r2);
11053 set_number_from_addition(mp->cur_y, h->y_coord, r1);
11054 free_number (r1);
11055 free_number (r2);
11056 }
11057 free_number(abs_x);
11058 free_number(abs_y);
11059 free_number(x);
11060 free_number(y);
11061 }
11062
11063
11064 @ @<Find the non-constant part of the transformation for |h|@>=
11065 {
11066 set_number_from_substraction(wx, h->left_x, h->x_coord);
11067 set_number_from_substraction(wy, h->left_y, h->y_coord);
11068 set_number_from_substraction(hx, h->right_x, h->x_coord);
11069 set_number_from_substraction(hy, h->right_y, h->y_coord);
11070 }
11071
11072
11073 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
11074 {
11075 mp_number r1, r2, arg1;
11076 new_number (arg1);
11077 new_fraction (r1);
11078 new_fraction (r2);
11079 take_fraction (r1, x, hy);
11080 number_clone (arg1, hx);
11081 number_negate (arg1);
11082 take_fraction (r2, y, arg1);
11083 number_add (r1, r2);
11084 number_negate (r1);
11085 number_clone(yy, r1);
11086 number_clone (arg1, wy);
11087 number_negate (arg1);
11088 take_fraction (r1, x, arg1);
11089 take_fraction (r2, y, wx);
11090 number_add (r1, r2);
11091 number_clone(xx, r1);
11092 free_number (arg1);
11093 free_number (r1);
11094 free_number (r2);
11095 }
11096 pyth_add (d, xx, yy);
11097 if (number_positive(d)) {
11098 mp_number ret;
11099 new_fraction (ret);
11100 make_fraction (ret, xx, d);
11101 number_half(ret);
11102 number_clone(xx, ret);
11103 make_fraction (ret, yy, d);
11104 number_half(ret);
11105 number_clone(yy, ret);
11106 free_number (ret);
11107 }
11108
11109 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
11110 But we can handle that case by just calling |find_offset| twice. The answer
11111 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
11112
11113 @c
11114 static void mp_pen_bbox (MP mp, mp_knot h) {
11115 mp_knot p; /* for scanning the knot list */
11116 if (pen_is_elliptical (h))
11117 @<Find the bounding box of an elliptical pen@>@;
11118 else {
11119 number_clone (mp_minx, h->x_coord);
11120 number_clone (mp_maxx, mp_minx);
11121 number_clone (mp_miny, h->y_coord);
11122 number_clone (mp_maxy, mp_miny);
11123 p = mp_next_knot (h);
11124 while (p != h) {
11125 if (number_less (p->x_coord, mp_minx))
11126 number_clone (mp_minx, p->x_coord);
11127 if (number_less (p->y_coord, mp_miny))
11128 number_clone (mp_miny, p->y_coord);
11129 if (number_greater (p->x_coord, mp_maxx))
11130 number_clone (mp_maxx, p->x_coord);
11131 if (number_greater (p->y_coord, mp_maxy))
11132 number_clone (mp_maxy, p->y_coord);
11133 p = mp_next_knot (p);
11134 }
11135 }
11136 }
11137
11138
11139 @ @<Find the bounding box of an elliptical pen@>=
11140 {
11141 mp_number arg1, arg2;
11142 new_number(arg1);
11143 new_fraction (arg2);
11144 number_clone(arg2, fraction_one_t);
11145 mp_find_offset (mp, arg1, arg2, h);
11146 number_clone (mp_maxx, mp->cur_x);
11147 number_clone (mp_minx, h->x_coord);
11148 number_double (mp_minx);
11149 number_substract (mp_minx, mp->cur_x);
11150 number_negate (arg2);
11151 mp_find_offset (mp, arg2, arg1, h);
11152 number_clone (mp_maxy, mp->cur_y);
11153 number_clone (mp_miny, h->y_coord);
11154 number_double (mp_miny);
11155 number_substract (mp_miny, mp->cur_y);
11156 free_number(arg1);
11157 free_number(arg2);
11158 }
11159
11160
11161 @* Numerical values.
11162
11163 This first set goes into the header
11164
11165 @s mp_fraction mp_number
11166 @s mp_angle mp_number
11167
11168 @<MPlib internal header stuff@>=
11169 #define mp_fraction mp_number
11170 #define mp_angle mp_number
11171 #define new_number(A) @[(((math_data *)(mp->math))->allocate)(mp, &(A), mp_scaled_type)@]
11172 #define new_fraction(A) @[(((math_data *)(mp->math))->allocate)(mp, &(A), mp_fraction_type)@]
11173 #define new_angle(A) @[(((math_data *)(mp->math))->allocate)(mp, &(A), mp_angle_type)@]
11174 #define free_number(A) @[(((math_data *)(mp->math))->free)(mp, &(A))@]
11175
11176 @
11177 @d set_precision() (((math_data *)(mp->math))->set_precision)(mp)
11178 @d free_math() (((math_data *)(mp->math))->free_math)(mp)
11179 @d scan_numeric_token(A) (((math_data *)(mp->math))->scan_numeric)(mp, A)
11180 @d scan_fractional_token(A) (((math_data *)(mp->math))->scan_fractional)(mp, A)
11181 @d set_number_from_of_the_way(A,t,B,C) (((math_data *)(mp->math))->from_oftheway)(mp, &(A),t,B,C)
11182 @d set_number_from_int(A,B) (((math_data *)(mp->math))->from_int)(&(A),B)
11183 @d set_number_from_scaled(A,B) (((math_data *)(mp->math))->from_scaled)(&(A),B)
11184 @d set_number_from_boolean(A,B) (((math_data *)(mp->math))->from_boolean)(&(A),B)
11185 @d set_number_from_double(A,B) (((math_data *)(mp->math))->from_double)(&(A),B)
11186 @d set_number_from_addition(A,B,C) (((math_data *)(mp->math))->from_addition)(&(A),B,C)
11187 @d set_number_from_substraction(A,B,C) (((math_data *)(mp->math))->from_substraction)(&(A),B,C)
11188 @d set_number_from_div(A,B,C) (((math_data *)(mp->math))->from_div)(&(A),B,C)
11189 @d set_number_from_mul(A,B,C) (((math_data *)(mp->math))->from_mul)(&(A),B,C)
11190 @d number_int_div(A,C) (((math_data *)(mp->math))->from_int_div)(&(A),A,C)
11191 @d set_number_from_int_mul(A,B,C) (((math_data *)(mp->math))->from_int_mul)(&(A),B,C)
11192 @#
11193 @d set_number_to_unity(A) (((math_data *)(mp->math))->clone)(&(A), unity_t)
11194 @d set_number_to_zero(A) (((math_data *)(mp->math))->clone)(&(A), zero_t)
11195 @d set_number_to_inf(A) (((math_data *)(mp->math))->clone)(&(A), inf_t)
11196 @d set_number_to_neg_inf(A) do { set_number_to_inf(A); number_negate (A); } while (0)@;
11197 @#
11198 @d init_randoms(A) (((math_data *)(mp->math))->init_randoms)(mp,A)
11199 @d print_number(A) (((math_data *)(mp->math))->print)(mp,A)
11200 @d number_tostring(A) (((math_data *)(mp->math))->tostring)(mp,A)
11201 @d make_scaled(R,A,B) (((math_data *)(mp->math))->make_scaled)(mp,&(R),A,B)
11202 @d take_scaled(R,A,B) (((math_data *)(mp->math))->take_scaled)(mp,&(R),A,B)
11203 @d make_fraction(R,A,B) (((math_data *)(mp->math))->make_fraction)(mp,&(R),A,B)
11204 @d take_fraction(R,A,B) (((math_data *)(mp->math))->take_fraction)(mp,&(R),A,B)
11205 @d pyth_add(R,A,B) (((math_data *)(mp->math))->pyth_add)(mp,&(R),A,B)
11206 @d pyth_sub(R,A,B) (((math_data *)(mp->math))->pyth_sub)(mp,&(R),A,B)
11207 @d n_arg(R,A,B) (((math_data *)(mp->math))->n_arg)(mp,&(R),A,B)
11208 @d m_log(R,A) (((math_data *)(mp->math))->m_log)(mp,&(R),A)
11209 @d m_exp(R,A) (((math_data *)(mp->math))->m_exp)(mp,&(R),A)
11210 @d m_unif_rand(R,A) (((math_data *)(mp->math))->m_unif_rand)(mp,&(R),A)
11211 @d m_norm_rand(R) (((math_data *)(mp->math))->m_norm_rand)(mp,&(R))
11212 @d velocity(R,A,B,C,D,E) (((math_data *)(mp->math))->velocity)(mp,&(R),A,B,C,D,E)
11213 @d ab_vs_cd(R,A,B,C,D) (((math_data *)(mp->math))->ab_vs_cd)(mp,&(R),A,B,C,D)
11214 @d crossing_point(R,A,B,C) (((math_data *)(mp->math))->crossing_point)(mp,&(R),A,B,C)
11215 @d n_sin_cos(A,S,C) (((math_data *)(mp->math))->sin_cos)(mp,A,&(S),&(C))
11216 @d square_rt(A,S) (((math_data *)(mp->math))->sqrt)(mp,&(A),S)
11217 @d slow_add(R,A,B) (((math_data *)(mp->math))->slow_add)(mp,&(R),A,B)
11218 @d round_unscaled(A) (((math_data *)(mp->math))->round_unscaled)(A)
11219 @d floor_scaled(A) (((math_data *)(mp->math))->floor_scaled)(&(A))
11220 @d fraction_to_round_scaled(A) (((math_data *)(mp->math))->fraction_to_round_scaled)(&(A))
11221 @d number_to_int(A) (((math_data *)(mp->math))->to_int)(A)
11222 @d number_to_boolean(A) (((math_data *)(mp->math))->to_boolean)(A)
11223 @d number_to_scaled(A) (((math_data *)(mp->math))->to_scaled)(A)
11224 @d number_to_double(A) (((math_data *)(mp->math))->to_double)(A)
11225 @d number_negate(A) (((math_data *)(mp->math))->negate)(&(A))
11226 @d number_add(A,B) (((math_data *)(mp->math))->add)(&(A),B)
11227 @d number_substract(A,B) (((math_data *)(mp->math))->substract)(&(A),B)
11228 @d number_half(A) (((math_data *)(mp->math))->half)(&(A))
11229 @d number_halfp(A) (((math_data *)(mp->math))->halfp)(&(A))
11230 @d number_double(A) (((math_data *)(mp->math))->do_double)(&(A))
11231 @d number_add_scaled(A,B) (((math_data *)(mp->math))->add_scaled)(&(A),B)
11232 @d number_multiply_int(A,B) (((math_data *)(mp->math))->multiply_int)(&(A),B)
11233 @d number_divide_int(A,B) (((math_data *)(mp->math))->divide_int)(&(A),B)
11234 @d number_abs(A) (((math_data *)(mp->math))->abs)(&(A))
11235 @d number_modulo(A,B) (((math_data *)(mp->math))->modulo)(&(A), B)
11236 @d number_nonequalabs(A,B) (((math_data *)(mp->math))->nonequalabs)(A,B)
11237 @d number_odd(A) (((math_data *)(mp->math))->odd)(A)
11238 @d number_equal(A,B) (((math_data *)(mp->math))->equal)(A,B)
11239 @d number_greater(A,B) (((math_data *)(mp->math))->greater)(A,B)
11240 @d number_less(A,B) (((math_data *)(mp->math))->less)(A,B)
11241 @d number_clone(A,B) (((math_data *)(mp->math))->clone)(&(A),B)
11242 @d number_swap(A,B) (((math_data *)(mp->math))->swap)(&(A),&(B));
11243 @d convert_scaled_to_angle(A) (((math_data *)(mp->math))->scaled_to_angle)(&(A));
11244 @d convert_angle_to_scaled(A) (((math_data *)(mp->math))->angle_to_scaled)(&(A));
11245 @d convert_fraction_to_scaled(A) (((math_data *)(mp->math))->fraction_to_scaled)(&(A));
11246 @d convert_scaled_to_fraction(A) (((math_data *)(mp->math))->scaled_to_fraction)(&(A));
11247 @d m_get_left_endpoint(R,A) (((math_data *)(mp->math))->m_get_left_endpoint)(mp,&(R),A) /* math interval new primitives */
11248 @d m_get_right_endpoint(R,A) (((math_data *)(mp->math))->m_get_right_endpoint)(mp,&(R),A) /* math interval new primitives */
11249 @d m_interval_set(R,A,B) (((math_data *)(mp->math))->m_interval_set)(mp,&(R),A,B) /* math interval new primitives */
11250 @#
11251 @d number_zero(A) number_equal(A, zero_t)
11252 @d number_infinite(A) number_equal(A, inf_t)
11253 @d number_unity(A) number_equal(A, unity_t)
11254 @d number_negative(A) number_less(A, zero_t)
11255 @d number_nonnegative(A) (!number_negative(A))
11256 @d number_positive(A) number_greater(A, zero_t)
11257 @d number_nonpositive(A) (!number_positive(A))
11258 @d number_nonzero(A) (!number_zero(A))
11259 @d number_greaterequal(A,B) (!number_less(A,B))
11260 @d number_lessequal(A,B) (!number_greater(A,B))
11261
11262 @* Edge structures.
11263 Now we come to \MP's internal scheme for representing pictures.
11264 The representation is very different from \MF's edge structures
11265 because \MP\ pictures contain \ps\ graphics objects instead of pixel
11266 images. However, the basic idea is somewhat similar in that shapes
11267 are represented via their boundaries.
11268
11269 The main purpose of edge structures is to keep track of graphical objects
11270 until it is time to translate them into \ps. Since \MP\ does not need to
11271 know anything about an edge structure other than how to translate it into
11272 \ps\ and how to find its bounding box, edge structures can be just linked
11273 lists of graphical objects. \MP\ has no easy way to determine whether
11274 two such objects overlap, but it suffices to draw the first one first and
11275 let the second one overwrite it if necessary.
11276
11277 @<MPlib header stuff@>=
11278 enum mp_graphical_object_code {
11279 @<Graphical object codes@>@;
11280 mp_final_graphic
11281 };
11282
11283 @ Let's consider the types of graphical objects one at a time.
11284 First of all, a filled contour is represented by a eight-word node. The first
11285 word contains |type| and |link| fields, and the next six words contain a
11286 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
11287 parameter. If a pen is used for filling |pen_p|, |ljoin| and |miterlim|
11288 give the relevant information.
11289
11290 @d mp_path_p(A) (A)->path_p_ /* a pointer to the path that needs filling */
11291 @d mp_pen_p(A) (A)->pen_p_ /* a pointer to the pen to fill or stroke with */
11292 @d mp_color_model(A) ((mp_fill_node)(A))->color_model_ /* the color model */
11293 @d cyan red
11294 @d grey red
11295 @d magenta green
11296 @d yellow blue
11297 @d mp_pre_script(A) ((mp_fill_node)(A))->pre_script_
11298 @d mp_post_script(A) ((mp_fill_node)(A))->post_script_
11299
11300 @<MPlib internal header stuff@>=
11301 typedef struct mp_fill_node_data {
11302 NODE_BODY;@+@t}\6{@>
11303 halfword color_model_;
11304 mp_number red;
11305 mp_number green;
11306 mp_number blue;
11307 mp_number black;
11308 mp_string pre_script_;
11309 mp_string post_script_;
11310 mp_knot path_p_;
11311 mp_knot pen_p_;
11312 unsigned char ljoin;
11313 mp_number miterlim;
11314 } mp_fill_node_data;
11315 typedef struct mp_fill_node_data *mp_fill_node;
11316
11317 @ @<Graphical object codes@>=
11318 mp_fill_code = 1,@[@]@;
11319
11320 @ Make a fill node for cyclic path |p| and color black.
11321
11322 @d fill_node_size sizeof(struct mp_fill_node_data)
11323
11324 @c
11325 static mp_node mp_new_fill_node (MP mp, mp_knot p) {
11326 mp_fill_node t = malloc_node (fill_node_size);
11327 mp_type (t) = mp_fill_node_type;
11328 mp_path_p (t) = p;
11329 mp_pen_p (t) = NULL; /* |NULL| means don't use a pen */
11330 new_number(t->red);
11331 new_number(t->green);
11332 new_number(t->blue);
11333 new_number(t->black);
11334 new_number(t->miterlim);
11335 clear_color (t);
11336 mp_color_model (t) = mp_uninitialized_model;
11337 mp_pre_script (t) = NULL;
11338 mp_post_script (t) = NULL;
11339 /* Set the |ljoin| and |miterlim| fields in object |t| */
11340 if (number_greater(internal_value (mp_linejoin), unity_t))
11341 t->ljoin = 2;
11342 else if (number_positive(internal_value (mp_linejoin)))
11343 t->ljoin = 1;
11344 else
11345 t->ljoin = 0;
11346 if (number_less(internal_value (mp_miterlimit), unity_t)) {
11347 set_number_to_unity(t->miterlim);
11348 } else {
11349 number_clone(t->miterlim,internal_value (mp_miterlimit));
11350 }
11351 return (mp_node) t;
11352 }
11353
11354 @ @c
11355 static void mp_free_fill_node (MP mp, mp_fill_node p) {
11356 mp_toss_knot_list (mp, mp_path_p (p));
11357 if (mp_pen_p (p) != NULL)
11358 mp_toss_knot_list (mp, mp_pen_p (p));
11359 if (mp_pre_script (p) != NULL)
11360 delete_str_ref (mp_pre_script (p));
11361 if (mp_post_script (p) != NULL)
11362 delete_str_ref (mp_post_script (p));
11363 free_number(p->red);
11364 free_number(p->green);
11365 free_number(p->blue);
11366 free_number(p->black);
11367 free_number(p->miterlim);
11368 mp_free_node (mp, (mp_node)p, fill_node_size);
11369 }
11370
11371
11372
11373 @ A stroked path is represented by an eight-word node that is like a filled
11374 contour node except that it contains the current \&{linecap} value, a scale
11375 factor for the dash pattern, and a pointer that is non-NULL if the stroke
11376 is to be dashed. The purpose of the scale factor is to allow a picture to
11377 be transformed without touching the picture that |dash_p| points to.
11378
11379 @d mp_dash_p(A) ((mp_stroked_node)(A))->dash_p_ /* a pointer to the edge structure that gives the dash pattern */
11380
11381 @<MPlib internal header stuff@>=
11382 typedef struct mp_stroked_node_data {
11383 NODE_BODY;@+@t}\6{@>
11384 halfword color_model_;
11385 mp_number red;
11386 mp_number green;
11387 mp_number blue;
11388 mp_number black;
11389 mp_string pre_script_;
11390 mp_string post_script_;
11391 mp_knot path_p_;
11392 mp_knot pen_p_;
11393 unsigned char ljoin;
11394 mp_number miterlim;
11395 unsigned char lcap;
11396 mp_node dash_p_;
11397 mp_number dash_scale;
11398 } mp_stroked_node_data;
11399 typedef struct mp_stroked_node_data *mp_stroked_node;
11400
11401
11402 @ @<Graphical object codes@>=
11403 mp_stroked_code = 2,@[@]@;
11404
11405 @ Make a stroked node for path |p| with |mp_pen_p(p)| temporarily |NULL|.
11406
11407 @d stroked_node_size sizeof(struct mp_stroked_node_data)
11408
11409 @c
11410 static mp_node mp_new_stroked_node (MP mp, mp_knot p) {
11411 mp_stroked_node t = malloc_node (stroked_node_size);
11412 mp_type (t) = mp_stroked_node_type;
11413 mp_path_p (t) = p;
11414 mp_pen_p (t) = NULL;
11415 mp_dash_p (t) = NULL;
11416 new_number(t->dash_scale);
11417 set_number_to_unity(t->dash_scale);
11418 new_number(t->red);
11419 new_number(t->green);
11420 new_number(t->blue);
11421 new_number(t->black);
11422 new_number(t->miterlim);
11423 clear_color(t);
11424 mp_pre_script (t) = NULL;
11425 mp_post_script (t) = NULL;
11426 /* Set the |ljoin| and |miterlim| fields in object |t| */
11427 if (number_greater(internal_value (mp_linejoin), unity_t))
11428 t->ljoin = 2;
11429 else if (number_positive(internal_value (mp_linejoin)))
11430 t->ljoin = 1;
11431 else
11432 t->ljoin = 0;
11433 if (number_less(internal_value (mp_miterlimit), unity_t)) {
11434 set_number_to_unity(t->miterlim);
11435 } else {
11436 number_clone(t->miterlim,internal_value (mp_miterlimit));
11437 }
11438 if (number_greater(internal_value (mp_linecap), unity_t))
11439 t->lcap = 2;
11440 else if (number_positive(internal_value (mp_linecap)))
11441 t->lcap = 1;
11442 else
11443 t->lcap = 0;
11444 return (mp_node) t;
11445 }
11446
11447 @ @s mp_edge_header_node int @c
11448 static mp_edge_header_node mp_free_stroked_node (MP mp, mp_stroked_node p) {
11449 mp_edge_header_node e = NULL;
11450 mp_toss_knot_list (mp, mp_path_p (p));
11451 if (mp_pen_p (p) != NULL)
11452 mp_toss_knot_list (mp, mp_pen_p (p));
11453 if (mp_pre_script (p) != NULL)
11454 delete_str_ref (mp_pre_script (p));
11455 if (mp_post_script (p) != NULL)
11456 delete_str_ref (mp_post_script (p));
11457 e = (mp_edge_header_node)mp_dash_p (p);
11458 free_number(p->dash_scale);
11459 free_number(p->red);
11460 free_number(p->green);
11461 free_number(p->blue);
11462 free_number(p->black);
11463 free_number(p->miterlim);
11464 mp_free_node (mp, (mp_node)p, stroked_node_size);
11465 return e;
11466 }
11467
11468 @ When a dashed line is computed in a transformed coordinate system, the dash
11469 lengths get scaled like the pen shape and we need to compensate for this. Since
11470 there is no unique scale factor for an arbitrary transformation, we use the
11471 square root of the determinant. The properties of the determinant make it
11472 easier to maintain the |dash_scale|. The computation is fairly straight-forward
11473 except for the initialization of the scale factor |s|. The factor of 64 is
11474 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
11475 to counteract the effect of |take_fraction|.
11476
11477 @c
11478 void mp_sqrt_det (MP mp, mp_number *ret, mp_number a_orig, mp_number b_orig, mp_number c_orig, mp_number d_orig) {
11479 mp_number a,b,c,d;
11480 mp_number maxabs; /* |max(a,b,c,d)| */
11481 unsigned s; /* amount by which the result of |square_rt| needs to be scaled */
11482 new_number(a);
11483 new_number(b);
11484 new_number(c);
11485 new_number(d);
11486 new_number(maxabs);
11487 number_clone(a, a_orig);
11488 number_clone(b, b_orig);
11489 number_clone(c, c_orig);
11490 number_clone(d, d_orig);
11491 /* Initialize |maxabs| */
11492 {
11493 mp_number tmp;
11494 new_number (tmp);
11495 number_clone(maxabs, a);
11496 number_abs(maxabs);
11497 number_clone(tmp, b);
11498 number_abs(tmp);
11499 if (number_greater(tmp, maxabs))
11500 number_clone(maxabs, tmp);
11501 number_clone(tmp, c);
11502 number_abs(tmp);
11503 if (number_greater(tmp, maxabs))
11504 number_clone(maxabs, tmp);
11505 number_clone(tmp, d);
11506 number_abs(tmp);
11507 if (number_greater(tmp, maxabs))
11508 number_clone(maxabs, tmp);
11509 free_number(tmp);
11510 }
11511
11512
11513 s = 64;
11514 while ((number_less(maxabs, fraction_one_t)) && (s > 1)) {
11515 number_double(a);
11516 number_double(b);
11517 number_double(c);
11518 number_double(d);
11519 number_double(maxabs);
11520 s = s/2;
11521 }
11522 {
11523 mp_number r1, r2;
11524 new_fraction (r1);
11525 new_fraction (r2);
11526 take_fraction (r1, a, d);
11527 take_fraction (r2, b, c);
11528 number_substract (r1, r2);
11529 number_abs (r1);
11530 square_rt(*ret, r1);
11531 number_multiply_int(*ret, s);
11532 free_number (r1);
11533 free_number (r2);
11534 }
11535 free_number(a);
11536 free_number(b);
11537 free_number(c);
11538 free_number(d);
11539 free_number(maxabs);
11540 }
11541 @#
11542 static void mp_get_pen_scale (MP mp, mp_number *ret, mp_knot p) {
11543 if (p == NULL) {
11544 set_number_to_zero(*ret);
11545 } else {
11546 mp_number a,b,c,d;
11547 new_number(a);
11548 new_number(b);
11549 new_number(c);
11550 new_number(d);
11551 set_number_from_substraction(a, p->left_x, p->x_coord);
11552 set_number_from_substraction(b, p->right_x, p->x_coord);
11553 set_number_from_substraction(c, p->left_y, p->y_coord);
11554 set_number_from_substraction(d, p->right_y, p->y_coord);
11555 mp_sqrt_det (mp, ret, a, b, c, d);
11556 free_number(a);
11557 free_number(b);
11558 free_number(c);
11559 free_number(d);
11560 }
11561 }
11562
11563
11564 @ @<Declarations@>=
11565 static void mp_sqrt_det (MP mp, mp_number *ret, mp_number a, mp_number b, mp_number c, mp_number d);
11566
11567 @ When a picture contains text, this is represented by a fourteen-word node
11568 where the color information and |type| and |link| fields are augmented by
11569 additional fields that describe the text and how it is transformed.
11570 The |path_p| and |mp_pen_p| pointers are replaced by a number that identifies
11571 the font and a string number that gives the text to be displayed.
11572 The |width|, |height|, and |depth| fields
11573 give the dimensions of the text at its design size, and the remaining six
11574 words give a transformation to be applied to the text. The |new_text_node|
11575 function initializes everything to default values so that the text comes out
11576 black with its reference point at the origin.
11577
11578 @d mp_text_p(A) ((mp_text_node)(A))->text_p_ /* a string pointer for the text to display */
11579 @d mp_font_n(A) ((mp_text_node)(A))->font_n_ /* the font number */
11580
11581 @<MPlib internal header stuff@>=
11582 typedef struct mp_text_node_data {
11583 NODE_BODY;@+@t}\6{@>
11584 halfword color_model_;
11585 mp_number red;
11586 mp_number green;
11587 mp_number blue;
11588 mp_number black;
11589 mp_string pre_script_;
11590 mp_string post_script_;
11591 mp_string text_p_;
11592 halfword font_n_;
11593 mp_number width;
11594 mp_number height;
11595 mp_number depth;
11596 mp_number tx;
11597 mp_number ty;
11598 mp_number txx;
11599 mp_number txy;
11600 mp_number tyx;
11601 mp_number tyy;
11602 } mp_text_node_data;
11603 typedef struct mp_text_node_data *mp_text_node;
11604
11605 @ @<Graphical object codes@>=
11606 mp_text_code = 3,@[@]@;
11607
11608 @ Make a text node for font |f| and text string |s|.
11609
11610 @d text_node_size sizeof(struct mp_text_node_data)
11611
11612 @c
11613 static mp_node mp_new_text_node (MP mp, char *f, mp_string s) {
11614 mp_text_node t = malloc_node (text_node_size);
11615 mp_type (t) = mp_text_node_type;
11616 mp_text_p (t) = s;
11617 add_str_ref(s);
11618 mp_font_n (t) = (halfword) mp_find_font (mp, f); /* this identifies the font */
11619 new_number(t->red);
11620 new_number(t->green);
11621 new_number(t->blue);
11622 new_number(t->black);
11623 new_number(t->width);
11624 new_number(t->height);
11625 new_number(t->depth);
11626 clear_color (t);
11627 mp_pre_script (t) = NULL;
11628 mp_post_script (t) = NULL;
11629 new_number(t->tx);
11630 new_number(t->ty);
11631 new_number(t->txx);
11632 new_number(t->txy);
11633 new_number(t->tyx);
11634 new_number(t->tyy);
11635 /* |tx_val (t) = 0; ty_val (t) = 0;| */
11636 /* |txy_val (t) = 0; tyx_val (t) = 0;| */
11637 set_number_to_unity(t->txx);
11638 set_number_to_unity(t->tyy);
11639 mp_set_text_box (mp, t); /* this finds the bounding box */
11640 return (mp_node) t;
11641 }
11642
11643 @ @c
11644 static void mp_free_text_node (MP mp, mp_text_node p) {
11645 /* |delete_str_ref (mp_text_p (p));| */ /* gives errors */
11646 if (mp_pre_script (p) != NULL)
11647 delete_str_ref (mp_pre_script (p));
11648 if (mp_post_script (p) != NULL)
11649 delete_str_ref (mp_post_script (p));
11650 free_number(p->red);
11651 free_number(p->green);
11652 free_number(p->blue);
11653 free_number(p->black);
11654 free_number(p->width);
11655 free_number(p->height);
11656 free_number(p->depth);
11657 free_number(p->tx);
11658 free_number(p->ty);
11659 free_number(p->txx);
11660 free_number(p->txy);
11661 free_number(p->tyx);
11662 free_number(p->tyy);
11663 mp_free_node (mp, (mp_node)p, text_node_size);
11664 }
11665
11666 @ The last two types of graphical objects that can occur in an edge structure
11667 are clipping paths and \&{setbounds} paths. These are slightly more difficult
11668 @:set_bounds_}{\&{setbounds} primitive@>
11669 to implement because we must keep track of exactly what is being clipped or
11670 bounded when pictures get merged together. For this reason, each clipping or
11671 \&{setbounds} operation is represented by a pair of nodes: first comes a
11672 node whose |path_p| gives the relevant path, then there is the list
11673 of objects to clip or bound followed by a closing node.
11674
11675 @d has_color(A) (mp_type((A))<mp_start_clip_node_type)
11676 /* does a graphical object have color fields? */
11677 @d has_pen(A) (mp_type((A))<mp_text_node_type)
11678 /* does a graphical object have a |mp_pen_p| field? */
11679 @d is_start_or_stop(A) (mp_type((A))>=mp_start_clip_node_type)
11680 @d is_stop(A) (mp_type((A))>=mp_stop_clip_node_type)
11681
11682 @<MPlib internal header stuff@>=
11683 typedef struct mp_start_clip_node_data {
11684 NODE_BODY;@+@t}\6{@>
11685 mp_knot path_p_;
11686 } mp_start_clip_node_data;
11687 typedef struct mp_start_clip_node_data *mp_start_clip_node;
11688 typedef struct mp_start_bounds_node_data {
11689 NODE_BODY;@+@t}\6{@>
11690 mp_knot path_p_;
11691 } mp_start_bounds_node_data;
11692 typedef struct mp_start_bounds_node_data *mp_start_bounds_node;
11693 typedef struct mp_stop_clip_node_data {
11694 NODE_BODY;
11695 } mp_stop_clip_node_data;
11696 typedef struct mp_stop_clip_node_data *mp_stop_clip_node;
11697 typedef struct mp_stop_bounds_node_data {
11698 NODE_BODY;
11699 } mp_stop_bounds_node_data;
11700 typedef struct mp_stop_bounds_node_data *mp_stop_bounds_node;
11701
11702
11703 @ @<Graphical object codes@>=
11704 mp_start_clip_code = 4, /* |type| of a node that starts clipping */
11705 mp_start_bounds_code = 5, /* |type| of a node that gives a \&{setbounds} path */
11706 mp_stop_clip_code = 6, /* |type| of a node that stops clipping */
11707 mp_stop_bounds_code = 7,@[@]@; /* |type| of a node that stops \&{setbounds} */
11708
11709
11710 @
11711 @d start_clip_size sizeof(struct mp_start_clip_node_data)
11712 @d stop_clip_size sizeof(struct mp_stop_clip_node_data)
11713 @d start_bounds_size sizeof(struct mp_start_bounds_node_data)
11714 @d stop_bounds_size sizeof(struct mp_stop_bounds_node_data)
11715
11716 @c
11717 static mp_node mp_new_bounds_node (MP mp, mp_knot p, quarterword c) {
11718 /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
11719 if (c == mp_start_clip_node_type) {
11720 mp_start_clip_node t; /* the new node */
11721 t = (mp_start_clip_node) malloc_node (start_clip_size);
11722 t->path_p_ = p;
11723 mp_type (t) = c;
11724 t->link = NULL;
11725 return (mp_node) t;
11726 } else if (c == mp_start_bounds_node_type) {
11727 mp_start_bounds_node t; /* the new node */
11728 t = (mp_start_bounds_node) malloc_node (start_bounds_size);
11729 t->path_p_ = p;
11730 mp_type (t) = c;
11731 t->link = NULL;
11732 return (mp_node) t;
11733 } else if (c == mp_stop_clip_node_type) {
11734 mp_stop_clip_node t; /* the new node */
11735 t = (mp_stop_clip_node) malloc_node (stop_clip_size);
11736 mp_type (t) = c;
11737 t->link = NULL;
11738 return (mp_node) t;
11739 } else if (c == mp_stop_bounds_node_type) {
11740 mp_stop_bounds_node t; /* the new node */
11741 t = (mp_stop_bounds_node) malloc_node (stop_bounds_size);
11742 mp_type (t) = c;
11743 t->link = NULL;
11744 return (mp_node) t;
11745 } else {
11746 assert (0);
11747 }
11748 return NULL;
11749 }
11750
11751
11752 @ @c
11753 static void mp_free_start_clip_node (MP mp, mp_start_clip_node p) {
11754 mp_toss_knot_list (mp, mp_path_p (p));
11755 mp_free_node (mp, (mp_node)p, start_clip_size);
11756 }
11757 static void mp_free_start_bounds_node (MP mp, mp_start_bounds_node p) {
11758 mp_toss_knot_list (mp, mp_path_p (p));
11759 mp_free_node (mp, (mp_node)p, start_bounds_size);
11760 }
11761 static void mp_free_stop_clip_node (MP mp, mp_stop_clip_node p) {
11762 mp_free_node (mp, (mp_node)p, stop_clip_size);
11763 }
11764 static void mp_free_stop_bounds_node (MP mp, mp_stop_bounds_node p) {
11765 mp_free_node (mp, (mp_node)p, stop_bounds_size);
11766 }
11767
11768
11769 @ All the essential information in an edge structure is encoded as a linked list
11770 of graphical objects as we have just seen, but it is helpful to add some
11771 redundant information. A single edge structure might be used as a dash pattern
11772 many times, and it would be nice to avoid scanning the same structure
11773 repeatedly. Thus, an edge structure known to be a suitable dash pattern
11774 has a header that gives a list of dashes in a sorted order designed for rapid
11775 translation into \ps.
11776
11777 Each dash is represented by a three-word node containing the initial and final
11778 $x$~coordinates as well as the usual |link| field. The |link| fields points to
11779 the dash node with the next higher $x$-coordinates and the final link points
11780 to a special location called |null_dash|. (There should be no overlap between
11781 dashes). Since the $y$~coordinate of the dash pattern is needed to determine
11782 the period of repetition, this needs to be stored in the edge header along
11783 with a pointer to the list of dash nodes.
11784
11785 The |dash_info| is explained below.
11786
11787 @d dash_list(A) (mp_dash_node)(((mp_dash_node)(A))->link) /* in an edge header this points to the first dash node */
11788 @d set_dash_list(A,B) ((mp_dash_node)(A))->link=(mp_node)((B)) /* in an edge header this points to the first dash node */
11789
11790 @<MPlib internal header stuff@>=
11791 typedef struct mp_dash_node_data {
11792 NODE_BODY;@+@t}\6{@>
11793 mp_number start_x; /* the starting $x$~coordinate in a dash node */
11794 mp_number stop_x; /* the ending $x$~coordinate in a dash node */
11795 mp_number dash_y; /* $y$ value for the dash list in an edge header */
11796 mp_node dash_info_;
11797 } mp_dash_node_data;
11798
11799 @ @<Types...@>=
11800 typedef struct mp_dash_node_data *mp_dash_node;
11801
11802 @ @<Initialize table entries@>=
11803 mp->null_dash = mp_get_dash_node (mp);
11804
11805 @ @<Free table entries@>=
11806 mp_free_node (mp, (mp_node)mp->null_dash, dash_node_size);
11807
11808 @ @d dash_node_size sizeof(struct mp_dash_node_data)
11809
11810 @c
11811 static mp_dash_node mp_get_dash_node (MP mp) {
11812 mp_dash_node p = (mp_dash_node) malloc_node (dash_node_size);
11813 p->has_number = 0;
11814 new_number(p->start_x);
11815 new_number(p->stop_x);
11816 new_number(p->dash_y);
11817 mp_type (p) = mp_dash_node_type;
11818 return p;
11819 }
11820
11821
11822 @ It is also convenient for an edge header to contain the bounding
11823 box information needed by the \&{llcorner} and \&{urcorner} operators
11824 so that this does not have to be recomputed unnecessarily. This is done by
11825 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
11826 how far the bounding box computation has gotten. Thus if the user asks for
11827 the bounding box and then adds some more text to the picture before asking
11828 for more bounding box information, the second computation need only look at
11829 the additional text.
11830
11831 When the bounding box has not been computed, the |bblast| pointer points
11832 to a dummy link at the head of the graphical object list while the |minx_val|
11833 and |miny_val| fields contain |EL_GORDO| and the |maxx_val| and |maxy_val|
11834 fields contain |-EL_GORDO|.
11835
11836 Since the bounding box of pictures containing objects of type
11837 |mp_start_bounds_node| depends on the value of \&{truecorners}, the bounding box
11838 @:mp_true_corners_}{\&{truecorners} primitive@>
11839 data might not be valid for all values of this parameter. Hence, the |bbtype|
11840 field is needed to keep track of this.
11841
11842 @d bblast(A) ((mp_edge_header_node)(A))->bblast_ /* last item considered in bounding box computation */
11843 @d edge_list(A) ((mp_edge_header_node)(A))->list_ /* where the object list begins in an edge header */
11844
11845 @<MPlib internal header stuff@>=
11846 typedef struct mp_edge_header_node_data {
11847 NODE_BODY;@+@t}\6{@>
11848 mp_number start_x;
11849 mp_number stop_x;
11850 mp_number dash_y;
11851 mp_node dash_info_;
11852 mp_number minx;
11853 mp_number miny;
11854 mp_number maxx;
11855 mp_number maxy;
11856 mp_node bblast_;
11857 int bbtype; /* tells how bounding box data depends on \&{truecorners} */
11858 mp_node list_;
11859 mp_node obj_tail_; /* explained below */
11860 halfword ref_count_; /* explained below */
11861 } mp_edge_header_node_data;
11862 typedef struct mp_edge_header_node_data *mp_edge_header_node;
11863
11864 @
11865 @d no_bounds 0 /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
11866 @d bounds_set 1 /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
11867 @d bounds_unset 2 /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
11868 @c
11869 static void mp_init_bbox (MP mp, mp_edge_header_node h) {
11870 /* Initialize the bounding box information in edge structure |h| */
11871 (void) mp;
11872 bblast (h) = edge_list (h);
11873 h->bbtype = no_bounds;
11874 set_number_to_inf(h->minx);
11875 set_number_to_inf(h->miny);
11876 set_number_to_neg_inf(h->maxx);
11877 set_number_to_neg_inf(h->maxy);
11878 }
11879
11880
11881 @ The only other entries in an edge header are a reference count in the first
11882 word and a pointer to the tail of the object list in the last word.
11883
11884 @d obj_tail(A) ((mp_edge_header_node)(A))->obj_tail_ /* points to the last entry in the object list */
11885 @d edge_ref_count(A) ((mp_edge_header_node)(A))->ref_count_
11886
11887 @d edge_header_size sizeof(struct mp_edge_header_node_data)
11888
11889 @c
11890 static mp_edge_header_node mp_get_edge_header_node (MP mp) {
11891 mp_edge_header_node p = (mp_edge_header_node) malloc_node (edge_header_size);
11892 mp_type (p) = mp_edge_header_node_type;
11893 new_number(p->start_x);
11894 new_number(p->stop_x);
11895 new_number(p->dash_y);
11896 new_number(p->minx);
11897 new_number(p->miny);
11898 new_number(p->maxx);
11899 new_number(p->maxy);
11900 p->list_ = mp_get_token_node (mp); /* or whatever, just a need a link handle */
11901 return p;
11902 }
11903 static void mp_init_edges (MP mp, mp_edge_header_node h) {
11904 /* initialize an edge header to \.{NULL} values */
11905 set_dash_list (h, mp->null_dash);
11906 obj_tail (h) = edge_list (h);
11907 mp_link (edge_list (h)) = NULL;
11908 edge_ref_count (h) = 0;
11909 mp_init_bbox (mp, h);
11910 }
11911
11912
11913 @ Here is how edge structures are deleted. The process can be recursive because
11914 of the need to dereference edge structures that are used as dash patterns.
11915 @^recursion@>
11916
11917 @d add_edge_ref(A) incr(edge_ref_count((A)))
11918 @d delete_edge_ref(A) {
11919 if ( edge_ref_count((A))==0 )
11920 mp_toss_edges(mp, (mp_edge_header_node)(A));
11921 else
11922 decr(edge_ref_count((A)));
11923 }
11924
11925 @<Declarations@>=
11926 static void mp_flush_dash_list (MP mp, mp_edge_header_node h);
11927 static mp_edge_header_node mp_toss_gr_object (MP mp, mp_node p);
11928 static void mp_toss_edges (MP mp, mp_edge_header_node h);
11929
11930 @ @c
11931 void mp_toss_edges (MP mp, mp_edge_header_node h) {
11932 mp_node p, q; /* pointers that scan the list being recycled */
11933 mp_edge_header_node r; /* an edge structure that object |p| refers to */
11934 mp_flush_dash_list (mp, h);
11935 q = mp_link (edge_list (h));
11936 while ((q != NULL)) {
11937 p = q;
11938 q = mp_link (q);
11939 r = mp_toss_gr_object (mp, p);
11940 if (r != NULL)
11941 delete_edge_ref (r);
11942 }
11943 free_number(h->start_x);
11944 free_number(h->stop_x);
11945 free_number(h->dash_y);
11946 free_number(h->minx);
11947 free_number(h->miny);
11948 free_number(h->maxx);
11949 free_number(h->maxy);
11950 mp_free_token_node (mp, h->list_);
11951 mp_free_node (mp, (mp_node)h, edge_header_size);
11952 }
11953 void mp_flush_dash_list (MP mp, mp_edge_header_node h) {
11954 mp_dash_node p, q; /* pointers that scan the list being recycled */
11955 q = dash_list (h);
11956 while (q != mp->null_dash) { /* TODO: |NULL| check should not be needed */
11957 p = q;
11958 q = (mp_dash_node)mp_link (q);
11959 mp_free_node (mp, (mp_node)p, dash_node_size);
11960 }
11961 set_dash_list (h,mp->null_dash);
11962 }
11963 mp_edge_header_node mp_toss_gr_object (MP mp, mp_node p) {
11964 /* returns an edge structure that needs to be dereferenced */
11965 mp_edge_header_node e = NULL; /* the edge structure to return */
11966 switch (mp_type (p)) {
11967 case mp_fill_node_type:
11968 mp_free_fill_node (mp, (mp_fill_node)p);
11969 break;
11970 case mp_stroked_node_type:
11971 e = mp_free_stroked_node (mp, (mp_stroked_node)p);
11972 break;
11973 case mp_text_node_type:
11974 mp_free_text_node(mp, (mp_text_node)p);
11975 break;
11976 case mp_start_clip_node_type:
11977 mp_free_start_clip_node(mp, (mp_start_clip_node)p);
11978 break;
11979 case mp_start_bounds_node_type:
11980 mp_free_start_bounds_node(mp, (mp_start_bounds_node)p);
11981 break;
11982 case mp_stop_clip_node_type:
11983 mp_free_stop_clip_node(mp, (mp_stop_clip_node)p);
11984 break;
11985 case mp_stop_bounds_node_type:
11986 mp_free_stop_bounds_node(mp, (mp_stop_bounds_node)p);
11987 break;
11988 default: /* there are no other valid cases, but please the compiler */
11989 break;
11990 }
11991 return e;
11992 }
11993
11994
11995 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
11996 to be done before making a significant change to an edge structure. Much of
11997 the work is done in a separate routine |copy_objects| that copies a list of
11998 graphical objects into a new edge header.
11999
12000 @c
12001 static mp_edge_header_node mp_private_edges (MP mp, mp_edge_header_node h) {
12002 /* make a private copy of the edge structure headed by |h| */
12003 mp_edge_header_node hh; /* the edge header for the new copy */
12004 mp_dash_node p, pp; /* pointers for copying the dash list */
12005 assert (mp_type (h) == mp_edge_header_node_type);
12006 if (edge_ref_count (h) == 0) {
12007 return h;
12008 } else {
12009 decr (edge_ref_count (h));
12010 hh = (mp_edge_header_node)mp_copy_objects (mp, mp_link (edge_list (h)), NULL);
12011 @<Copy the dash list from |h| to |hh|@>;
12012 @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
12013 point into the new object list@>;
12014 return hh;
12015 }
12016 }
12017
12018
12019 @ Here we use the fact that |dash_list(hh)=mp_link(hh)|.
12020 @^data structure assumptions@>
12021
12022 @<Copy the dash list from |h| to |hh|@>=
12023 pp = (mp_dash_node)hh;
12024 p = dash_list (h);
12025 while ((p != mp->null_dash)) {
12026 mp_link (pp) = (mp_node)mp_get_dash_node (mp);
12027 pp = (mp_dash_node)mp_link (pp);
12028 number_clone(pp->start_x, p->start_x);
12029 number_clone(pp->stop_x, p->stop_x);
12030 p = (mp_dash_node)mp_link (p);
12031 }
12032 mp_link (pp) = (mp_node)mp->null_dash;
12033 number_clone(hh->dash_y, h->dash_y )@;
12034
12035
12036 @ |h| is an edge structure
12037
12038 @s mp_dash_object int
12039
12040 @c
12041 static mp_dash_object *mp_export_dashes (MP mp, mp_stroked_node q, mp_number w) {
12042 mp_dash_object *d;
12043 mp_dash_node p, h;
12044 mp_number scf; /* scale factor */
12045 mp_number dashoff;
12046 double *dashes = NULL;
12047 int num_dashes = 1;
12048 h = (mp_dash_node)mp_dash_p (q);
12049 if (h == NULL || dash_list (h) == mp->null_dash)
12050 return NULL;
12051 new_number (scf);
12052 p = dash_list (h);
12053 mp_get_pen_scale (mp, &scf, mp_pen_p (q));
12054 if (number_zero(scf)) {
12055 if (number_zero(w)) {
12056 number_clone(scf, q->dash_scale);
12057 } else {
12058 free_number(scf);
12059 return NULL;
12060 }
12061 } else {
12062 mp_number ret;
12063 new_number (ret);
12064 make_scaled (ret, w, scf);
12065 take_scaled (scf, ret, q->dash_scale);
12066 free_number (ret);
12067 }
12068 number_clone(w, scf);
12069 d = xmalloc (1, sizeof (mp_dash_object));
12070 add_var_used (sizeof (mp_dash_object));
12071 set_number_from_addition(mp->null_dash->start_x, p->start_x, h->dash_y);
12072 {
12073 mp_number ret, arg1;
12074 new_number (ret);
12075 new_number (arg1);
12076 new_number (dashoff);
12077 while (p != mp->null_dash) {
12078 dashes = xrealloc (dashes, (num_dashes + 2), sizeof (double));
12079 set_number_from_substraction (arg1, p->stop_x, p->start_x);
12080 take_scaled (ret, arg1, scf);
12081 dashes[(num_dashes - 1)] = number_to_double (ret);
12082 set_number_from_substraction (arg1, ((mp_dash_node)mp_link (p))->start_x, p->stop_x);
12083 take_scaled (ret, arg1, scf);
12084 dashes[(num_dashes)] = number_to_double (ret);
12085 dashes[(num_dashes + 1)] = -1.0; /* terminus */
12086 num_dashes += 2;
12087 p = (mp_dash_node)mp_link (p);
12088 }
12089 d->array = dashes;
12090 mp_dash_offset (mp, &dashoff, h);
12091 take_scaled (ret, dashoff, scf);
12092 d->offset = number_to_double(ret);
12093 free_number (ret);
12094 free_number (arg1);
12095 }
12096 free_number (dashoff);
12097 free_number(scf);
12098 return d;
12099 }
12100
12101
12102 @ @<Copy the bounding box information from |h| to |hh|...@>=
12103 number_clone(hh->minx, h->minx);
12104 number_clone(hh->miny, h->miny);
12105 number_clone(hh->maxx, h->maxx);
12106 number_clone(hh->maxy, h->maxy);
12107 hh->bbtype = h->bbtype;
12108 p = (mp_dash_node)edge_list (h);
12109 pp = (mp_dash_node)edge_list (hh);
12110 while ((p != (mp_dash_node)bblast (h))) {
12111 if (p == NULL)
12112 mp_confusion (mp, "bblast");
12113 @:this can't happen bblast}{\quad bblast@>
12114 p = (mp_dash_node)mp_link (p);
12115 pp = (mp_dash_node)mp_link (pp);
12116 }
12117 bblast (hh) = (mp_node)pp
12118
12119 @ Here is the promised routine for copying graphical objects into a new edge
12120 structure. It starts copying at object~|p| and stops just before object~|q|.
12121 If |q| is NULL, it copies the entire sublist headed at |p|. The resulting edge
12122 structure requires further initialization by |init_bbox|.
12123
12124 @<Declarations@>=
12125 static mp_edge_header_node mp_copy_objects (MP mp, mp_node p, mp_node q);
12126
12127 @ @c
12128 mp_edge_header_node mp_copy_objects (MP mp, mp_node p, mp_node q) {
12129 mp_edge_header_node hh; /* the new edge header */
12130 mp_node pp; /* the last newly copied object */
12131 quarterword k = 0; /* temporary register */
12132 hh = mp_get_edge_header_node (mp);
12133 set_dash_list (hh, mp->null_dash);
12134 edge_ref_count (hh) = 0;
12135 pp = edge_list (hh);
12136 while (p != q)
12137 @<Make |mp_link(pp)| point to a copy of object |p|,
12138 and update |p| and |pp|@>@;
12139 obj_tail (hh) = pp;
12140 mp_link (pp) = NULL;
12141 return hh;
12142 }
12143
12144
12145 @ @<Make |mp_link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
12146 {
12147 switch (mp_type (p)) {
12148 case mp_start_clip_node_type:
12149 k = start_clip_size;
12150 break;
12151 case mp_start_bounds_node_type:
12152 k = start_bounds_size;
12153 break;
12154 case mp_fill_node_type:
12155 k = fill_node_size;
12156 break;
12157 case mp_stroked_node_type:
12158 k = stroked_node_size;
12159 break;
12160 case mp_text_node_type:
12161 k = text_node_size;
12162 break;
12163 case mp_stop_clip_node_type:
12164 k = stop_clip_size;
12165 break;
12166 case mp_stop_bounds_node_type:
12167 k = stop_bounds_size;
12168 break;
12169 default: /* there are no other valid cases, but please the compiler */
12170 break;
12171 }
12172 mp_link (pp) = malloc_node ((size_t) k); /* |gr_object| */
12173 pp = mp_link (pp);
12174 memcpy (pp, p, (size_t) k);
12175 pp->link = NULL;
12176 @<Fix anything in graphical object |pp| that should differ from the
12177 corresponding field in |p|@>;
12178 p = mp_link (p);
12179 }
12180
12181
12182 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
12183 switch (mp_type (p)) {
12184 case mp_start_clip_node_type:
12185 {
12186 mp_start_clip_node tt = (mp_start_clip_node)pp;
12187 mp_start_clip_node t = (mp_start_clip_node)p;
12188 mp_path_p (tt) = mp_copy_path (mp, mp_path_p (t));
12189 }
12190 break;
12191 case mp_start_bounds_node_type:
12192 {
12193 mp_start_bounds_node tt = (mp_start_bounds_node)pp;
12194 mp_start_bounds_node t = (mp_start_bounds_node)p;
12195 mp_path_p (tt) = mp_copy_path (mp, mp_path_p (t));
12196 }
12197 break;
12198 case mp_fill_node_type:
12199 {
12200 mp_fill_node tt = (mp_fill_node)pp;
12201 mp_fill_node t = (mp_fill_node)p;
12202 new_number(tt->red); number_clone(tt->red, t->red);
12203 new_number(tt->green); number_clone(tt->green, t->green);
12204 new_number(tt->blue); number_clone(tt->blue, t->blue);
12205 new_number(tt->black); number_clone(tt->black, t->black);
12206 new_number(tt->miterlim); number_clone(tt->miterlim,t->miterlim);
12207 mp_path_p (tt) = mp_copy_path (mp, mp_path_p (t));
12208 if (mp_pre_script (p) != NULL)
12209 add_str_ref (mp_pre_script (p));
12210 if (mp_post_script (p) != NULL)
12211 add_str_ref (mp_post_script (p));
12212 if (mp_pen_p (t) != NULL)
12213 mp_pen_p (tt) = copy_pen (mp_pen_p (t));
12214 }
12215 break;
12216 case mp_stroked_node_type:
12217 {
12218 mp_stroked_node tt = (mp_stroked_node)pp;
12219 mp_stroked_node t = (mp_stroked_node)p;
12220 new_number(tt->red); number_clone(tt->red, t->red);
12221 new_number(tt->green); number_clone(tt->green, t->green);
12222 new_number(tt->blue); number_clone(tt->blue, t->blue);
12223 new_number(tt->black); number_clone(tt->black, t->black);
12224 new_number(tt->miterlim); number_clone(tt->miterlim,t->miterlim);
12225 new_number(tt->dash_scale); number_clone(tt->dash_scale,t->dash_scale);
12226 if (mp_pre_script (p) != NULL)
12227 add_str_ref (mp_pre_script (p));
12228 if (mp_post_script (p) != NULL)
12229 add_str_ref (mp_post_script (p));
12230 mp_path_p (tt) = mp_copy_path (mp, mp_path_p (t));
12231 mp_pen_p (tt) = copy_pen (mp_pen_p (t));
12232 if (mp_dash_p (p) != NULL)
12233 add_edge_ref (mp_dash_p (pp));
12234 }
12235 break;
12236 case mp_text_node_type:
12237 {
12238 mp_text_node tt = (mp_text_node)pp;
12239 mp_text_node t = (mp_text_node)p;
12240 new_number(tt->red); number_clone(tt->red, t->red);
12241 new_number(tt->green); number_clone(tt->green, t->green);
12242 new_number(tt->blue); number_clone(tt->blue, t->blue);
12243 new_number(tt->black); number_clone(tt->black, t->black);
12244 new_number(tt->width); number_clone(tt->width, t->width);
12245 new_number(tt->height); number_clone(tt->height, t->height);
12246 new_number(tt->depth); number_clone(tt->depth, t->depth);
12247 new_number(tt->tx); number_clone(tt->tx, t->tx);
12248 new_number(tt->ty); number_clone(tt->ty, t->ty);
12249 new_number(tt->txx); number_clone(tt->txx, t->txx);
12250 new_number(tt->tyx); number_clone(tt->tyx, t->tyx);
12251 new_number(tt->txy); number_clone(tt->txy, t->txy);
12252 new_number(tt->tyy); number_clone(tt->tyy, t->tyy);
12253 if (mp_pre_script (p) != NULL)
12254 add_str_ref (mp_pre_script (p));
12255 if (mp_post_script (p) != NULL)
12256 add_str_ref (mp_post_script (p));
12257 add_str_ref (mp_text_p (pp));
12258 }
12259 break;
12260 case mp_stop_clip_node_type:
12261 case mp_stop_bounds_node_type:
12262 break;
12263 default: /* there are no other valid cases, but please the compiler */
12264 break;
12265 }
12266
12267
12268 @ Here is one way to find an acceptable value for the second argument to
12269 |copy_objects|. Given a non-NULL graphical object list, |skip_1component|
12270 skips past one picture component, where a ``picture component'' is a single
12271 graphical object, or a start bounds or start clip object and everything up
12272 through the matching stop bounds or stop clip object.
12273
12274 @c
12275 static mp_node mp_skip_1component (MP mp, mp_node p) {
12276 integer lev; /* current nesting level */
12277 lev = 0;
12278 (void) mp;
12279 do {
12280 if (is_start_or_stop (p)) {
12281 if (is_stop (p))
12282 decr (lev);
12283 else
12284 incr (lev);
12285 }
12286 p = mp_link (p);
12287 } while (lev != 0);
12288 return p;
12289 }
12290
12291
12292 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
12293
12294 @<Declarations@>=
12295 static void mp_print_edges (MP mp, mp_node h, const char *s, boolean nuline);
12296
12297 @ @c
12298 void mp_print_edges (MP mp, mp_node h, const char *s, boolean nuline) {
12299 mp_node p; /* a graphical object to be printed */
12300 mp_number scf; /* a scale factor for the dash pattern */
12301 boolean ok_to_dash; /* |false| for polygonal pen strokes */
12302 new_number (scf);
12303 mp_print_diagnostic (mp, "Edge structure", s, nuline);
12304 p = edge_list (h);
12305 while (mp_link (p) != NULL) {
12306 p = mp_link (p);
12307 mp_print_ln (mp);
12308 switch (mp_type (p)) {
12309 @<Cases for printing graphical object node |p|@>;
12310 default:
12311 mp_print (mp, "[unknown object type!]");
12312 break;
12313 }
12314 }
12315 mp_print_nl (mp, "End edges");
12316 if (p != obj_tail (h))
12317 mp_print (mp, "?");
12318 @.End edges?@>
12319 mp_end_diagnostic (mp, true);
12320 free_number (scf);
12321 }
12322
12323
12324 @ @<Cases for printing graphical object node |p|@>=
12325 case mp_fill_node_type:
12326 mp_print (mp, "Filled contour ");
12327 mp_print_obj_color (mp, p);
12328 mp_print_char (mp, xord (':'));
12329 mp_print_ln (mp);
12330 mp_pr_path (mp, mp_path_p ((mp_fill_node) p));
12331 mp_print_ln (mp);
12332 if ((mp_pen_p ((mp_fill_node) p) != NULL)) {
12333 @<Print join type for graphical object |p|@>;
12334 mp_print (mp, " with pen");
12335 mp_print_ln (mp);
12336 mp_pr_pen (mp, mp_pen_p ((mp_fill_node) p));
12337 }
12338 break;
12339
12340 @ @<Print join type for graphical object |p|@>=
12341 switch (((mp_stroked_node)p)->ljoin) {
12342 case 0:
12343 mp_print (mp, "mitered joins limited ");
12344 print_number (((mp_stroked_node)p)->miterlim);
12345 break;
12346 case 1:
12347 mp_print (mp, "round joins");
12348 break;
12349 case 2:
12350 mp_print (mp, "beveled joins");
12351 break;
12352 default:
12353 mp_print (mp, "?? joins");
12354 @.??@>
12355 break;
12356 }
12357
12358
12359 @ For stroked nodes, we need to print |lcap_val(p)| as well.
12360
12361 @<Print join and cap types for stroked node |p|@>=
12362 switch (((mp_stroked_node)p)->lcap ) {
12363 case 0:
12364 mp_print (mp, "butt");
12365 break;
12366 case 1:
12367 mp_print (mp, "round");
12368 break;
12369 case 2:
12370 mp_print (mp, "square");
12371 break;
12372 default:
12373 mp_print (mp, "??");
12374 break;
12375 @.??@>
12376 }
12377 mp_print (mp, " ends, ");
12378 @<Print join type for graphical object |p|@>@;
12379
12380
12381 @ Here is a routine that prints the color of a graphical object if it isn't
12382 black (the default color).
12383
12384 @<Declarations@>=
12385 static void mp_print_obj_color (MP mp, mp_node p);
12386
12387 @ @c
12388 void mp_print_obj_color (MP mp, mp_node p) {
12389 mp_stroked_node p0 = (mp_stroked_node) p;
12390 if (mp_color_model (p) == mp_grey_model) {
12391 if (number_positive(p0->grey)) {
12392 mp_print (mp, "greyed ");
12393 mp_print_char (mp, xord ('('));
12394 print_number (p0->grey);
12395 mp_print_char (mp, xord (')'));
12396 }
12397 } else if (mp_color_model (p) == mp_cmyk_model) {
12398 if (number_positive(p0->cyan) || number_positive(p0->magenta) ||
12399 number_positive(p0->yellow) || number_positive(p0->black)) {
12400 mp_print (mp, "processcolored ");
12401 mp_print_char (mp, xord ('('));
12402 print_number (p0->cyan);
12403 mp_print_char (mp, xord (','));
12404 print_number (p0->magenta);
12405 mp_print_char (mp, xord (','));
12406 print_number (p0->yellow);
12407 mp_print_char (mp, xord (','));
12408 print_number (p0->black);
12409 mp_print_char (mp, xord (')'));
12410 }
12411 } else if (mp_color_model (p) == mp_rgb_model) {
12412 if (number_positive(p0->red) || number_positive(p0->green) ||
12413 number_positive(p0->blue)) {
12414 mp_print (mp, "colored ");
12415 mp_print_char (mp, xord ('('));
12416 print_number (p0->red);
12417 mp_print_char (mp, xord (','));
12418 print_number (p0->green);
12419 mp_print_char (mp, xord (','));
12420 print_number (p0->blue);
12421 mp_print_char (mp, xord (')'));
12422 }
12423 }
12424 }
12425
12426
12427 @ @<Cases for printing graphical object node |p|@>=
12428 case mp_stroked_node_type:
12429 mp_print (mp, "Filled pen stroke ");
12430 mp_print_obj_color (mp, p);
12431 mp_print_char (mp, xord (':'));
12432 mp_print_ln (mp);
12433 mp_pr_path (mp, mp_path_p ((mp_stroked_node) p));
12434 if (mp_dash_p (p) != NULL) {
12435 mp_print_nl (mp, "dashed (");
12436 @<Finish printing the dash pattern that |p| refers to@>;
12437 }
12438 mp_print_ln (mp);
12439 @<Print join and cap types for stroked node |p|@>
12440 mp_print (mp, " with pen");
12441 mp_print_ln (mp);
12442 if (mp_pen_p ((mp_stroked_node) p) == NULL) {
12443 mp_print (mp, "???"); /* shouldn't happen */
12444 @.???@>
12445 } else {
12446 mp_pr_pen (mp, mp_pen_p ((mp_stroked_node) p));
12447 }
12448 break;
12449
12450 @ Normally, the |dash_list| field in an edge header is set to |null_dash|
12451 when it is not known to define a suitable dash pattern. This is disallowed
12452 here because the |mp_dash_p| field should never point to such an edge header.
12453 Note that memory is allocated for |start_x(null_dash)| and we are free to
12454 give it any convenient value.
12455
12456 @<Finish printing the dash pattern that |p| refers to@>=
12457 {
12458 mp_dash_node ppd, hhd;
12459 ok_to_dash = pen_is_elliptical (mp_pen_p ((mp_stroked_node) p));
12460 if (!ok_to_dash)
12461 set_number_to_unity (scf);
12462 else
12463 number_clone(scf, ((mp_stroked_node) p)->dash_scale);
12464 hhd = (mp_dash_node)mp_dash_p (p);
12465 ppd = dash_list (hhd);
12466 if ((ppd == mp->null_dash) || number_negative(hhd->dash_y)) {
12467 mp_print (mp, " ??");
12468 } else {
12469 mp_number dashoff;
12470 mp_number ret, arg1;
12471 new_number (ret);
12472 new_number (arg1);
12473 new_number (dashoff);
12474 set_number_from_addition(mp->null_dash->start_x, ppd->start_x, hhd->dash_y );
12475 while (ppd != mp->null_dash) {
12476 mp_print (mp, "on ");
12477 set_number_from_substraction (arg1, ppd->stop_x, ppd->start_x);
12478 take_scaled (ret, arg1, scf);
12479 print_number ( ret);
12480 mp_print (mp, " off ");
12481 set_number_from_substraction (arg1, ((mp_dash_node)mp_link (ppd))->start_x, ppd->stop_x);
12482 take_scaled (ret, arg1, scf);
12483 print_number (ret);
12484 ppd = (mp_dash_node)mp_link (ppd);
12485 if (ppd != mp->null_dash)
12486 mp_print_char (mp, xord (' '));
12487 }
12488 mp_print (mp, ") shifted ");
12489 mp_dash_offset (mp, &dashoff, hhd);
12490 take_scaled (ret, dashoff, scf);
12491 number_negate (ret);
12492 print_number (ret);
12493 free_number (dashoff);
12494 free_number (ret);
12495 free_number (arg1);
12496 if (!ok_to_dash || number_zero(hhd->dash_y) )
12497 mp_print (mp, " (this will be ignored)");
12498 }
12499 }
12500
12501 @ @<Declarations@>=
12502 static void mp_dash_offset (MP mp, mp_number *x, mp_dash_node h);
12503
12504 @ @c
12505 void mp_dash_offset (MP mp, mp_number *x, mp_dash_node h) {
12506 if (dash_list (h) == mp->null_dash || number_negative(h->dash_y ))
12507 mp_confusion (mp, "dash0");
12508 @:this can't happen dash0}{\quad dash0@>
12509 if (number_zero(h->dash_y)) {
12510 set_number_to_zero(*x);
12511 } else {
12512 number_clone (*x, (dash_list (h))->start_x );
12513 number_modulo (*x, h->dash_y);
12514 number_negate (*x);
12515 if (number_negative(*x))
12516 number_add(*x, h->dash_y);
12517 }
12518 }
12519
12520
12521 @ @<Cases for printing graphical object node |p|@>=
12522 case mp_text_node_type:
12523 {
12524 mp_text_node p0 = (mp_text_node)p;
12525 mp_print_char (mp, xord ('"'));
12526 mp_print_str (mp, mp_text_p (p));
12527 mp_print (mp, "\" infont \"");
12528 mp_print (mp, mp->font_name[mp_font_n (p)]);
12529 mp_print_char (mp, xord ('"'));
12530 mp_print_ln (mp);
12531 mp_print_obj_color (mp, p);
12532 mp_print (mp, "transformed ");
12533 mp_print_char (mp, xord ('('));
12534 print_number (p0->tx);
12535 mp_print_char (mp, xord (','));
12536 print_number (p0->ty);
12537 mp_print_char (mp, xord (','));
12538 print_number (p0->txx);
12539 mp_print_char (mp, xord (','));
12540 print_number (p0->txy);
12541 mp_print_char (mp, xord (','));
12542 print_number (p0->tyx);
12543 mp_print_char (mp, xord (','));
12544 print_number (p0->tyy);
12545 mp_print_char (mp, xord (')'));
12546 }
12547 break;
12548
12549 @ @<Cases for printing graphical object node |p|@>=
12550 case mp_start_clip_node_type:
12551 mp_print (mp, "clipping path:");
12552 mp_print_ln (mp);
12553 mp_pr_path (mp, mp_path_p ((mp_start_clip_node) p));
12554 break;
12555 case mp_stop_clip_node_type:
12556 mp_print (mp, "stop clipping");
12557 break;
12558
12559 @ @<Cases for printing graphical object node |p|@>=
12560 case mp_start_bounds_node_type:
12561 mp_print (mp, "setbounds path:");
12562 mp_print_ln (mp);
12563 mp_pr_path (mp, mp_path_p ((mp_start_bounds_node) p));
12564 break;
12565 case mp_stop_bounds_node_type:
12566 mp_print (mp, "end of setbounds");
12567 break;
12568
12569 @ To initialize the |dash_list| field in an edge header~|h|, we need a
12570 subroutine that scans an edge structure and tries to interpret it as a dash
12571 pattern. This can only be done when there are no filled regions or clipping
12572 paths and all the pen strokes have the same color. The first step is to let
12573 $y_0$ be the initial $y$~coordinate of the first pen stroke. Then we implicitly
12574 project all the pen stroke paths onto the line $y=y_0$ and require that there
12575 be no retracing. If the resulting paths cover a range of $x$~coordinates of
12576 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
12577 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
12578
12579 @c
12580 static mp_edge_header_node mp_make_dashes (MP mp, mp_edge_header_node h) { /* returns |h| or |NULL| */
12581 mp_node p; /* this scans the stroked nodes in the object list */
12582 mp_node p0; /* if not |NULL| this points to the first stroked node */
12583 mp_knot pp, qq, rr; /* pointers into |mp_path_p(p)| */
12584 mp_dash_node d, dd; /* pointers used to create the dash list */
12585 mp_number y0;
12586 @<Other local variables in |make_dashes|@>;
12587 if (dash_list (h) != mp->null_dash)
12588 return h;
12589 new_number (y0); /* the initial $y$ coordinate */
12590 p0 = NULL;
12591 p = mp_link (edge_list (h));
12592 while (p != NULL) {
12593 if (mp_type (p) != mp_stroked_node_type) {
12594 @<Complain that the edge structure contains a node of the wrong type
12595 and |goto not_found|@>;
12596 }
12597 pp = mp_path_p ((mp_stroked_node) p);
12598 if (p0 == NULL) {
12599 p0 = p;
12600 number_clone(y0, pp->y_coord);
12601 }
12602 @<Make |d| point to a new dash node created from stroke |p| and path |pp|
12603 or |goto not_found| if there is an error@>;
12604 @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
12605 p = mp_link (p);
12606 }
12607 if (dash_list (h) == mp->null_dash)
12608 goto NOT_FOUND; /* No error message */
12609 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
12610 @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
12611 free_number (y0);
12612 return h;
12613 NOT_FOUND:
12614 free_number (y0);
12615 @<Flush the dash list, recycle |h| and return |NULL|@>;
12616 }
12617
12618
12619 @ @<Complain that the edge structure contains a node of the wrong type...@>=
12620 {
12621 const char *hlp[] = {
12622 "When you say `dashed p', picture p should not contain any",
12623 "text, filled regions, or clipping paths. This time it did",
12624 "so I'll just make it a solid line instead.",
12625 NULL };
12626 mp_back_error (mp, "Picture is too complicated to use as a dash pattern", hlp, true);
12627 mp_get_x_next (mp);
12628 goto NOT_FOUND;
12629 }
12630
12631
12632 @ A similar error occurs when monotonicity fails.
12633
12634 @<Declarations@>=
12635 static void mp_x_retrace_error (MP mp);
12636
12637 @ @c
12638 void mp_x_retrace_error (MP mp) {
12639 const char *hlp[] = {
12640 "When you say `dashed p', every path in p should be monotone",
12641 "in x and there must be no overlapping. This failed",
12642 "so I'll just make it a solid line instead.",
12643 NULL };
12644 mp_back_error (mp, "Picture is too complicated to use as a dash pattern", hlp, true);
12645 mp_get_x_next (mp);
12646 }
12647
12648
12649 @ We stash |p| in |dash_info(d)| if |mp_dash_p(p)<>0| so that subsequent processing can
12650 handle the case where the pen stroke |p| is itself dashed.
12651
12652 @d dash_info(A) ((mp_dash_node)(A))->dash_info_ /* in an edge header this points to the first dash node */
12653
12654 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
12655 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
12656 an error@>;
12657 rr = pp;
12658 if (mp_next_knot (pp) != pp) {
12659 do {
12660 qq = rr;
12661 rr = mp_next_knot (rr);
12662 @<Check for retracing between knots |qq| and |rr| and |goto not_found|
12663 if there is a problem@>;
12664 } while (mp_right_type (rr) != mp_endpoint);
12665 }
12666 d = (mp_dash_node)mp_get_dash_node (mp);
12667 if (mp_dash_p (p) == NULL)
12668 dash_info (d) = NULL;
12669 else
12670 dash_info (d) = p;
12671 if (number_less (pp->x_coord, rr->x_coord)) {
12672 number_clone(d->start_x, pp->x_coord);
12673 number_clone(d->stop_x, rr->x_coord);
12674 } else {
12675 number_clone(d->start_x, rr->x_coord);
12676 number_clone(d->stop_x, pp->x_coord);
12677 }
12678
12679
12680 @ We also need to check for the case where the segment from |qq| to |rr| is
12681 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
12682
12683 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
12684 {
12685 mp_number x0, x1, x2, x3; /* $x$ coordinates of the segment from |qq| to |rr| */
12686 new_number(x0);
12687 new_number(x1);
12688 new_number(x2);
12689 new_number(x3);
12690 number_clone(x0, qq->x_coord);
12691 number_clone(x1, qq->right_x);
12692 number_clone(x2, rr->left_x);
12693 number_clone(x3, rr->x_coord);
12694 if (number_greater(x0, x1) || number_greater(x1, x2) || number_greater(x2, x3)) {
12695 if (number_less(x0, x1) || number_less(x1, x2) || number_less(x2, x3)) {
12696 mp_number a1, a2, a3, a4;
12697 mp_number test;
12698 new_number(test);
12699 new_number(a1);
12700 new_number(a2);
12701 new_number(a3);
12702 new_number(a4);
12703 set_number_from_substraction(a1, x2, x1);
12704 set_number_from_substraction(a2, x2, x1);
12705 set_number_from_substraction(a3, x1, x0);
12706 set_number_from_substraction(a4, x3, x2);
12707 ab_vs_cd (test, a1, a2, a3, a4);
12708 free_number(a1);
12709 free_number(a2);
12710 free_number(a3);
12711 free_number(a4);
12712 if (number_positive(test)) {
12713 mp_x_retrace_error (mp);
12714 free_number(x0);
12715 free_number(x1);
12716 free_number(x2);
12717 free_number(x3);
12718 free_number(test);
12719 goto NOT_FOUND;
12720 }
12721 free_number(test);
12722 }
12723 }
12724 if (number_greater(pp->x_coord, x0) || number_greater(x0, x3)) {
12725 if (number_less (pp->x_coord, x0) || number_less(x0, x3)) {
12726 mp_x_retrace_error (mp);
12727 free_number(x0);
12728 free_number(x1);
12729 free_number(x2);
12730 free_number(x3);
12731 goto NOT_FOUND;
12732 }
12733 }
12734 free_number(x0);
12735 free_number(x1);
12736 free_number(x2);
12737 free_number(x3);
12738 }
12739
12740 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
12741 if (!number_equal(((mp_stroked_node)p)->red, ((mp_stroked_node)p0)->red) ||
12742 !number_equal(((mp_stroked_node)p)->black, ((mp_stroked_node)p0)->black) ||
12743 !number_equal(((mp_stroked_node)p)->green, ((mp_stroked_node)p0)->green) ||
12744 !number_equal(((mp_stroked_node)p)->blue, ((mp_stroked_node)p0)->blue)
12745 ) {
12746 const char *hlp[] = {
12747 "When you say `dashed p', everything in picture p should",
12748 "be the same color. I can\'t handle your color changes",
12749 "so I'll just make it a solid line instead.",
12750 NULL };
12751 mp_back_error (mp, "Picture is too complicated to use as a dash pattern", hlp, true);
12752 mp_get_x_next (mp);
12753 goto NOT_FOUND;
12754 }
12755
12756 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
12757 number_clone(mp->null_dash->start_x, d->stop_x);
12758 dd = (mp_dash_node)h; /* this makes |mp_link(dd)=dash_list(h)| */
12759 while (number_less(((mp_dash_node)mp_link (dd))->start_x, d->stop_x ))
12760 dd = (mp_dash_node)mp_link (dd);
12761 if (dd != (mp_dash_node)h) {
12762 if (number_greater(dd->stop_x, d->start_x)) {
12763 mp_x_retrace_error (mp);
12764 goto NOT_FOUND;
12765 }
12766 }
12767 mp_link (d) = mp_link (dd);
12768 mp_link (dd) = (mp_node)d@;
12769
12770 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
12771 d = dash_list (h);
12772 while ((mp_link (d) != (mp_node)mp->null_dash))
12773 d = (mp_dash_node)mp_link (d);
12774 dd = dash_list (h);
12775 set_number_from_substraction(h->dash_y, d->stop_x, dd->start_x);
12776 {
12777 mp_number absval;
12778 new_number (absval);
12779 number_clone (absval, y0);
12780 number_abs (absval);
12781 if (number_greater (absval, h->dash_y) ) {
12782 number_clone(h->dash_y, absval);
12783 } else if (d != dd) {
12784 set_dash_list (h, mp_link (dd));
12785 set_number_from_addition(d->stop_x, dd->stop_x, h->dash_y);
12786 mp_free_node (mp, (mp_node)dd, dash_node_size);
12787 }
12788 free_number (absval);
12789 }
12790 @ We get here when the argument is a NULL picture or when there is an error.
12791 Recovering from an error involves making |dash_list(h)| empty to indicate
12792 that |h| is not known to be a valid dash pattern. We also dereference |h|
12793 since it is not being used for the return value.
12794
12795 @<Flush the dash list, recycle |h| and return |NULL|@>=
12796 mp_flush_dash_list (mp, h);
12797 delete_edge_ref (h);
12798 return NULL@;
12799
12800 @ Having carefully saved the dashed stroked nodes in the
12801 corresponding dash nodes, we must be prepared to break up these dashes into
12802 smaller dashes.
12803
12804 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
12805 {
12806 mp_number hsf; /* the dash pattern from |hh| gets scaled by this */
12807 new_number (hsf);
12808 d = (mp_dash_node)h; /* now |mp_link(d)=dash_list(h)| */
12809 while (mp_link (d) != (mp_node)mp->null_dash) {
12810 ds = dash_info (mp_link (d));
12811 if (ds == NULL) {
12812 d = (mp_dash_node)mp_link (d);
12813 } else {
12814 hh = (mp_edge_header_node)mp_dash_p (ds);
12815 number_clone(hsf, ((mp_stroked_node)ds)->dash_scale);
12816 if (hh == NULL)
12817 mp_confusion (mp, "dash1");
12818 @:this can't happen dash0}{\quad dash1@>
12819 assert(hh);
12820 /* clang: dereference null pointer 'hh' */
12821 if (number_zero(((mp_dash_node)hh)->dash_y )) {
12822 d = (mp_dash_node)mp_link (d);
12823 } else {
12824 if (dash_list (hh) == NULL)
12825 mp_confusion (mp, "dash1");
12826 @:this can't happen dash0}{\quad dash1@>
12827 @<Replace |mp_link(d)| by a dashed version as determined by edge header
12828 |hh| and scale factor |ds|@>;
12829 }
12830 }
12831 }
12832 free_number (hsf);
12833 }
12834
12835 @ @<Other local variables in |make_dashes|@>=
12836 mp_dash_node dln; /* |mp_link(d)| */
12837 mp_edge_header_node hh; /* an edge header that tells how to break up |dln| */
12838 mp_node ds; /* the stroked node from which |hh| and |hsf| are derived */
12839
12840 @ @<Replace |mp_link(d)| by a dashed version as determined by edge header...@>=
12841 {
12842 mp_number xoff; /* added to $x$ values in |dash_list(hh)| to match |dln| */
12843 mp_number dashoff;
12844 mp_number r1, r2;
12845 new_number (r1);
12846 new_number (r2);
12847 dln = (mp_dash_node)mp_link (d);
12848 dd = dash_list (hh);
12849 /* clang: dereference null pointer 'dd' */ assert(dd);
12850 new_number (xoff);
12851 new_number (dashoff);
12852 mp_dash_offset (mp, &dashoff, (mp_dash_node)hh);
12853 take_scaled (r1, hsf, dd->start_x);
12854 take_scaled (r2, hsf, dashoff);
12855 number_add (r1, r2);
12856 set_number_from_substraction(xoff, dln->start_x, r1);
12857 free_number (dashoff);
12858 take_scaled (r1, hsf, dd->start_x);
12859 take_scaled (r2, hsf, hh->dash_y);
12860 set_number_from_addition(mp->null_dash->start_x, r1, r2);
12861 number_clone(mp->null_dash->stop_x, mp->null_dash->start_x);
12862 @<Advance |dd| until finding the first dash that overlaps |dln| when
12863 offset by |xoff|@>;
12864 while (number_lessequal(dln->start_x, dln->stop_x)) {
12865 @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
12866 @<Insert a dash between |d| and |dln| for the overlap with the offset version
12867 of |dd|@>;
12868 dd = (mp_dash_node)mp_link (dd);
12869 take_scaled (r1, hsf, dd->start_x);
12870 set_number_from_addition(dln->start_x , xoff, r1);
12871 }
12872 free_number(xoff);
12873 free_number (r1);
12874 free_number (r2);
12875 mp_link (d) = mp_link (dln);
12876 mp_free_node (mp, (mp_node)dln, dash_node_size);
12877 }
12878
12879
12880 @ The name of this module is a bit of a lie because we just find the
12881 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
12882 overlap possible. It could be that the unoffset version of dash |dln| falls
12883 in the gap between |dd| and its predecessor.
12884
12885 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
12886 {
12887 mp_number r1;
12888 new_number (r1);
12889 take_scaled (r1, hsf, dd->stop_x);
12890 number_add (r1, xoff);
12891 while (number_less(r1, dln->start_x)) {
12892 dd = (mp_dash_node)mp_link (dd);
12893 take_scaled (r1, hsf, dd->stop_x);
12894 number_add (r1, xoff);
12895 }
12896 free_number (r1);
12897 }
12898
12899 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
12900 if (dd == mp->null_dash) {
12901 mp_number ret;
12902 new_number (ret);
12903 dd = dash_list (hh);
12904 take_scaled (ret, hsf, hh->dash_y);
12905 number_add(xoff, ret);
12906 free_number (ret);
12907 }
12908
12909 @ At this point we already know that |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
12910
12911 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
12912 {
12913 mp_number r1;
12914 new_number (r1);
12915 take_scaled (r1, hsf, dd->start_x);
12916 number_add (r1, xoff);
12917 if (number_lessequal(r1, dln->stop_x)) {
12918 mp_link (d) = (mp_node)mp_get_dash_node (mp);
12919 d = (mp_dash_node)mp_link (d);
12920 mp_link (d) = (mp_node)dln;
12921 take_scaled (r1, hsf, dd->start_x );
12922 number_add (r1, xoff);
12923 if (number_greater(dln->start_x, r1))
12924 number_clone(d->start_x, dln->start_x);
12925 else
12926 number_clone(d->start_x, r1);
12927 take_scaled (r1, hsf, dd->stop_x);
12928 number_add (r1, xoff);
12929 if (number_less(dln->stop_x, r1))
12930 number_clone(d->stop_x, dln->stop_x );
12931 else
12932 number_clone(d->stop_x, r1);
12933 }
12934 free_number (r1);
12935 }
12936
12937 @ The next major task is to update the bounding box information in an edge
12938 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
12939 header's bounding box to accommodate the box computed by |path_bbox| or
12940 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
12941 |maxy|.)
12942
12943 @c
12944 static void mp_adjust_bbox (MP mp, mp_edge_header_node h) {
12945 if (number_less (mp_minx, h->minx))
12946 number_clone(h->minx, mp_minx);
12947 if (number_less (mp_miny, h->miny))
12948 number_clone(h->miny, mp_miny);
12949 if (number_greater (mp_maxx, h->maxx))
12950 number_clone(h->maxx, mp_maxx);
12951 if (number_greater (mp_maxy, h->maxy))
12952 number_clone(h->maxy, mp_maxy);
12953 }
12954
12955
12956 @ Here is a special routine for updating the bounding box information in
12957 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
12958 that is to be stroked with the pen~|pp|.
12959
12960 @c
12961 static void mp_box_ends (MP mp, mp_knot p, mp_knot pp, mp_edge_header_node h) {
12962 mp_knot q; /* a knot node adjacent to knot |p| */
12963 mp_fraction dx, dy; /* a unit vector in the direction out of the path at~|p| */
12964 mp_number d; /* a factor for adjusting the length of |(dx,dy)| */
12965 mp_number z; /* a coordinate being tested against the bounding box */
12966 mp_number xx, yy; /* the extreme pen vertex in the |(dx,dy)| direction */
12967 integer i; /* a loop counter */
12968 new_fraction(dx);
12969 new_fraction(dy);
12970 new_number(xx);
12971 new_number(yy);
12972 new_number(z);
12973 new_number(d);
12974 if (mp_right_type (p) != mp_endpoint) {
12975 q = mp_next_knot (p);
12976 while (1) {
12977 @<Make |(dx,dy)| the final direction for the path segment from
12978 |q| to~|p|; set~|d|@>;
12979 pyth_add (d, dx, dy);
12980 if (number_positive(d)) {
12981 @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
12982 for (i = 1; i <= 2; i++) {
12983 @<Use |(dx,dy)| to generate a vertex of the square end cap and
12984 update the bounding box to accommodate it@>;
12985 number_negate(dx);
12986 number_negate(dy);
12987 }
12988 }
12989 if (mp_right_type (p) == mp_endpoint) {
12990 goto DONE;
12991 } else
12992 @<Advance |p| to the end of the path and make |q| the previous knot@>@;
12993 }
12994 }
12995 DONE:
12996 free_number (dx);
12997 free_number (dy);
12998 free_number (xx);
12999 free_number (yy);
13000 free_number (z);
13001 free_number (d);
13002 }
13003
13004
13005 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
13006 if (q == mp_next_knot (p)) {
13007 set_number_from_substraction(dx, p->x_coord, p->right_x);
13008 set_number_from_substraction(dy, p->y_coord, p->right_y);
13009 if (number_zero(dx) && number_zero(dy)) {
13010 set_number_from_substraction(dx, p->x_coord, q->left_x);
13011 set_number_from_substraction(dy, p->y_coord, q->left_y);
13012 }
13013 } else {
13014 set_number_from_substraction(dx, p->x_coord, p->left_x);
13015 set_number_from_substraction(dy, p->y_coord, p->left_y);
13016 if (number_zero(dx) && number_zero(dy)) {
13017 set_number_from_substraction(dx, p->x_coord, q->right_x);
13018 set_number_from_substraction(dy, p->y_coord, q->right_y);
13019 }
13020 }
13021 set_number_from_substraction(dx, p->x_coord, q->x_coord);
13022 set_number_from_substraction(dy, p->y_coord, q->y_coord);
13023
13024
13025 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
13026 {
13027 mp_number arg1, r;
13028 new_fraction (r);
13029 new_number(arg1);
13030 make_fraction (r, dx, d);
13031 number_clone(dx, r);
13032 make_fraction (r, dy, d);
13033 number_clone(dy, r);
13034 free_number (r);
13035 number_clone(arg1, dy);
13036 number_negate(arg1);
13037 mp_find_offset (mp, arg1, dx, pp);
13038 free_number(arg1);
13039 number_clone(xx, mp->cur_x);
13040 number_clone(yy, mp->cur_y);
13041 }
13042
13043 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
13044 {
13045 mp_number r1, r2, arg1;
13046 new_number (arg1);
13047 new_fraction (r1);
13048 new_fraction (r2);
13049 mp_find_offset (mp, dx, dy, pp);
13050 set_number_from_substraction (arg1, xx, mp->cur_x);
13051 take_fraction (r1, arg1, dx);
13052 set_number_from_substraction (arg1, yy, mp->cur_y);
13053 take_fraction (r2, arg1, dy);
13054 set_number_from_addition(d, r1, r2);
13055 if ((number_negative(d) && (i == 1)) || (number_positive(d) && (i == 2)))
13056 mp_confusion (mp, "box_ends");
13057 @:this can't happen box ends}{\quad\\{box\_ends}@>
13058 take_fraction (r1, d, dx);
13059 set_number_from_addition(z, p->x_coord, mp->cur_x);
13060 number_add (z, r1);
13061 if (number_less(z, h->minx))
13062 number_clone(h->minx, z);
13063 if (number_greater(z, h->maxx))
13064 number_clone(h->maxx, z);
13065 take_fraction (r1, d, dy);
13066 set_number_from_addition(z, p->y_coord, mp->cur_y);
13067 number_add (z, r1);
13068 if (number_less(z, h->miny))
13069 number_clone(h->miny, z);
13070 if (number_greater(z, h->maxy))
13071 number_clone(h->maxy, z);
13072 free_number (r1);
13073 free_number (r2);
13074 free_number (arg1);
13075 }
13076
13077 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
13078 do {
13079 q = p;
13080 p = mp_next_knot (p);
13081 } while (mp_right_type (p) != mp_endpoint);
13082
13083 @ The major difficulty in finding the bounding box of an edge structure is the
13084 effect of clipping paths. We treat them conservatively by only clipping to the
13085 clipping path's bounding box, but this still
13086 requires recursive calls to |set_bbox| in order to find the bounding box of
13087 @^recursion@>
13088 the objects to be clipped. Such calls are distinguished by the fact that the
13089 boolean parameter |top_level| is false.
13090
13091 @c
13092 void mp_set_bbox (MP mp, mp_edge_header_node h, boolean top_level) {
13093 mp_node p; /* a graphical object being considered */
13094 integer lev; /* nesting level for |mp_start_bounds_node| nodes */
13095 /* Wipe out any existing bounding box information if |bbtype(h)| is
13096 incompatible with |internal[mp_true_corners]| */
13097 switch (h->bbtype ) {
13098 case no_bounds:
13099 break;
13100 case bounds_set:
13101 if (number_positive(internal_value (mp_true_corners)))
13102 mp_init_bbox (mp, h);
13103 break;
13104 case bounds_unset:
13105 if (number_nonpositive(internal_value (mp_true_corners)))
13106 mp_init_bbox (mp, h);
13107 break;
13108 } /* there are no other cases */
13109
13110 while (mp_link (bblast (h)) != NULL) {
13111 p = mp_link (bblast (h));
13112 bblast (h) = p;
13113 switch (mp_type (p)) {
13114 case mp_stop_clip_node_type:
13115 if (top_level)
13116 mp_confusion (mp, "bbox");
13117 else
13118 return;
13119 @:this can't happen bbox}{\quad bbox@>
13120 break;
13121 @t\4@>@<Other cases for updating the bounding box based on the type of object |p|@>@;
13122 default: /* there are no other valid cases, but please the compiler */
13123 break;
13124 }
13125 }
13126 if (!top_level)
13127 mp_confusion (mp, "bbox");
13128 }
13129
13130
13131 @ @<Declarations@>=
13132 static void mp_set_bbox (MP mp, mp_edge_header_node h, boolean top_level);
13133
13134
13135 @ @<Other cases for updating the bounding box...@>=
13136 case mp_fill_node_type:
13137 mp_path_bbox (mp, mp_path_p ((mp_fill_node) p));
13138 if (mp_pen_p ((mp_fill_node) p) != NULL) {
13139 mp_number x0a, y0a, x1a, y1a;
13140 new_number (x0a);
13141 new_number (y0a);
13142 new_number (x1a);
13143 new_number (y1a);
13144 number_clone (x0a, mp_minx);
13145 number_clone (y0a, mp_miny);
13146 number_clone (x1a, mp_maxx);
13147 number_clone (y1a, mp_maxy);
13148 mp_pen_bbox (mp, mp_pen_p ((mp_fill_node) p));
13149 number_add (mp_minx, x0a);
13150 number_add (mp_miny, y0a);
13151 number_add (mp_maxx, x1a);
13152 number_add (mp_maxy, y1a);
13153 free_number (x0a);
13154 free_number (y0a);
13155 free_number (x1a);
13156 free_number (y1a);
13157 }
13158 mp_adjust_bbox (mp, h);
13159 break;
13160
13161 @ @<Other cases for updating the bounding box...@>=
13162 case mp_start_bounds_node_type:
13163 if (number_positive (internal_value (mp_true_corners))) {
13164 h->bbtype = bounds_unset;
13165 } else {
13166 h->bbtype = bounds_set;
13167 mp_path_bbox (mp, mp_path_p ((mp_start_bounds_node) p));
13168 mp_adjust_bbox (mp, h);
13169 @<Scan to the matching |mp_stop_bounds_node| node and update |p| and
13170 |bblast(h)|@>;
13171 }
13172 break;
13173 case mp_stop_bounds_node_type:
13174 if (number_nonpositive (internal_value (mp_true_corners)))
13175 mp_confusion (mp, "bbox2");
13176 @:this can't happen bbox2}{\quad bbox2@>
13177 break;
13178
13179 @ @<Scan to the matching |mp_stop_bounds_node| node and update |p| and...@>=
13180 lev = 1;
13181 while (lev != 0) {
13182 if (mp_link (p) == NULL)
13183 mp_confusion (mp, "bbox2");
13184 @:this can't happen bbox2}{\quad bbox2@>
13185 /* clang: dereference null pointer */ assert(mp_link(p));
13186 p = mp_link (p);
13187 if (mp_type (p) == mp_start_bounds_node_type)
13188 incr (lev);
13189 else if (mp_type (p) == mp_stop_bounds_node_type)
13190 decr (lev);
13191 }
13192 bblast (h) = p@;
13193
13194 @ It saves a lot of grief here to be slightly conservative and not account for
13195 omitted parts of dashed lines. We also don't worry about the material omitted
13196 when using butt end caps. The basic computation is for round end caps and
13197 |box_ends| augments it for square end caps.
13198
13199 @<Other cases for updating the bounding box...@>=
13200 case mp_stroked_node_type:
13201 mp_path_bbox (mp, mp_path_p ((mp_stroked_node) p));
13202 {
13203 mp_number x0a, y0a, x1a, y1a;
13204 new_number (x0a);
13205 new_number (y0a);
13206 new_number (x1a);
13207 new_number (y1a);
13208 number_clone (x0a, mp_minx);
13209 number_clone (y0a, mp_miny);
13210 number_clone (x1a, mp_maxx);
13211 number_clone (y1a, mp_maxy);
13212 mp_pen_bbox (mp, mp_pen_p ((mp_stroked_node) p));
13213 number_add (mp_minx, x0a);
13214 number_add (mp_miny, y0a);
13215 number_add (mp_maxx, x1a);
13216 number_add (mp_maxy, y1a);
13217 free_number (x0a);
13218 free_number (y0a);
13219 free_number (x1a);
13220 free_number (y1a);
13221 }
13222 mp_adjust_bbox (mp, h);
13223 if ((mp_left_type (mp_path_p ((mp_stroked_node) p)) == mp_endpoint) @|
13224 && (((mp_stroked_node) p)->lcap == 2))
13225 mp_box_ends (mp, mp_path_p ((mp_stroked_node) p),
13226 mp_pen_p ((mp_stroked_node) p), h);
13227 break;
13228
13229 @ The height width and depth information stored in a text node determines a
13230 rectangle that needs to be transformed according to the transformation
13231 parameters stored in the text node.
13232
13233 @<Other cases for updating the bounding box...@>=
13234 case mp_text_node_type:
13235 {
13236 mp_number x0a, y0a, x1a, y1a, arg1;
13237 mp_text_node p0 = (mp_text_node)p;
13238 new_number (x0a);
13239 new_number (x1a);
13240 new_number (y0a);
13241 new_number (y1a);
13242 new_number (arg1);
13243 number_clone (arg1, p0->depth);
13244 number_negate (arg1);
13245 take_scaled (x1a, p0->txx, p0->width);
13246 take_scaled (y0a, p0->txy, arg1);
13247 take_scaled (y1a, p0->txy, p0->height);
13248 number_clone (mp_minx, p0->tx);
13249 number_clone (mp_maxx, mp_minx);
13250 if (number_less(y0a, y1a)) {
13251 number_add (mp_minx, y0a);
13252 number_add (mp_maxx, y1a);
13253 } else {
13254 number_add (mp_minx, y1a);
13255 number_add (mp_maxx, y0a);
13256 }
13257 if (number_negative(x1a))
13258 number_add (mp_minx, x1a);
13259 else
13260 number_add (mp_maxx, x1a);
13261 take_scaled (x1a, p0->tyx, p0->width);
13262 number_clone (arg1, p0->depth);
13263 number_negate (arg1);
13264 take_scaled (y0a, p0->tyy, arg1);
13265 take_scaled (y1a, p0->tyy, p0->height);
13266 number_clone (mp_miny, p0->ty);
13267 number_clone (mp_maxy, mp_miny);
13268 if (number_less (y0a, y1a)) {
13269 number_add (mp_miny, y0a);
13270 number_add (mp_maxy, y1a);
13271 } else {
13272 number_add (mp_miny, y1a);
13273 number_add (mp_maxy, y0a);
13274 }
13275 if (number_negative(x1a))
13276 number_add (mp_miny, x1a);
13277 else
13278 number_add (mp_maxy, x1a);
13279 mp_adjust_bbox (mp, h);
13280 free_number (x0a);
13281 free_number (y0a);
13282 free_number (x1a);
13283 free_number (y1a);
13284 free_number (arg1);
13285 }
13286 break;
13287
13288 @ This case involves a recursive call that advances |bblast(h)| to the node of
13289 type |mp_stop_clip_node| that matches |p|.
13290
13291 @<Other cases for updating the bounding box...@>=
13292 case mp_start_clip_node_type:
13293 {
13294 mp_number sminx, sminy, smaxx, smaxy;
13295 /* for saving the bounding box during recursive calls */
13296 mp_number x0a, y0a, x1a, y1a;
13297 new_number (x0a);
13298 new_number (y0a);
13299 new_number (x1a);
13300 new_number (y1a);
13301 new_number (sminx);
13302 new_number (sminy);
13303 new_number (smaxx);
13304 new_number (smaxy);
13305 mp_path_bbox (mp, mp_path_p ((mp_start_clip_node) p));
13306 number_clone (x0a, mp_minx);
13307 number_clone (y0a, mp_miny);
13308 number_clone (x1a, mp_maxx);
13309 number_clone (y1a, mp_maxy);
13310 number_clone (sminx, h->minx);
13311 number_clone (sminy, h->miny);
13312 number_clone (smaxx, h->maxx);
13313 number_clone (smaxy, h->maxy);
13314 @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
13315 starting at |mp_link(p)|@>;
13316 @<Clip the bounding box in |h| to the rectangle given by |x0a|, |x1a|,
13317 |y0a|, |y1a|@>;
13318 number_clone (mp_minx, sminx);
13319 number_clone (mp_miny, sminy);
13320 number_clone (mp_maxx, smaxx);
13321 number_clone (mp_maxy, smaxy);
13322 mp_adjust_bbox (mp, h);
13323 free_number (sminx);
13324 free_number (sminy);
13325 free_number (smaxx);
13326 free_number (smaxy);
13327 free_number (x0a);
13328 free_number (y0a);
13329 free_number (x1a);
13330 free_number (y1a);
13331 }
13332 break;
13333
13334 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
13335 set_number_to_inf(h->minx);
13336 set_number_to_inf(h->miny);
13337 set_number_to_neg_inf(h->maxx);
13338 set_number_to_neg_inf(h->maxy);
13339 mp_set_bbox (mp, h, false)@;
13340
13341
13342 @ @<Clip the bounding box in |h| to the rectangle given by |x0a|, |x1a|,...@>=
13343 if (number_less(h->minx, x0a))
13344 number_clone(h->minx, x0a);
13345 if (number_less(h->miny, y0a))
13346 number_clone(h->miny, y0a);
13347 if (number_greater(h->maxx, x1a))
13348 number_clone(h->maxx, x1a);
13349 if (number_greater(h->maxy, y1a))
13350 number_clone(h->maxy, y1a);
13351
13352 @* Finding an envelope.
13353 When \MP\ has a path and a polygonal pen, it needs to express the desired
13354 shape in terms of things \ps\ can understand. The present task is to compute
13355 a new path that describes the region to be filled. It is convenient to
13356 define this as a two step process where the first step is determining what
13357 offset to use for each segment of the path.
13358
13359 @ Given a pointer |c| to a cyclic path,
13360 and a pointer~|h| to the first knot of a pen polygon,
13361 the |offset_prep| routine changes the path into cubics that are
13362 associated with particular pen offsets. Thus if the cubic between |p|
13363 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
13364 has offset |l| then |mp_info(q)=zero_off+l-k|. (The constant |zero_off| is added
13365 to because |l-k| could be negative.)
13366
13367 After overwriting the type information with offset differences, we no longer
13368 have a true path so we refer to the knot list returned by |offset_prep| as an
13369 ``envelope spec.''
13370 @^envelope spec@>
13371 Since an envelope spec only determines relative changes in pen offsets,
13372 |offset_prep| sets a global variable |spec_offset| to the relative change from
13373 |h| to the first offset.
13374
13375 @d zero_off 16384 /* added to offset changes to make them positive */
13376
13377 @<Glob...@>=
13378 integer spec_offset; /* number of pen edges between |h| and the initial offset */
13379
13380 @ The next function calculates $1/3 B'(t) = (-p + (3c_1 + (-3c_2 + q)))*t^2 + (2p + (-4c_1 + 2*c_2))t + (-p + c_1)$,
13381 for cubic curve |B(t)| given by |p|,|c1|,|c2|,|q|
13382 and it's used for |t| near 0 and |t| near 1. We use double mode, otherwise we have to
13383 take care of overflow.
13384
13385 @c
13386 static mp_knot mp_offset_prep (MP mp, mp_knot c, mp_knot h) {
13387 int n; /* the number of vertices in the pen polygon */
13388 mp_knot c0, p, q, q0, r, w, ww; /* for list manipulation */
13389 int k_needed; /* amount to be added to |mp_info(p)| when it is computed */
13390 mp_knot w0; /* a pointer to pen offset to use just before |p| */
13391 mp_number dxin, dyin; /* the direction into knot |p| */
13392 integer turn_amt; /* change in pen offsets for the current cubic */
13393 mp_number max_coef; /* used while scaling */
13394 mp_number ss;
13395 @<Other local variables for |offset_prep|@>;
13396 new_number(max_coef);
13397 new_number(dxin);
13398 new_number(dyin);
13399 new_number(dx0);
13400 new_number(dy0);
13401 new_number(x0);
13402 new_number(y0);
13403 new_number(x1);
13404 new_number(y1);
13405 new_number(x2);
13406 new_number(y2);
13407 new_number(du);
13408 new_number(dv);
13409 new_number(dx);
13410 new_number(dy);
13411 new_number(x0a);
13412 new_number(y0a);
13413 new_number(x1a);
13414 new_number(y1a);
13415 new_number(x2a);
13416 new_number(y2a);
13417 new_number(t0);
13418 new_number(t1);
13419 new_number(t2);
13420 new_number(u0);
13421 new_number(u1);
13422 new_number(v0);
13423 new_number(v1);
13424 new_number(dx_m);
13425 new_number(dy_m);
13426 new_number(dxin_m);
13427 new_number(dx_ap);
13428 new_number(dy_ap);
13429 new_number(dxin_ap);
13430 new_number(dyin_ap);
13431 new_number(ueps_ap);
13432 new_fraction (ss);
13433 new_fraction (s);
13434 new_fraction (t);
13435 @<Initialize the pen size~|n|@>@;
13436 @<Initialize the incoming direction and pen offset at |c|@>
13437 p = c;
13438 c0 = c;
13439 k_needed = 0;
13440 #ifdef MPOST_DEBUG_ENVELOPE
13441 dbg_nl;dbg_str(@=--[==[BEGIN]==]@>);dbg_nl;
13442 dbg_str(@=return@>);dbg_nl;
13443 dbg_n(w0->x_coord);
13444 dbg_n(w0->y_coord);
13445 #endif
13446 do {
13447 q = mp_next_knot (p);
13448 #ifdef MPOST_DEBUG_ENVELOPE
13449 dbg_nl;dbg_open_t;dbg_str(@=--[==[begin loop]==]@>);dbg_nl;
13450 dbg_n(p->x_coord);dbg_n(p->y_coord);
13451 dbg_n(p->right_x);dbg_n(p->right_y);
13452 dbg_n(q->left_x);dbg_n(q->left_y);
13453 dbg_n(q->x_coord);dbg_n(q->y_coord);
13454 dbg_n(w0->x_coord);
13455 dbg_n(w0->y_coord);
13456 #endif
13457 @<Split the cubic between |p| and |q|, if necessary, into cubics
13458 associated with single offsets, after which |q| should
13459 point to the end of the final such cubic@>;
13460 #ifdef MPOST_DEBUG_ENVELOPE
13461 dbg_key(@=end Split the cubic between p and q@>);dbg_open_t;dbg_nl;
13462 dbg_n(w->x_coord);dbg_n(w->y_coord);
13463 dbg_n(w0->x_coord);dbg_n(w0->y_coord);
13464 dbg_close_t; dbg_comma;dbg_nl;
13465 #endif
13466 NOT_FOUND:
13467 @<Advance |p| to node |q|, removing any ``dead'' cubics that
13468 might have been introduced by the splitting process@>;
13469 #ifdef MPOST_DEBUG_ENVELOPE
13470 dbg_n(w0->x_coord);dbg_n(w0->y_coord);
13471 dbg_str(@=--[==[end loop]==]@>);dbg_nl; dbg_close_t;dbg_comma;dbg_nl;
13472 #endif
13473 } while (q != c);
13474 #ifdef MPOST_DEBUG_ENVELOPE
13475 dbg_key(@=Fix the offset change@>);dbg_open_t;dbg_nl;
13476 dbg_n(p->x_coord);dbg_n(p->y_coord);
13477 dbg_key_ival(info pre,mp_knot_info(p));dbg_comma;dbg_nl;
13478 dbg_n(c->x_coord);dbg_n(c->y_coord);
13479 dbg_key_ival(info pre,mp_knot_info(c));dbg_close_t;dbg_comma;dbg_nl;
13480 #endif
13481 @<Fix the offset change in |mp_knot_info(c)| and set |c| to the return value of
13482 |offset_prep|@>;
13483 #ifdef MPOST_DEBUG_ENVELOPE
13484 dbg_n(p->x_coord);dbg_n(p->y_coord);
13485 dbg_key_ival(info post,mp_knot_info(p));dbg_comma;dbg_nl;
13486 dbg_n(c->x_coord);dbg_n(c->y_coord);
13487 dbg_key_ival(info post,mp_knot_info(c));
13488 dbg_close_t;
13489 dbg_nl;dbg_str(@=--[==[END]==]@>);dbg_nl;
13490 #endif
13491 free_number (ss);
13492 free_number (s);
13493 free_number (dxin);
13494 free_number (dyin);
13495 free_number (dx0);
13496 free_number (dy0);
13497 free_number (x0);
13498 free_number (y0);
13499 free_number (x1);
13500 free_number (y1);
13501 free_number (x2);
13502 free_number (y2);
13503 free_number (max_coef);
13504 free_number (du);
13505 free_number (dv);
13506 free_number (dx);
13507 free_number (dy);
13508 free_number (x0a);
13509 free_number (y0a);
13510 free_number (x1a);
13511 free_number (y1a);
13512 free_number (x2a);
13513 free_number (y2a);
13514 free_number (t0);
13515 free_number (t1);
13516 free_number (t2);
13517 free_number (u0);
13518 free_number (u1);
13519 free_number (v0);
13520 free_number (v1);
13521 free_number(dx_m);
13522 free_number(dy_m);
13523 free_number(dxin_m);
13524 free_number(dx_ap);
13525 free_number(dy_ap);
13526 free_number(dxin_ap);
13527 free_number(dyin_ap);
13528 free_number(ueps_ap);
13529 free_number (t);
13530 return c;
13531 }
13532
13533
13534 @ We shall want to keep track of where certain knots on the cyclic path
13535 wind up in the envelope spec. It doesn't suffice just to keep pointers to
13536 knot nodes because some nodes are deleted while removing dead cubics. Thus
13537 |offset_prep| updates the following pointers
13538
13539 @<Glob...@>=
13540 mp_knot spec_p1;
13541 mp_knot spec_p2; /* pointers to distinguished knots */
13542
13543 @ @<Set init...@>=
13544 mp->spec_p1 = NULL;
13545 mp->spec_p2 = NULL;
13546
13547 @ @<Initialize the pen size~|n|@>=
13548 n = 0;
13549 p = h;
13550 do {
13551 incr (n);
13552 p = mp_next_knot (p);
13553 } while (p != h);
13554
13555 @ Since the true incoming direction isn't known yet, we just pick a direction
13556 consistent with the pen offset~|h|. If this is wrong, it can be corrected
13557 later.
13558
13559 @<Initialize the incoming direction and pen offset at |c|@>=
13560 {
13561 mp_knot hn = mp_next_knot (h);
13562 mp_knot hp = mp_prev_knot (h);
13563 set_number_from_substraction(dxin, hn->x_coord, hp->x_coord);
13564 set_number_from_substraction(dyin, hn->y_coord, hp->y_coord);
13565 if (number_zero(dxin) && number_zero(dyin)) {
13566 set_number_from_substraction(dxin, hp->y_coord, h->y_coord);
13567 set_number_from_substraction(dyin, h->x_coord, hp->x_coord);
13568 }
13569 }
13570 w0 = h;
13571
13572 @ We must be careful not to remove the only cubic in a cycle.
13573
13574 But we must also be careful for another reason. If the user-supplied
13575 path starts with a set of degenerate cubics, the target node |q| can
13576 be collapsed to the initial node |p| which might be the same as the
13577 initial node |c| of the curve. This would cause the |offset_prep| routine
13578 to bail out too early, causing distress later on. (See for example
13579 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
13580 on Sarovar.)
13581
13582 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
13583 #ifdef MPOST_DEBUG_ENVELOPE
13584 dbg_comment(@=Advance p to node q@>);dbg_nl;
13585 #endif
13586 q0 = q;
13587 do {
13588 r = mp_next_knot (p);
13589 if (number_equal (p->x_coord, p->right_x) &&
13590 number_equal (p->y_coord, p->right_y) && @|
13591 number_equal (p->x_coord, r->left_x) &&
13592 number_equal (p->y_coord, r->left_y) && @|
13593 number_equal (p->x_coord, r->x_coord) &&
13594 number_equal (p->y_coord, r->y_coord) && @|
13595 r != p && r != q)
13596 @<Remove the cubic following |p| and update the data structures
13597 to merge |r| into |p|@>@;
13598 p = r;
13599 } while (p != q);
13600 /* Check if we removed too much */
13601 if ((q != q0) && (q != c || c == c0))
13602 q = mp_next_knot (q)
13603
13604
13605 @ @<Remove the cubic following |p| and update the data structures...@>=
13606 {
13607 #ifdef MPOST_DEBUG_ENVELOPE
13608 dbg_key(@=Remove the cubic following p@>);dbg_open_t;dbg_nl;
13609 dbg_n(p->x_coord);dbg_n(p->y_coord);
13610 dbg_key_ival(pre info(p),mp_knot_info(p)); dbg_close_t;dbg_comma;dbg_nl;
13611 #endif
13612 k_needed = mp_knot_info (p) - zero_off;
13613 if (r == q) {
13614 q = p;
13615 } else {
13616 mp_knot_info (p) = k_needed + mp_knot_info (r);
13617 k_needed = 0;
13618 }
13619 if (r == c) {
13620 mp_knot_info (p) = mp_knot_info (c);
13621 c = p;
13622 }
13623 if (r == mp->spec_p1)
13624 mp->spec_p1 = p;
13625 if (r == mp->spec_p2)
13626 mp->spec_p2 = p;
13627 r = p;
13628 mp_remove_cubic (mp, p);
13629 #ifdef MPOST_DEBUG_ENVELOPE
13630 dbg_key(@=Remove the cubic following p@>);dbg_open_t;dbg_nl;
13631 dbg_n(p->x_coord);dbg_n(p->y_coord);
13632 dbg_key_ival(post info(p),mp_knot_info (p)); dbg_close_t;dbg_comma;dbg_nl;
13633 #endif
13634 }
13635
13636
13637 @ Not setting the |info| field of the newly created knot allows the splitting
13638 routine to work for paths.
13639
13640 @<Declarations@>=
13641 static void mp_split_cubic (MP mp, mp_knot p, mp_number t);
13642
13643 @ @c
13644 void mp_split_cubic (MP mp, mp_knot p, mp_number t) { /* splits the cubic after |p| */
13645 mp_number v; /* an intermediate value */
13646 mp_knot q, r; /* for list manipulation */
13647 q = mp_next_knot (p);
13648 r = mp_new_knot (mp);
13649 mp_next_knot (p) = r;
13650 mp_next_knot (r) = q;
13651 mp_originator (r) = mp_program_code;
13652 mp_left_type (r) = mp_explicit;
13653 mp_right_type (r) = mp_explicit;
13654 new_number(v);
13655 set_number_from_of_the_way (v, t, p->right_x, q->left_x);
13656 set_number_from_of_the_way (p->right_x, t, p->x_coord, p->right_x);
13657 set_number_from_of_the_way (q->left_x, t, q->left_x, q->x_coord);
13658 set_number_from_of_the_way (r->left_x, t, p->right_x, v);
13659 set_number_from_of_the_way (r->right_x, t, v, q->left_x);
13660 set_number_from_of_the_way (r->x_coord, t, r->left_x, r->right_x);
13661 set_number_from_of_the_way (v, t, p->right_y, q->left_y);
13662 set_number_from_of_the_way (p->right_y, t, p->y_coord, p->right_y);
13663 set_number_from_of_the_way (q->left_y, t, q->left_y, q->y_coord);
13664 set_number_from_of_the_way (r->left_y, t, p->right_y, v);
13665 set_number_from_of_the_way (r->right_y, t, v, q->left_y);
13666 set_number_from_of_the_way (r->y_coord, t, r->left_y, r->right_y);
13667 free_number (v);
13668 }
13669
13670
13671 @ This does not set |mp_knot_info(p)| or |mp_right_type(p)|.
13672
13673 @<Declarations@>=
13674 static void mp_remove_cubic (MP mp, mp_knot p);
13675
13676 @ @c
13677 void mp_remove_cubic (MP mp, mp_knot p) { /* removes the dead cubic following~|p| */
13678 mp_knot q; /* the node that disappears */
13679 (void) mp;
13680 q = mp_next_knot (p);
13681 mp_next_knot (p) = mp_next_knot (q);
13682 number_clone (p->right_x, q->right_x);
13683 number_clone (p->right_y, q->right_y);
13684 mp_xfree (q);
13685 }
13686
13687
13688 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
13689 strictly between zero and $180^\circ$. Then we can define $d\preceq d'$ to
13690 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
13691 $k$th pen offset, the $k$th pen edge direction is defined by the formula
13692 $$d_k=(u\k-u_k,\,v\k-v_k).$$
13693 When listed by increasing $k$, these directions occur in counter-clockwise
13694 order so that $d_k\preceq d\k$ for all~$k$.
13695 The goal of |offset_prep| is to find an offset index~|k| to associate with
13696 each cubic, such that the direction $d(t)$ of the cubic satisfies
13697 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
13698 We may have to split a cubic into many pieces before each
13699 piece corresponds to a unique offset.
13700
13701 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
13702 #ifdef MPOST_DEBUG_ENVELOPE
13703 dbg_comment(@=Split the cubic between p and q@>);dbg_nl;
13704 dbg_key(@=Split the cubic@>);dbg_open_t;dbg_nl;
13705 dbg_key_ival(pre info(p),mp_knot_info(p));dbg_comma;
13706 dbg_n(w0->x_coord);dbg_n(w0->y_coord);
13707 #endif
13708 mp_knot_info (p) = zero_off + k_needed;
13709 #ifdef MPOST_DEBUG_ENVELOPE
13710 dbg_key_ival(post info(p),mp_knot_info(p));dbg_close_t;dbg_comma; dbg_nl;
13711 #endif
13712 k_needed = 0;
13713 @<Prepare for derivative computations;
13714 |goto not_found| if the current cubic is dead@>;
13715 @<Find the initial direction |(dx,dy)|@>
13716 @<Update |mp_knot_info(p)| and find the offset $w_k$ such that
13717 $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
13718 the direction change at |p|@>;
13719 @<Find the final direction |(dxin,dyin)|@>
13720 @<Decide on the net change in pen offsets and set |turn_amt|@>
13721 @<Complete the offset splitting process@>
13722 w0 = mp_pen_walk (mp, w0, turn_amt)@;
13723
13724
13725 @ @<Declarations@>=
13726 static mp_knot mp_pen_walk (MP mp, mp_knot w, integer k);
13727
13728 @ @c
13729 mp_knot mp_pen_walk (MP mp, mp_knot w, integer k) {
13730 /* walk |k| steps around a pen from |w| */
13731 (void) mp;
13732 while (k > 0) {
13733 w = mp_next_knot (w);
13734 decr (k);
13735 }
13736 while (k < 0) {
13737 w = mp_prev_knot (w);
13738 incr (k);
13739 }
13740 return w;
13741 }
13742
13743
13744 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
13745 calculated from the quadratic polynomials
13746 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
13747 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
13748 Since we may be calculating directions from several cubics
13749 split from the current one, it is desirable to do these calculations
13750 without losing too much precision. ``Scaled up'' values of the
13751 derivatives, which will be less tainted by accumulated errors than
13752 derivatives found from the cubics themselves, are maintained in
13753 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
13754 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
13755 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)$.
13756
13757 @<Other local variables for |offset_prep|@>=
13758 mp_number x0, x1, x2, y0, y1, y2; /* representatives of derivatives */
13759 mp_number t0, t1, t2; /* coefficients of polynomial for slope testing */
13760 mp_number du, dv, dx, dy; /* for directions of the pen and the curve */
13761 mp_number dx0, dy0; /* initial direction for the first cubic in the curve */
13762 mp_number x0a, x1a, x2a, y0a, y1a, y2a; /* intermediate values */
13763 mp_number t; /* where the derivative passes through zero */
13764 mp_number s; /* a temporary value */
13765 mp_number dx_m; /* signal a pertubation of dx */
13766 mp_number dy_m; /* signal a pertubation of dx */
13767 mp_number dxin_m; /* signal a pertubation of dxin */
13768
13769
13770 @ @<Prepare for derivative computations...@>=
13771 set_number_from_substraction(x0, p->right_x, p->x_coord);
13772 set_number_from_substraction(x2, q->x_coord, q->left_x);
13773 set_number_from_substraction(x1, q->left_x, p->right_x);
13774 set_number_from_substraction(y0, p->right_y, p->y_coord);
13775 set_number_from_substraction(y2, q->y_coord, q->left_y);
13776 set_number_from_substraction(y1, q->left_y, p->right_y);
13777 #ifdef MPOST_DEBUG_ENVELOPE
13778 dbg_key(@=Prepare for derivative computations@>);dbg_open_t;dbg_nl;
13779 dbg_n(x0);dbg_n(y0);dbg_n(x1);dbg_n(y1);dbg_n(x2);dbg_n(y2);
13780 dbg_close_t;dbg_comma;dbg_nl;
13781 #endif
13782 {
13783 mp_number absval;
13784 new_number (absval);
13785 number_clone(absval, x1);
13786 number_abs(absval);
13787 number_clone(max_coef, x0);
13788 number_abs (max_coef);
13789 if (number_greater(absval, max_coef)) {
13790 number_clone(max_coef, absval);
13791 }
13792 number_clone(absval, x2);
13793 number_abs(absval);
13794 if (number_greater(absval, max_coef)) {
13795 number_clone(max_coef, absval);
13796 }
13797 number_clone(absval, y0);
13798 number_abs(absval);
13799 if (number_greater(absval, max_coef)) {
13800 number_clone(max_coef, absval);
13801 }
13802 number_clone(absval, y1);
13803 number_abs(absval);
13804 if (number_greater(absval, max_coef)) {
13805 number_clone(max_coef, absval);
13806 }
13807 number_clone(absval, y2);
13808 number_abs(absval);
13809 if (number_greater(absval, max_coef)) {
13810 number_clone(max_coef, absval);
13811 }
13812 if (number_zero(max_coef)) {
13813 goto NOT_FOUND;
13814 }
13815 free_number (absval);
13816 }
13817 while (number_less(max_coef, fraction_half_t)) {
13818 number_double (max_coef);
13819 number_double (x0);
13820 number_double (x1);
13821 number_double (x2);
13822 number_double (y0);
13823 number_double (y1);
13824 number_double (y2);
13825 }
13826
13827
13828 @ Let us first solve a special case of the problem: Suppose we
13829 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
13830 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
13831 $d(0)\succ d_{k-1}$.
13832 Then, in a sense, we're halfway done, since one of the two relations
13833 in $(*)$ is satisfied, and the other couldn't be satisfied for
13834 any other value of~|k|.
13835
13836 Actually, the conditions can be relaxed somewhat since a relation such as
13837 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
13838 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
13839 the origin. The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
13840 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
13841 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
13842 counterclockwise direction.
13843
13844 The |fin_offset_prep| subroutine solves the stated subproblem.
13845 It has a parameter called |rise| that is |1| in
13846 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
13847 the derivative of the cubic following |p|.
13848 The |w| parameter should point to offset~$w_k$ and |mp_info(p)| should already
13849 be set properly. The |turn_amt| parameter gives the absolute value of the
13850 overall net change in pen offsets.
13851
13852 @<Declarations@>=
13853 static void mp_fin_offset_prep (MP mp, mp_knot p, mp_knot w, @|
13854 mp_number x0, mp_number x1, mp_number x2, @|
13855 mp_number y0, mp_number y1, mp_number y2, @|
13856 integer rise, integer turn_amt);
13857
13858 @ @c
13859 void mp_fin_offset_prep (MP mp, mp_knot p, mp_knot w, @|
13860 mp_number x0, mp_number x1, mp_number x2, @|
13861 mp_number y0, mp_number y1, mp_number y2, @|
13862 integer rise, integer turn_amt) {
13863 mp_knot ww; /* for list manipulation */
13864 mp_number du, dv; /* for slope calculation */
13865 mp_number t0, t1, t2; /* test coefficients */
13866 mp_number t; /* place where the derivative passes a critical slope */
13867 mp_number s; /* slope or reciprocal slope */
13868 mp_number v; /* intermediate value for updating |x0..y2| */
13869 mp_knot q; /* original |mp_next_knot(p)| */
13870 q = mp_next_knot (p);
13871 new_number(du);
13872 new_number(dv);
13873 new_number(v);
13874 new_number(t0);
13875 new_number(t1);
13876 new_number(t2);
13877 new_fraction(s);
13878 new_fraction(t);
13879 #ifdef MPOST_DEBUG_ENVELOPE
13880 dbg_key(mp_fin_offset_prep);dbg_open_t;dbg_nl;
13881 #endif
13882 while (1) {
13883 if (rise > 0)
13884 ww = mp_next_knot (w); /* a pointer to $w\k$ */
13885 else
13886 ww = mp_prev_knot (w); /* a pointer to $w_{k-1}$ */
13887 #ifdef MPOST_DEBUG_ENVELOPE
13888 dbg_comment(@=begin iteration@>);
13889 dbg_open_t;dbg_nl;
13890 dbg_n(w->x_coord);dbg_n(w->y_coord);
13891 dbg_n(ww->x_coord);dbg_n(ww->y_coord);
13892 dbg_n(x0);dbg_n(x1);dbg_n(x2);
13893 dbg_n(y0);dbg_n(y1);dbg_n(y2);
13894 dbg_in(rise);
13895 #endif
13896 @<Compute test coefficients |(t0,t1,t2)|
13897 for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
13898 #ifdef MPOST_DEBUG_ENVELOPE
13899 dbg_comment(@=crossing_point@>);
13900 #endif
13901 crossing_point (t, t0, t1, t2);
13902 #ifdef MPOST_DEBUG_ENVELOPE
13903 dbg_n(t);dbg_n(t0);dbg_n(t1);dbg_n(t2);
13904 dbg_in(number_greaterequal(t, fraction_one_t));
13905 dbg_in(turn_amt);
13906 dbg_close_t; dbg_comma;dbg_nl;
13907 #endif
13908 if (number_greaterequal(t, fraction_one_t)) {
13909 if (turn_amt > 0)
13910 number_clone(t, fraction_one_t);
13911 else
13912 goto RETURN;
13913 }
13914 #ifdef MPOST_DEBUG_ENVELOPE
13915 dbg_comment(@=Split the cubic at t, and split off another cubic if the derivative crosses back@>);
13916 #endif
13917 @<Split the cubic at $t$,
13918 and split off another cubic if the derivative crosses back@>;
13919 w = ww;
13920 #ifdef MPOST_DEBUG_ENVELOPE
13921 dbg_comment(@=end iteration@>);
13922 #endif
13923 }
13924 RETURN:
13925 #ifdef MPOST_DEBUG_ENVELOPE
13926 dbg_comment(@=RETURN@>);
13927 dbg_n(t);
13928 #endif
13929 free_number (s);
13930 free_number (t);
13931 free_number (du);
13932 free_number (dv);
13933 free_number (v);
13934 free_number (t0);
13935 free_number (t1);
13936 free_number (t2);
13937 #ifdef MPOST_DEBUG_ENVELOPE
13938 dbg_close_t; dbg_comma;dbg_nl;
13939 #endif
13940 }
13941
13942
13943 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
13944 $-90^\circ$ rotation of the vector from |w| to |ww|. This makes the resulting
13945 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
13946 begins to fail.
13947
13948 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
13949 {
13950 mp_number abs_du, abs_dv;
13951 new_number (abs_du);
13952 new_number (abs_dv);
13953 #ifdef MPOST_DEBUG_ENVELOPE
13954 dbg_key(@=Compute test coefficients (t0,t1,t2) for d(t) versus...@>);dbg_open_t;dbg_nl;
13955 #endif
13956 set_number_from_substraction(du, ww->x_coord, w->x_coord);
13957 set_number_from_substraction(dv, ww->y_coord, w->y_coord);
13958 number_clone(abs_du, du);
13959 number_abs(abs_du);
13960 number_clone(abs_dv, dv);
13961 number_abs(abs_dv);
13962 #ifdef MPOST_DEBUG_ENVELOPE
13963 dbg_CUBIC;
13964 dbg_n(w->x_coord);dbg_n(w->y_coord);
13965 dbg_n(ww->x_coord);dbg_n(ww->y_coord);
13966 dbg_n(x0);dbg_n(x1);dbg_n(x2);
13967 dbg_n(y0);dbg_n(y1);dbg_n(y2);
13968 dbg_n(abs_du);dbg_n(abs_dv);
13969 dbg_n(du);dbg_n(dv);
13970 dbg_in(number_greaterequal(abs_du, abs_dv));
13971 #endif
13972 if (number_greaterequal(abs_du, abs_dv)) {
13973 mp_number r1;
13974 new_fraction (r1);
13975 make_fraction (s, dv, du);
13976 take_fraction (r1, x0, s);
13977 set_number_from_substraction(t0, r1, y0);
13978 take_fraction (r1, x1, s);
13979 set_number_from_substraction(t1, r1, y1);
13980 take_fraction (r1, x2, s);
13981 set_number_from_substraction(t2, r1, y2);
13982 if (number_negative(du)) {
13983 number_negate (t0);
13984 number_negate (t1);
13985 number_negate (t2);
13986 }
13987 free_number (r1);
13988 } else {
13989 mp_number r1;
13990 new_fraction (r1);
13991 make_fraction (s, du, dv);
13992 take_fraction (r1, y0, s);
13993 set_number_from_substraction(t0, x0, r1);
13994 take_fraction (r1, y1, s);
13995 set_number_from_substraction(t1, x1, r1);
13996 take_fraction (r1, y2, s);
13997 set_number_from_substraction(t2, x2, r1);
13998 if (number_negative(dv)) {
13999 number_negate (t0);
14000 number_negate (t1);
14001 number_negate (t2);
14002 }
14003 free_number (r1);
14004 }
14005 free_number (abs_du);
14006 free_number (abs_dv);
14007 if (number_negative(t0))
14008 set_number_to_zero(t0); /* should be positive without rounding error */
14009 #ifdef MPOST_DEBUG_ENVELOPE
14010 dbg_n(t0);dbg_n(t1);dbg_n(t2);
14011 dbg_close_t; dbg_comma;dbg_nl;
14012 #endif
14013 }
14014
14015
14016 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
14017 $(*)$, and it might cross again and return towards $s_{k-1}$ or $s_k$,
14018 respectively, yielding another solution of $(*)$.
14019
14020 @<Split the cubic at $t$, and split off another...@>=
14021 {
14022 mp_split_cubic (mp, p, t);
14023 p = mp_next_knot (p);
14024 mp_knot_info (p) = zero_off + rise;
14025 decr (turn_amt);
14026 set_number_from_of_the_way(v, t, x0, x1);
14027 set_number_from_of_the_way(x1, t, x1, x2);
14028 set_number_from_of_the_way(x0, t, v, x1);
14029 set_number_from_of_the_way(v, t, y0, y1);
14030 set_number_from_of_the_way(y1, t, y1, y2);
14031 set_number_from_of_the_way(y0, t, v, y1);
14032 if (turn_amt < 0) {
14033 mp_number arg1, arg2, arg3;
14034 new_number (arg1);
14035 new_number (arg2);
14036 new_number (arg3);
14037 set_number_from_of_the_way(t1, t, t1, t2);
14038 if (number_positive(t1))
14039 set_number_to_zero(t1); /* without rounding error, |t1| would be |<=0| */
14040 number_clone(arg2, t1);
14041 number_negate(arg2);
14042 number_clone(arg3, t2);
14043 number_negate(arg3);
14044 crossing_point (t, arg1, arg2, arg3); /* arg1 is zero */
14045 free_number (arg1);
14046 free_number (arg2);
14047 free_number (arg3);
14048 if (number_greater(t, fraction_one_t))
14049 number_clone(t, fraction_one_t);
14050 incr (turn_amt);
14051 if (number_equal(t,fraction_one_t) && (mp_next_knot (p) != q)) {
14052 mp_knot_info (mp_next_knot (p)) = mp_knot_info (mp_next_knot (p)) - rise;
14053 } else {
14054 mp_split_cubic (mp, p, t);
14055 mp_knot_info (mp_next_knot (p)) = zero_off - rise;
14056 set_number_from_of_the_way(v, t, x1, x2);
14057 set_number_from_of_the_way(x1, t, x0, x1);
14058 set_number_from_of_the_way(x2, t, x1, v);
14059 set_number_from_of_the_way(v, t, y1, y2);
14060 set_number_from_of_the_way(y1, t, y0, y1);
14061 set_number_from_of_the_way(y2, t, y1, v);
14062 }
14063 }
14064 }
14065
14066
14067 @ Now we must consider the general problem of |offset_prep|, when
14068 nothing is known about a given cubic. We start by finding its
14069 direction in the vicinity of |t=0|.
14070
14071 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
14072 has not yet introduced any more numerical errors. Thus we can compute
14073 the true initial direction for the given cubic, even if it is almost
14074 degenerate.
14075
14076 @<Find the initial direction |(dx,dy)|@>=
14077 #ifdef MPOST_DEBUG_ENVELOPE
14078 dbg_nl;
14079 dbg_comment(@=Find the initial direction (dx,dy)@>);dbg_nl;
14080 dbg_n(w0->x_coord);dbg_n(w0->y_coord);
14081 #endif
14082 number_clone(dx_m, zero_t);
14083 number_clone(dy_m, zero_t);
14084 number_clone(dx, x0);
14085 number_clone(dy, y0);
14086 if (number_zero(dx) && number_zero(dy)) {
14087 number_clone(dx, x1);
14088 number_clone(dy, y1);
14089 if (number_zero(dx) && number_zero(dy)) {
14090 number_clone(dx, x2);
14091 number_clone(dy, y2);
14092 }
14093 }
14094 if (p == c) {
14095 number_clone(dx0, dx);
14096 number_clone(dy0, dy);
14097 }
14098 /* BEGIN PATCH */
14099 #ifdef MPOST_DEBUG_ENVELOPE
14100 dbg_nl;dbg_key(mp_dx_dy_approx_t_1);dbg_open_t;dbg_nl;
14101 dbg_n(ueps_ap);
14102 dbg_n(p->x_coord);dbg_n(p->y_coord);
14103 dbg_n(p->right_x);dbg_n(p->right_y);
14104 dbg_n(q->left_x);dbg_n(q->left_y);
14105 dbg_n(q->x_coord);dbg_n(q->y_coord);
14106 #endif
14107 #ifdef MPOST_DEBUG_ENVELOPE
14108 dbg_n(dxin_ap);dbg_n(dyin_ap);
14109 dbg_close_t;dbg_comma;dbg_nl;
14110 #endif
14111 #ifdef MPOST_DEBUG_ENVELOPE
14112 dbg_nl;dbg_key(mp_dx_dy_approx_t_0);dbg_open_t;dbg_nl;
14113 dbg_n(ueps_ap);
14114 dbg_n(p->x_coord);dbg_n(p->y_coord);
14115 dbg_n(p->right_x);dbg_n(p->right_y);
14116 dbg_n(q->left_x);dbg_n(q->left_y);
14117 dbg_n(q->x_coord);dbg_n(q->y_coord);
14118 #endif
14119 #ifdef MPOST_DEBUG_ENVELOPE
14120 dbg_close_t;dbg_comma;dbg_nl;
14121 dbg_key(@=derivatives@>);dbg_open_t;dbg_nl;
14122 dbg_n(dx_m);dbg_n(dy_m);
14123 dbg_n(dx);dbg_n(dy);dbg_n(dx_ap);dbg_n(dy_ap);dbg_close_t;dbg_comma;dbg_nl;
14124 #endif
14125 #ifdef MPOST_DEBUG_ENVELOPE
14126 dbg_key(@=derivatives after first patch@>);dbg_open_t;dbg_nl;
14127 dbg_n(dx_m);dbg_n(dy_m);
14128 dbg_n(dx);dbg_n(dy);dbg_n(dx_ap);dbg_n(dy_ap);dbg_close_t;dbg_comma;dbg_nl;
14129 #endif
14130 #ifdef MPOST_DEBUG_ENVELOPE
14131 dbg_key(@=derivatives patched@>);dbg_open_t;dbg_nl;
14132 dbg_n(dx_m);dbg_n(dy_m);
14133 dbg_n(dx);dbg_n(dy);dbg_n(dx_ap);dbg_n(dy_ap);dbg_close_t;dbg_comma;dbg_nl;
14134 #endif
14135 /* END PATCH */
14136
14137
14138 @ @<Find the final direction |(dxin,dyin)|@>=
14139 number_clone(dxin, x2);
14140 number_clone(dyin, y2);
14141 if (number_zero(dxin) && number_zero(dyin)) {
14142 number_clone(dxin, x1);
14143 number_clone(dyin, y1);
14144 if (number_zero(dxin) && number_zero(dyin)) {
14145 number_clone(dxin, x0);
14146 number_clone(dyin, y0);
14147 }
14148 }
14149 #ifdef MPOST_DEBUG_ENVELOPE
14150 dbg_key(@=dxin dyin before@>);dbg_open_t;dbg_nl;
14151 dbg_n(dxin);dbg_n(dyin);
14152 dbg_close_t;dbg_comma;
14153 #endif
14154 #ifdef MPOST_DEBUG_ENVELOPE
14155 dbg_key(@=dxin dyin after@>);dbg_open_t;dbg_nl;
14156 dbg_n(dxin);dbg_n(dyin);
14157 dbg_close_t;dbg_comma;
14158 #endif
14159 /* BEGIN PATCH */
14160 #ifdef MPOST_DEBUG_ENVELOPE
14161 dbg_key(@=dx dy dxin dyin after patch@>);dbg_open_t;dbg_nl;
14162 dbg_n(dx);dbg_n(dy);dbg_n(dx_ap);dbg_n(dy_ap);
14163 dbg_n(dxin);dbg_n(dyin);dbg_n(dxin_ap);dbg_n(dyin_ap);
14164 dbg_close_t;dbg_comma;
14165 #endif
14166 /* END PATCH */
14167
14168 @ The next step is to bracket the initial direction between consecutive
14169 edges of the pen polygon. We must be careful to turn clockwise only if
14170 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
14171 counter-clockwise in order to make \&{doublepath} envelopes come out
14172 @:double_path_}{\&{doublepath} primitive@>
14173 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
14174
14175 @<Update |mp_knot_info(p)| and find the offset $w_k$ such that...@>=
14176 {
14177 mp_number ab_vs_cd;
14178 new_number (ab_vs_cd);
14179 ab_vs_cd (ab_vs_cd, dy, dxin, dx, dyin);
14180 #ifdef MPOST_DEBUG_ENVELOPE
14181 dbg_nl;
14182 dbg_comment(@=Update mp_knot_info(p)@>);dbg_nl;
14183 dbg_key(mp_get_turn_amt_dx_dy);dbg_open_t;dbg_str(@=--[==[call mp_get_turn_amt]==]@>);dbg_nl;
14184 dbg_n(w0->x_coord);dbg_n(w0->y_coord);dbg_n(dx);dbg_n(dy);dbg_in(number_nonnegative(ab_vs_cd));
14185 dbg_n(ab_vs_cd);
14186 #endif
14187 is_dxdy=true;
14188 turn_amt = mp_get_turn_amt (mp, w0, dx, dy, number_nonnegative(ab_vs_cd));
14189 is_dxdy=false;
14190 #ifdef MPOST_DEBUG_ENVELOPE
14191 dbg_dn(turn_amt);
14192 dbg_close_t;dbg_comma;
14193 dbg_nl;
14194 #endif
14195 free_number (ab_vs_cd);
14196 #ifdef MPOST_DEBUG_ENVELOPE
14197 dbg_key(@=w0 before walk@>);dbg_open_t;dbg_nl;
14198 dbg_n(w0->x_coord);dbg_n(w0->y_coord);
14199 dbg_dn(turn_amt);
14200 dbg_close_t;dbg_comma;
14201 #endif
14202 w = mp_pen_walk (mp, w0, turn_amt);
14203 w0 = w;
14204 #ifdef MPOST_DEBUG_ENVELOPE
14205 dbg_key(@=w0 after walk@>);dbg_open_t;dbg_nl;
14206 dbg_n(w0->x_coord);dbg_n(w0->y_coord);
14207 dbg_close_t;dbg_comma;
14208 dbg_open_t;dbg_in(mp_knot_info(p));
14209 #endif
14210 mp_knot_info (p) = mp_knot_info (p) + turn_amt;
14211 #ifdef MPOST_DEBUG_ENVELOPE
14212 dbg_in(mp_knot_info(p));dbg_close_t;dbg_comma;
14213 #endif
14214 }
14215
14216 @ Decide how many pen offsets to go away from |w| in order to find the offset
14217 for |(dx,dy)|, going counterclockwise if |ccw| is |true|. This assumes that
14218 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
14219 in the sense determined by |ccw| is less than or equal to $180^\circ$.
14220
14221 If the pen polygon has only two edges, they could both be parallel
14222 to |(dx,dy)|. In this case, we must be careful to stop after crossing the first
14223 such edge in order to avoid an infinite loop.
14224
14225 @<Declarations@>=
14226 static integer mp_get_turn_amt (MP mp, mp_knot w, mp_number dx,
14227 mp_number dy, boolean ccw);
14228
14229 @ @c
14230 integer mp_get_turn_amt (MP mp, mp_knot w, mp_number dx, mp_number dy, boolean ccw) {
14231 mp_knot ww; /* a neighbor of knot~|w| */
14232 integer s; /* turn amount so far */
14233 mp_number t; /* |ab_vs_cd| result */
14234 mp_number t_ap; /* |ab_vs_cd| approx. result */
14235 mp_number arg1, arg2;
14236 s = 0;
14237 new_number (arg1);
14238 new_number (arg2);
14239 new_number (t);
14240 new_number (t_ap);
14241 if (ccw) {
14242 ww = mp_next_knot (w);
14243 do {
14244 set_number_from_substraction (arg1, ww->x_coord, w->x_coord);
14245 set_number_from_substraction (arg2, ww->y_coord, w->y_coord);
14246 ab_vs_cd (t, dy, arg1, dx, arg2);
14247 #ifdef MPOST_DEBUG_ENVELOPE
14248 dbg_sp;
14249 dbg_open_t;dbg_str(@=--[==[inside mp_get_turn_amt do loop]==]@>);dbg_nl;
14250 dbg_n(w->x_coord);dbg_n(w->y_coord);dbg_n(ww->x_coord);dbg_n(ww->y_coord);
14251 dbg_n(t);dbg_n(dy);dbg_n(arg1);dbg_n(dx);dbg_n(arg2);
14252 dbg_n(t_ap);dbg_n(dy_ap);dbg_n(dx_ap);dbg_n(dyin_ap);dbg_n(dxin_ap);
14253 dbg_close_t;dbg_comma;
14254 dbg_in(number_zero(dx) && number_zero(arg1) && number_positive(dy) && number_positive(arg2) && is_dxdy);
14255 dbg_in(is_dxdy && number_zero(dx) && number_zero(arg1) && number_negative(dy) && number_negative(arg2) && number_positive(dyin_ap));
14256 dbg_in(is_dxindyin && number_zero(dx) && number_zero(arg1) && number_positive(dy) && number_positive(arg2) && number_negative(dyin_ap));
14257 dbg_in(number_zero(dy) && number_zero(arg2) && number_negative(dx) && number_negative(arg1));
14258 dbg_in(number_zero(dx) && number_zero(arg1) && number_negative(dy) && number_positive(arg2));
14259 dbg_in(number_zero(dy) && number_zero(arg2) && number_positive(dx) && number_negative(arg1));
14260 dbg_nl;
14261 #endif
14262 if (number_negative(t))
14263 break;
14264 incr (s);
14265 w = ww;
14266 ww = mp_next_knot (ww);
14267 } while (number_positive(t));
14268 } else {
14269 ww = mp_prev_knot (w);
14270 set_number_from_substraction (arg1, w->x_coord, ww->x_coord);
14271 set_number_from_substraction (arg2, w->y_coord, ww->y_coord);
14272 ab_vs_cd (t, dy, arg1, dx, arg2);
14273 #ifdef MPOST_DEBUG_ENVELOPE
14274 dbg_sp;
14275 dbg_open_t;dbg_str(@=--[==[outside mp_get_turn_amt do loop]==]@>);dbg_nl;
14276 dbg_n(w->x_coord);dbg_n(w->y_coord);dbg_n(ww->x_coord);dbg_n(ww->y_coord);
14277 dbg_n(t);dbg_n(dy);dbg_n(arg1);dbg_n(dx);dbg_n(arg2);
14278 dbg_n(t_ap);dbg_n(dy_ap);dbg_n(dx_ap);dbg_n(dyin_ap);dbg_n(dxin_ap);
14279 dbg_close_t;dbg_comma;
14280 dbg_nl;
14281 #endif
14282 while (number_negative(t)) {
14283 decr (s);
14284 w = ww;
14285 ww = mp_prev_knot (ww);
14286 set_number_from_substraction (arg1, w->x_coord, ww->x_coord);
14287 set_number_from_substraction (arg2, w->y_coord, ww->y_coord);
14288 ab_vs_cd (t, dy, arg1, dx, arg2);
14289 #ifdef MPOST_DEBUG_ENVELOPE
14290 dbg_sp;
14291 dbg_open_t;dbg_str(@=--[==[inside mp_get_turn_amt do loop for t<0]==]@>);dbg_nl;
14292 dbg_n(w->x_coord);dbg_n(w->y_coord);dbg_n(ww->x_coord);dbg_n(ww->y_coord);
14293 dbg_n(t);dbg_n(dy);dbg_n(arg1);dbg_n(dx);dbg_n(arg2);
14294 dbg_n(t_ap);dbg_n(dy_ap);dbg_n(dx_ap);
14295 dbg_close_t;dbg_comma;
14296 dbg_nl;
14297 #endif
14298 }
14299 }
14300 free_number (t);
14301 free_number (t_ap);
14302 free_number (arg1);
14303 free_number (arg2);
14304 return s;
14305 }
14306
14307
14308 @ When we're all done, the final offset is |w0| and the final curve direction
14309 is |(dxin,dyin)|. With this knowledge of the incoming direction at |c|, we
14310 can correct |mp_info(c)| which was erroneously based on an incoming offset
14311 of~|h|.
14312
14313 @d fix_by(A) mp_knot_info(c)=mp_knot_info(c)+(A)
14314
14315 @<Fix the offset change in |mp_knot_info(c)| and set |c| to the return value of...@>=
14316 mp->spec_offset = mp_knot_info (c) - zero_off;
14317 if (mp_next_knot (c) == c) {
14318 mp_knot_info (c) = zero_off + n;
14319 } else {
14320 mp_number ab_vs_cd;
14321 new_number (ab_vs_cd);
14322 fix_by (k_needed);
14323 while (w0 != h) {
14324 fix_by (1);
14325 w0 = mp_next_knot (w0);
14326 }
14327 while (mp_knot_info (c) <= zero_off - n)
14328 fix_by (n);
14329 while (mp_knot_info (c) > zero_off)
14330 fix_by (-n);
14331 ab_vs_cd (ab_vs_cd, dy0, dxin, dx0, dyin);
14332 if ((mp_knot_info (c) != zero_off) && number_nonnegative(ab_vs_cd))
14333 fix_by (n);
14334 free_number (ab_vs_cd);
14335 }
14336
14337
14338 @ Finally we want to reduce the general problem to situations that
14339 |fin_offset_prep| can handle. We split the cubic into at most three parts
14340 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
14341
14342 @<Complete the offset splitting process@>=
14343 ww = mp_prev_knot (w);
14344 #ifdef MPOST_DEBUG_ENVELOPE
14345 dbg_key(@=Complete the offset splitting process@>);dbg_open_t;dbg_nl;
14346 dbg_n(w->x_coord);dbg_n(w->y_coord);
14347 dbg_n(ww->x_coord);dbg_n(ww->y_coord);
14348 dbg_close_t; dbg_comma;dbg_nl;
14349 #endif
14350 @<Compute test coeff...@>
14351 #ifdef MPOST_DEBUG_ENVELOPE
14352 dbg_key(@=after Compute test coeff@>);dbg_open_t;dbg_nl;
14353 dbg_n(w->x_coord);dbg_n(w->y_coord);
14354 dbg_n(ww->x_coord);dbg_n(ww->y_coord);
14355 dbg_close_t; dbg_comma;dbg_nl;
14356 #endif
14357 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
14358 |t:=fraction_one+1|@>;
14359 if (number_greater(t, fraction_one_t)) {
14360 #ifdef MPOST_DEBUG_ENVELOPE
14361 dbg_key(@=t > fraction_one_t@>);dbg_open_t;dbg_nl;
14362 dbg_n(p->x_coord);dbg_n(p->y_coord);
14363 dbg_n(w->x_coord);dbg_n(w->y_coord);
14364 dbg_n(x0);dbg_n(x1);dbg_n(x2);
14365 dbg_n(y0);dbg_n(y1);dbg_n(y2);
14366 dbg_close_t; dbg_comma;dbg_nl;
14367 #endif
14368 mp_fin_offset_prep (mp, p, w, x0, x1, x2, y0, y1, y2, 1, turn_amt);
14369 } else {
14370 mp_split_cubic (mp, p, t);
14371 r = mp_next_knot (p);
14372 set_number_from_of_the_way(x1a, t, x0, x1);
14373 set_number_from_of_the_way(x1, t, x1, x2);
14374 set_number_from_of_the_way(x2a, t, x1a, x1);
14375 set_number_from_of_the_way(y1a, t, y0, y1);
14376 set_number_from_of_the_way(y1, t, y1, y2);
14377 set_number_from_of_the_way(y2a, t, y1a, y1);
14378 #ifdef MPOST_DEBUG_ENVELOPE
14379 dbg_key(@=t <= fraction_one_t@>);dbg_open_t;dbg_nl;
14380 dbg_n(p->x_coord);dbg_n(p->y_coord);
14381 dbg_n(t);
14382 dbg_n(r->x_coord);dbg_n(r->y_coord);
14383 dbg_n(w->x_coord);dbg_n(w->y_coord);
14384 dbg_n(x0);dbg_n(x1a);dbg_n(x2a);
14385 dbg_n(y0);dbg_n(y1a);dbg_n(y2a);
14386 dbg_close_t; dbg_comma;dbg_nl;
14387 #endif
14388 mp_fin_offset_prep (mp, p, w, x0, x1a, x2a, y0, y1a, y2a, 1, 0);
14389 number_clone(x0, x2a);
14390 number_clone(y0, y2a);
14391 mp_knot_info (r) = zero_off - 1;
14392 if (turn_amt >= 0) {
14393 mp_number arg1, arg2, arg3;
14394 new_number(arg1);
14395 new_number(arg2);
14396 new_number(arg3);
14397 set_number_from_of_the_way(t1, t, t1, t2);
14398 if (number_positive(t1))
14399 set_number_to_zero(t1);
14400 number_clone(arg2, t1);
14401 number_negate(arg2);
14402 number_clone(arg3, t2);
14403 number_negate(arg3);
14404 crossing_point (t, arg1, arg2, arg3);
14405 free_number (arg1);
14406 free_number (arg2);
14407 free_number (arg3);
14408 if (number_greater(t, fraction_one_t))
14409 number_clone (t, fraction_one_t);
14410 @<Split off another rising cubic for |fin_offset_prep|@>;
14411 mp_fin_offset_prep (mp, r, ww, x0, x1, x2, y0, y1, y2, -1, 0);
14412 } else {
14413 mp_fin_offset_prep (mp, r, ww, x0, x1, x2, y0, y1, y2, -1, (-1 - turn_amt));
14414 }
14415 }
14416 #ifdef MPOST_DEBUG_ENVELOPE
14417 dbg_key(@=end Complete the offset splitting process@>);dbg_open_t;dbg_nl;
14418 dbg_n(w->x_coord);dbg_n(w->y_coord);
14419 dbg_n(w0->x_coord);dbg_n(w0->y_coord);
14420 dbg_in(turn_amt);
14421 dbg_close_t; dbg_comma;dbg_nl;
14422 #endif
14423
14424 @ @<Split off another rising cubic for |fin_offset_prep|@>=
14425 mp_split_cubic (mp, r, t);
14426 mp_knot_info (mp_next_knot (r)) = zero_off + 1;
14427 set_number_from_of_the_way(x1a, t, x1, x2);
14428 set_number_from_of_the_way(x1, t, x0, x1);
14429 set_number_from_of_the_way(x0a, t, x1, x1a);
14430 set_number_from_of_the_way(y1a, t, y1, y2);
14431 set_number_from_of_the_way(y1, t, y0, y1);
14432 set_number_from_of_the_way(y0a, t, y1, y1a);
14433 mp_fin_offset_prep (mp, mp_next_knot (r), w, x0a, x1a, x2, y0a, y1a, y2, 1, turn_amt);
14434 number_clone(x2, x0a);
14435 number_clone(y2, y0a)@;
14436
14437 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
14438 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
14439 need to decide whether the directions are parallel or antiparallel. We
14440 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
14441 should be avoided when the value of |turn_amt| already determines the
14442 answer. If |t2<0|, there is one crossing and it is antiparallel only if
14443 |turn_amt>=0|. If |turn_amt<0|, there should always be at least one
14444 crossing and the first crossing cannot be antiparallel.
14445
14446 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
14447 #ifdef MPOST_DEBUG_ENVELOPE
14448 dbg_key(@=Find the first t where@>);dbg_open_t;dbg_nl;
14449 #endif
14450 crossing_point (t, t0, t1, t2);
14451 if (turn_amt >= 0) {
14452 if (number_negative(t2)) {
14453 number_clone(t, fraction_one_t);
14454 number_add_scaled (t, 1);
14455 } else {
14456 mp_number tmp, arg1, r1;
14457 new_fraction (r1);
14458 new_number(tmp);
14459 new_number(arg1);
14460 set_number_from_of_the_way(u0, t, x0, x1);
14461 set_number_from_of_the_way(u1, t, x1, x2);
14462 set_number_from_of_the_way(tmp, t, u0, u1);
14463 number_clone (arg1, du);
14464 number_negate(arg1);
14465 take_fraction (ss, arg1, tmp);
14466 set_number_from_of_the_way(v0, t, y0, y1);
14467 set_number_from_of_the_way(v1, t, y1, y2);
14468 set_number_from_of_the_way(tmp, t, v0, v1);
14469 number_clone (arg1, dv);
14470 number_negate(arg1);
14471 take_fraction (r1, arg1, tmp);
14472 number_add (ss, r1);
14473 free_number (tmp);
14474 if (number_negative(ss)) {
14475 number_clone(t, fraction_one_t);
14476 number_add_scaled (t, 1);
14477 }
14478 free_number(arg1);
14479 free_number(r1);
14480 }
14481 } else if (number_greater(t, fraction_one_t)) {
14482 number_clone (t, fraction_one_t);
14483 }
14484 #ifdef MPOST_DEBUG_ENVELOPE
14485 dbg_n(t);
14486 dbg_close_t; dbg_comma;dbg_nl;
14487 #endif
14488
14489
14490 @ @<Other local variables for |offset_prep|@>=
14491 mp_number u0, u1, v0, v1; /* intermediate values for $d(t)$ calculation */
14492 int d_sign; /* sign of overall change in direction for this cubic */
14493
14494 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
14495 problem to decide which way it loops around but that's OK as long we're
14496 consistent. To make \&{doublepath} envelopes work properly, reversing
14497 the path should always change the sign of |turn_amt|.
14498
14499 @<Decide on the net change in pen offsets and set |turn_amt|@>=
14500 {
14501 mp_number ab_vs_cd;
14502 mp_number t_ap;
14503 new_number (t_ap);
14504 new_number (ab_vs_cd);
14505 #ifdef MPOST_DEBUG_ENVELOPE
14506 dbg_sp;
14507 dbg_key(@=Decide on the net change in pen offsets and set turn_amt@>);dbg_open_t;dbg_nl;
14508 #endif
14509 ab_vs_cd (ab_vs_cd, dx, dyin, dxin, dy);
14510 #ifdef MPOST_DEBUG_ENVELOPE
14511 dbg_n(ab_vs_cd);dbg_n(dx);dbg_n(dyin);dbg_n(dxin);dbg_n(dy);
14512 #endif
14513 /* BEGIN PATCH */
14514 #ifdef MPOST_DEBUG_ENVELOPE
14515 dbg_key_nval(ab_vs_cd patched,ab_vs_cd);
14516 dbg_close_t;dbg_comma;dbg_nl;
14517 #endif
14518 /* END PATCH */
14519 if (number_negative (ab_vs_cd))
14520 d_sign = -1;
14521 else if (number_zero (ab_vs_cd))
14522 d_sign = 0;
14523 else
14524 d_sign = 1;
14525 free_number (ab_vs_cd);
14526 free_number (t_ap);
14527 }
14528 if (d_sign == 0)
14529 @<Check rotation direction based on node position@>@;
14530 if (d_sign == 0) {
14531 if (number_zero(dx)) {
14532 if (number_positive(dy))
14533 d_sign = 1;
14534 else
14535 d_sign = -1;
14536 } else {
14537 if (number_positive(dx))
14538 d_sign = 1;
14539 else
14540 d_sign = -1;
14541 }
14542 }
14543 @<Make |ss| negative if and only if the total change in direction is
14544 more than $180^\circ$@>;
14545 #ifdef MPOST_DEBUG_ENVELOPE
14546 dbg_nl;
14547 dbg_key(@=Make ss negative if and only if@>); dbg_open_t;dbg_nl;
14548 dbg_key(mp_get_turn_amt_dxin_dyin);dbg_open_t;dbg_str(@=--[==[call mp_get_turn_amt]==]@>);dbg_nl;
14549 dbg_n(w->x_coord);dbg_n(w->y_coord);dbg_n(dxin);dbg_n(dyin);dbg_in((d_sign > 0));
14550 #endif
14551 is_dxindyin=true;
14552 turn_amt = mp_get_turn_amt (mp, w, dxin, dyin, (d_sign > 0));
14553 is_dxindyin=false;
14554 #ifdef MPOST_DEBUG_ENVELOPE
14555 dbg_key_dval(turn_amt 1,turn_amt);dbg_comma;dbg_nl;
14556 dbg_key_nval(ss,ss);dbg_comma;dbg_nl;
14557 dbg_key_ival(d_sign,d_sign);dbg_comma;dbg_nl;
14558 dbg_key_ival(n,n);dbg_comma;dbg_nl;
14559 #endif
14560 if (number_negative(ss))
14561 turn_amt = turn_amt - d_sign * n;
14562 #ifdef MPOST_DEBUG_ENVELOPE
14563 dbg_key_dval(turn_amt 2,turn_amt);dbg_comma;dbg_nl;
14564 dbg_close_t;dbg_comma;dbg_nl;
14565 dbg_close_t;dbg_comma;dbg_nl;
14566 #endif
14567
14568
14569 @ We check rotation direction by looking at the vector connecting the current
14570 node with the next. If its angle with incoming and outgoing tangents has the
14571 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
14572 Otherwise we proceed to the cusp code.
14573
14574 @<Check rotation direction based on node position@>=
14575 {
14576 mp_number ab_vs_cd1, ab_vs_cd2, t;
14577 new_number (ab_vs_cd1);
14578 new_number (ab_vs_cd2);
14579 new_number (t);
14580 set_number_from_substraction(u0, q->x_coord, p->x_coord);
14581 set_number_from_substraction(u1, q->y_coord, p->y_coord);
14582 ab_vs_cd (ab_vs_cd1, dx, u1, u0, dy);
14583 ab_vs_cd (ab_vs_cd2, u0, dyin, dxin, u1);
14584 set_number_from_addition (t, ab_vs_cd1, ab_vs_cd2);
14585 number_half (t);
14586 if (number_negative (t))
14587 d_sign = -1;
14588 else if (number_zero (t))
14589 d_sign = 0;
14590 else
14591 d_sign = 1;
14592 free_number (t);
14593 free_number (ab_vs_cd1);
14594 free_number (ab_vs_cd2);
14595 }
14596
14597 @ In order to be invariant under path reversal, the result of this computation
14598 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
14599 then swapped with |(x2,y2)|. We make use of the identities
14600 |take_fraction(-a,-b)=take_fraction(a,b)| and
14601 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
14602
14603 @<Make |ss| negative if and only if the total change in direction is...@>=
14604 {
14605 mp_number r1, r2, arg1;
14606 new_number (arg1);
14607 new_fraction (r1);
14608 new_fraction (r2);
14609 take_fraction (r1, x0, y2);
14610 take_fraction (r2, x2, y0);
14611 #ifdef MPOST_DEBUG_ENVELOPE
14612 dbg_sp;
14613 dbg_open_t;dbg_dn(d_sign);dbg_close_t;dbg_comma;dbg_nl;
14614 #endif
14615 number_half (r1);
14616 number_half (r2);
14617 set_number_from_substraction(t0, r1, r2);
14618 set_number_from_addition (arg1, y0, y2);
14619 take_fraction (r1, x1, arg1);
14620 set_number_from_addition (arg1, x0, x2);
14621 /*|take_fraction (r1, y1, arg1);|*//* The old one, is it correct ?*/
14622 take_fraction (r2, y1, arg1);
14623 number_half (r1);
14624 number_half (r2);
14625 set_number_from_substraction(t1, r1, r2);
14626 free_number (arg1);
14627 free_number (r1);
14628 free_number (r2);
14629 }
14630 if (number_zero(t0))
14631 set_number_from_scaled(t0, d_sign); /* path reversal always negates |d_sign| */
14632 if (number_positive(t0)) {
14633 mp_number arg3;
14634 new_number(arg3);
14635 number_clone(arg3, t0);
14636 number_negate(arg3);
14637 crossing_point (t, t0, t1, arg3);
14638 free_number (arg3);
14639 set_number_from_of_the_way(u0, t, x0, x1);
14640 set_number_from_of_the_way(u1, t, x1, x2);
14641 set_number_from_of_the_way(v0, t, y0, y1);
14642 set_number_from_of_the_way(v1, t, y1, y2);
14643 } else {
14644 mp_number arg1;
14645 new_number(arg1);
14646 number_clone(arg1, t0);
14647 number_negate(arg1);
14648 crossing_point (t, arg1, t1, t0);
14649 free_number (arg1);
14650 set_number_from_of_the_way(u0, t, x2, x1);
14651 set_number_from_of_the_way(u1, t, x1, x0);
14652 set_number_from_of_the_way(v0, t, y2, y1);
14653 set_number_from_of_the_way(v1, t, y1, y0);
14654 }
14655 {
14656 mp_number tmp1, tmp2, r1, r2, arg1;
14657 mp_number abs_ss, eps_ss;
14658 new_fraction (r1);
14659 new_fraction (r2);
14660 new_number(arg1);
14661 new_number(tmp1);
14662 new_number(tmp2);
14663 set_number_from_of_the_way(tmp1, t, u0, u1);
14664 set_number_from_of_the_way(tmp2, t, v0, v1);
14665 set_number_from_addition(arg1, x0, x2);
14666 take_fraction (r1, arg1, tmp1);
14667 set_number_from_addition(arg1, y0, y2);
14668 take_fraction (r2, arg1, tmp2);
14669 set_number_from_addition (ss, r1, r2);
14670 /* BEGIN PATCH */
14671 #ifdef MPOST_DEBUG_ENVELOPE
14672 dbg_key(@=patch ss before@>);dbg_open_t;
14673 dbg_n(ss);dbg_close_t;dbg_comma;
14674 #endif
14675 #ifdef MPOST_DEBUG_ENVELOPE
14676 dbg_key(@=patch ss after@>);dbg_open_t;
14677 dbg_n(ss);dbg_close_t;dbg_comma;
14678 #endif
14679 free_number(abs_ss);
14680 free_number(eps_ss);
14681 /* END PATCH */
14682 free_number (arg1);
14683 free_number (r1);
14684 free_number (r2);
14685 free_number (tmp1);
14686 free_number (tmp2);
14687 }
14688
14689
14690 @ Here's a routine that prints an envelope spec in symbolic form. It assumes
14691 that the |cur_pen| has not been walked around to the first offset.
14692
14693 @c
14694 static void mp_print_spec (MP mp, mp_knot cur_spec, mp_knot cur_pen,
14695 const char *s) {
14696 mp_knot p, q; /* list traversal */
14697 mp_knot w; /* the current pen offset */
14698 mp_print_diagnostic (mp, "Envelope spec", s, true);
14699 p = cur_spec;
14700 w = mp_pen_walk (mp, cur_pen, mp->spec_offset);
14701 mp_print_ln (mp);
14702 mp_print_two (mp, cur_spec->x_coord, cur_spec->y_coord);
14703 mp_print (mp, " % beginning with offset ");
14704 mp_print_two (mp, w->x_coord, w->y_coord);
14705 do {
14706 while (1) {
14707 q = mp_next_knot (p);
14708 @<Print the cubic between |p| and |q|@>;
14709 p = q;
14710 if ((p == cur_spec) || (mp_knot_info (p) != zero_off))
14711 break;
14712 }
14713 if (mp_knot_info (p) != zero_off)
14714 @<Update |w| as indicated by |mp_knot_info(p)| and print an explanation@>@;
14715 } while (p != cur_spec);
14716 mp_print_nl (mp, " & cycle");
14717 mp_end_diagnostic (mp, true);
14718 }
14719
14720
14721 @ @<Update |w| as indicated by |mp_knot_info(p)| and print an explanation@>=
14722 {
14723 w = mp_pen_walk (mp, w, (mp_knot_info (p) - zero_off));
14724 mp_print (mp, " % ");
14725 #ifdef MPOST_DEBUG_ENVELOPE
14726 dbg_nl;dbg_open_t;dbg_str(@=--[==[START]==]@>);dbg_nl;
14727 dbg_key(@=Printing mp_knot_info (p)@>);dbg_open_t;dbg_nl;
14728 dbg_n(p->x_coord);dbg_n(p->y_coord);
14729 dbg_in(mp_knot_info(p));
14730 dbg_close_t;dbg_close_t;dbg_comma;dbg_nl;
14731 dbg_nl;dbg_str(@=--[==[STOP]==]@>);dbg_nl;
14732 #endif
14733 if (mp_knot_info (p) > zero_off)
14734 mp_print (mp, "counter");
14735 mp_print (mp, "clockwise to offset ");
14736 mp_print_two (mp, w->x_coord, w->y_coord);
14737 }
14738
14739
14740 @ @<Print the cubic between |p| and |q|@>=
14741 {
14742 mp_print_nl (mp, " ..controls ");
14743 mp_print_two (mp, p->right_x, p->right_y);
14744 mp_print (mp, " and ");
14745 mp_print_two (mp, q->left_x, q->left_y);
14746 mp_print_nl (mp, " ..");
14747 mp_print_two (mp, q->x_coord, q->y_coord);
14748 }
14749
14750
14751 @ Once we have an envelope spec, the remaining task to construct the actual
14752 envelope by offsetting each cubic as determined by the |info| fields in
14753 the knots. First we use |offset_prep| to convert the |c| into an envelope
14754 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
14755 the envelope.
14756
14757 The |ljoin| and |miterlim| parameters control the treatment of points where the
14758 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
14759 The endpoints are easily located because |c| is given in undoubled form
14760 and then doubled in this procedure. We use |spec_p1| and |spec_p2| to keep
14761 track of the endpoints and treat them like very sharp corners.
14762 Butt end caps are treated like beveled joins; round end caps are treated like
14763 round joins; and square end caps are achieved by setting |join_type:=3|.
14764
14765 None of these parameters apply to inside joins where the convolution tracing
14766 has retrograde lines. In such cases we use a simple connect-the-endpoints
14767 approach that is achieved by setting |join_type:=2|.
14768
14769 @c
14770 static mp_knot mp_make_envelope (MP mp, mp_knot c, mp_knot h, quarterword ljoin,
14771 quarterword lcap, mp_number miterlim) {
14772 mp_knot p, q, r, q0; /* for manipulating the path */
14773 mp_knot w, w0; /* the pen knot for the current offset */
14774 halfword k, k0; /* controls pen edge insertion */
14775 mp_number qx, qy; /* unshifted coordinates of |q| */
14776 mp_fraction dxin, dyin, dxout, dyout; /* directions at |q| when square or mitered */
14777 int join_type = 0; /* codes |0..3| for mitered, round, beveled, or square */
14778 @<Other local variables for |make_envelope|@>;
14779 new_number (max_ht);
14780 new_number (tmp);
14781 new_fraction(dxin);
14782 new_fraction(dyin);
14783 new_fraction(dxout);
14784 new_fraction(dyout);
14785 mp->spec_p1 = NULL;
14786 mp->spec_p2 = NULL;
14787 new_number(qx);
14788 new_number(qy);
14789 @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
14790 @<Use |offset_prep| to compute the envelope spec then walk |h| around to
14791 the initial offset@>;
14792 w = h;
14793 p = c;
14794 do {
14795 q = mp_next_knot (p);
14796 q0 = q;
14797 number_clone (qx, q->x_coord);
14798 number_clone (qy, q->y_coord);
14799 k = mp_knot_info (q);
14800 k0 = k;
14801 w0 = w;
14802 if (k != zero_off)
14803 @<Set |join_type| to indicate how to handle offset changes at~|q|@>@;
14804 @<Add offset |w| to the cubic from |p| to |q|@>;
14805 while (k != zero_off) {
14806 @<Step |w| and move |k| one step closer to |zero_off|@>;
14807 if ((join_type == 1) || (k == zero_off)) {
14808 mp_number xtot, ytot;
14809 new_number(xtot);
14810 new_number(ytot);
14811 set_number_from_addition (xtot, qx, w->x_coord);
14812 set_number_from_addition (ytot, qy, w->y_coord);
14813 q = mp_insert_knot (mp, q, xtot, ytot);
14814 free_number (xtot);
14815 free_number (ytot);
14816 }
14817 }
14818 if (q != mp_next_knot (p))
14819 @<Set |p=mp_link(p)| and add knots between |p| and |q| as
14820 required by |join_type|@>@;
14821 p = q;
14822 } while (q0 != c);
14823 free_number (max_ht);
14824 free_number (tmp);
14825 free_number (qx);
14826 free_number (qy);
14827 free_number (dxin);
14828 free_number (dyin);
14829 free_number (dxout);
14830 free_number (dyout);
14831 return c;
14832 }
14833
14834
14835 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
14836 c = mp_offset_prep (mp, c, h);
14837 if (number_positive(internal_value (mp_tracing_specs)))
14838 mp_print_spec (mp, c, h, "");
14839 h = mp_pen_walk (mp, h, mp->spec_offset)
14840
14841
14842 @ Mitered and squared-off joins depend on path directions that are difficult to
14843 compute for degenerate cubics. The envelope spec computed by |offset_prep| can
14844 have degenerate cubics only if the entire cycle collapses to a single
14845 degenerate cubic. Setting |join_type:=2| in this case makes the computed
14846 envelope degenerate as well.
14847
14848 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
14849 {
14850 if (k < zero_off) {
14851 join_type = 2;
14852 } else {
14853 if ((q != mp->spec_p1) && (q != mp->spec_p2))
14854 join_type = ljoin;
14855 else if (lcap == 2)
14856 join_type = 3;
14857 else
14858 join_type = 2 - lcap;
14859 if ((join_type == 0) || (join_type == 3)) {
14860 @<Set the incoming and outgoing directions at |q|; in case of
14861 degeneracy set |join_type:=2|@>;
14862 if (join_type == 0)
14863 @<If |miterlim| is less than the secant of half the angle at |q|
14864 then set |join_type:=2|@>@;
14865 }
14866 }
14867 }
14868
14869 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
14870 {
14871 mp_number r1, r2;
14872 new_fraction (r1);
14873 new_fraction (r2);
14874 take_fraction (r1, dxin, dxout);
14875 take_fraction (r2, dyin, dyout);
14876 number_add (r1, r2);
14877 number_half (r1);
14878 number_add (r1, fraction_half_t);
14879 take_fraction (tmp, miterlim, r1);
14880 if (number_less(tmp, unity_t)) {
14881 mp_number ret;
14882 new_number (ret);
14883 take_scaled (ret, miterlim, tmp);
14884 if (number_less(ret, unity_t))
14885 join_type = 2;
14886 free_number (ret);
14887 }
14888 free_number (r1);
14889 free_number (r2);
14890 }
14891
14892
14893 @ @<Other local variables for |make_envelope|@>=
14894 mp_number tmp; /* a temporary value */
14895
14896 @ The coordinates of |p| have already been shifted unless |p| is the first
14897 knot in which case they get shifted at the very end.
14898
14899 @<Add offset |w| to the cubic from |p| to |q|@>=
14900 number_add (p->right_x, w->x_coord);
14901 number_add (p->right_y, w->y_coord);
14902 number_add (q->left_x, w->x_coord);
14903 number_add (q->left_y, w->y_coord);
14904 number_add (q->x_coord, w->x_coord);
14905 number_add (q->y_coord, w->y_coord);
14906 mp_left_type (q) = mp_explicit;
14907 mp_right_type (q) = mp_explicit@;
14908
14909 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
14910 if (k > zero_off) {
14911 w = mp_next_knot (w);
14912 decr (k);
14913 } else {
14914 w = mp_prev_knot (w);
14915 incr (k);
14916 }
14917
14918
14919 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
14920 the |mp_right_x| and |mp_right_y| fields of |r| are set from |q|. This is done in
14921 case the cubic containing these control points is ``yet to be examined.''
14922
14923 @<Declarations@>=
14924 static mp_knot mp_insert_knot (MP mp, mp_knot q, mp_number x, mp_number y);
14925
14926 @ @c
14927 mp_knot mp_insert_knot (MP mp, mp_knot q, mp_number x, mp_number y) {
14928 /* returns the inserted knot */
14929 mp_knot r; /* the new knot */
14930 r = mp_new_knot (mp);
14931 mp_next_knot (r) = mp_next_knot (q);
14932 mp_next_knot (q) = r;
14933 number_clone (r->right_x, q->right_x);
14934 number_clone (r->right_y, q->right_y);
14935 number_clone (r->x_coord, x);
14936 number_clone (r->y_coord, y);
14937 number_clone (q->right_x, q->x_coord);
14938 number_clone (q->right_y, q->y_coord);
14939 number_clone (r->left_x, r->x_coord);
14940 number_clone (r->left_y, r->y_coord);
14941 mp_left_type (r) = mp_explicit;
14942 mp_right_type (r) = mp_explicit;
14943 mp_originator (r) = mp_program_code;
14944 return r;
14945 }
14946
14947
14948 @ After setting |p:=mp_link(p)|, either |join_type=1| or |q=mp_link(p)|.
14949
14950 @<Set |p=mp_link(p)| and add knots between |p| and |q| as...@>=
14951 {
14952 p = mp_next_knot (p);
14953 if ((join_type == 0) || (join_type == 3)) {
14954 if (join_type == 0)
14955 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>@;
14956 else
14957 @<Make |r| the last of two knots inserted between |p| and |q| to form a
14958 squared join@>@;
14959 if (r != NULL) {
14960 number_clone (r->right_x, r->x_coord);
14961 number_clone (r->right_y, r->y_coord);
14962 }
14963 }
14964 }
14965
14966
14967 @ For very small angles, adding a knot is unnecessary and would cause numerical
14968 problems, so we just set |r:=NULL| in that case.
14969
14970 @d near_zero_angle_k ((math_data *)mp->math)->near_zero_angle_t
14971
14972 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
14973 {
14974 mp_number det; /* a determinant used for mitered join calculations */
14975 mp_number absdet;
14976 mp_number r1, r2;
14977 new_fraction (r1);
14978 new_fraction (r2);
14979 new_fraction (det);
14980 new_fraction (absdet);
14981 take_fraction (r1, dyout, dxin);
14982 take_fraction (r2, dxout, dyin);
14983 set_number_from_substraction(det, r1, r2);
14984 number_clone (absdet, det);
14985 number_abs (absdet);
14986 if (number_less (absdet, near_zero_angle_k)) {
14987 r = NULL; /* sine $<10^{-4}$ */
14988 } else {
14989 mp_number xtot, ytot, xsub, ysub;
14990 new_fraction(xsub);
14991 new_fraction(ysub);
14992 new_number(xtot);
14993 new_number(ytot);
14994 set_number_from_substraction (tmp, q->x_coord, p->x_coord);
14995 take_fraction (r1, tmp, dyout);
14996 set_number_from_substraction (tmp, q->y_coord, p->y_coord);
14997 take_fraction (r2, tmp, dxout);
14998 set_number_from_substraction (tmp, r1, r2);
14999 make_fraction (r1, tmp, det);
15000 number_clone (tmp, r1);
15001 take_fraction (xsub, tmp, dxin);
15002 take_fraction (ysub, tmp, dyin);
15003 set_number_from_addition(xtot, p->x_coord, xsub);
15004 set_number_from_addition(ytot, p->y_coord, ysub);
15005 r = mp_insert_knot (mp, p, xtot, ytot);
15006 free_number (xtot);
15007 free_number (ytot);
15008 free_number (xsub);
15009 free_number (ysub);
15010 }
15011 free_number (r1);
15012 free_number (r2);
15013 free_number (det);
15014 free_number (absdet);
15015 }
15016
15017
15018 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
15019 {
15020 mp_number ht_x, ht_y; /* perpendicular to the segment from |p| to |q| */
15021 mp_number ht_x_abs, ht_y_abs; /* absolutes */
15022 mp_number xtot, ytot, xsub, ysub;
15023 new_fraction(xsub);
15024 new_fraction(ysub);
15025 new_number(xtot);
15026 new_number(ytot);
15027 new_fraction (ht_x);
15028 new_fraction (ht_y);
15029 new_fraction (ht_x_abs);
15030 new_fraction (ht_y_abs);
15031 set_number_from_substraction(ht_x, w->y_coord, w0->y_coord);
15032 set_number_from_substraction(ht_y, w0->x_coord, w->x_coord);
15033 number_clone (ht_x_abs, ht_x);
15034 number_clone (ht_y_abs, ht_y);
15035 number_abs (ht_x_abs);
15036 number_abs (ht_y_abs);
15037 while (number_less(ht_x_abs, fraction_half_t) && number_less(ht_y_abs, fraction_half_t)) {
15038 number_double(ht_x);
15039 number_double(ht_y);
15040 number_clone (ht_x_abs, ht_x);
15041 number_clone (ht_y_abs, ht_y);
15042 number_abs (ht_x_abs);
15043 number_abs (ht_y_abs);
15044 }
15045 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
15046 product with |(ht_x,ht_y)|@>;
15047 {
15048 mp_number r1 ,r2;
15049 new_fraction (r1);
15050 new_fraction (r2);
15051 take_fraction (r1, dxin, ht_x);
15052 take_fraction (r2, dyin, ht_y);
15053 number_add (r1, r2);
15054 make_fraction (tmp, max_ht, r1);
15055 free_number (r1);
15056 free_number (r2);
15057 }
15058 take_fraction (xsub, tmp, dxin);
15059 take_fraction (ysub, tmp, dyin);
15060 set_number_from_addition(xtot, p->x_coord, xsub);
15061 set_number_from_addition(ytot, p->y_coord, ysub);
15062 r = mp_insert_knot (mp, p, xtot, ytot);
15063 /* clang: value never read */ assert(r);
15064 {
15065 mp_number r1 ,r2;
15066 new_fraction (r1);
15067 new_fraction (r2);
15068 take_fraction (r1, dxout, ht_x);
15069 take_fraction (r2, dyout, ht_y);
15070 number_add (r1, r2);
15071 make_fraction (tmp, max_ht, r1);
15072 free_number (r1);
15073 free_number (r2);
15074 }
15075 take_fraction (xsub, tmp, dxout);
15076 take_fraction (ysub, tmp, dyout);
15077 set_number_from_addition(xtot, q->x_coord, xsub);
15078 set_number_from_addition(ytot, q->y_coord, ysub);
15079 r = mp_insert_knot (mp, r, xtot, ytot);
15080 free_number (xsub);
15081 free_number (ysub);
15082 free_number (xtot);
15083 free_number (ytot);
15084 free_number (ht_x);
15085 free_number (ht_y);
15086 free_number (ht_x_abs);
15087 free_number (ht_y_abs);
15088 }
15089
15090
15091 @ @<Other local variables for |make_envelope|@>=
15092 mp_number max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
15093 halfword kk; /* keeps track of the pen vertices being scanned */
15094 mp_knot ww; /* the pen vertex being tested */
15095
15096 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
15097 from zero to |max_ht|.
15098
15099 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
15100 set_number_to_zero (max_ht);
15101 kk = zero_off;
15102 ww = w;
15103 while (1) {
15104 @<Step |ww| and move |kk| one step closer to |k0|@>;
15105 if (kk == k0)
15106 break;
15107 {
15108 mp_number r1, r2;
15109 new_fraction (r1);
15110 new_fraction (r2);
15111 set_number_from_substraction (tmp, ww->x_coord, w0->x_coord);
15112 take_fraction (r1, tmp, ht_x);
15113 set_number_from_substraction (tmp, ww->y_coord, w0->y_coord);
15114 take_fraction (r2, tmp, ht_y);
15115 set_number_from_addition (tmp, r1, r2);
15116 free_number (r1);
15117 free_number (r2);
15118 }
15119 if (number_greater(tmp, max_ht))
15120 number_clone(max_ht, tmp);
15121 }
15122
15123
15124 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
15125 if (kk > k0) {
15126 ww = mp_next_knot (ww);
15127 decr (kk);
15128 } else {
15129 ww = mp_prev_knot (ww);
15130 incr (kk);
15131 }
15132
15133
15134 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
15135 if (mp_left_type (c) == mp_endpoint) {
15136 mp->spec_p1 = mp_htap_ypoc (mp, c);
15137 mp->spec_p2 = mp->path_tail;
15138 mp_originator (mp->spec_p1) = mp_program_code;
15139 mp_next_knot (mp->spec_p2) = mp_next_knot (mp->spec_p1);
15140 mp_next_knot (mp->spec_p1) = c;
15141 mp_remove_cubic (mp, mp->spec_p1);
15142 c = mp->spec_p1;
15143 if (c != mp_next_knot (c)) {
15144 mp_originator (mp->spec_p2) = mp_program_code;
15145 mp_remove_cubic (mp, mp->spec_p2);
15146 } else
15147 @<Make |c| look like a cycle of length one@>@;
15148 }
15149
15150 @ @<Make |c| look like a cycle of length one@>=
15151 {
15152 mp_left_type (c) = mp_explicit;
15153 mp_right_type (c) = mp_explicit;
15154 number_clone(c->left_x, c->x_coord);
15155 number_clone(c->left_y, c->y_coord);
15156 number_clone(c->right_x, c->x_coord);
15157 number_clone(c->right_y, c->y_coord);
15158 }
15159
15160
15161 @ In degenerate situations we might have to look at the knot preceding~|q|.
15162 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
15163
15164 @<Set the incoming and outgoing directions at |q|; in case of...@>=
15165 {
15166 set_number_from_substraction(dxin, q->x_coord, q->left_x);
15167 set_number_from_substraction(dyin, q->y_coord, q->left_y);
15168 if (number_zero(dxin) && number_zero(dyin)) {
15169 set_number_from_substraction(dxin, q->x_coord, p->right_x);
15170 set_number_from_substraction(dyin, q->y_coord, p->right_y);
15171 if (number_zero(dxin) && number_zero(dyin)) {
15172 set_number_from_substraction(dxin, q->x_coord, p->x_coord);
15173 set_number_from_substraction(dyin, q->y_coord, p->y_coord);
15174 if (p != c) { /* the coordinates of |p| have been offset by |w| */
15175 number_add(dxin, w->x_coord);
15176 number_add(dyin, w->y_coord);
15177 }
15178 }
15179 }
15180 pyth_add (tmp, dxin, dyin);
15181 if (number_zero(tmp)) {
15182 join_type = 2;
15183 } else {
15184 mp_number r1;
15185 new_fraction (r1);
15186 make_fraction (r1, dxin, tmp);
15187 number_clone(dxin, r1);
15188 make_fraction (r1, dyin, tmp);
15189 number_clone(dyin, r1);
15190 free_number (r1);
15191 @<Set the outgoing direction at |q|@>;
15192 }
15193 }
15194
15195
15196 @ If |q=c| then the coordinates of |r| and the control points between |q|
15197 and~|r| have already been offset by~|h|.
15198
15199 @<Set the outgoing direction at |q|@>=
15200 {
15201 set_number_from_substraction(dxout, q->right_x, q->x_coord);
15202 set_number_from_substraction(dyout, q->right_y, q->y_coord);
15203 if (number_zero(dxout) && number_zero(dyout)) {
15204 r = mp_next_knot (q);
15205 set_number_from_substraction(dxout, r->left_x, q->x_coord);
15206 set_number_from_substraction(dyout, r->left_y, q->y_coord);
15207 if (number_zero(dxout) && number_zero(dyout)) {
15208 set_number_from_substraction(dxout, r->x_coord, q->x_coord);
15209 set_number_from_substraction(dyout, r->y_coord, q->y_coord);
15210 }
15211 }
15212 if (q == c) {
15213 number_substract(dxout, h->x_coord);
15214 number_substract(dyout, h->y_coord);
15215 }
15216 pyth_add (tmp, dxout, dyout);
15217 if (number_zero(tmp)) {
15218 /* |mp_confusion (mp, "degenerate spec");| */
15219 @:this can't happen degenerate spec}{\quad degenerate spec@>
15220 /* But apparently, it actually can happen. The test case is this:
15221
15222 path p;
15223 linejoin := mitered;
15224 p:= (10,0)..(0,10)..(-10,0)..(0,-10)..cycle;
15225 addto currentpicture contour p withpen pensquare;
15226
15227 The reason for failure here is the addition of |r != q| in revision 1757
15228 in ``Advance |p| to node |q|, removing any ``dead'' cubics'', which itself
15229 was needed to fix a bug with disappearing knots in a path that was rotated
15230 exactly 45 degrees (luatex.org bug 530).
15231 */
15232 } else {
15233 mp_number r1;
15234 new_fraction (r1);
15235 make_fraction (r1, dxout, tmp);
15236 number_clone(dxout, r1);
15237 make_fraction (r1, dyout, tmp);
15238 number_clone(dyout, r1);
15239 free_number (r1);
15240 }
15241 }
15242
15243
15244 @* Direction and intersection times.
15245 A path of length $n$ is defined parametrically by functions $x(t)$ and
15246 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
15247 reaches the point $\bigl(x(t),y(t)\bigr)$. In this section of the program
15248 we shall consider operations that determine special times associated with
15249 given paths: the first time that a path travels in a given direction, and
15250 a pair of times at which two paths cross each other.
15251
15252 @ Let's start with the easier task. The function |find_direction_time| is
15253 given a direction |(x,y)| and a path starting at~|h|. If the path never
15254 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
15255 it will be nonnegative.
15256
15257 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
15258 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
15259 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
15260 assumed to match any given direction at time~|t|.
15261
15262 The routine solves this problem in nondegenerate cases by rotating the path
15263 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
15264 to find when a given path first travels ``due east.''
15265
15266 @c
15267 static void mp_find_direction_time (MP mp, mp_number *ret, mp_number x_orig, mp_number y_orig, mp_knot h) {
15268 mp_number max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
15269 mp_knot p, q; /* for list traversal */
15270 mp_number n; /* the direction time at knot |p| */
15271 mp_number tt; /* the direction time within a cubic */
15272 mp_number x, y;
15273 mp_number abs_x, abs_y;
15274 /* Other local variables for |find_direction_time| */
15275 mp_number x1, x2, x3, y1, y2, y3; /* multiples of rotated derivatives */
15276 mp_number phi; /* angles of exit and entry at a knot */
15277 mp_number t; /* temp storage */
15278 mp_number ab_vs_cd;
15279 new_number(max);
15280 new_number(x1);
15281 new_number(x2);
15282 new_number(x3);
15283 new_number(y1);
15284 new_number(y2);
15285 new_number(y3);
15286 new_fraction(t);
15287 new_angle(phi);
15288 new_number (ab_vs_cd);
15289 set_number_to_zero (*ret); /* just in case */
15290 new_number (x);
15291 new_number (y);
15292 new_number (abs_x);
15293 new_number (abs_y);
15294 new_number (n);
15295 new_fraction (tt);
15296 number_clone (x, x_orig);
15297 number_clone (y, y_orig);
15298 number_clone (abs_x, x_orig);
15299 number_clone (abs_y, y_orig);
15300 number_abs (abs_x);
15301 number_abs (abs_y);
15302 /* Normalize the given direction for better accuracy;
15303 but |return| with zero result if it's zero */
15304 if (number_less(abs_x, abs_y)) {
15305 mp_number r1;
15306 new_fraction (r1);
15307 make_fraction (r1, x, abs_y);
15308 number_clone(x, r1);
15309 free_number (r1);
15310 if (number_positive(y)) {
15311 number_clone(y, fraction_one_t);
15312 } else {
15313 number_clone(y, fraction_one_t);
15314 number_negate(y);
15315 }
15316 } else if (number_zero(x)) {
15317 goto FREE;
15318 } else {
15319 mp_number r1;
15320 new_fraction (r1);
15321 make_fraction (r1, y, abs_x);
15322 number_clone(y, r1);
15323 free_number (r1);
15324 if (number_positive(x)) {
15325 number_clone(x, fraction_one_t);
15326 } else {
15327 number_clone(x, fraction_one_t);
15328 number_negate(x);
15329 }
15330 }
15331
15332 p = h;
15333 while (1) {
15334 if (mp_right_type (p) == mp_endpoint)
15335 break;
15336 q = mp_next_knot (p);
15337 @<Rotate the cubic between |p| and |q|; then
15338 |goto found| if the rotated cubic travels due east at some time |tt|;
15339 but |break| if an entire cyclic path has been traversed@>;
15340 p = q;
15341 number_add(n, unity_t);
15342 }
15343 set_number_to_unity (*ret);
15344 number_negate(*ret);
15345 goto FREE;
15346 FOUND:
15347 set_number_from_addition (*ret, n, tt);
15348 goto FREE;
15349 FREE:
15350 free_number (x);
15351 free_number (y);
15352 free_number (abs_x);
15353 free_number (abs_y);
15354 /* Free local variables for |find_direction_time| */
15355 free_number (x1);
15356 free_number (x2);
15357 free_number (x3);
15358 free_number (y1);
15359 free_number (y2);
15360 free_number (y3);
15361 free_number (t);
15362 free_number (phi);
15363 free_number (ab_vs_cd);
15364
15365 free_number (n);
15366 free_number (max);
15367 free_number (tt);
15368 }
15369
15370
15371
15372 @ Since we're interested in the tangent directions, we work with the
15373 derivative $${1\over3}B'(x_0,x_1,x_2,x_3;t)=
15374 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
15375 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scale-d up
15376 in order to achieve better accuracy.
15377
15378 The given path may turn abruptly at a knot, and it might pass the critical
15379 tangent direction at such a time. Therefore we remember the direction |phi|
15380 in which the previous rotated cubic was traveling. (The value of |phi| will be
15381 undefined on the first cubic, i.e., when |n=0|.)
15382
15383 @d we_found_it {
15384 number_clone (tt, t);
15385 fraction_to_round_scaled (tt);
15386 goto FOUND;
15387 }
15388
15389 @<Rotate the cubic between |p| and |q|; then...@>=
15390 set_number_to_zero(tt);
15391 /* Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
15392 points of the rotated derivatives */
15393 {
15394 mp_number absval;
15395 new_number (absval);
15396 set_number_from_substraction(x1, p->right_x, p->x_coord);
15397 set_number_from_substraction(x2, q->left_x, p->right_x);
15398 set_number_from_substraction(x3, q->x_coord, q->left_x);
15399 set_number_from_substraction(y1, p->right_y, p->y_coord);
15400 set_number_from_substraction(y2, q->left_y, p->right_y);
15401 set_number_from_substraction(y3, q->y_coord, q->left_y);
15402 number_clone(absval, x2);
15403 number_abs(absval);
15404 number_clone(max, x1);
15405 number_abs(max);
15406 if (number_greater(absval, max)) {
15407 number_clone(max, absval);
15408 }
15409 number_clone(absval, x3);
15410 number_abs(absval);
15411 if (number_greater(absval, max)) {
15412 number_clone(max, absval);
15413 }
15414 number_clone(absval, y1);
15415 number_abs(absval);
15416 if (number_greater(absval, max)) {
15417 number_clone(max, absval);
15418 }
15419 number_clone(absval, y2);
15420 number_abs(absval);
15421 if (number_greater(absval, max)) {
15422 number_clone(max, absval);
15423 }
15424 number_clone(absval, y3);
15425 number_abs(absval);
15426 if (number_greater(absval, max)) {
15427 number_clone(max, absval);
15428 }
15429 free_number (absval);
15430 if (number_zero(max))
15431 goto FOUND;
15432 while (number_less (max, fraction_half_t)) {
15433 number_double(max);
15434 number_double(x1);
15435 number_double(x2);
15436 number_double(x3);
15437 number_double(y1);
15438 number_double(y2);
15439 number_double(y3);
15440 }
15441 number_clone(t, x1);
15442 {
15443 mp_number r1, r2;
15444 new_fraction (r1);
15445 new_fraction (r2);
15446 take_fraction (r1, x1, x);
15447 take_fraction (r2, y1, y);
15448 set_number_from_addition(x1, r1, r2);
15449 take_fraction (r1, y1, x);
15450 take_fraction (r2, t, y);
15451 set_number_from_substraction(y1, r1, r2);
15452 number_clone(t, x2);
15453 take_fraction (r1, x2, x);
15454 take_fraction (r2, y2, y);
15455 set_number_from_addition(x2, r1, r2);
15456 take_fraction (r1, y2, x);
15457 take_fraction (r2, t, y);
15458 set_number_from_substraction(y2, r1, r2);
15459 number_clone(t, x3);
15460 take_fraction (r1, x3 ,x);
15461 take_fraction (r2, y3, y);
15462 set_number_from_addition(x3, r1, r2);
15463 take_fraction (r1, y3, x);
15464 take_fraction (r2, t, y);
15465 set_number_from_substraction(y3, r1, r2);
15466 free_number (r1);
15467 free_number (r2);
15468 }
15469 }
15470 if (number_zero(y1))
15471 if (number_zero(x1) || number_positive(x1))
15472 goto FOUND;
15473 if (number_positive(n)) {
15474 /* Exit to |found| if an eastward direction occurs at knot |p| */
15475 mp_number theta;
15476 mp_number tmp;
15477 new_angle (theta);
15478 n_arg (theta, x1, y1);
15479 new_angle (tmp);
15480 set_number_from_substraction (tmp, theta, one_eighty_deg_t);
15481
15482 if (number_nonnegative(theta) && number_nonpositive(phi) && number_greaterequal(phi, tmp)) {
15483 free_number (tmp);
15484 free_number (theta);
15485 goto FOUND;
15486 }
15487 set_number_from_addition (tmp, theta, one_eighty_deg_t);
15488 if (number_nonpositive(theta) && number_nonnegative(phi) && number_lessequal(phi, tmp)) {
15489 free_number (tmp);
15490 free_number (theta);
15491 goto FOUND;
15492 }
15493 free_number (tmp);
15494 free_number (theta);
15495
15496 if (p == h)
15497 break;
15498 }
15499 if (number_nonzero(x3) || number_nonzero(y3)) {
15500 n_arg (phi, x3, y3);
15501 }
15502 /* Exit to |found| if the curve whose derivatives are specified by
15503 |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|.*/
15504 /*In this step we want to use the |crossing_point| routine to find the
15505 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
15506 Several complications arise: If the quadratic equation has a double root,
15507 the curve never crosses zero, and |crossing_point| will find nothing;
15508 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
15509 equation has simple roots, or only one root, we may have to negate it
15510 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
15511 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
15512 identically zero.*/
15513 if (number_negative(x1))
15514 if (number_negative(x2))
15515 if (number_negative(x3))
15516 goto DONE;
15517 {
15518 ab_vs_cd (ab_vs_cd, y1, y3, y2, y2);
15519 if (number_zero(ab_vs_cd)) {
15520 /* Handle the test for eastward directions when $y_1y_3=y_2^2$;
15521 either |goto found| or |goto done| */
15522 {
15523 ab_vs_cd (ab_vs_cd, y1, y2, zero_t, zero_t);
15524 if (number_negative(ab_vs_cd)) {
15525 mp_number tmp, arg2;
15526 new_number(tmp);
15527 new_number(arg2);
15528 set_number_from_substraction (arg2, y1, y2);
15529 make_fraction (t, y1, arg2);
15530 free_number (arg2);
15531 set_number_from_of_the_way(x1, t, x1, x2);
15532 set_number_from_of_the_way(x2, t, x2, x3);
15533 set_number_from_of_the_way(tmp, t, x1, x2);
15534 if (number_zero(tmp) || number_positive(tmp)) {
15535 free_number (tmp);
15536 we_found_it;
15537 }
15538 free_number (tmp);
15539 } else if (number_zero(y3)) {
15540 if (number_zero(y1)) {
15541 /* Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0| */
15542 /* At this point we know that the derivative of |y(t)| is identically zero,
15543 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
15544 traveling east. */
15545 {
15546 mp_number arg1, arg2, arg3;
15547 new_number (arg1);
15548 new_number (arg2);
15549 new_number (arg3);
15550 number_clone(arg1, x1);
15551 number_negate(arg1);
15552 number_clone(arg2, x2);
15553 number_negate(arg2);
15554 number_clone(arg3, x3);
15555 number_negate(arg3);
15556 crossing_point (t, arg1, arg2, arg3);
15557 free_number (arg1);
15558 free_number (arg2);
15559 free_number (arg3);
15560 if (number_lessequal (t, fraction_one_t))
15561 we_found_it;
15562 ab_vs_cd (ab_vs_cd, x1, x3, x2, x2);
15563 if (number_nonpositive(ab_vs_cd)) {
15564 mp_number arg2;
15565 new_number (arg2);
15566 set_number_from_substraction (arg2, x1, x2);
15567 make_fraction (t, x1, arg2);
15568 free_number (arg2);
15569 we_found_it;
15570 }
15571 }
15572
15573
15574
15575 } else if (number_zero(x3) || number_positive(x3)) {
15576 set_number_to_unity(tt);
15577 goto FOUND;
15578 }
15579 }
15580 goto DONE;
15581 }
15582
15583
15584 }
15585 }
15586 if (number_zero(y1) || number_negative(y1)) {
15587 if (number_negative(y1)) {
15588 number_negate(y1);
15589 number_negate(y2);
15590 number_negate(y3);
15591 } else if (number_positive(y2)) {
15592 number_negate(y2);
15593 number_negate(y3);
15594 }
15595 }
15596 /* Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
15597 $B(x_1,x_2,x_3;t)\ge0$ */
15598 /* The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
15599 two roots, because we know that it isn't identically zero.
15600
15601 It must be admitted that the |crossing_point| routine is not perfectly accurate;
15602 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
15603 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
15604 subject to rounding errors. Yet this code optimistically tries to
15605 do the right thing.
15606
15607 */
15608 crossing_point (t, y1, y2, y3);
15609 if (number_greater (t, fraction_one_t))
15610 goto DONE;
15611 set_number_from_of_the_way(y2, t, y2, y3);
15612 set_number_from_of_the_way(x1, t, x1, x2);
15613 set_number_from_of_the_way(x2, t, x2, x3);
15614 set_number_from_of_the_way(x1, t, x1, x2);
15615 if (number_zero(x1) || number_positive(x1))
15616 we_found_it;
15617 if (number_positive(y2))
15618 set_number_to_zero(y2);
15619 number_clone(tt, t);
15620 {
15621 mp_number arg1, arg2, arg3;
15622 new_number (arg1);
15623 new_number (arg2);
15624 new_number (arg3);
15625 number_clone(arg2, y2);
15626 number_negate(arg2);
15627 number_clone(arg3, y3);
15628 number_negate(arg3);
15629 crossing_point (t, arg1, arg2, arg3);
15630 free_number (arg1);
15631 free_number (arg2);
15632 free_number (arg3);
15633 }
15634 if (number_greater (t, fraction_one_t))
15635 goto DONE;
15636 {
15637 mp_number tmp;
15638 new_number(tmp);
15639 set_number_from_of_the_way(x1, t, x1, x2);
15640 set_number_from_of_the_way(x2, t, x2, x3);
15641 set_number_from_of_the_way(tmp, t, x1, x2);
15642 if (number_nonnegative(tmp)) {
15643 free_number (tmp);
15644 set_number_from_of_the_way (t, t, tt, fraction_one_t);
15645 we_found_it;
15646 }
15647 free_number (tmp);
15648 }
15649 DONE:
15650
15651
15652 @ The intersection of two cubics can be found by an interesting variant
15653 of the general bisection scheme described in the introduction to
15654 |crossing_point|.\
15655 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)$,
15656 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
15657 if an intersection exists. First we find the smallest rectangle that
15658 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
15659 the smallest rectangle that encloses
15660 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
15661 But if the rectangles do overlap, we bisect the intervals, getting
15662 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
15663 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
15664 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
15665 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
15666 levels of bisection we will have determined the intersection times $t_1$
15667 and~$t_2$ to $l$~bits of accuracy.
15668
15669 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
15670 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
15671 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
15672 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
15673 to determine when the enclosing rectangles overlap. Here's why:
15674 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
15675 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
15676 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
15677 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
15678 overlap if and only if $u\submin\L x\submax$ and
15679 $x\submin\L u\submax$. Letting
15680 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
15681 U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
15682 we have $2^lu\submin=2^lu_0+U\submin$, etc.; the condition for overlap
15683 reduces to
15684 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
15685 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
15686 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
15687 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
15688 because of the overlap condition; i.e., we know that $X\submin$,
15689 $X\submax$, and their relatives are bounded, hence $X\submax-
15690 U\submin$ and $X\submin-U\submax$ are bounded.
15691
15692 @ Incidentally, if the given cubics intersect more than once, the process
15693 just sketched will not necessarily find the lexicographically smallest pair
15694 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
15695 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
15696 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
15697 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
15698 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
15699 Shuffled order agrees with lexicographic order if all pairs of solutions
15700 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
15701 $t_2<t_2'$; but in general, lexicographic order can be quite different,
15702 and the bisection algorithm would be substantially less efficient if it were
15703 constrained by lexicographic order.
15704
15705 For example, suppose that an overlap has been found for $l=3$ and
15706 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
15707 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
15708 Then there is probably an intersection in one of the subintervals
15709 $(.1011,.011x)$; but lexicographic order would require us to explore
15710 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
15711 want to store all of the subdivision data for the second path, so the
15712 subdivisions would have to be regenerated many times. Such inefficiencies
15713 would be associated with every `1' in the binary representation of~$t_1$.
15714
15715 @ The subdivision process introduces rounding errors, hence we need to
15716 make a more liberal test for overlap. It is not hard to show that the
15717 computed values of $U_i$ differ from the truth by at most~$l$, on
15718 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
15719 If $\beta$ is an upper bound on the absolute error in the computed
15720 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
15721 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
15722 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
15723
15724 More accuracy is obtained if we try the algorithm first with |tol=0|;
15725 the more liberal tolerance is used only if an exact approach fails.
15726 It is convenient to do this double-take by letting `3' in the preceding
15727 paragraph be a parameter, which is first 0, then 3.
15728
15729 @<Glob...@>=
15730 unsigned int tol_step; /* either 0 or 3, usually */
15731
15732 @ We shall use an explicit stack to implement the recursive bisection
15733 method described above. The |bisect_stack| array will contain numerous 5-word
15734 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
15735 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
15736
15737 The following macros define the allocation of stack positions to
15738 the quantities needed for bisection-intersection.
15739
15740 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
15741 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
15742 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
15743 @d stack_min(A) mp->bisect_stack[(A)+3]
15744 /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
15745 @d stack_max(A) mp->bisect_stack[(A)+4]
15746 /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
15747 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
15748 @#
15749 @d u_packet(A) ((A)-5)
15750 @d v_packet(A) ((A)-10)
15751 @d x_packet(A) ((A)-15)
15752 @d y_packet(A) ((A)-20)
15753 @d l_packets (mp->bisect_ptr-int_packets)
15754 @d r_packets mp->bisect_ptr
15755 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
15756 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
15757 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
15758 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
15759 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
15760 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
15761 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
15762 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
15763 @#
15764 @d u1l stack_1(ul_packet) /* $U'_1$ */
15765 @d u2l stack_2(ul_packet) /* $U'_2$ */
15766 @d u3l stack_3(ul_packet) /* $U'_3$ */
15767 @d v1l stack_1(vl_packet) /* $V'_1$ */
15768 @d v2l stack_2(vl_packet) /* $V'_2$ */
15769 @d v3l stack_3(vl_packet) /* $V'_3$ */
15770 @d x1l stack_1(xl_packet) /* $X'_1$ */
15771 @d x2l stack_2(xl_packet) /* $X'_2$ */
15772 @d x3l stack_3(xl_packet) /* $X'_3$ */
15773 @d y1l stack_1(yl_packet) /* $Y'_1$ */
15774 @d y2l stack_2(yl_packet) /* $Y'_2$ */
15775 @d y3l stack_3(yl_packet) /* $Y'_3$ */
15776 @d u1r stack_1(ur_packet) /* $U''_1$ */
15777 @d u2r stack_2(ur_packet) /* $U''_2$ */
15778 @d u3r stack_3(ur_packet) /* $U''_3$ */
15779 @d v1r stack_1(vr_packet) /* $V''_1$ */
15780 @d v2r stack_2(vr_packet) /* $V''_2$ */
15781 @d v3r stack_3(vr_packet) /* $V''_3$ */
15782 @d x1r stack_1(xr_packet) /* $X''_1$ */
15783 @d x2r stack_2(xr_packet) /* $X''_2$ */
15784 @d x3r stack_3(xr_packet) /* $X''_3$ */
15785 @d y1r stack_1(yr_packet) /* $Y''_1$ */
15786 @d y2r stack_2(yr_packet) /* $Y''_2$ */
15787 @d y3r stack_3(yr_packet) /* $Y''_3$ */
15788 @#
15789 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
15790 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
15791 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
15792 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
15793 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
15794 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
15795
15796 @<Glob...@>=
15797 mp_number *bisect_stack;
15798 integer bisect_ptr;
15799
15800 @ @<Allocate or initialize ...@>=
15801 mp->bisect_stack = xmalloc ((bistack_size + 1), sizeof (mp_number));
15802 {
15803 int i;
15804 for (i=0;i<bistack_size + 1;i++) {
15805 new_number (mp->bisect_stack[i]);
15806 }
15807 }
15808
15809 @ @<Dealloc variables@>=
15810 {
15811 int i;
15812 for (i=0;i<bistack_size + 1;i++) {
15813 free_number (mp->bisect_stack[i]);
15814 }
15815 }
15816 xfree (mp->bisect_stack);
15817
15818 @ @<Check the ``constant''...@>=
15819 if (int_packets + (17+2) * int_increment > bistack_size)
15820 mp->bad = 19;
15821
15822 @ Computation of the min and max is a tedious but fairly fast sequence of
15823 instructions; exactly four comparisons are made in each branch.
15824
15825 @d set_min_max(A) @/
15826 debug_number (stack_1(A));
15827 debug_number (stack_3(A));
15828 debug_number (stack_2(A));
15829 debug_number (stack_min(A));
15830 debug_number (stack_max(A));
15831 if ( number_negative(stack_1((A))) ) {
15832 if ( number_nonnegative (stack_3((A))) ) {
15833 if ( number_negative (stack_2((A))) )
15834 set_number_from_addition (stack_min((A)), stack_1((A)), stack_2((A)));
15835 else
15836 number_clone (stack_min((A)), stack_1((A)));
15837 set_number_from_addition (stack_max((A)), stack_1((A)), stack_2((A)));
15838 number_add (stack_max((A)), stack_3((A)));
15839 if ( number_negative (stack_max((A))) )
15840 set_number_to_zero (stack_max((A)));
15841 } else {
15842 set_number_from_addition (stack_min((A)), stack_1((A)), stack_2((A)));
15843 number_add (stack_min((A)), stack_3((A)));
15844 if ( number_greater (stack_min((A)), stack_1((A))))
15845 number_clone (stack_min((A)), stack_1((A)));
15846 set_number_from_addition (stack_max((A)), stack_1((A)), stack_2((A)));
15847 if ( number_negative (stack_max((A))) )
15848 set_number_to_zero (stack_max((A)));
15849 }
15850 } else if ( number_nonpositive (stack_3((A)))) {
15851 if ( number_positive (stack_2((A))) )
15852 set_number_from_addition (stack_max((A)), stack_1((A)), stack_2((A)));
15853 else
15854 number_clone (stack_max((A)), stack_1((A)));
15855 set_number_from_addition (stack_min((A)), stack_1((A)), stack_2((A)));
15856 number_add (stack_min((A)), stack_3((A)));
15857 if ( number_positive (stack_min((A))) )
15858 set_number_to_zero (stack_min((A)));
15859 } else {
15860 set_number_from_addition (stack_max((A)), stack_1((A)), stack_2((A)));
15861 number_add (stack_max((A)), stack_3((A)));
15862 if ( number_less (stack_max((A)), stack_1((A))))
15863 number_clone (stack_max((A)), stack_1((A)));
15864 set_number_from_addition (stack_min((A)), stack_1((A)), stack_2((A)));
15865 if ( number_positive (stack_min((A))) )
15866 set_number_to_zero (stack_min((A)));
15867 }
15868
15869 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
15870 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
15871 routine uses global variables |cur_t| and |cur_tt| for this purpose;
15872 after successful completion, |cur_t| and |cur_tt| will contain |unity|
15873 plus the |scaled| values of $t_1$ and~$t_2$.
15874
15875 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
15876 finds no intersection. The routine gives up and gives an approximate answer
15877 if it has backtracked
15878 more than 5000 times (otherwise there are cases where several minutes
15879 of fruitless computation would be possible).
15880
15881 @d max_patience 5000
15882
15883 @<Glob...@>=
15884 mp_number cur_t;
15885 mp_number cur_tt; /* controls and results of |cubic_intersection| */
15886 integer time_to_go; /* this many backtracks before giving up */
15887 mp_number max_t; /* maximum of $2^{l+1}$ so far achieved */
15888
15889 @ @<Initialize table ...@>=
15890 new_number (mp->cur_t);
15891 new_number (mp->cur_tt);
15892 new_number (mp->max_t);
15893
15894 @ @<Dealloc ...@>=
15895 free_number (mp->cur_t);
15896 free_number (mp->cur_tt);
15897 free_number (mp->max_t);
15898
15899 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
15900 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,mp_link(p))|
15901 and |(pp,mp_link(pp))|, respectively.
15902
15903 @d half(A) ((A)/2)
15904
15905 @c
15906 static void mp_cubic_intersection (MP mp, mp_knot p, mp_knot pp) {
15907 mp_knot q, qq; /* |mp_link(p)|, |mp_link(pp)| */
15908 mp_number x_two_t; /* increment bit precision */
15909 mp_number x_two_t_low_precision; /* check for low precision */
15910 mp->time_to_go = max_patience;
15911 set_number_from_scaled (mp->max_t, 2);
15912 new_number (x_two_t);
15913 new_number (x_two_t_low_precision);
15914
15915 number_clone (x_two_t,two_t);
15916 number_double(x_two_t);number_double(x_two_t); /* added 2 bit of precision */
15917 set_number_from_double (x_two_t_low_precision,-0.5);
15918 number_add (x_two_t_low_precision,x_two_t);
15919
15920 @<Initialize for intersections at level zero@>;
15921 CONTINUE:
15922 while (1) {
15923 /* When we are in arbitrary precision math, low precisions can */
15924 /* lead to access locations beyond the |stack_size|: in this case */
15925 /* we say that there is no intersection.*/
15926 if ( ((x_packet (mp->xy))+4)>bistack_size ||
15927 ((u_packet (mp->uv))+4)>bistack_size || @|
15928 ((y_packet (mp->xy))+4)>bistack_size ||
15929 ((v_packet (mp->uv))+4)>bistack_size ){
15930 set_number_from_scaled (mp->cur_t, 1);
15931 set_number_from_scaled (mp->cur_tt, 1);
15932 goto NOT_FOUND;
15933 }
15934 /* Also, low precision can lead to wrong result in comparing */
15935 /* so we check that the level of bisection stay low, and later */
15936 /* we will also check that the bisection level are safe from */
15937 /* approximations. */
15938 if (number_greater (mp->max_t, x_two_t)){
15939 set_number_from_scaled (mp->cur_t, 1);
15940 set_number_from_scaled (mp->cur_tt, 1);
15941 goto NOT_FOUND;
15942 }
15943
15944 if (number_to_scaled (mp->delx) - mp->tol <=
15945 number_to_scaled (stack_max (x_packet (mp->xy))) - number_to_scaled (stack_min (u_packet (mp->uv))))
15946 if (number_to_scaled (mp->delx) + mp->tol >=
15947 number_to_scaled (stack_min (x_packet (mp->xy))) - number_to_scaled (stack_max (u_packet (mp->uv))))
15948 if (number_to_scaled (mp->dely) - mp->tol <=
15949 number_to_scaled (stack_max (y_packet (mp->xy))) - number_to_scaled (stack_min (v_packet (mp->uv))))
15950 if (number_to_scaled (mp->dely) + mp->tol >=
15951 number_to_scaled (stack_min (y_packet (mp->xy))) - number_to_scaled (stack_max (v_packet (mp->uv)))) {
15952 if (number_to_scaled (mp->cur_t) >= number_to_scaled (mp->max_t)) {
15953 if ( number_equal(mp->max_t, x_two_t) || number_greater(mp->max_t,x_two_t_low_precision)) { /* we've done 17+2 bisections */
15954 number_divide_int(mp->cur_t,1<<2);number_divide_int(mp->cur_tt,1<<2); /* restore values due bit precision */
15955 set_number_from_scaled (mp->cur_t, ((number_to_scaled (mp->cur_t) + 1)/2));
15956 set_number_from_scaled (mp->cur_tt, ((number_to_scaled (mp->cur_tt) + 1)/2));
15957 return;
15958 }
15959 number_double(mp->max_t);
15960 number_clone (mp->appr_t, mp->cur_t);
15961 number_clone (mp->appr_tt, mp->cur_tt);
15962 }
15963 @<Subdivide for a new level of intersection@>;
15964 goto CONTINUE;
15965 }
15966 if (mp->time_to_go > 0) {
15967 decr (mp->time_to_go);
15968 } else {
15969 /* we have added 2 bit of precision */
15970 number_divide_int(mp->appr_t,1<<2);number_divide_int(mp->appr_tt,1<<2);
15971 while (number_less (mp->appr_t, unity_t)) {
15972 number_double(mp->appr_t);
15973 number_double(mp->appr_tt);
15974 }
15975 number_clone (mp->cur_t, mp->appr_t);
15976 number_clone (mp->cur_tt, mp->appr_tt);
15977 return;
15978 }
15979 NOT_FOUND:
15980 /* Advance to the next pair |(cur_t,cur_tt)| */
15981 if (odd (number_to_scaled (mp->cur_tt))) {
15982 if (odd (number_to_scaled (mp->cur_t))) {
15983 /* Descend to the previous level and |goto not_found| */
15984 set_number_from_scaled (mp->cur_t, half (number_to_scaled (mp->cur_t)));
15985 set_number_from_scaled (mp->cur_tt, half (number_to_scaled (mp->cur_tt)));
15986 if (number_to_scaled (mp->cur_t) == 0)
15987 return;
15988 mp->bisect_ptr -= int_increment;
15989 mp->three_l -= (integer) mp->tol_step;
15990 number_clone (mp->delx, stack_dx);
15991 number_clone (mp->dely, stack_dy);
15992 mp->tol = number_to_scaled (stack_tol);
15993 mp->uv = number_to_scaled (stack_uv);
15994 mp->xy = number_to_scaled (stack_xy);
15995 goto NOT_FOUND;
15996 } else {
15997 set_number_from_scaled (mp->cur_t, number_to_scaled (mp->cur_t) + 1);
15998 number_add (mp->delx, stack_1 (u_packet (mp->uv)));
15999 number_add (mp->delx, stack_2 (u_packet (mp->uv)));
16000 number_add (mp->delx, stack_3 (u_packet (mp->uv)));
16001 number_add (mp->dely, stack_1 (v_packet (mp->uv)));
16002 number_add (mp->dely, stack_2 (v_packet (mp->uv)));
16003 number_add (mp->dely, stack_3 (v_packet (mp->uv)));
16004 mp->uv = mp->uv + int_packets; /* switch from |l_packets| to |r_packets| */
16005 set_number_from_scaled (mp->cur_tt, number_to_scaled (mp->cur_tt) - 1);
16006 mp->xy = mp->xy - int_packets;
16007 number_add (mp->delx, stack_1 (x_packet (mp->xy)));
16008 number_add (mp->delx, stack_2 (x_packet (mp->xy)));
16009 number_add (mp->delx, stack_3 (x_packet (mp->xy)));
16010 number_add (mp->dely, stack_1 (y_packet (mp->xy)));
16011 number_add (mp->dely, stack_2 (y_packet (mp->xy)));
16012 number_add (mp->dely, stack_3 (y_packet (mp->xy)));
16013 }
16014 } else {
16015 set_number_from_scaled (mp->cur_tt, number_to_scaled (mp->cur_tt) + 1);
16016 mp->tol = mp->tol + mp->three_l;
16017 number_substract (mp->delx, stack_1 (x_packet (mp->xy)));
16018 number_substract (mp->delx, stack_2 (x_packet (mp->xy)));
16019 number_substract (mp->delx, stack_3 (x_packet (mp->xy)));
16020 number_substract (mp->dely, stack_1 (y_packet (mp->xy)));
16021 number_substract (mp->dely, stack_2 (y_packet (mp->xy)));
16022 number_substract (mp->dely, stack_3 (y_packet (mp->xy)));
16023 mp->xy = mp->xy + int_packets; /* switch from |l_packets| to |r_packets| */
16024 }
16025 }
16026 }
16027
16028
16029 @ The following variables are global, although they are used only by
16030 |cubic_intersection|, because it is necessary on some machines to
16031 split |cubic_intersection| up into two procedures.
16032
16033 @<Glob...@>=
16034 mp_number delx;
16035 mp_number dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
16036 mpinteger64 tol; /* bound on the uncertainty in the overlap test */
16037 mpinteger64 uv;
16038 mpinteger64 xy; /* pointers to the current packets of interest */
16039 mpinteger64 three_l; /* |tol_step| times the bisection level */
16040 mp_number appr_t;
16041 mp_number appr_tt; /* best approximations known to the answers */
16042
16043 @ @<Initialize table ...@>=
16044 new_number (mp->delx);
16045 new_number (mp->dely);
16046 new_number (mp->appr_t);
16047 new_number (mp->appr_tt);
16048
16049 @ @<Dealloc...@>=
16050 free_number (mp->delx);
16051 free_number (mp->dely);
16052 free_number (mp->appr_t);
16053 free_number (mp->appr_tt);
16054
16055 @ We shall assume that the coordinates are sufficiently non-extreme that
16056 integer overflow will not occur.
16057 @^overflow in arithmetic@>
16058
16059 @<Initialize for intersections at level zero@>=
16060 q = mp_next_knot (p);
16061 qq = mp_next_knot (pp);
16062 mp->bisect_ptr = int_packets;
16063 set_number_from_substraction (u1r, p->right_x, p->x_coord);
16064 set_number_from_substraction (u2r, q->left_x, p->right_x);
16065 set_number_from_substraction (u3r, q->x_coord, q->left_x);
16066 set_min_max (ur_packet);
16067 set_number_from_substraction (v1r, p->right_y, p->y_coord );
16068 set_number_from_substraction (v2r, q->left_y, p->right_y);
16069 set_number_from_substraction (v3r, q->y_coord, q->left_y );
16070 set_min_max (vr_packet);
16071 set_number_from_substraction (x1r, pp->right_x, pp->x_coord );
16072 set_number_from_substraction (x2r, qq->left_x, pp->right_x );
16073 set_number_from_substraction (x3r, qq->x_coord, qq->left_x );
16074 set_min_max (xr_packet);
16075 set_number_from_substraction (y1r, pp->right_y, pp->y_coord );
16076 set_number_from_substraction (y2r, qq->left_y, pp->right_y);
16077 set_number_from_substraction (y3r, qq->y_coord, qq->left_y);
16078 set_min_max (yr_packet);
16079 set_number_from_substraction (mp->delx, p->x_coord, pp->x_coord );
16080 set_number_from_substraction (mp->dely, p->y_coord, pp->y_coord );
16081 mp->tol = 0;
16082 mp->uv = r_packets;
16083 mp->xy = r_packets;
16084 mp->three_l = 0;
16085 set_number_from_scaled (mp->cur_t, 1);
16086 set_number_from_scaled (mp->cur_tt, 1)@;
16087
16088 @ @<Subdivide for a new level of intersection@>=
16089 number_clone (stack_dx, mp->delx);
16090 number_clone (stack_dy, mp->dely);
16091 set_number_from_scaled (stack_tol, mp->tol);
16092 set_number_from_scaled (stack_uv, mp->uv);
16093 set_number_from_scaled (stack_xy, mp->xy);
16094 mp->bisect_ptr = mp->bisect_ptr + int_increment;
16095 number_double (mp->cur_t);
16096 number_double (mp->cur_tt);
16097 number_clone (u1l, stack_1 (u_packet (mp->uv)));
16098 number_clone (u3r, stack_3 (u_packet (mp->uv)));
16099 set_number_from_addition (u2l, u1l, stack_2 (u_packet (mp->uv))); number_half (u2l);
16100 set_number_from_addition (u2r, u3r, stack_2 (u_packet (mp->uv))); number_half (u2r);
16101 set_number_from_addition (u3l, u2l, u2r); number_half (u3l);
16102 number_clone (u1r, u3l);
16103 set_min_max (ul_packet);
16104 set_min_max (ur_packet);
16105 number_clone (v1l, stack_1 (v_packet (mp->uv)));
16106 number_clone (v3r, stack_3 (v_packet (mp->uv)));
16107 set_number_from_addition (v2l, v1l, stack_2 (v_packet (mp->uv))); number_half(v2l);
16108 set_number_from_addition (v2r, v3r, stack_2 (v_packet (mp->uv))); number_half(v2r);
16109 set_number_from_addition (v3l, v2l, v2r); number_half(v3l);
16110 number_clone (v1r, v3l);
16111 set_min_max (vl_packet);
16112 set_min_max (vr_packet);
16113 number_clone (x1l, stack_1 (x_packet (mp->xy)));
16114 number_clone (x3r, stack_3 (x_packet (mp->xy)));
16115 set_number_from_addition (x2l, x1l, stack_2 (x_packet (mp->xy))); number_half(x2l);
16116 set_number_from_addition (x2r, x3r, stack_2 (x_packet (mp->xy))); number_half(x2r);
16117 set_number_from_addition (x3l, x2l, x2r); number_half(x3l);
16118 number_clone (x1r, x3l);
16119 set_min_max (xl_packet);
16120 set_min_max (xr_packet);
16121 number_clone (y1l, stack_1 (y_packet (mp->xy)));
16122 number_clone (y3r, stack_3 (y_packet (mp->xy)));
16123 set_number_from_addition (y2l, y1l, stack_2 (y_packet (mp->xy))); number_half (y2l);
16124 set_number_from_addition (y2r, y3r, stack_2 (y_packet (mp->xy))); number_half (y2r);
16125 set_number_from_addition (y3l, y2l, y2r); number_half (y3l);
16126 number_clone (y1r, y3l);
16127 set_min_max (yl_packet);
16128 set_min_max (yr_packet);
16129 mp->uv = l_packets;
16130 mp->xy = l_packets;
16131 number_double(mp->delx);
16132 number_double(mp->dely);
16133 mp->tol = mp->tol - mp->three_l + (integer) mp->tol_step;
16134 mp->tol += mp->tol;
16135 mp->three_l = mp->three_l + (integer) mp->tol_step@;
16136
16137 @ The |path_intersection| procedure is much simpler.
16138 It invokes |cubic_intersection| in lexicographic order until finding a
16139 pair of cubics that intersect. The final intersection times are placed in
16140 |cur_t| and~|cur_tt|.
16141
16142 @c
16143 static void mp_path_intersection (MP mp, mp_knot h, mp_knot hh) {
16144 mp_knot p, pp; /* link registers that traverse the given paths */
16145 mp_number n, nn; /* integer parts of intersection times, minus |unity| */
16146 @<Change one-point paths into dead cycles@>;
16147 new_number (n);
16148 new_number (nn);
16149 mp->tol_step = 0;
16150 do {
16151 set_number_to_unity(n);
16152 number_negate (n);
16153 p = h;
16154 do {
16155 if (mp_right_type (p) != mp_endpoint) {
16156 set_number_to_unity(nn);
16157 number_negate (nn);
16158 pp = hh;
16159 do {
16160 if (mp_right_type (pp) != mp_endpoint) {
16161 mp_cubic_intersection (mp, p, pp);
16162 if (number_positive (mp->cur_t)) {
16163 number_add (mp->cur_t, n);
16164 number_add (mp->cur_tt, nn);
16165 goto DONE;
16166 }
16167 }
16168 number_add(nn, unity_t);
16169 pp = mp_next_knot (pp);
16170 } while (pp != hh);
16171 }
16172 number_add(n, unity_t);
16173 p = mp_next_knot (p);
16174 } while (p != h);
16175 mp->tol_step = mp->tol_step + 3;
16176 } while (mp->tol_step <= 3);
16177 number_clone (mp->cur_t, unity_t);
16178 number_negate (mp->cur_t);
16179 number_clone (mp->cur_tt, unity_t);
16180 number_negate (mp->cur_tt);
16181 DONE:
16182 free_number (n);
16183 free_number (nn);
16184 }
16185
16186
16187 @ @<Change one-point paths...@>=
16188 if (mp_right_type (h) == mp_endpoint) {
16189 number_clone (h->right_x, h->x_coord);
16190 number_clone (h->left_x, h->x_coord);
16191 number_clone (h->right_y, h->y_coord);
16192 number_clone (h->left_y, h->y_coord);
16193 mp_right_type (h) = mp_explicit;
16194 }
16195 if (mp_right_type (hh) == mp_endpoint) {
16196 number_clone (hh->right_x, hh->x_coord);
16197 number_clone (hh->left_x, hh->x_coord);
16198 number_clone (hh->right_y, hh->y_coord);
16199 number_clone (hh->left_y, hh->y_coord);
16200 mp_right_type (hh) = mp_explicit;
16201 }
16202
16203 @* Dynamic linear equations.
16204 \MP\ users define variables implicitly by stating equations that should be
16205 satisfied; the computer is supposed to be smart enough to solve those equations.
16206 And indeed, the computer tries valiantly to do so, by distinguishing five
16207 different types of numeric values:
16208
16209 \smallskip\hang
16210 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
16211 of the variable whose address is~|p|.
16212
16213 \smallskip\hang
16214 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
16215 points to a {\sl dependency list\/} that expresses the value of variable~|p|
16216 as a |scaled| number plus a sum of independent variables with |fraction|
16217 coefficients.
16218
16219 \smallskip\hang
16220 |type(p)=mp_independent| means that |indep_value(p)=s|, where |s>0| is a ``serial
16221 number'' reflecting the time this variable was first used in an equation;
16222 and there is an extra field |indep_scale(p)=m|, with |0<=m<64|, each dependent
16223 variable that refers to this one is actually referring to the future value of
16224 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
16225 scaling are sometimes needed to keep the coefficients in dependency lists
16226 from getting too large. The value of~|m| will always be even.)
16227
16228 \smallskip\hang
16229 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
16230 equation before, but it has been explicitly declared to be numeric.
16231
16232 \smallskip\hang
16233 |type(p)=undefined| means that variable |p| hasn't appeared before.
16234
16235 \smallskip\noindent
16236 We have actually discussed these five types in the reverse order of their
16237 history during a computation: Once |known|, a variable never again
16238 becomes |dependent|; once |dependent|, it almost never again becomes
16239 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
16240 and once |mp_numeric_type|, it never again becomes |undefined| (except
16241 of course when the user specifically decides to scrap the old value
16242 and start again). A backward step may, however, take place: Sometimes
16243 a |dependent| variable becomes |mp_independent| again, when one of the
16244 independent variables it depends on is reverting to |undefined|.
16245
16246 @d indep_scale(A) ((mp_value_node)(A))->data.indep.scale
16247 @d set_indep_scale(A,B) ((mp_value_node)(A))->data.indep.scale=(B)
16248 @d indep_value(A) ((mp_value_node)(A))->data.indep.serial
16249 @d set_indep_value(A,B) ((mp_value_node)(A))->data.indep.serial=(B)
16250
16251
16252 @c
16253 void mp_new_indep(MP mp, mp_node p) { /* create a new independent variable */
16254 if ( mp->serial_no>=max_integer ) {
16255 mp_fatal_error(mp, "variable instance identifiers exhausted");
16256 }
16257 mp_type(p)=mp_independent;
16258 mp->serial_no=mp->serial_no+1;
16259 set_indep_scale(p,0);
16260 set_indep_value(p,mp->serial_no);
16261 }
16262
16263 @ @<Declarations@>=
16264 void mp_new_indep(MP mp, mp_node p);
16265
16266
16267 @ @<Glob...@>=
16268 integer serial_no; /* the most recent serial number */
16269
16270 @ But how are dependency lists represented? It's simple: The linear combination
16271 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
16272 |q=dep_list(p)| points to this list, and if |k>0|, then |dep_value(q)=
16273 @t$\alpha_1$@>| (which is a |fraction|); |dep_info(q)| points to the location
16274 of $\alpha_1$; and |mp_link(p)| points to the dependency list
16275 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
16276 then |dep_value(q)=@t$\beta$@>| (which is |scaled|) and |dep_info(q)=NULL|.
16277 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
16278 they appear in decreasing order of their |value| fields (i.e., of
16279 their serial numbers). \ (It is convenient to use decreasing order,
16280 since |value(NULL)=0|. If the independent variables were not sorted by
16281 serial number but by some other criterion, such as their location in |mem|,
16282 the equation-solving mechanism would be too system-dependent, because
16283 the ordering can affect the computed results.)
16284
16285 The |link| field in the node that contains the constant term $\beta$ is
16286 called the {\sl final link\/} of the dependency list. \MP\ maintains
16287 a doubly-linked master list of all dependency lists, in terms of a permanently
16288 allocated node
16289 in |mem| called |dep_head|. If there are no dependencies, we have
16290 |mp_link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
16291 otherwise |mp_link(dep_head)| points to the first dependent variable, say~|p|,
16292 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
16293 points to its dependency list. If the final link of that dependency list
16294 occurs in location~|q|, then |mp_link(q)| points to the next dependent
16295 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
16296
16297 Dependency nodes sometimes mutate into value nodes and vice versa, so their
16298 structures have to match.
16299
16300 @d dep_value(A) ((mp_value_node)(A))->data.n
16301 @d set_dep_value(A,B) do_set_dep_value(mp,(A),(B))
16302 @d dep_info(A) get_dep_info(mp, (A))
16303 @d set_dep_info(A,B) do {
16304 mp_value_node d = (mp_value_node)(B);
16305 FUNCTION_TRACE4("set_dep_info(%p,%p) on %d\n",(A),d,__LINE__);
16306 ((mp_value_node)(A))->parent_ = (mp_node)d;
16307 } while (0)@;
16308 @d dep_list(A) ((mp_value_node)(A))->attr_head_ /* half of the |value| field in a |dependent| variable */
16309 @d set_dep_list(A,B) do {
16310 mp_value_node d = (mp_value_node)(B);
16311 FUNCTION_TRACE4("set_dep_list(%p,%p) on %d\n",(A),d,__LINE__);
16312 dep_list((A)) = (mp_node)d;
16313 } while (0)@;
16314 @d prev_dep(A) ((mp_value_node)(A))->subscr_head_ /* the other half; makes a doubly linked list */
16315 @d set_prev_dep(A,B) do {
16316 mp_value_node d = (mp_value_node)(B);
16317 FUNCTION_TRACE4("set_prev_dep(%p,%p) on %d\n",(A),d,__LINE__);
16318 prev_dep((A)) = (mp_node)d;
16319 } while (0)@;
16320
16321 @c
16322 static mp_node get_dep_info (MP mp, mp_value_node p) {
16323 mp_node d;
16324 d = p->parent_; /* half of the |value| field in a |dependent| variable */
16325 FUNCTION_TRACE3 ("%p = dep_info(%p)\n", d, p);
16326 return d;
16327 }
16328 static void do_set_dep_value (MP mp, mp_value_node p, mp_number q) {
16329 number_clone (p->data.n, q); /* half of the |value| field in a |dependent| variable */
16330 FUNCTION_TRACE3("set_dep_value(%p,%d)\n", p, q);
16331 p->attr_head_ = NULL;
16332 p->subscr_head_ = NULL;
16333 }
16334
16335 @ @<Declarations...@>=
16336 static mp_node get_dep_info (MP mp, mp_value_node p);
16337
16338 @ @c
16339 static mp_value_node mp_get_dep_node (MP mp) {
16340 mp_value_node p = (mp_value_node) mp_get_value_node (mp);
16341 mp_type (p) = mp_dep_node_type;
16342 return p;
16343 }
16344 static void mp_free_dep_node (MP mp, mp_value_node p) {
16345 mp_free_value_node (mp, (mp_node) p);
16346 }
16347
16348
16349 @ @<Declarations...@>=
16350 static void mp_free_dep_node (MP mp, mp_value_node p);
16351
16352 @ @<Initialize table entries@>=
16353 mp->serial_no = 0;
16354 mp->dep_head = mp_get_dep_node (mp);
16355 set_mp_link (mp->dep_head, (mp_node) mp->dep_head);
16356 set_prev_dep (mp->dep_head, (mp_node) mp->dep_head);
16357 set_dep_info (mp->dep_head, NULL);
16358 set_dep_list (mp->dep_head, NULL);
16359
16360 @ @<Free table entries@>=
16361 mp_free_dep_node (mp, mp->dep_head);
16362
16363 @ Actually the description above contains a little white lie. There's
16364 another kind of variable called |mp_proto_dependent|, which is
16365 just like a |dependent| one except that the $\alpha$ coefficients
16366 in its dependency list are |scaled| instead of being fractions.
16367 Proto-dependency lists are mixed with dependency lists in the
16368 nodes reachable from |dep_head|.
16369
16370 @ Here is a procedure that prints a dependency list in symbolic form.
16371 The second parameter should be either |dependent| or |mp_proto_dependent|,
16372 to indicate the scaling of the coefficients.
16373
16374 @<Declarations@>=
16375 static void mp_print_dependency (MP mp, mp_value_node p, quarterword t);
16376
16377 @ @c
16378 void mp_print_dependency (MP mp, mp_value_node p, quarterword t) {
16379 mp_number v; /* a coefficient */
16380 mp_value_node pp; /* for list manipulation */
16381 mp_node q;
16382 pp = p;
16383 new_number (v);
16384 while (true) {
16385 number_clone (v, dep_value (p));
16386 number_abs (v);
16387 q = dep_info (p);
16388 if (q == NULL) { /* the constant term */
16389 if (number_nonzero(v) || (p == pp)) {
16390 if (number_positive(dep_value (p)))
16391 if (p != pp)
16392 mp_print_char (mp, xord ('+'));
16393 print_number (dep_value (p));
16394 }
16395 return;
16396 }
16397 /* Print the coefficient, unless it's $\pm1.0$ */
16398 if (number_negative(dep_value (p)))
16399 mp_print_char (mp, xord ('-'));
16400 else if (p != pp)
16401 mp_print_char (mp, xord ('+'));
16402 if (t == mp_dependent) {
16403 fraction_to_round_scaled (v);
16404 }
16405 if (!number_equal (v, unity_t))
16406 print_number (v);
16407
16408 if (mp_type (q) != mp_independent)
16409 mp_confusion (mp, "dep");
16410 mp_print_variable_name (mp, q);
16411 set_number_from_scaled (v, indep_scale(q));
16412 while (number_positive (v)) {
16413 mp_print (mp, "*4");
16414 number_add_scaled (v, -2);
16415 }
16416 p = (mp_value_node) mp_link (p);
16417 }
16418 }
16419
16420
16421
16422 @ The maximum absolute value of a coefficient in a given dependency list
16423 is returned by the following simple function.
16424
16425 @c
16426 static void mp_max_coef (MP mp, mp_number *x, mp_value_node p) {
16427 mp_number (absv);
16428 new_number (absv);
16429 set_number_to_zero (*x);
16430 while (dep_info (p) != NULL) {
16431 number_clone (absv, dep_value (p));
16432 number_abs (absv);
16433 if (number_greater (absv, *x)) {
16434 number_clone (*x, absv);
16435 }
16436 p = (mp_value_node) mp_link (p);
16437 }
16438 free_number (absv);
16439 }
16440
16441
16442 @ One of the main operations needed on dependency lists is to add a multiple
16443 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
16444 to dependency lists and |f| is a fraction.
16445
16446 If the coefficient of any independent variable becomes |coef_bound| or
16447 more, in absolute value, this procedure changes the type of that variable
16448 to `|independent_needing_fix|', and sets the global variable |fix_needed|
16449 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
16450 $\mu^2+\mu<8$; this means that the numbers we deal with won't
16451 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
16452 2.3723$, the safer value 7/3 is taken as the threshold.)
16453
16454 The changes mentioned in the preceding paragraph are actually done only if
16455 the global variable |watch_coefs| is |true|. But it usually is; in fact,
16456 it is |false| only when \MP\ is making a dependency list that will soon
16457 be equated to zero.
16458
16459 Several procedures that act on dependency lists, including |p_plus_fq|,
16460 set the global variable |dep_final| to the final (constant term) node of
16461 the dependency list that they produce.
16462
16463 @d independent_needing_fix 0
16464
16465 @<Glob...@>=
16466 boolean fix_needed; /* does at least one |independent| variable need scaling? */
16467 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
16468 mp_value_node dep_final; /* location of the constant term and final link */
16469
16470 @ @<Set init...@>=
16471 mp->fix_needed = false;
16472 mp->watch_coefs = true;
16473
16474 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
16475 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
16476 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
16477 should be |mp_proto_dependent| if |q| is a proto-dependency list.
16478
16479 List |q| is unchanged by the operation; but list |p| is totally destroyed.
16480
16481 The final link of the dependency list or proto-dependency list returned
16482 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
16483 constant term of the result will be located in the same |mem| location
16484 as the original constant term of~|p|.
16485
16486 Coefficients of the result are assumed to be zero if they are less than
16487 a certain threshold. This compensates for inevitable rounding errors,
16488 and tends to make more variables `|known|'. The threshold is approximately
16489 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
16490 proto-dependencies.
16491
16492 @d fraction_threshold_k ((math_data *)mp->math)->fraction_threshold_t
16493 @d half_fraction_threshold_k ((math_data *)mp->math)->half_fraction_threshold_t
16494 @d scaled_threshold_k ((math_data *)mp->math)->scaled_threshold_t
16495 @d half_scaled_threshold_k ((math_data *)mp->math)->half_scaled_threshold_t
16496
16497 @<Declarations@>=
16498 static mp_value_node mp_p_plus_fq (MP mp, mp_value_node p, mp_number f,
16499 mp_value_node q, mp_variable_type t,
16500 mp_variable_type tt);
16501
16502 @ @c
16503 static mp_value_node mp_p_plus_fq (MP mp, mp_value_node p, mp_number f,
16504 mp_value_node q, mp_variable_type t,
16505 mp_variable_type tt) {
16506 mp_node pp, qq; /* |dep_info(p)| and |dep_info(q)|, respectively */
16507 mp_value_node r, s; /* for list manipulation */
16508 mp_number threshold, half_threshold; /* defines a neighborhood of zero */
16509 mp_number v, vv; /* temporary registers */
16510 new_number (v);
16511 new_number (vv);
16512 new_number (threshold);
16513 new_number (half_threshold);
16514 if (t == mp_dependent) {
16515 number_clone (threshold, fraction_threshold_k);
16516 number_clone (half_threshold, half_fraction_threshold_k);
16517 } else {
16518 number_clone (threshold, scaled_threshold_k);
16519 number_clone (half_threshold, half_scaled_threshold_k);
16520 }
16521 r = (mp_value_node) mp->temp_head;
16522 pp = dep_info (p);
16523 qq = dep_info (q);
16524 while (1) {
16525 if (pp == qq) {
16526 if (pp == NULL) {
16527 break;
16528 } else {
16529 /* Contribute a term from |p|, plus |f| times the
16530 corresponding term from |q| */
16531 mp_number r1;
16532 mp_number absv;
16533 new_fraction (r1);
16534 new_number (absv);
16535 if (tt == mp_dependent) {
16536 take_fraction (r1, f, dep_value (q));
16537 } else {
16538 take_scaled (r1, f, dep_value (q));
16539 }
16540 set_number_from_addition (v, dep_value (p), r1);
16541 free_number (r1);
16542 set_dep_value (p, v);
16543 s = p;
16544 p = (mp_value_node) mp_link (p);
16545 number_clone (absv, v);
16546 number_abs(absv);
16547 if (number_less (absv, threshold)) {
16548 mp_free_dep_node (mp, s);
16549 } else {
16550 if (number_greaterequal (absv, coef_bound_k) && mp->watch_coefs) {
16551 mp_type (qq) = independent_needing_fix;
16552 /* If we set this , then we can drop |(mp_type(pp) == independent_needing_fix && mp->fix_needed)| later */
16553 /* |set_number_from_scaled (value_number (qq), indep_value(qq));| */
16554 mp->fix_needed = true;
16555 }
16556 set_mp_link (r, (mp_node) s);
16557 r = s;
16558 }
16559 free_number (absv);
16560 pp = dep_info (p);
16561 q = (mp_value_node) mp_link (q);
16562 qq = dep_info (q);
16563 }
16564
16565 } else {
16566 if (pp == NULL)
16567 set_number_to_neg_inf(v);
16568 else if (mp_type(pp) == mp_independent || (mp_type(pp) == independent_needing_fix && mp->fix_needed))
16569 set_number_from_scaled(v, indep_value(pp));
16570 else
16571 number_clone (v, value_number (pp));
16572 if (qq == NULL)
16573 set_number_to_neg_inf(vv);
16574 else if (mp_type(qq) == mp_independent || (mp_type(qq) == independent_needing_fix && mp->fix_needed))
16575 set_number_from_scaled(vv, indep_value(qq));
16576 else
16577 number_clone (vv, value_number (qq));
16578 if (number_less (v, vv)) {
16579 /* Contribute a term from |q|, multiplied by~|f| */
16580 mp_number absv;
16581 new_number (absv);
16582 {
16583 mp_number r1;
16584 mp_number arg1, arg2;
16585 new_fraction (r1);
16586 new_number (arg1);
16587 new_number (arg2);
16588 number_clone (arg1, f);
16589 number_clone (arg2, dep_value (q));
16590 if (tt == mp_dependent) {
16591 take_fraction (r1, arg1, arg2);
16592 } else {
16593 take_scaled (r1, arg1, arg2);
16594 }
16595 number_clone (v, r1);
16596 free_number (r1);
16597 free_number (arg1);
16598 free_number (arg2);
16599 }
16600 number_clone (absv, v);
16601 number_abs(absv);
16602 if (number_greater (absv, half_threshold)) {
16603 s = mp_get_dep_node (mp);
16604 set_dep_info (s, qq);
16605 set_dep_value (s, v);
16606 if (number_greaterequal(absv, coef_bound_k) && mp->watch_coefs) {
16607 /* clang: dereference of a null pointer ('qq') */ assert(qq);
16608 mp_type (qq) = independent_needing_fix;
16609 mp->fix_needed = true;
16610 }
16611 set_mp_link (r, (mp_node) s);
16612 r = s;
16613 }
16614 q = (mp_value_node) mp_link (q);
16615 qq = dep_info (q);
16616 free_number (absv);
16617
16618 } else {
16619 set_mp_link (r, (mp_node) p);
16620 r = p;
16621 p = (mp_value_node) mp_link (p);
16622 pp = dep_info (p);
16623 }
16624 }
16625 }
16626 {
16627 mp_number r1;
16628 mp_number arg1, arg2;
16629 new_fraction (r1);
16630 new_number (arg1);
16631 new_number (arg2);
16632 number_clone (arg1, dep_value (q));
16633 number_clone (arg2, f);
16634 if (t == mp_dependent) {
16635 take_fraction (r1, arg1, arg2);
16636 } else {
16637 take_scaled (r1, arg1, arg2);
16638 }
16639 slow_add (arg1, dep_value (p), r1);
16640 set_dep_value (p, arg1);
16641 free_number (r1);
16642 free_number (arg1);
16643 free_number (arg2);
16644 }
16645 set_mp_link (r, (mp_node) p);
16646 mp->dep_final = p;
16647 free_number (threshold);
16648 free_number (half_threshold);
16649 free_number (v);
16650 free_number (vv);
16651 return (mp_value_node) mp_link (mp->temp_head);
16652 }
16653
16654
16655 @ It is convenient to have another subroutine for the special case
16656 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
16657 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
16658
16659 @c
16660 static mp_value_node mp_p_plus_q (MP mp, mp_value_node p, mp_value_node q,
16661 mp_variable_type t) {
16662 mp_node pp, qq; /* |dep_info(p)| and |dep_info(q)|, respectively */
16663 mp_value_node s; /* for list manipulation */
16664 mp_value_node r; /* for list manipulation */
16665 mp_number threshold; /* defines a neighborhood of zero */
16666 mp_number v, vv; /* temporary register */
16667 new_number (v);
16668 new_number (vv);
16669 new_number (threshold);
16670 if (t == mp_dependent)
16671 number_clone (threshold, fraction_threshold_k);
16672 else
16673 number_clone (threshold, scaled_threshold_k);
16674 r = (mp_value_node) mp->temp_head;
16675 pp = dep_info (p);
16676 qq = dep_info (q);
16677 while (1) {
16678 if (pp == qq) {
16679 if (pp == NULL) {
16680 break;
16681 } else {
16682 /* Contribute a term from |p|, plus the corresponding term from |q| */
16683 mp_number test;
16684 new_number (test);
16685 set_number_from_addition (v, dep_value (p), dep_value (q));
16686 set_dep_value (p, v);
16687 s = p;
16688 p = (mp_value_node) mp_link (p);
16689 pp = dep_info (p);
16690 number_clone (test, v);
16691 number_abs(test);
16692 if (number_less (test, threshold)) {
16693 mp_free_dep_node (mp, s);
16694 } else {
16695 if (number_greaterequal(test, coef_bound_k) && mp->watch_coefs) {
16696 mp_type (qq) = independent_needing_fix;
16697 /* If we set this , then we can drop |(mp_type(pp) == independent_needing_fix && mp->fix_needed)| later */
16698 /* |set_number_from_scaled (value_number (qq), indep_value(qq));| */
16699 mp->fix_needed = true;
16700 }
16701 set_mp_link (r, (mp_node) s);
16702 r = s;
16703 }
16704 free_number (test);
16705 q = (mp_value_node) mp_link (q);
16706 qq = dep_info (q);
16707 }
16708
16709 } else {
16710 if (pp == NULL)
16711 set_number_to_zero (v);
16712 else if (mp_type(pp) == mp_independent || (mp_type(pp) == independent_needing_fix && mp->fix_needed))
16713 set_number_from_scaled (v, indep_value(pp));
16714 else
16715 number_clone (v, value_number (pp));
16716 if (qq == NULL)
16717 set_number_to_zero (vv);
16718 else if (mp_type(qq) == mp_independent || (mp_type(qq) == independent_needing_fix && mp->fix_needed))
16719 set_number_from_scaled (vv, indep_value(qq));
16720 else
16721 number_clone (vv, value_number (qq));
16722 if (number_less (v, vv)) {
16723 s = mp_get_dep_node (mp);
16724 set_dep_info (s, qq);
16725 set_dep_value (s, dep_value (q));
16726 q = (mp_value_node) mp_link (q);
16727 qq = dep_info (q);
16728 set_mp_link (r, (mp_node) s);
16729 r = s;
16730 } else {
16731 set_mp_link (r, (mp_node) p);
16732 r = p;
16733 p = (mp_value_node) mp_link (p);
16734 pp = dep_info (p);
16735 }
16736 }
16737 }
16738 {
16739 mp_number r1;
16740 new_number (r1);
16741 slow_add (r1, dep_value (p), dep_value (q));
16742 set_dep_value (p, r1);
16743 free_number (r1);
16744 }
16745 set_mp_link (r, (mp_node) p);
16746 mp->dep_final = p;
16747 free_number (v);
16748 free_number (vv);
16749 free_number (threshold);
16750 return (mp_value_node) mp_link (mp->temp_head);
16751 }
16752
16753 @ A somewhat simpler routine will multiply a dependency list
16754 by a given constant~|v|. The constant is either a |fraction| less than
16755 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
16756 convert a dependency list to a proto-dependency list.
16757 Parameters |t0| and |t1| are the list types before and after;
16758 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
16759 and |v_is_scaled=true|.
16760
16761 @c
16762 static mp_value_node mp_p_times_v (MP mp, mp_value_node p, mp_number v,
16763 quarterword t0, quarterword t1,
16764 boolean v_is_scaled) {
16765 mp_value_node r, s; /* for list manipulation */
16766 mp_number w; /* tentative coefficient */
16767 mp_number threshold;
16768 boolean scaling_down;
16769 new_number (threshold);
16770 new_number (w);
16771 if (t0 != t1)
16772 scaling_down = true;
16773 else
16774 scaling_down = (!v_is_scaled);
16775 if (t1 == mp_dependent)
16776 number_clone (threshold, half_fraction_threshold_k);
16777 else
16778 number_clone (threshold, half_scaled_threshold_k);
16779 r = (mp_value_node) mp->temp_head;
16780 while (dep_info (p) != NULL) {
16781 mp_number test;
16782 new_number (test);
16783 if (scaling_down) {
16784 take_fraction (w, v, dep_value (p));
16785 } else {
16786 take_scaled (w, v, dep_value (p));
16787 }
16788 number_clone (test, w);
16789 number_abs(test);
16790 if (number_lessequal (test, threshold)) {
16791 s = (mp_value_node) mp_link (p);
16792 mp_free_dep_node (mp, p);
16793 p = s;
16794 } else {
16795 if (number_greaterequal(test, coef_bound_k)) {
16796 mp->fix_needed = true;
16797 mp_type (dep_info (p)) = independent_needing_fix;
16798 }
16799 set_mp_link (r, (mp_node) p);
16800 r = p;
16801 set_dep_value (p, w);
16802 p = (mp_value_node) mp_link (p);
16803 }
16804 free_number (test);
16805 }
16806 set_mp_link (r, (mp_node) p);
16807 {
16808 mp_number r1;
16809 new_number (r1);
16810 if (v_is_scaled) {
16811 take_scaled (r1, dep_value (p), v);
16812 } else {
16813 take_fraction (r1, dep_value (p), v);
16814 }
16815 set_dep_value (p, r1);
16816 free_number (r1);
16817 }
16818 free_number (w);
16819 free_number (threshold);
16820 return (mp_value_node) mp_link (mp->temp_head);
16821 }
16822
16823
16824 @ Similarly, we sometimes need to divide a dependency list
16825 by a given |scaled| constant.
16826
16827 @<Declarations@>=
16828 static mp_value_node mp_p_over_v (MP mp, mp_value_node p, mp_number v, quarterword
16829 t0, quarterword t1);
16830
16831 @ @d p_over_v_threshold_k ((math_data *)mp->math)->p_over_v_threshold_t
16832
16833 @c
16834 mp_value_node mp_p_over_v (MP mp, mp_value_node p, mp_number v_orig, quarterword
16835 t0, quarterword t1) {
16836 mp_value_node r, s; /* for list manipulation */
16837 mp_number w; /* tentative coefficient */
16838 mp_number threshold;
16839 mp_number v;
16840 boolean scaling_down;
16841 new_number (v);
16842 new_number (w);
16843 new_number (threshold);
16844 number_clone (v, v_orig);
16845 if (t0 != t1)
16846 scaling_down = true;
16847 else
16848 scaling_down = false;
16849 if (t1 == mp_dependent)
16850 number_clone (threshold, half_fraction_threshold_k);
16851 else
16852 number_clone (threshold, half_scaled_threshold_k);
16853 r = (mp_value_node) mp->temp_head;
16854 while (dep_info (p) != NULL) {
16855 if (scaling_down) {
16856 mp_number x, absv;
16857 new_number (x);
16858 new_number (absv);
16859 number_clone (absv, v);
16860 number_abs (absv);
16861 if (number_less (absv, p_over_v_threshold_k)) {
16862 number_clone (x, v);
16863 convert_scaled_to_fraction (x);
16864 make_scaled (w, dep_value (p), x);
16865 } else {
16866 number_clone (x, dep_value (p));
16867 fraction_to_round_scaled (x);
16868 make_scaled (w, x, v);
16869 }
16870 free_number (x);
16871 free_number (absv);
16872 } else {
16873 make_scaled (w, dep_value (p), v);
16874 }
16875 {
16876 mp_number test;
16877 new_number (test);
16878 number_clone (test, w);
16879 number_abs(test);
16880 if (number_lessequal (test, threshold)) {
16881 s = (mp_value_node) mp_link (p);
16882 mp_free_dep_node (mp, p);
16883 p = s;
16884 } else {
16885 if (number_greaterequal (test, coef_bound_k)) {
16886 mp->fix_needed = true;
16887 mp_type (dep_info (p)) = independent_needing_fix;
16888 }
16889 set_mp_link (r, (mp_node) p);
16890 r = p;
16891 set_dep_value (p, w);
16892 p = (mp_value_node) mp_link (p);
16893 }
16894 free_number (test);
16895 }
16896 }
16897 set_mp_link (r, (mp_node) p);
16898 {
16899 mp_number ret;
16900 new_number (ret);
16901 make_scaled (ret, dep_value (p), v);
16902 set_dep_value (p, ret);
16903 free_number (ret);
16904 }
16905 free_number (v);
16906 free_number (w);
16907 free_number (threshold);
16908 return (mp_value_node) mp_link (mp->temp_head);
16909 }
16910
16911
16912 @ Here's another utility routine for dependency lists. When an independent
16913 variable becomes dependent, we want to remove it from all existing
16914 dependencies. The |p_with_x_becoming_q| function computes the
16915 dependency list of~|p| after variable~|x| has been replaced by~|q|.
16916
16917 This procedure has basically the same calling conventions as |p_plus_fq|:
16918 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
16919 final link are inherited from~|p|; and the fourth parameter tells whether
16920 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
16921 is not altered if |x| does not occur in list~|p|.
16922
16923 @c
16924 static mp_value_node mp_p_with_x_becoming_q (MP mp, mp_value_node p,
16925 mp_node x, mp_node q,
16926 quarterword t) {
16927 mp_value_node r, s; /* for list manipulation */
16928 integer sx; /* serial number of |x| */
16929 s = p;
16930 r = (mp_value_node) mp->temp_head;
16931 sx = indep_value (x);
16932 while (dep_info (s) != NULL && indep_value (dep_info (s)) > sx) {
16933 r = s;
16934 s = (mp_value_node) mp_link (s);
16935 }
16936 if (dep_info (s) == NULL || dep_info (s) != x) {
16937 return p;
16938 } else {
16939 mp_value_node ret;
16940 mp_number v1;
16941 new_number (v1);
16942 set_mp_link (mp->temp_head, (mp_node) p);
16943 set_mp_link (r, mp_link (s));
16944 number_clone (v1, dep_value (s));
16945 mp_free_dep_node (mp, s);
16946 ret = mp_p_plus_fq (mp, (mp_value_node) mp_link (mp->temp_head), v1,
16947 (mp_value_node) q, t, mp_dependent);
16948 free_number (v1);
16949 return ret;
16950 }
16951 }
16952
16953
16954 @ Here's a simple procedure that reports an error when a variable
16955 has just received a known value that's out of the required range.
16956
16957 @<Declarations@>=
16958 static void mp_val_too_big (MP mp, mp_number x);
16959
16960 @ @c
16961 static void mp_val_too_big (MP mp, mp_number x) {
16962 if (number_positive (internal_value (mp_warning_check))) {
16963 char msg[256];
16964 const char *hlp[] = {
16965 "The equation I just processed has given some variable a",
16966 "value outside of the safety range. Continue and I'll try",
16967 "to cope with that big value; but it might be dangerous.",
16968 "(Set warningcheck:=0 to suppress this message.)",
16969 NULL };
16970 mp_snprintf (msg, 256, "Value is too large (%s)", number_tostring(x));
16971 mp_error (mp, msg, hlp, true);
16972 }
16973 }
16974
16975 @ When a dependent variable becomes known, the following routine
16976 removes its dependency list. Here |p| points to the variable, and
16977 |q| points to the dependency list (which is one node long).
16978
16979 @<Declarations@>=
16980 static void mp_make_known (MP mp, mp_value_node p, mp_value_node q);
16981
16982 @ @c
16983 void mp_make_known (MP mp, mp_value_node p, mp_value_node q) {
16984 mp_variable_type t; /* the previous type */
16985 mp_number absp;
16986 new_number (absp);
16987 set_prev_dep (mp_link (q), prev_dep (p));
16988 set_mp_link (prev_dep (p), mp_link (q));
16989 t = mp_type (p);
16990 mp_type (p) = mp_known;
16991 set_value_number (p, dep_value (q));
16992 mp_free_dep_node (mp, q);
16993 number_clone (absp, value_number (p));
16994 number_abs (absp);
16995 if (number_greaterequal (absp, warning_limit_t))
16996 mp_val_too_big (mp, value_number (p));
16997 if ((number_positive(internal_value (mp_tracing_equations)))
16998 && mp_interesting (mp, (mp_node) p)) {
16999 mp_begin_diagnostic (mp);
17000 mp_print_nl (mp, "#### ");
17001 mp_print_variable_name (mp, (mp_node) p);
17002 mp_print_char (mp, xord ('='));
17003 print_number (value_number (p));
17004 mp_end_diagnostic (mp, false);
17005 }
17006 if (cur_exp_node () == (mp_node) p && mp->cur_exp.type == t) {
17007 mp->cur_exp.type = mp_known;
17008 set_cur_exp_value_number (value_number (p));
17009 mp_free_value_node (mp, (mp_node) p);
17010 }
17011 free_number (absp);
17012 }
17013
17014
17015 @ The |fix_dependencies| routine is called into action when |fix_needed|
17016 has been triggered. The program keeps a list~|s| of independent variables
17017 whose coefficients must be divided by~4.
17018
17019 In unusual cases, this fixup process might reduce one or more coefficients
17020 to zero, so that a variable will become known more or less by default.
17021
17022 @<Declarations@>=
17023 static void mp_fix_dependencies (MP mp);
17024
17025 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
17026 @c
17027 static void mp_fix_dependencies (MP mp) {
17028 mp_value_node p, q, r, s, t; /* list manipulation registers */
17029 mp_node x; /* an independent variable */
17030 r = (mp_value_node) mp_link (mp->dep_head);
17031 s = NULL;
17032 while (r != mp->dep_head) {
17033 t = r;
17034 /* Run through the dependency list for variable |t|, fixing
17035 all nodes, and ending with final link~|q| */
17036 while (1) {
17037 if (t==r) {
17038 q = (mp_value_node) dep_list(t);
17039 } else {
17040 q = (mp_value_node) mp_link (r);
17041 }
17042 x = dep_info (q);
17043 if (x == NULL)
17044 break;
17045 if (mp_type (x) <= independent_being_fixed) {
17046 if (mp_type (x) < independent_being_fixed) {
17047 p = mp_get_dep_node (mp);
17048 set_mp_link (p, (mp_node) s);
17049 s = p;
17050 set_dep_info (s, x);
17051 mp_type (x) = independent_being_fixed;
17052 }
17053 set_dep_value (q, dep_value (q));
17054 number_divide_int (dep_value (q), 4);
17055 if (number_zero(dep_value (q))) {
17056 set_mp_link (r, mp_link (q));
17057 mp_free_dep_node (mp, q);
17058 q = r;
17059 }
17060 }
17061 r = q;
17062 }
17063
17064 r = (mp_value_node) mp_link (q);
17065 if (q == (mp_value_node) dep_list (t))
17066 mp_make_known (mp, t, q);
17067 }
17068 while (s != NULL) {
17069 p = (mp_value_node) mp_link (s);
17070 x = dep_info (s);
17071 mp_free_dep_node (mp, s);
17072 s = p;
17073 mp_type (x) = mp_independent;
17074 set_indep_scale (x, indep_scale (x) + 2);
17075 }
17076 mp->fix_needed = false;
17077 }
17078
17079
17080 @ The |new_dep| routine installs a dependency list~|p| based on the value node~|q|,
17081 linking it into the list of all known dependencies. It replaces |q| with the new
17082 dependency node. We assume that |dep_final| points to the final node of list~|p|.
17083
17084 @c
17085 static void mp_new_dep (MP mp, mp_node q, mp_variable_type newtype,
17086 mp_value_node p) {
17087 mp_node r; /* what used to be the first dependency */
17088 FUNCTION_TRACE4 ("mp_new_dep(%p,%d,%p)\n", q, newtype, p);
17089 mp_type (q) = newtype;
17090 set_dep_list (q, p);
17091 set_prev_dep (q, (mp_node) mp->dep_head);
17092 r = mp_link (mp->dep_head);
17093 set_mp_link (mp->dep_final, r);
17094 set_prev_dep (r, (mp_node) mp->dep_final);
17095 set_mp_link (mp->dep_head, q);
17096 }
17097
17098
17099 @ Here is one of the ways a dependency list gets started.
17100 The |const_dependency| routine produces a list that has nothing but
17101 a constant term.
17102
17103 @c
17104 static mp_value_node mp_const_dependency (MP mp, mp_number v) {
17105 mp->dep_final = mp_get_dep_node (mp);
17106 set_dep_value (mp->dep_final, v);
17107 set_dep_info (mp->dep_final, NULL);
17108 FUNCTION_TRACE3 ("%p = mp_const_dependency(%d)\n", mp->dep_final, number_to_scaled (v));
17109 return mp->dep_final;
17110 }
17111
17112
17113 @ And here's a more interesting way to start a dependency list from scratch:
17114 The parameter to |single_dependency| is the location of an
17115 independent variable~|x|, and the result is the simple dependency list
17116 `|x+0|'.
17117
17118 In the unlikely event that the given independent variable has been doubled so
17119 often that we can't refer to it with a nonzero coefficient,
17120 |single_dependency| returns the simple list `0'. This case can be
17121 recognized by testing that the returned list pointer is equal to
17122 |dep_final|.
17123
17124 @d two_to_the(A) (1<<(unsigned)(A))
17125
17126 @c
17127 static mp_value_node mp_single_dependency (MP mp, mp_node p) {
17128 mp_value_node q, rr; /* the new dependency list */
17129 integer m; /* the number of doublings */
17130 m = indep_scale (p);
17131 if (m > 28) {
17132 q = mp_const_dependency (mp, zero_t);
17133 } else {
17134 q = mp_get_dep_node (mp);
17135 set_dep_value (q, zero_t);
17136 set_number_from_scaled (dep_value (q), (integer) two_to_the (28 - m));
17137 set_dep_info (q, p);
17138 rr = mp_const_dependency (mp, zero_t);
17139 set_mp_link (q, (mp_node) rr);
17140 }
17141 FUNCTION_TRACE3 ("%p = mp_single_dependency(%p)\n", q, p);
17142 return q;
17143 }
17144
17145
17146 @ We sometimes need to make an exact copy of a dependency list.
17147
17148 @c
17149 static mp_value_node mp_copy_dep_list (MP mp, mp_value_node p) {
17150 mp_value_node q; /* the new dependency list */
17151 FUNCTION_TRACE2 ("mp_copy_dep_list(%p)\n", p);
17152 q = mp_get_dep_node (mp);
17153 mp->dep_final = q;
17154 while (1) {
17155 set_dep_info (mp->dep_final, dep_info (p));
17156 set_dep_value (mp->dep_final, dep_value (p));
17157 if (dep_info (mp->dep_final) == NULL)
17158 break;
17159 set_mp_link (mp->dep_final, (mp_node) mp_get_dep_node (mp));
17160 mp->dep_final = (mp_value_node) mp_link (mp->dep_final);
17161 p = (mp_value_node) mp_link (p);
17162 }
17163 return q;
17164 }
17165
17166
17167 @ But how do variables normally become known? Ah, now we get to the heart of the
17168 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
17169 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
17170 appears. It equates this list to zero, by choosing an independent variable
17171 with the largest coefficient and making it dependent on the others. The
17172 newly dependent variable is eliminated from all current dependencies,
17173 thereby possibly making other dependent variables known.
17174
17175 The given list |p| is, of course, totally destroyed by all this processing.
17176
17177 @c
17178 static mp_value_node find_node_with_largest_coefficient(MP mp, mp_value_node p, mp_number *v);
17179 static void display_new_dependency (MP mp, mp_value_node p, mp_node x, integer n);
17180 static void change_to_known (MP mp, mp_value_node p, mp_node x, mp_value_node final_node, integer n);
17181 static mp_value_node divide_p_by_minusv_removing_q (MP mp, mp_value_node p, mp_value_node q,
17182 mp_value_node *final_node, mp_number v, quarterword t);
17183 static mp_value_node divide_p_by_2_n (MP mp, mp_value_node p, integer n);
17184 static void mp_linear_eq (MP mp, mp_value_node p, quarterword t) {
17185 mp_value_node r; /* for link manipulation */
17186 mp_node x; /* the variable that loses its independence */
17187 integer n; /* the number of times |x| had been halved */
17188 mp_number v; /* the coefficient of |x| in list |p| */
17189 mp_value_node prev_r; /* lags one step behind |r| */
17190 mp_value_node final_node; /* the constant term of the new dependency list */
17191 mp_value_node qq;
17192 new_number (v);
17193 FUNCTION_TRACE3 ("mp_linear_eq(%p,%d)\n", p, t);
17194 qq = find_node_with_largest_coefficient(mp, p, &v);
17195 x = dep_info (qq);
17196 n = indep_scale (x);
17197 p = divide_p_by_minusv_removing_q(mp, p, qq, &final_node, v, t);
17198 if (number_positive (internal_value (mp_tracing_equations))) {
17199 display_new_dependency(mp,p,(mp_node)x,n);
17200 }
17201 prev_r = (mp_value_node) mp->dep_head;
17202 r = (mp_value_node) mp_link (mp->dep_head);
17203 while (r != mp->dep_head) {
17204 mp_value_node s = (mp_value_node) dep_list (r);
17205 mp_value_node q = mp_p_with_x_becoming_q (mp, s, x, (mp_node) p, mp_type (r));
17206 if (dep_info (q) == NULL) {
17207 mp_make_known (mp, r, q);
17208 } else {
17209 set_dep_list (r, q);
17210 do {
17211 q = (mp_value_node) mp_link (q);
17212 } while (dep_info (q) != NULL);
17213 prev_r = q;
17214 }
17215 r = (mp_value_node) mp_link (prev_r);
17216 }
17217 if (n > 0) {
17218 p = divide_p_by_2_n(mp, p, n);
17219 }
17220 change_to_known(mp,p,(mp_node)x,final_node,n);
17221 if (mp->fix_needed)
17222 mp_fix_dependencies (mp);
17223 free_number (v);
17224 }
17225
17226
17227 @ @c
17228 static mp_value_node find_node_with_largest_coefficient(MP mp, mp_value_node p, mp_number *v) {
17229 mp_number vabs; /* its absolute value of v*/
17230 mp_number rabs; /* the absolute value of |dep_value(r)| */
17231 mp_value_node q = p;
17232 mp_value_node r = (mp_value_node) mp_link (p);
17233 new_number (vabs);
17234 new_number (rabs);
17235 number_clone (*v, dep_value (q));
17236 while (dep_info (r) != NULL) {
17237 number_clone (vabs, *v);
17238 number_abs (vabs);
17239 number_clone (rabs, dep_value (r));
17240 number_abs (rabs);
17241 if (number_greater (rabs, vabs)) {
17242 q = r;
17243 number_clone (*v, dep_value (r));
17244 }
17245 r = (mp_value_node) mp_link (r);
17246 }
17247 free_number (vabs);
17248 free_number (rabs);
17249 return q;
17250 }
17251
17252
17253 @ Here we want to change the coefficients from |scaled| to |fraction|,
17254 except in the constant term. In the common case of a trivial equation
17255 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
17256
17257 @c
17258 static mp_value_node divide_p_by_minusv_removing_q (MP mp, mp_value_node p, mp_value_node q,
17259 mp_value_node *final_node, mp_number v, quarterword t) {
17260 mp_value_node r; /* for link manipulation */
17261 mp_value_node s;
17262 s = (mp_value_node) mp->temp_head;
17263 set_mp_link (s, (mp_node) p);
17264 r = p;
17265 do {
17266 if (r == q) {
17267 set_mp_link (s, mp_link (r));
17268 mp_free_dep_node (mp, r);
17269 } else {
17270 mp_number w; /* a tentative coefficient */
17271 mp_number absw;
17272 new_number (w);
17273 new_number (absw);
17274 make_fraction (w, dep_value (r), v);
17275 number_clone (absw, w);
17276 number_abs (absw);
17277 if (number_lessequal (absw, half_fraction_threshold_k)) {
17278 set_mp_link (s, mp_link (r));
17279 mp_free_dep_node (mp, r);
17280 } else {
17281 number_negate (w);
17282 set_dep_value (r, w);
17283 s = r;
17284 }
17285 free_number(w);
17286 free_number (absw);
17287 }
17288 r = (mp_value_node) mp_link (s);
17289 } while (dep_info (r) != NULL);
17290
17291 if (t == mp_proto_dependent) {
17292 mp_number ret;
17293 new_number (ret);
17294 make_scaled (ret, dep_value (r), v);
17295 number_negate (ret);
17296 set_dep_value (r, ret);
17297 free_number (ret);
17298 } else if (number_to_scaled (v) != -number_to_scaled (fraction_one_t)) {
17299 mp_number ret;
17300 new_fraction (ret);
17301 make_fraction (ret, dep_value (r), v);
17302 number_negate (ret);
17303 set_dep_value (r, ret);
17304 free_number (ret);
17305 }
17306 *final_node = r;
17307 return (mp_value_node) mp_link (mp->temp_head);
17308 }
17309
17310
17311 @ @c
17312 static void display_new_dependency (MP mp, mp_value_node p, mp_node x, integer n) {
17313 if (mp_interesting (mp, x)) {
17314 int w0;
17315 mp_begin_diagnostic (mp);
17316 mp_print_nl (mp, "## ");
17317 mp_print_variable_name (mp, x);
17318 w0 = n;
17319 while (w0 > 0) {
17320 mp_print (mp, "*4");
17321 w0 = w0 - 2;
17322 }
17323 mp_print_char (mp, xord ('='));
17324 mp_print_dependency (mp, p, mp_dependent);
17325 mp_end_diagnostic (mp, false);
17326 }
17327 }
17328
17329 @ The |n > 0| test is repeated here because it is of vital importance to the
17330 function's functioning.
17331
17332 @c
17333 static mp_value_node divide_p_by_2_n (MP mp, mp_value_node p, integer n) {
17334 mp_value_node pp = NULL;
17335 if (n > 0) {
17336 /* Divide list |p| by $2^n$ */
17337 mp_value_node r;
17338 mp_value_node s;
17339 mp_number absw;
17340 mp_number w; /* a tentative coefficient */
17341 new_number (w);
17342 new_number (absw);
17343 s = (mp_value_node) mp->temp_head;
17344 set_mp_link (mp->temp_head, (mp_node) p);
17345 r = p;
17346 do {
17347 if (n > 30) {
17348 set_number_to_zero (w);
17349 } else {
17350 number_clone (w, dep_value (r));
17351 number_divide_int (w, two_to_the (n));
17352 }
17353 number_clone (absw, w);
17354 number_abs (absw);
17355 if (number_lessequal(absw, half_fraction_threshold_k) && (dep_info (r) != NULL)) {
17356 set_mp_link (s, mp_link (r));
17357 mp_free_dep_node (mp, r);
17358 } else {
17359 set_dep_value (r, w);
17360 s = r;
17361 }
17362 r = (mp_value_node) mp_link (s);
17363 } while (dep_info (s) != NULL);
17364 pp = (mp_value_node) mp_link (mp->temp_head);
17365 free_number (absw);
17366 free_number (w);
17367 }
17368 return pp;
17369 }
17370
17371 @ @c
17372 static void change_to_known (MP mp, mp_value_node p, mp_node x, mp_value_node final_node, integer n) {
17373 (void)n;
17374 if (dep_info (p) == NULL) {
17375 mp_number absx;
17376 new_number (absx);
17377 mp_type (x) = mp_known;
17378 set_value_number (x, dep_value (p));
17379 number_clone (absx, value_number (x));
17380 number_abs (absx);
17381 if (number_greaterequal (absx, warning_limit_t))
17382 mp_val_too_big (mp, value_number (x));
17383 free_number (absx);
17384 mp_free_dep_node (mp, p);
17385 if (cur_exp_node () == x && mp->cur_exp.type == mp_independent) {
17386 set_cur_exp_value_number (value_number (x));
17387 mp->cur_exp.type = mp_known;
17388 mp_free_value_node (mp, x);
17389 }
17390 } else {
17391 mp->dep_final = final_node;
17392 mp_new_dep (mp, x, mp_dependent, p);
17393 if (cur_exp_node () == x && mp->cur_exp.type == mp_independent) {
17394 mp->cur_exp.type = mp_dependent;
17395 }
17396 }
17397 }
17398
17399 @* Dynamic nonlinear equations.
17400 Variables of numeric type are maintained by the general scheme of
17401 independent, dependent, and known values that we have just studied;
17402 and the components of pair and transform variables are handled in the
17403 same way. But \MP\ also has five other types of values: \&{boolean},
17404 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
17405
17406 Equations are allowed between nonlinear quantities, but only in a
17407 simple form. Two variables that haven't yet been assigned values are
17408 either equal to each other, or they're not.
17409
17410 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
17411 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
17412 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
17413 |NULL| (which means that no other variables are equivalent to this one), or
17414 it points to another variable of the same undefined type. The pointers in the
17415 latter case form a cycle of nodes, which we shall call a ``ring.''
17416 Rings of undefined variables may include capsules, which arise as
17417 intermediate results within expressions or as \&{expr} parameters to macros.
17418
17419 When one member of a ring receives a value, the same value is given to
17420 all the other members. In the case of paths and pictures, this implies
17421 making separate copies of a potentially large data structure; users should
17422 restrain their enthusiasm for such generality, unless they have lots and
17423 lots of memory space.
17424
17425 @ The following procedure is called when a capsule node is being
17426 added to a ring (e.g., when an unknown variable is mentioned in an expression).
17427
17428 @c
17429 static mp_node mp_new_ring_entry (MP mp, mp_node p) {
17430 mp_node q; /* the new capsule node */
17431 q = mp_get_value_node (mp);
17432 mp_name_type (q) = mp_capsule;
17433 mp_type (q) = mp_type (p);
17434 if (value_node (p) == NULL)
17435 set_value_node (q, p);
17436 else
17437 set_value_node (q, value_node (p));
17438 set_value_node (p, q);
17439 return q;
17440 }
17441
17442
17443 @ Conversely, we might delete a capsule or a variable before it becomes known.
17444 The following procedure simply detaches a quantity from its ring,
17445 without recycling the storage.
17446
17447 @<Declarations@>=
17448 static void mp_ring_delete (MP mp, mp_node p);
17449
17450 @ @c
17451 void mp_ring_delete (MP mp, mp_node p) {
17452 mp_node q;
17453 (void) mp;
17454 q = value_node (p);
17455 if (q != NULL && q != p) {
17456 while (value_node (q) != p)
17457 q = value_node (q);
17458 set_value_node (q, value_node (p));
17459 }
17460 }
17461
17462
17463 @ Eventually there might be an equation that assigns values to all of the
17464 variables in a ring. The |nonlinear_eq| subroutine does the necessary
17465 propagation of values.
17466
17467 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
17468 value, it will soon be recycled.
17469
17470 @c
17471 static void mp_nonlinear_eq (MP mp, mp_value v, mp_node p, boolean flush_p) {
17472 mp_variable_type t; /* the type of ring |p| */
17473 mp_node q, r; /* link manipulation registers */
17474 t = (mp_type (p) - unknown_tag);
17475 q = value_node (p);
17476 if (flush_p)
17477 mp_type (p) = mp_vacuous;
17478 else
17479 p = q;
17480 do {
17481 r = value_node (q);
17482 mp_type (q) = t;
17483 switch (t) {
17484 case mp_boolean_type:
17485 set_value_number (q, v.data.n);
17486 break;
17487 case mp_string_type:
17488 set_value_str (q, v.data.str);
17489 add_str_ref (v.data.str);
17490 break;
17491 case mp_pen_type:
17492 set_value_knot (q, copy_pen (v.data.p));
17493 break;
17494 case mp_path_type:
17495 set_value_knot (q, mp_copy_path (mp, v.data.p));
17496 break;
17497 case mp_picture_type:
17498 set_value_node (q, v.data.node);
17499 add_edge_ref (v.data.node);
17500 break;
17501 default:
17502 break;
17503 } /* there ain't no more cases */
17504 q = r;
17505 } while (q != p);
17506 }
17507
17508
17509 @ If two members of rings are equated, and if they have the same type,
17510 the |ring_merge| procedure is called on to make them equivalent.
17511
17512 @c
17513 static void mp_ring_merge (MP mp, mp_node p, mp_node q) {
17514 mp_node r; /* traverses one list */
17515 r = value_node (p);
17516 while (r != p) {
17517 if (r == q) {
17518 exclaim_redundant_equation(mp);
17519 return;
17520 }
17521 r = value_node (r);
17522 }
17523 r = value_node (p);
17524 set_value_node (p, value_node (q));
17525 set_value_node (q, r);
17526 }
17527
17528
17529 @ @c
17530 static void exclaim_redundant_equation (MP mp) {
17531 const char *hlp[] = {
17532 "I already knew that this equation was true.",
17533 "But perhaps no harm has been done; let's continue.",
17534 NULL };
17535 mp_back_error (mp, "Redundant equation", hlp, true);
17536 mp_get_x_next (mp);
17537 }
17538
17539 @ @<Declarations@>=
17540 static void exclaim_redundant_equation (MP mp);
17541
17542 @* Introduction to the syntactic routines.
17543 Let's pause a moment now and try to look at the Big Picture.
17544 The \MP\ program consists of three main parts: syntactic routines,
17545 semantic routines, and output routines. The chief purpose of the
17546 syntactic routines is to deliver the user's input to the semantic routines,
17547 while parsing expressions and locating operators and operands. The
17548 semantic routines act as an interpreter responding to these operators,
17549 which may be regarded as commands. And the output routines are
17550 periodically called on to produce compact font descriptions that can be
17551 used for typesetting or for making interim proof drawings. We have
17552 discussed the basic data structures and many of the details of semantic
17553 operations, so we are good and ready to plunge into the part of \MP\ that
17554 actually controls the activities.
17555
17556 Our current goal is to come to grips with the |get_next| procedure,
17557 which is the keystone of \MP's input mechanism. Each call of |get_next|
17558 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
17559 representing the next input token.
17560 $$\vbox{\halign{#\hfil\cr
17561 \hbox{|cur_cmd| denotes a command code from the long list of codes
17562 given earlier;}\cr
17563 \hbox{|cur_mod| denotes a modifier or operand of the command code;}\cr
17564 \hbox{|cur_sym| is the hash address of the symbolic token that was
17565 just scanned,}\cr
17566 \hbox{\qquad or zero in the case of a numeric or string
17567 or capsule token.}\cr}}$$
17568 Underlying this external behavior of |get_next| is all the machinery
17569 necessary to convert from character files to tokens. At a given time we
17570 may be only partially finished with the reading of several files (for
17571 which \&{input} was specified), and partially finished with the expansion
17572 of some user-defined macros and/or some macro parameters, and partially
17573 finished reading some text that the user has inserted online,
17574 and so on. When reading a character file, the characters must be
17575 converted to tokens; comments and blank spaces must
17576 be removed, numeric and string tokens must be evaluated.
17577
17578 To handle these situations, which might all be present simultaneously,
17579 \MP\ uses various stacks that hold information about the incomplete
17580 activities, and there is a finite state control for each level of the
17581 input mechanism. These stacks record the current state of an implicitly
17582 recursive process, but the |get_next| procedure is not recursive.
17583
17584 @d cur_cmd() (unsigned)(mp->cur_mod_->type) /* TODO: In C23 check if we can remove (unsigned) */
17585 @d set_cur_cmd(A) mp->cur_mod_->type=(A)
17586 @d cur_mod_int() number_to_int (mp->cur_mod_->data.n) /* operand of current command */
17587 @d cur_mod() number_to_scaled (mp->cur_mod_->data.n) /* operand of current command */
17588 @d cur_mod_number() mp->cur_mod_->data.n /* operand of current command */
17589 @d set_cur_mod(A) set_number_from_scaled (mp->cur_mod_->data.n, (A))
17590 @d set_cur_mod_number(A) number_clone (mp->cur_mod_->data.n, (A))
17591 @d cur_mod_node() mp->cur_mod_->data.node
17592 @d set_cur_mod_node(A) mp->cur_mod_->data.node=(A)
17593 @d cur_mod_str() mp->cur_mod_->data.str
17594 @d set_cur_mod_str(A) mp->cur_mod_->data.str=(A)
17595 @d cur_sym() mp->cur_mod_->data.sym
17596 @d set_cur_sym(A) mp->cur_mod_->data.sym=(A)
17597 @d cur_sym_mod() mp->cur_mod_->name_type
17598 @d set_cur_sym_mod(A) mp->cur_mod_->name_type=(A)
17599
17600 @<Glob...@>=
17601 mp_node cur_mod_; /* current command, symbol, and its operands */
17602
17603 @ @<Initialize table...@>=
17604 mp->cur_mod_ = mp_get_symbolic_node(mp);
17605
17606 @ @<Free table...@>=
17607 mp_free_symbolic_node(mp, mp->cur_mod_);
17608
17609 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
17610 command code and its modifier.
17611 It consists of a rather tedious sequence of print
17612 commands, and most of it is essentially an inverse to the |primitive|
17613 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
17614 all of this procedure appears elsewhere in the program, together with the
17615 corresponding |primitive| calls.
17616
17617 @<Declarations@>=
17618 static void mp_print_cmd_mod (MP mp, mpinteger64 c, mpinteger64 m);
17619
17620 @ @c
17621 void mp_print_cmd_mod (MP mp, mpinteger64 c, mpinteger64 m) {
17622 switch (c) {
17623 @t\4@>@<Cases of |print_cmd_mod| for symbolic printing of primitives@>@;
17624 default:
17625 mp_print (mp, "[unknown command code!]");
17626 break;
17627 }
17628 }
17629
17630
17631 @ Here is a procedure that displays a given command in braces, in the
17632 user's transcript file.
17633
17634 @d show_cur_cmd_mod mp_show_cmd_mod(mp, cur_cmd(),cur_mod())
17635
17636 @c
17637 static void mp_show_cmd_mod (MP mp, mpinteger64 c, mpinteger64 m) {
17638 mp_begin_diagnostic (mp);
17639 mp_print_nl (mp, "{");
17640 mp_print_cmd_mod (mp, c, m);
17641 mp_print_char (mp, xord ('}'));
17642 mp_end_diagnostic (mp, false);
17643 }
17644
17645
17646 @* Input stacks and states.
17647 The state of \MP's input mechanism appears in the input stack, whose
17648 entries are records with five fields, called |index|, |start|, |loc|,
17649 |limit|, and |name|. The top element of this stack is maintained in a
17650 global variable for which no subscripting needs to be done; the other
17651 elements of the stack appear in an array. Hence the stack is declared thus:
17652
17653 @<Types...@>=
17654 typedef struct {
17655 char *long_name_field;
17656 halfword start_field, loc_field, limit_field;
17657 mp_node nstart_field, nloc_field;
17658 mp_string name_field;
17659 quarterword index_field;
17660 } in_state_record;
17661
17662 @ @<Glob...@>=
17663 in_state_record *input_stack;
17664 integer input_ptr; /* first unused location of |input_stack| */
17665 integer max_in_stack; /* largest value of |input_ptr| when pushing */
17666 in_state_record cur_input; /* the ``top'' input state */
17667 int stack_size; /* maximum number of simultaneous input sources */
17668
17669 @ @<Allocate or initialize ...@>=
17670 mp->stack_size = 16;
17671 mp->input_stack = xmalloc ((mp->stack_size + 1), sizeof (in_state_record));
17672
17673 @ @<Dealloc variables@>=
17674 xfree (mp->input_stack);
17675
17676 @ We've already defined the special variable |loc==cur_input.loc_field|
17677 in our discussion of basic input-output routines. The other components of
17678 |cur_input| are defined in the same way:
17679
17680 @d iindex mp->cur_input.index_field /* reference for buffer information */
17681 @d start mp->cur_input.start_field /* starting position in |buffer| */
17682 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
17683 @d name mp->cur_input.name_field /* name of the current file */
17684
17685 @ Let's look more closely now at the five control variables
17686 (|index|,~|start|,~|loc|,~|limit|,~|name|),
17687 assuming that \MP\ is reading a line of characters that have been input
17688 from some file or from the user's terminal. There is an array called
17689 |buffer| that acts as a stack of all lines of characters that are
17690 currently being read from files, including all lines on subsidiary
17691 levels of the input stack that are not yet completed. \MP\ will return to
17692 the other lines when it is finished with the present input file.
17693
17694 (Incidentally, on a machine with byte-oriented addressing, it would be
17695 appropriate to combine |buffer| with the |str_pool| array,
17696 letting the buffer entries grow downward from the top of the string pool
17697 and checking that these two tables don't bump into each other.)
17698
17699 The line we are currently working on begins in position |start| of the
17700 buffer; the next character we are about to read is |buffer[loc]|; and
17701 |limit| is the location of the last character present. We always have
17702 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
17703 that the end of a line is easily sensed.
17704
17705 The |name| variable is a string number that designates the name of
17706 the current file, if we are reading an ordinary text file. Special codes
17707 |is_term..max_spec_src| indicate other sources of input text.
17708
17709 @d is_term (mp_string)0 /* |name| value when reading from the terminal for normal input */
17710 @d is_read (mp_string)1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
17711 @d is_scantok (mp_string)2 /* |name| value when reading text generated by \&{scantokens} */
17712 @d max_spec_src is_scantok
17713
17714 @ Additional information about the current line is available via the
17715 |index| variable, which counts how many lines of characters are present
17716 in the buffer below the current level. We have |index=0| when reading
17717 from the terminal and prompting the user for each line; then if the user types,
17718 e.g., `\.{input figs}', we will have |index=1| while reading
17719 the file \.{figs.mp}. However, it does not follow that |index| is the
17720 same as the input stack pointer, since many of the levels on the input
17721 stack may come from token lists and some |index| values may correspond
17722 to \.{MPX} files that are not currently on the stack.
17723
17724 The global variable |in_open| is equal to the highest |index| value counting
17725 \.{MPX} files but excluding token-list input levels. Thus, the number of
17726 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
17727 when we are not reading a token list.
17728
17729 If we are not currently reading from the terminal,
17730 we are reading from the file variable |input_file[index]|. We use
17731 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
17732 and |cur_file| as an abbreviation for |input_file[index]|.
17733
17734 When \MP\ is not reading from the terminal, the global variable |line| contains
17735 the line number in the current file, for use in error messages. More precisely,
17736 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
17737 the line number for each file in the |input_file| array.
17738
17739 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
17740 array so that the name doesn't get lost when the file is temporarily removed
17741 from the input stack.
17742 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
17743 and it contains translated \TeX\ pictures for |input_file[k-1]|.
17744 Since this is not an \.{MPX} file, we have
17745 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
17746 This |name| field is set to |finished| when |input_file[k]| is completely
17747 read.
17748
17749 If more information about the input state is needed, it can be
17750 included in small arrays like those shown here. For example,
17751 the current page or segment number in the input file might be put
17752 into a variable |page|, that is really a macro for the current entry
17753 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
17754 by analogy with |line_stack|.
17755 @^system dependencies@>
17756
17757 @d terminal_input (name==is_term) /* are we reading from the terminal? */
17758 @d cur_file mp->input_file[iindex] /* the current |void *| variable */
17759 @d line mp->line_stack[iindex] /* current line number in the current source file */
17760 @d in_ext mp->inext_stack[iindex] /* a string used to construct \.{MPX} file names */
17761 @d in_name mp->iname_stack[iindex] /* a string used to construct \.{MPX} file names */
17762 @d in_area mp->iarea_stack[iindex] /* another string for naming \.{MPX} files */
17763 @d absent (mp_string)1 /* |name_field| value for unused |mpx_in_stack| entries */
17764 @d mpx_reading (mp->mpx_name[iindex]>absent)
17765 /* when reading a file, is it an \.{MPX} file? */
17766 @d mpx_finished 0
17767 /* |name_field| value when the corresponding \.{MPX} file is finished */
17768
17769 @<Glob...@>=
17770 integer in_open; /* the number of lines in the buffer, less one */
17771 integer in_open_max; /* highest value of |in_open| ever seen */
17772 unsigned int open_parens; /* the number of open text files */
17773 void **input_file;
17774 mpinteger64 *line_stack; /* the line number for each file */
17775 char **inext_stack; /* used for naming \.{MPX} files */
17776 char **iname_stack; /* used for naming \.{MPX} files */
17777 char **iarea_stack; /* used for naming \.{MPX} files */
17778 mp_string *mpx_name;
17779
17780 @ @<Declarations@>=
17781 static void mp_reallocate_input_stack (MP mp, int newsize);
17782
17783 @ @c
17784 static void mp_reallocate_input_stack (MP mp, int newsize) {
17785 int k;
17786 int n = newsize +1;
17787 XREALLOC (mp->input_file, n, void *);
17788 XREALLOC (mp->line_stack, n, mpinteger64);
17789 XREALLOC (mp->inext_stack, n, char *);
17790 XREALLOC (mp->iname_stack, n, char *);
17791 XREALLOC (mp->iarea_stack, n, char *);
17792 XREALLOC (mp->mpx_name, n, mp_string);
17793 for (k = mp->max_in_open; k <= n; k++) {
17794 mp->input_file[k] = NULL;
17795 mp->line_stack[k] = 0;
17796 mp->inext_stack[k] = NULL;
17797 mp->iname_stack[k] = NULL;
17798 mp->iarea_stack[k] = NULL;
17799 mp->mpx_name[k] = NULL;
17800 }
17801 mp->max_in_open = newsize;
17802 }
17803
17804
17805 @ This has to be more than |file_bottom|, so:
17806 @<Allocate or ...@>=
17807 mp_reallocate_input_stack (mp, file_bottom+4);
17808
17809 @ @<Dealloc variables@>=
17810 {
17811 int l;
17812 for (l = 0; l <= mp->max_in_open; l++) {
17813 xfree (mp->inext_stack[l]);
17814 xfree (mp->iname_stack[l]);
17815 xfree (mp->iarea_stack[l]);
17816 }
17817 }
17818 xfree (mp->input_file);
17819 xfree (mp->line_stack);
17820 xfree (mp->inext_stack);
17821 xfree (mp->iname_stack);
17822 xfree (mp->iarea_stack);
17823 xfree (mp->mpx_name);
17824
17825
17826 @ However, all this discussion about input state really applies only to the
17827 case that we are inputting from a file. There is another important case,
17828 namely when we are currently getting input from a token list. In this case
17829 |iindex>max_in_open|, and the conventions about the other state variables
17830 are different:
17831
17832 \yskip\hang|nloc| is a pointer to the current node in the token list, i.e.,
17833 the node that will be read next. If |nloc=NULL|, the token list has been
17834 fully read.
17835
17836 \yskip\hang|start| points to the first node of the token list; this node
17837 may or may not contain a reference count, depending on the type of token
17838 list involved.
17839
17840 \yskip\hang|token_type|, which takes the place of |iindex| in the
17841 discussion above, is a code number that explains what kind of token list
17842 is being scanned.
17843
17844 \yskip\hang|name| points to the |eqtb| address of the control sequence
17845 being expanded, if the current token list is a macro not defined by
17846 \&{vardef}. Macros defined by \&{vardef} have |name=NULL|; their name
17847 can be deduced by looking at their first two parameters.
17848
17849 \yskip\hang|param_start|, which takes the place of |limit|, tells where
17850 the parameters of the current macro or loop text begin in the |param_stack|.
17851
17852 \yskip\noindent The |token_type| can take several values, depending on
17853 where the current token list came from:
17854
17855 \yskip
17856 \indent|forever_text|, if the token list being scanned is the body of
17857 a \&{forever} loop;
17858
17859 \indent|loop_text|, if the token list being scanned is the body of
17860 a \&{for} or \&{forsuffixes} loop;
17861
17862 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
17863
17864 \indent|backed_up|, if the token list being scanned has been inserted as
17865 `to be read again'.
17866
17867 \indent|inserted|, if the token list being scanned has been inserted as
17868 part of error recovery;
17869
17870 \indent|macro|, if the expansion of a user-defined symbolic token is being
17871 scanned.
17872
17873 \yskip\noindent
17874 The token list begins with a reference count if and only if |token_type=
17875 macro|.
17876 @^reference counts@>
17877
17878 @d nloc mp->cur_input.nloc_field /* location of next node node */
17879 @d nstart mp->cur_input.nstart_field /* location of next node node */
17880
17881 @d token_type iindex /* type of current token list */
17882 @d token_state (iindex<=macro) /* are we scanning a token list? */
17883 @d file_state (iindex>macro) /* are we scanning a file line? */
17884 @d param_start limit /* base of macro parameters in |param_stack| */
17885 @d forever_text 0 /* |token_type| code for loop texts */
17886 @d loop_text 1 /* |token_type| code for loop texts */
17887 @d parameter 2 /* |token_type| code for parameter texts */
17888 @d backed_up 3 /* |token_type| code for texts to be reread */
17889 @d inserted 4 /* |token_type| code for inserted texts */
17890 @d macro 5 /* |token_type| code for macro replacement texts */
17891 @d file_bottom 6 /* lowest file code */
17892
17893 @ The |param_stack| is an auxiliary array used to hold pointers to the token
17894 lists for parameters at the current level and subsidiary levels of input.
17895 This stack grows at a different rate from the others, and is dynamically reallocated
17896 when needed.
17897
17898 @<Glob...@>=
17899 mp_node *param_stack; /* token list pointers for parameters */
17900 integer param_ptr; /* first unused entry in |param_stack| */
17901 integer max_param_stack; /* largest value of |param_ptr| */
17902
17903 @ @<Allocate or initialize ...@>=
17904 mp->param_stack = xmalloc ((mp->param_size + 1), sizeof (mp_node));
17905
17906 @ @c
17907 static void mp_check_param_size (MP mp, int k) {
17908 while (k >= mp->param_size) {
17909 XREALLOC (mp->param_stack, (k + k / 4), mp_node);
17910 mp->param_size = k + k / 4;
17911 }
17912 }
17913
17914
17915 @ @<Dealloc variables@>=
17916 xfree (mp->param_stack);
17917
17918 @ Notice that the |line| isn't valid when |token_state| is true because it
17919 depends on |iindex|. If we really need to know the line number for the
17920 topmost file in the iindex stack we use the following function. If a page
17921 number or other information is needed, this routine should be modified to
17922 compute it as well.
17923 @^system dependencies@>
17924
17925 @<Declarations@>=
17926 static mpinteger64 mp_true_line (MP mp);
17927
17928 @ @c
17929 mpinteger64 mp_true_line (MP mp) {
17930 int k; /* an index into the input stack */
17931 if (file_state && (name > max_spec_src)) {
17932 return line;
17933 } else {
17934 k = mp->input_ptr;
17935 while ((k > 0) && @|
17936 ((mp->input_stack[(k - 1)].index_field < file_bottom) || @|
17937 (mp->input_stack[(k - 1)].name_field <= max_spec_src))) {
17938 decr (k);
17939 }
17940 return (k > 0 ? mp->line_stack[(k - 1) + file_bottom] : 0);
17941 }
17942 }
17943
17944
17945 @ Thus, the ``current input state'' can be very complicated indeed; there
17946 can be many levels and each level can arise in a variety of ways. The
17947 |show_context| procedure, which is used by \MP's error-reporting routine to
17948 print out the current input state on all levels down to the most recent
17949 line of characters from an input file, illustrates most of these conventions.
17950 The global variable |file_ptr| contains the lowest level that was
17951 displayed by this procedure.
17952
17953 @<Glob...@>=
17954 integer file_ptr; /* shallowest level shown by |show_context| */
17955
17956 @ The status at each level is indicated by printing two lines, where the first
17957 line indicates what was read so far and the second line shows what remains
17958 to be read. The context is cropped, if necessary, so that the first line
17959 contains at most |half_error_line| characters, and the second contains
17960 at most |error_line|. Non-current input levels whose |token_type| is
17961 `|backed_up|' are shown only if they have not been fully read.
17962
17963 @c
17964 void mp_show_context (MP mp) { /* prints where the scanner is */
17965 unsigned old_setting; /* saved |selector| setting */
17966 @<Local variables for formatting calculations@>;
17967 mp->file_ptr = mp->input_ptr;
17968 mp->input_stack[mp->file_ptr] = mp->cur_input;
17969 /* store current state */
17970 while (1) {
17971 mp->cur_input = mp->input_stack[mp->file_ptr]; /* enter into the context */
17972 @<Display the current context@>;
17973 if (file_state)
17974 if ((name > max_spec_src) || (mp->file_ptr == 0))
17975 break;
17976 decr (mp->file_ptr);
17977 }
17978 mp->cur_input = mp->input_stack[mp->input_ptr]; /* restore original state */
17979 }
17980
17981
17982 @ @<Display the current context@>=
17983 if ((mp->file_ptr == mp->input_ptr) || file_state ||
17984 (token_type != backed_up) || (nloc != NULL)) {
17985 /* we omit backed-up token lists that have already been read */
17986 mp->tally = 0; /* get ready to count characters */
17987 old_setting = mp->selector;
17988 if (file_state) {
17989 @<Print location of current line@>;
17990 @<Pseudoprint the line@>;
17991 } else {
17992 @<Print type of token list@>;
17993 @<Pseudoprint the token list@>;
17994 }
17995 mp->selector = old_setting; /* stop pseudoprinting */
17996 @<Print two lines using the tricky pseudoprinted information@>;
17997 }
17998
17999 @ This routine should be changed, if necessary, to give the best possible
18000 indication of where the current line resides in the input file.
18001 For example, on some systems it is best to print both a page and line number.
18002 @^system dependencies@>
18003
18004 @<Print location of current line@>=
18005 if (name > max_spec_src) {
18006 mp_print_nl (mp, "l.");
18007 mp_print_int (mp, mp_true_line (mp));
18008 } else if (terminal_input) {
18009 if (mp->file_ptr == 0)
18010 mp_print_nl (mp, "<*>");
18011 else
18012 mp_print_nl (mp, "<insert>");
18013 } else if (name == is_scantok) {
18014 mp_print_nl (mp, "<scantokens>");
18015 } else {
18016 mp_print_nl (mp, "<read>");
18017 }
18018 mp_print_char (mp, xord (' '))
18019
18020
18021 @ Can't use case statement here because the |token_type| is not
18022 a constant expression.
18023
18024 @<Print type of token list@>=
18025 {
18026 if (token_type == forever_text) {
18027 mp_print_nl (mp, "<forever> ");
18028 } else if (token_type == loop_text) {
18029 @<Print the current loop value@>;
18030 } else if (token_type == parameter) {
18031 mp_print_nl (mp, "<argument> ");
18032 } else if (token_type == backed_up) {
18033 if (nloc == NULL)
18034 mp_print_nl (mp, "<recently read> ");
18035 else
18036 mp_print_nl (mp, "<to be read again> ");
18037 } else if (token_type == inserted) {
18038 mp_print_nl (mp, "<inserted text> ");
18039 } else if (token_type == macro) {
18040 mp_print_ln (mp);
18041 if (name != NULL)
18042 mp_print_str (mp, name);
18043 else
18044 @<Print the name of a \&{vardef}'d macro@>;
18045 mp_print (mp, "->");
18046 } else {
18047 mp_print_nl (mp, "?"); /* this should never happen */
18048 @.?\relax@>
18049 }
18050 }
18051
18052
18053 @ The parameter that corresponds to a loop text is either a token list
18054 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
18055 We'll discuss capsules later; for now, all we need to know is that
18056 the |link| field in a capsule parameter is |void| and that
18057 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
18058
18059 @<Print the current loop value@>=
18060 {
18061 mp_node pp;
18062 mp_print_nl (mp, "<for(");
18063 pp = mp->param_stack[param_start];
18064 if (pp != NULL) {
18065 if (mp_link (pp) == MP_VOID)
18066 mp_print_exp (mp, pp, 0); /* we're in a \&{for} loop */
18067 else
18068 mp_show_token_list (mp, pp, NULL, 20, mp->tally);
18069 }
18070 mp_print (mp, ")> ");
18071 }
18072
18073
18074 @ The first two parameters of a macro defined by \&{vardef} will be token
18075 lists representing the macro's prefix and ``at point.'' By putting these
18076 together, we get the macro's full name.
18077
18078 @<Print the name of a \&{vardef}'d macro@>=
18079 {
18080 mp_node pp = mp->param_stack[param_start];
18081 if (pp == NULL) {
18082 mp_show_token_list (mp, mp->param_stack[param_start + 1], NULL, 20,
18083 mp->tally);
18084 } else {
18085 mp_node qq = pp;
18086 while (mp_link (qq) != NULL)
18087 qq = mp_link (qq);
18088 mp_link (qq) = mp->param_stack[param_start + 1];
18089 mp_show_token_list (mp, pp, NULL, 20, mp->tally);
18090 mp_link (qq) = NULL;
18091 }
18092 }
18093
18094
18095 @ Now it is necessary to explain a little trick. We don't want to store a long
18096 string that corresponds to a token list, because that string might take up
18097 lots of memory; and we are printing during a time when an error message is
18098 being given, so we dare not do anything that might overflow one of \MP's
18099 tables. So `pseudoprinting' is the answer: We enter a mode of printing
18100 that stores characters into a buffer of length |error_line|, where character
18101 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
18102 |k<trick_count|, otherwise character |k| is dropped. Initially we set
18103 |tally:=0| and |trick_count:=1000000|; then when we reach the
18104 point where transition from line 1 to line 2 should occur, we
18105 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
18106 tally+1+error_line-half_error_line)|. At the end of the
18107 pseudoprinting, the values of |first_count|, |tally|, and
18108 |trick_count| give us all the information we need to print the two lines,
18109 and all of the necessary text is in |trick_buf|.
18110
18111 Namely, let |l| be the length of the descriptive information that appears
18112 on the first line. The length of the context information gathered for that
18113 line is |k=first_count|, and the length of the context information
18114 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
18115 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
18116 descriptive information on line~1, and set |n:=l+k|; here |n| is the
18117 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
18118 and print `\.{...}' followed by
18119 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
18120 where subscripts of |trick_buf| are circular modulo |error_line|. The
18121 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
18122 unless |n+m>error_line|; in the latter case, further cropping is done.
18123 This is easier to program than to explain.
18124
18125 @<Local variables for formatting...@>=
18126 int i; /* index into |buffer| */
18127 integer l; /* length of descriptive information on line 1 */
18128 integer m; /* context information gathered for line 2 */
18129 int n; /* length of line 1 */
18130 integer p; /* starting or ending place in |trick_buf| */
18131 integer q; /* temporary index */
18132
18133 @ The following code tells the print routines to gather
18134 the desired information.
18135
18136 @d begin_pseudoprint {
18137 l=mp->tally; mp->tally=0; mp->selector=pseudo;
18138 mp->trick_count=1000000;
18139 }
18140 @d set_trick_count() {
18141 mp->first_count=mp->tally;
18142 mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
18143 if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
18144 }
18145
18146 @ And the following code uses the information after it has been gathered.
18147
18148 @<Print two lines using the tricky pseudoprinted information@>=
18149 if (mp->trick_count == 1000000)
18150 set_trick_count();
18151 /* |set_trick_count| must be performed */
18152 if (mp->tally < mp->trick_count)
18153 m = mp->tally - mp->first_count;
18154 else
18155 m = mp->trick_count - mp->first_count; /* context on line 2 */
18156 if (l + mp->first_count <= mp->half_error_line) {
18157 p = 0;
18158 n = l + mp->first_count;
18159 } else {
18160 mp_print (mp, "...");
18161 p = l + mp->first_count - mp->half_error_line + 3;
18162 n = mp->half_error_line;
18163 }
18164 for (q = p; q <= mp->first_count - 1; q++) {
18165 mp_print_char (mp, mp->trick_buf[q % mp->error_line]);
18166 }
18167 mp_print_ln (mp);
18168 for (q = 1; q <= n; q++) {
18169 mp_print_char (mp, xord (' ')); /* print |n| spaces to begin line~2 */
18170 }
18171 if (m + n <= mp->error_line)
18172 p = mp->first_count + m;
18173 else
18174 p = mp->first_count + (mp->error_line - n - 3);
18175 for (q = mp->first_count; q <= p - 1; q++) {
18176 mp_print_char (mp, mp->trick_buf[q % mp->error_line]);
18177 }
18178 if (m + n > mp->error_line)
18179 mp_print (mp, "...")
18180
18181
18182 @ But the trick is distracting us from our current goal, which is to
18183 understand the input state. So let's concentrate on the data structures that
18184 are being pseudoprinted as we finish up the |show_context| procedure.
18185
18186 @<Pseudoprint the line@>=
18187 begin_pseudoprint;
18188 if (limit > 0) {
18189 for (i = start; i <= limit - 1; i++) {
18190 if (i == loc)
18191 set_trick_count();
18192 mp_print_char (mp, mp->buffer[i]);
18193 }
18194 }
18195
18196 @ @<Pseudoprint the token list@>=
18197 begin_pseudoprint;
18198 if (token_type != macro)
18199 mp_show_token_list (mp, nstart, nloc, 100000, 0);
18200 else
18201 mp_show_macro (mp, nstart, nloc, 100000)
18202
18203
18204 @* Maintaining the input stacks.
18205 The following subroutines change the input status in commonly needed ways.
18206
18207 First comes |push_input|, which stores the current state and creates a
18208 new level (having, initially, the same properties as the old).
18209
18210 @d push_input { /* enter a new input level, save the old */
18211 if ( mp->input_ptr>mp->max_in_stack ) {
18212 mp->max_in_stack=mp->input_ptr;
18213 if ( mp->input_ptr==mp->stack_size ) {
18214 int l = (mp->stack_size+(mp->stack_size/4));
18215 /* The |mp->stack_size < 1001| condition is necessary to prevent C stack overflow due infinite recursion. */
18216 if (l>1000) {fprintf(stderr, "input stack overflow\n");exit(EXIT_FAILURE);}
18217 XREALLOC(mp->input_stack, l, in_state_record);
18218 mp->stack_size = l;
18219 }
18220 }
18221 mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
18222 incr(mp->input_ptr);
18223 }
18224
18225 @ And of course what goes up must come down.
18226
18227 @d pop_input { /* leave an input level, re-enter the old */
18228 decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
18229 }
18230
18231 @ Here is a procedure that starts a new level of token-list input, given
18232 a token list |p| and its type |t|. If |t=macro|, the calling routine should
18233 set |name|, reset~|loc|, and increase the macro's reference count.
18234
18235 @d back_list(A) mp_begin_token_list(mp, (A), (quarterword)backed_up) /* backs up a simple token list */
18236
18237 @c
18238 static void mp_begin_token_list (MP mp, mp_node p, quarterword t) {
18239 push_input;
18240 nstart = p;
18241 token_type = t;
18242 param_start = mp->param_ptr;
18243 nloc = p;
18244 }
18245
18246
18247 @ When a token list has been fully scanned, the following computations
18248 should be done as we leave that level of input.
18249 @^inner loop@>
18250
18251 @c
18252 static void mp_end_token_list (MP mp) { /* leave a token-list input level */
18253 mp_node p; /* temporary register */
18254 if (token_type >= backed_up) { /* token list to be deleted */
18255 if (token_type <= inserted) {
18256 mp_flush_token_list (mp, nstart);
18257 goto DONE;
18258 } else {
18259 mp_delete_mac_ref (mp, nstart); /* update reference count */
18260 }
18261 }
18262 while (mp->param_ptr > param_start) { /* parameters must be flushed */
18263 decr (mp->param_ptr);
18264 p = mp->param_stack[mp->param_ptr];
18265 if (p != NULL) {
18266 if (mp_link (p) == MP_VOID) { /* it's an \&{expr} parameter */
18267 mp_recycle_value (mp, p);
18268 mp_free_value_node (mp, p);
18269 } else {
18270 mp_flush_token_list (mp, p); /* it's a \&{suffix} or \&{text} parameter */
18271 }
18272 }
18273 }
18274 DONE:
18275 pop_input;
18276 check_interrupt;
18277 }
18278
18279
18280 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
18281 token by the |cur_tok| routine.
18282 @^inner loop@>
18283
18284 @c
18285 @<Declare the procedure called |make_exp_copy|@>
18286 static mp_node mp_cur_tok (MP mp) {
18287 mp_node p; /* a new token node */
18288 if (cur_sym() == NULL && (cur_sym_mod() == 0 || cur_sym_mod() == mp_normal_sym)) {
18289 if (cur_cmd() == mp_capsule_token) {
18290 mp_number save_exp_num; /* possible |cur_exp| numerical to be restored */
18291 mp_value save_exp = mp->cur_exp; /* |cur_exp| to be restored */
18292 new_number (save_exp_num);
18293 number_clone (save_exp_num, cur_exp_value_number());
18294 mp_make_exp_copy (mp, cur_mod_node());
18295 p = mp_stash_cur_exp (mp);
18296 mp_link (p) = NULL;
18297 mp->cur_exp = save_exp;
18298 number_clone (mp->cur_exp.data.n, save_exp_num);
18299 free_number (save_exp_num);
18300 } else {
18301 p = mp_get_token_node (mp);
18302 mp_name_type (p) = mp_token;
18303 if (cur_cmd() == mp_numeric_token) {
18304 set_value_number (p, cur_mod_number());
18305 mp_type (p) = mp_known;
18306 } else {
18307 set_value_str (p, cur_mod_str());
18308 mp_type (p) = mp_string_type;
18309 }
18310 }
18311 } else {
18312 p = mp_get_symbolic_node (mp);
18313 set_mp_sym_sym (p, cur_sym());
18314 mp_name_type (p) = cur_sym_mod();
18315 }
18316 return p;
18317 }
18318
18319
18320 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
18321 seen. The |back_input| procedure takes care of this by putting the token
18322 just scanned back into the input stream, ready to be read again.
18323 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
18324
18325 @<Declarations@>=
18326 static void mp_back_input (MP mp);
18327
18328 @ @c
18329 void mp_back_input (MP mp) { /* undoes one token of input */
18330 mp_node p; /* a token list of length one */
18331 p = mp_cur_tok (mp);
18332 while (token_state && (nloc == NULL))
18333 mp_end_token_list (mp); /* conserve stack space */
18334 back_list (p);
18335 }
18336
18337
18338 @ The |back_error| routine is used when we want to restore or replace an
18339 offending token just before issuing an error message. We disable interrupts
18340 during the call of |back_input| so that the help message won't be lost.
18341
18342 @<Declarations@>=
18343 static void mp_back_error (MP mp, const char *msg, const char **hlp, boolean deletions_allowed) ;
18344
18345 @ @c
18346 static void mp_back_error (MP mp, const char *msg, const char **hlp, boolean deletions_allowed) {
18347 /* back up one token and call |error| */
18348 mp->OK_to_interrupt = false;
18349 mp_back_input (mp);
18350 mp->OK_to_interrupt = true;
18351 mp_error (mp, msg, hlp, deletions_allowed);
18352 }
18353 static void mp_ins_error (MP mp, const char *msg, const char **hlp, boolean deletions_allowed) {
18354 /* back up one inserted token and call |error| */
18355 mp->OK_to_interrupt = false;
18356 mp_back_input (mp);
18357 token_type = (quarterword) inserted;
18358 mp->OK_to_interrupt = true;
18359 mp_error (mp, msg, hlp, deletions_allowed);
18360 }
18361
18362
18363 @ The |begin_file_reading| procedure starts a new level of input for lines
18364 of characters to be read from a file, or as an insertion from the
18365 terminal. It does not take care of opening the file, nor does it set |loc|
18366 or |limit| or |line|.
18367 @^system dependencies@>
18368
18369 @c
18370 void mp_begin_file_reading (MP mp) {
18371 if (mp->in_open == (mp->max_in_open-1))
18372 mp_reallocate_input_stack (mp, (mp->max_in_open + mp->max_in_open / 4));
18373 if (mp->first == mp->buf_size)
18374 mp_reallocate_buffer (mp, (mp->buf_size + mp->buf_size / 4));
18375 mp->in_open++;
18376 push_input;
18377 iindex = (quarterword) mp->in_open;
18378 if (mp->in_open_max < mp->in_open)
18379 mp->in_open_max = mp->in_open;
18380 mp->mpx_name[iindex] = absent;
18381 start = (halfword) mp->first;
18382 name = is_term; /* |terminal_input| is now |true| */
18383 }
18384
18385
18386 @ Conversely, the variables must be downdated when such a level of input
18387 is finished. Any associated \.{MPX} file must also be closed and popped
18388 off the file stack. While finishing preloading, it is possible that the file
18389 does not actually end with 'dump', so we capture that case here as well.
18390
18391 @c
18392 static void mp_end_file_reading (MP mp) {
18393 if (mp->reading_preload && mp->input_ptr == 0) {
18394 set_cur_sym(mp->frozen_dump);
18395 mp_back_input (mp);
18396 return;
18397 }
18398 if (mp->in_open > iindex) {
18399 if ((mp->mpx_name[mp->in_open] == absent) || (name <= max_spec_src)) {
18400 mp_confusion (mp, "endinput");
18401 @:this can't happen endinput}{\quad endinput@>
18402 } else {
18403 (mp->close_file) (mp, mp->input_file[mp->in_open]); /* close an \.{MPX} file */
18404 delete_str_ref (mp->mpx_name[mp->in_open]);
18405 decr (mp->in_open);
18406 }
18407 }
18408 mp->first = (size_t) start;
18409 if (iindex != mp->in_open)
18410 mp_confusion (mp, "endinput");
18411 if (name > max_spec_src) {
18412 (mp->close_file) (mp, cur_file);
18413 xfree (in_ext);
18414 xfree (in_name);
18415 xfree (in_area);
18416 }
18417 pop_input;
18418 decr (mp->in_open);
18419 }
18420
18421
18422 @ Here is a function that tries to resume input from an \.{MPX} file already
18423 associated with the current input file. It returns |false| if this doesn't
18424 work.
18425
18426 @c
18427 static boolean mp_begin_mpx_reading (MP mp) {
18428 if (mp->in_open != iindex + 1) {
18429 return false;
18430 } else {
18431 if (mp->mpx_name[mp->in_open] <= absent)
18432 mp_confusion (mp, "mpx");
18433 if (mp->first == mp->buf_size)
18434 mp_reallocate_buffer (mp, (mp->buf_size + (mp->buf_size / 4)));
18435 push_input;
18436 iindex = (quarterword) mp->in_open;
18437 start = (halfword) mp->first;
18438 name = mp->mpx_name[mp->in_open];
18439 add_str_ref (name);
18440 /* Put an empty line in the input buffer */
18441 /* We want to make it look as though we have just read a blank line
18442 without really doing so. */
18443 mp->last = mp->first;
18444 limit = (halfword) mp->last;
18445 /* simulate |input_ln| and |firm_up_the_line| */
18446 mp->buffer[limit] = xord ('%');
18447 mp->first = (size_t) (limit + 1);
18448 loc = start;
18449 return true;
18450 }
18451 }
18452
18453
18454 @ This procedure temporarily stops reading an \.{MPX} file.
18455
18456 @c
18457 static void mp_end_mpx_reading (MP mp) {
18458 if (mp->in_open != iindex)
18459 mp_confusion (mp, "mpx");
18460 @:this can't happen mpx}{\quad mpx@>
18461 if (loc < limit) {
18462 /* Complain that we are not at the end of a line in the \.{MPX} file */
18463 /* Here we enforce a restriction that simplifies the input stacks considerably.
18464 This should not inconvenience the user because \.{MPX} files are generated
18465 by an auxiliary program called \.{DVItoMP}. */
18466 const char *hlp[] = {
18467 "This file contains picture expressions for btex...etex",
18468 "blocks. Such files are normally generated automatically",
18469 "but this one seems to be messed up. I'm going to ignore",
18470 "the rest of this line.",
18471 NULL };
18472 mp_error (mp, "`mpxbreak' must be at the end of a line", hlp, true);
18473 }
18474 mp->first = (size_t) start;
18475 pop_input;
18476 }
18477
18478 @ In order to keep the stack from overflowing during a long sequence of
18479 inserted `\.{show}' commands, the following routine removes completed
18480 error-inserted lines from memory.
18481
18482 @c
18483 void mp_clear_for_error_prompt (MP mp) {
18484 while (file_state && terminal_input && (mp->input_ptr > 0) && (loc == limit))
18485 mp_end_file_reading (mp);
18486 mp_print_ln (mp);
18487 clear_terminal();
18488 }
18489
18490
18491 @ To get \MP's whole input mechanism going, we perform the following
18492 actions.
18493
18494 @<Initialize the input routines@>=
18495 {
18496 mp->input_ptr = 0;
18497 mp->max_in_stack = file_bottom;
18498 mp->in_open = file_bottom;
18499 mp->open_parens = 0;
18500 mp->max_buf_stack = 0;
18501 mp->param_ptr = 0;
18502 mp->max_param_stack = 0;
18503 mp->first = 0;
18504 start = 0;
18505 iindex = file_bottom;
18506 line = 0;
18507 name = is_term;
18508 mp->mpx_name[file_bottom] = absent;
18509 mp->force_eof = false;
18510 if (!mp_init_terminal (mp))
18511 mp_jump_out (mp);
18512 limit = (halfword) mp->last;
18513 mp->first = mp->last + 1;
18514 /* |init_terminal| has set |loc| and |last| */
18515 }
18516
18517
18518 @* Getting the next token.
18519 The heart of \MP's input mechanism is the |get_next| procedure, which
18520 we shall develop in the next few sections of the program. Perhaps we
18521 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
18522 eyes and mouth, reading the source files and gobbling them up. And it also
18523 helps \MP\ to regurgitate stored token lists that are to be processed again.
18524
18525 The main duty of |get_next| is to input one token and to set |cur_cmd|
18526 and |cur_mod| to that token's command code and modifier. Furthermore, if
18527 the input token is a symbolic token, that token's |hash| address
18528 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
18529
18530 Underlying this simple description is a certain amount of complexity
18531 because of all the cases that need to be handled.
18532 However, the inner loop of |get_next| is reasonably short and fast.
18533
18534 @ Before getting into |get_next|, we need to consider a mechanism by which
18535 \MP\ helps keep errors from propagating too far. Whenever the program goes
18536 into a mode where it keeps calling |get_next| repeatedly until a certain
18537 condition is met, it sets |scanner_status| to some value other than |normal|.
18538 Then if an input file ends, or if an `\&{outer}' symbol appears,
18539 an appropriate error recovery will be possible.
18540
18541 The global variable |warning_info| helps in this error recovery by providing
18542 additional information. For example, |warning_info| might indicate the
18543 name of a macro whose replacement text is being scanned.
18544
18545 @d normal 0 /* |scanner_status| at ``quiet times'' */
18546 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
18547 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
18548 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
18549 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
18550 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
18551 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
18552
18553 @<Glob...@>=
18554 #define tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
18555 integer scanner_status; /* are we scanning at high speed? */
18556 mp_sym warning_info; /* if so, what else do we need to know,
18557 in case an error occurs? */
18558 mpinteger64 warning_line;
18559 mp_node warning_info_node;
18560
18561 @ @<Initialize the input routines@>=
18562 mp->scanner_status = normal;
18563
18564 @ The following subroutine
18565 is called when an `\&{outer}' symbolic token has been scanned or
18566 when the end of a file has been reached. These two cases are distinguished
18567 by |cur_sym|, which is zero at the end of a file.
18568
18569 @c
18570 static boolean mp_check_outer_validity (MP mp) {
18571 mp_node p; /* points to inserted token list */
18572 if (mp->scanner_status == normal) {
18573 return true;
18574 } else if (mp->scanner_status == tex_flushing) {
18575 @<Check if the file has ended while flushing \TeX\ material and set the
18576 result value for |check_outer_validity|@>;
18577 } else {
18578 @<Back up an outer symbolic token so that it can be reread@>;
18579 if (mp->scanner_status > skipping) {
18580 @<Tell the user what has run away and try to recover@>;
18581 } else {
18582 char msg[256];
18583 const char *hlp[] = {
18584 "A forbidden `outer' token occurred in skipped text.",
18585 "This kind of error happens when you say `if...' and forget",
18586 "the matching `fi'. I've inserted a `fi'; this might work.",
18587 NULL };
18588 mp_snprintf(msg, 256, "Incomplete if; all text was ignored after line %d", (int)mp->warning_line);
18589 @.Incomplete if...@>
18590 if (cur_sym() == NULL) {
18591 hlp[0] = "The file ended while I was skipping conditional text.";
18592 }
18593 set_cur_sym (mp->frozen_fi);
18594 mp_ins_error (mp, msg, hlp, false);
18595 }
18596 return false;
18597 }
18598 }
18599
18600
18601 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
18602 if (cur_sym() != NULL) {
18603 return true;
18604 } else {
18605 char msg[256];
18606 const char *hlp[] = {
18607 "The file ended while I was looking for the `etex' to",
18608 "finish this TeX material. I've inserted `etex' now.",
18609 NULL };
18610 mp_snprintf(msg, 256, "TeX mode didn't end; all text was ignored after line %d", (int)mp->warning_line);
18611 set_cur_sym(mp->frozen_etex);
18612 mp_ins_error (mp, msg, hlp, false);
18613 return false;
18614 }
18615
18616
18617 @ @<Back up an outer symbolic token so that it can be reread@>=
18618 if (cur_sym() != NULL) {
18619 p = mp_get_symbolic_node (mp);
18620 set_mp_sym_sym (p, cur_sym());
18621 mp_name_type (p) = cur_sym_mod();
18622 back_list (p); /* prepare to read the symbolic token again */
18623 }
18624
18625 @ @<Tell the user what has run away...@>=
18626 {
18627 char msg[256];
18628 const char *msg_start = NULL;
18629 const char *hlp[] = {
18630 "I suspect you have forgotten an `enddef',",
18631 "causing me to read past where you wanted me to stop.",
18632 "I'll try to recover; but if the error is serious,",
18633 "you'd better type `E' or `X' now and fix your file.",
18634 NULL };
18635 mp_runaway (mp); /* print the definition-so-far */
18636 if (cur_sym() == NULL) {
18637 msg_start = "File ended while scanning";
18638 @.File ended while scanning...@>
18639 } else {
18640 msg_start = "Forbidden token found while scanning";
18641 @.Forbidden token found...@>
18642 }
18643 switch (mp->scanner_status) {
18644 @<Complete the error message,
18645 and set |cur_sym| to a token that might help recover from the error@>@;
18646 } /* there are no other cases */
18647 mp_ins_error (mp, msg, hlp, true);
18648 }
18649
18650
18651 @ As we consider various kinds of errors, it is also appropriate to
18652 change the first line of the help message just given; |help_line[3]|
18653 points to the string that might be changed.
18654
18655 @<Complete the error message,...@>=
18656 case flushing:
18657 mp_snprintf (msg, 256, "%s to the end of the statement", msg_start);
18658 hlp[0] = "A previous error seems to have propagated,";
18659 set_cur_sym(mp->frozen_semicolon);
18660 break;
18661 case absorbing:
18662 mp_snprintf (msg, 256, "%s a text argument", msg_start);
18663 hlp[0] = "It seems that a right delimiter was left out,";
18664 if (mp->warning_info == NULL) {
18665 set_cur_sym(mp->frozen_end_group);
18666 } else {
18667 set_cur_sym(mp->frozen_right_delimiter);
18668 /* the next line makes sure that the inserted delimiter will
18669 match the delimiter that already was read. */
18670 set_equiv_sym (cur_sym(), mp->warning_info);
18671 }
18672 break;
18673 case var_defining:
18674 {
18675 mp_string s;
18676 int old_setting = mp->selector;
18677 mp->selector = new_string;
18678 mp_print_variable_name (mp, mp->warning_info_node);
18679 s = mp_make_string (mp);
18680 mp->selector = old_setting;
18681 mp_snprintf (msg, 256, "%s the definition of %s", msg_start, s->str);
18682 delete_str_ref(s);
18683 }
18684 set_cur_sym(mp->frozen_end_def);
18685 break;
18686 case op_defining:
18687 {
18688 char *s = mp_str(mp, text(mp->warning_info));
18689 mp_snprintf (msg, 256, "%s the definition of %s", msg_start, s);
18690 }
18691 set_cur_sym(mp->frozen_end_def);
18692 break;
18693 case loop_defining:
18694 {
18695 char *s = mp_str(mp, text(mp->warning_info));
18696 mp_snprintf (msg, 256, "%s the text of a %s loop", msg_start, s);
18697 }
18698 hlp[0] = "I suspect you have forgotten an `endfor',";
18699 set_cur_sym(mp->frozen_end_for);
18700 break;
18701
18702 @ The |runaway| procedure displays the first part of the text that occurred
18703 when \MP\ began its special |scanner_status|, if that text has been saved.
18704
18705 @<Declarations@>=
18706 static void mp_runaway (MP mp);
18707
18708 @ @c
18709 void mp_runaway (MP mp) {
18710 if (mp->scanner_status > flushing) {
18711 mp_print_nl (mp, "Runaway ");
18712 switch (mp->scanner_status) {
18713 case absorbing:
18714 mp_print (mp, "text?");
18715 break;
18716 case var_defining:
18717 case op_defining:
18718 mp_print (mp, "definition?");
18719 break;
18720 case loop_defining:
18721 mp_print (mp, "loop?");
18722 break;
18723 } /* there are no other cases */
18724 mp_print_ln (mp);
18725 mp_show_token_list (mp, mp_link (mp->hold_head), NULL, mp->error_line - 10,
18726 0);
18727 }
18728 }
18729
18730
18731 @ We need to mention a procedure that may be called by |get_next|.
18732
18733 @<Declarations@>=
18734 static void mp_firm_up_the_line (MP mp);
18735
18736 @ And now we're ready to take the plunge into |get_next| itself.
18737 Note that the behavior depends on the |scanner_status| because percent signs
18738 and double quotes need to be passed over when skipping \TeX\ material.
18739
18740 @c
18741 void mp_get_next (MP mp) {
18742 /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
18743 mp_sym cur_sym_; /* speed up access */
18744 RESTART:
18745 set_cur_sym(NULL);
18746 set_cur_sym_mod(0);
18747 if (file_state) {
18748 int k; /* an index into |buffer| */
18749 ASCII_code c; /* the current character in the buffer */
18750 int cclass; /* its class number */
18751 /* Input from external file; |goto restart| if no input found,
18752 or |return| if a non-symbolic token is found */
18753 /* A percent sign appears in |buffer[limit]|; this makes it unnecessary
18754 to have a special test for end-of-line. */
18755 SWITCH:
18756 c = mp->buffer[loc];
18757 incr (loc);
18758 cclass = mp->char_class[c];
18759 switch (cclass) {
18760 case digit_class:
18761 scan_numeric_token((c - '0'));
18762 return;
18763 break;
18764 case period_class:
18765 cclass = mp->char_class[mp->buffer[loc]];
18766 if (cclass > period_class) {
18767 goto SWITCH;
18768 } else if (cclass < period_class) { /* |class=digit_class| */
18769 scan_fractional_token(0);
18770 return;
18771 }
18772 break;
18773 case space_class:
18774 goto SWITCH;
18775 break;
18776 case percent_class:
18777 if (mp->scanner_status == tex_flushing) {
18778 if (loc < limit)
18779 goto SWITCH;
18780 }
18781 /* Move to next line of file, or |goto restart| if there is no next line */
18782 switch (move_to_next_line(mp)) {
18783 case 1: goto RESTART; break;
18784 case 2: goto COMMON_ENDING; break;
18785 default: break;
18786 }
18787 check_interrupt;
18788 goto SWITCH;
18789 break;
18790 case string_class:
18791 if (mp->scanner_status == tex_flushing) {
18792 goto SWITCH;
18793 } else {
18794 if (mp->buffer[loc] == '"') {
18795 set_cur_mod_str(mp_rts(mp,""));
18796 } else {
18797 k = loc;
18798 mp->buffer[limit + 1] = xord ('"');
18799 do {
18800 incr (loc);
18801 } while (mp->buffer[loc] != '"');
18802 if (loc > limit) {
18803 /* Decry the missing string delimiter and |goto restart| */
18804 /* We go to |restart| after this error message, not to |SWITCH|,
18805 because the |clear_for_error_prompt| routine might have reinstated
18806 |token_state| after |error| has finished. */
18807 const char *hlp[] = {
18808 "Strings should finish on the same line as they began.",
18809 "I've deleted the partial string; you might want to",
18810 "insert another by typing, e.g., `I\"new string\"'.",
18811 NULL };
18812 loc = limit; /* the next character to be read on this line will be |"%"| */
18813 mp_error (mp, "Incomplete string token has been flushed", hlp, false);
18814 goto RESTART;
18815 }
18816 str_room ((size_t) (loc - k));
18817 do {
18818 append_char (mp->buffer[k]);
18819 incr (k);
18820 } while (k != loc);
18821 set_cur_mod_str(mp_make_string (mp));
18822 }
18823 incr (loc);
18824 set_cur_cmd((mp_variable_type)mp_string_token);
18825 return;
18826 }
18827 break;
18828 case isolated_classes:
18829 k = loc - 1;
18830 goto FOUND;
18831 break;
18832 case invalid_class:
18833 if (mp->scanner_status == tex_flushing) {
18834 goto SWITCH;
18835 } else {
18836 /* Decry the invalid character and |goto restart| */
18837 /* We go to |restart| instead of to |SWITCH|, because we might enter
18838 |token_state| after the error has been dealt with
18839 (cf.\ |clear_for_error_prompt|). */
18840 const char *hlp[] = {
18841 "A funny symbol that I can\'t read has just been input.",
18842 "Continue, and I'll forget that it ever happened.",
18843 NULL };
18844 mp_error(mp, "Text line contains an invalid character", hlp, false);
18845 goto RESTART;
18846 }
18847 break;
18848 default:
18849 break; /* letters, etc. */
18850 }
18851 k = loc - 1;
18852 while (mp->char_class[mp->buffer[loc]] == cclass)
18853 incr (loc);
18854 FOUND:
18855 set_cur_sym(mp_id_lookup (mp, (char *) (mp->buffer + k), (size_t) (loc - k), true));
18856
18857 } else {
18858 /* Input from token list; |goto restart| if end of list or
18859 if a parameter needs to be expanded,
18860 or |return| if a non-symbolic token is found */
18861 if (nloc != NULL && mp_type (nloc) == mp_symbol_node) { /* symbolic token */
18862 int cur_sym_mod_ = mp_name_type (nloc);
18863 halfword cur_info = mp_sym_info (nloc);
18864 set_cur_sym(mp_sym_sym (nloc));
18865 set_cur_sym_mod(cur_sym_mod_);
18866 nloc = mp_link (nloc); /* move to next */
18867 if (cur_sym_mod_ == mp_expr_sym) {
18868 set_cur_cmd((mp_variable_type)mp_capsule_token);
18869 set_cur_mod_node(mp->param_stack[param_start + cur_info]);
18870 set_cur_sym_mod(0);
18871 set_cur_sym(NULL);
18872 return;
18873 } else if (cur_sym_mod_ == mp_suffix_sym || cur_sym_mod_ == mp_text_sym) {
18874 mp_begin_token_list (mp,
18875 mp->param_stack[param_start + cur_info],
18876 (quarterword) parameter);
18877 goto RESTART;
18878 }
18879 } else if (nloc != NULL) {
18880 /* Get a stored numeric or string or capsule token and |return| */
18881 if (mp_name_type (nloc) == mp_token) {
18882 if (mp_type (nloc) == mp_known) {
18883 set_cur_mod_number(value_number (nloc));
18884 set_cur_cmd((mp_variable_type)mp_numeric_token);
18885 } else {
18886 set_cur_mod_str(value_str (nloc));
18887 set_cur_cmd((mp_variable_type)mp_string_token);
18888 add_str_ref (cur_mod_str());
18889 }
18890 } else {
18891 set_cur_mod_node(nloc);
18892 set_cur_cmd((mp_variable_type)mp_capsule_token);
18893 }
18894 nloc = mp_link (nloc);
18895 return;
18896 } else { /* we are done with this token list */
18897 mp_end_token_list (mp);
18898 goto RESTART; /* resume previous level */
18899 }
18900 }
18901 COMMON_ENDING:
18902 /* When a symbolic token is declared to be `\&{outer}', its command code
18903 is increased by |outer_tag|. */
18904 cur_sym_ = cur_sym();
18905 set_cur_cmd(eq_type (cur_sym_));
18906 set_cur_mod(equiv (cur_sym_));
18907 set_cur_mod_node(equiv_node (cur_sym_));
18908 if (cur_cmd() >= mp_outer_tag) {
18909 if (mp_check_outer_validity (mp))
18910 set_cur_cmd(cur_cmd() - mp_outer_tag);
18911 else
18912 goto RESTART;
18913 }
18914 }
18915
18916 @ The global variable |force_eof| is normally |false|; it is set |true|
18917 by an \&{endinput} command.
18918
18919 @<Glob...@>=
18920 boolean force_eof; /* should the next \&{input} be aborted early? */
18921
18922 @ @<Declarations@>=
18923 static int move_to_next_line (MP mp);
18924
18925 @ @c
18926 static int move_to_next_line (MP mp) {
18927 if (name > max_spec_src) {
18928 /* Read next line of file into |buffer|, or return 1
18929 (|goto restart|) if the file has ended */
18930 /* We must decrement |loc| in order to leave the buffer in a valid state
18931 when an error condition causes us to |goto restart| without calling
18932 |end_file_reading|. */
18933 {
18934 incr (line);
18935 mp->first = (size_t) start;
18936 if (!mp->force_eof) {
18937 if (mp_input_ln (mp, cur_file)) /* not end of file */
18938 mp_firm_up_the_line (mp); /* this sets |limit| */
18939 else
18940 mp->force_eof = true;
18941 }
18942 if (mp->force_eof) {
18943 mp->force_eof = false;
18944 decr (loc);
18945 if (mpx_reading) {
18946 /* Complain that the \.{MPX} file ended unexpectedly; then set
18947 |cur_sym:=mp->frozen_mpx_break| and |goto common_ending| */
18948 /* We should never actually come to the end of an \.{MPX} file because such
18949 files should have an \&{mpxbreak} after the translation of the last
18950 \&{btex}$\,\ldots\,$\&{etex} block. */
18951 const char *hlp[] = {"The file had too few picture expressions for btex...etex",
18952 "blocks. Such files are normally generated automatically",
18953 "but this one got messed up. You might want to insert a",
18954 "picture expression now.",
18955 NULL };
18956 mp->mpx_name[iindex] = mpx_finished;
18957 mp_error (mp, "mpx file ended unexpectedly", hlp, false);
18958 set_cur_sym(mp->frozen_mpx_break);
18959 return 2;
18960 } else {
18961 mp_print_char (mp, xord (')'));
18962 decr (mp->open_parens);
18963 update_terminal(); /* show user that file has been read */
18964 mp_end_file_reading (mp); /* resume previous level */
18965 if (mp_check_outer_validity (mp))
18966 return 1;
18967 else
18968 return 1;
18969 }
18970 }
18971 mp->buffer[limit] = xord ('%');
18972 mp->first = (size_t) (limit + 1);
18973 loc = start; /* ready to read */
18974 }
18975
18976
18977 } else {
18978 if (mp->input_ptr > 0) {
18979 /* text was inserted during error recovery or by \&{scantokens} */
18980 mp_end_file_reading (mp);
18981 /* goto RESTART */
18982 return 1; /* resume previous level */
18983 }
18984 if (mp->job_name == NULL
18985 && (mp->selector < log_only || mp->selector >= write_file))
18986 mp_open_log_file (mp);
18987 if (mp->interaction > mp_nonstop_mode) {
18988 if (limit == start) /* previous line was empty */
18989 mp_print_nl (mp, "(Please type a command or say `end')");
18990 mp_print_ln (mp);
18991 mp->first = (size_t) start;
18992 prompt_input ("*"); /* input on-line into |buffer| */
18993 limit = (halfword) mp->last;
18994 mp->buffer[limit] = xord ('%');
18995 mp->first = (size_t) (limit + 1);
18996 loc = start;
18997 } else {
18998 mp_fatal_error (mp, "*** (job aborted, no legal end found)");
18999 /* nonstop mode, which is intended for overnight batch processing,
19000 never waits for on-line input */
19001 }
19002 }
19003 return 0;
19004 }
19005
19006
19007 @ If the user has set the |mp_pausing| parameter to some positive value,
19008 and if nonstop mode has not been selected, each line of input is displayed
19009 on the terminal and the transcript file, followed by `\.{=>}'.
19010 \MP\ waits for a response. If the response is NULL (i.e., if nothing is
19011 typed except perhaps a few blank spaces), the original
19012 line is accepted as it stands; otherwise the line typed is
19013 used instead of the line in the file.
19014
19015 @c
19016 void mp_firm_up_the_line (MP mp) {
19017 size_t k; /* an index into |buffer| */
19018 limit = (halfword) mp->last;
19019 if ((!mp->noninteractive)
19020 && (number_positive (internal_value (mp_pausing)))
19021 && (mp->interaction > mp_nonstop_mode)) {
19022 wake_up_terminal();
19023 mp_print_ln (mp);
19024 if (start < limit) {
19025 for (k = (size_t) start; k < (size_t) limit; k++) {
19026 mp_print_char (mp, mp->buffer[k]);
19027 }
19028 }
19029 mp->first = (size_t) limit;
19030 prompt_input ("=>"); /* wait for user response */
19031 @.=>@>
19032 if (mp->last > mp->first) {
19033 for (k = mp->first; k < mp->last; k++) { /* move line down in buffer */
19034 mp->buffer[k + (size_t) start - mp->first] = mp->buffer[k];
19035 }
19036 limit = (halfword) ((size_t) start + mp->last - mp->first);
19037 }
19038 }
19039 }
19040
19041
19042 @* Dealing with \TeX\ material.
19043 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
19044 features need to be implemented at a low level in the scanning process
19045 so that \MP\ can stay in sync with the a preprocessor that treats
19046 blocks of \TeX\ material as they occur in the input file without trying
19047 to expand \MP\ macros. Thus we need a special version of |get_next|
19048 that does not expand macros and such but does handle \&{btex},
19049 \&{verbatimtex}, etc.
19050
19051 The special version of |get_next| is called |get_t_next|. It works by flushing
19052 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
19053 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
19054 \&{btex}, and switching back when it sees \&{mpxbreak}.
19055
19056 @d btex_code 0
19057 @d verbatim_code 1
19058
19059 @ @<Put each...@>=
19060 mp_primitive (mp, "btex", mp_start_tex, btex_code);
19061 @:btex_}{\&{btex} primitive@>
19062 mp_primitive (mp, "verbatimtex", mp_start_tex, verbatim_code);
19063 @:verbatimtex_}{\&{verbatimtex} primitive@>
19064 mp_primitive (mp, "etex", mp_etex_marker, 0);
19065 mp->frozen_etex = mp_frozen_primitive (mp, "etex", mp_etex_marker, 0);
19066 @:etex_}{\&{etex} primitive@>
19067 mp_primitive (mp, "mpxbreak", mp_mpx_break, 0);
19068 mp->frozen_mpx_break = mp_frozen_primitive (mp, "mpxbreak", mp_mpx_break, 0);
19069 @:mpx_break_}{\&{mpxbreak} primitive@>
19070
19071
19072 @ @<Cases of |print_cmd...@>=
19073 case mp_start_tex:
19074 if (m == btex_code)
19075 mp_print (mp, "btex");
19076 else
19077 mp_print (mp, "verbatimtex");
19078 break;
19079 case mp_etex_marker:
19080 mp_print (mp, "etex");
19081 break;
19082 case mp_mpx_break:
19083 mp_print (mp, "mpxbreak");
19084 break;
19085
19086 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
19087 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
19088 is encountered.
19089
19090 @d get_t_next(a) do {
19091 mp_get_next (mp);
19092 if (cur_cmd() <= mp_max_pre_command)
19093 mp_t_next (mp);
19094 } while (0)@;
19095
19096 @ @<Declarations@>=
19097 static void mp_t_next (MP mp);
19098 static void mp_start_mpx_input (MP mp);
19099
19100 @ @c
19101 static void mp_t_next (MP mp) {
19102 int old_status; /* saves the |scanner_status| */
19103 mpinteger64 old_info; /* saves the |warning_info| */
19104
19105 if ((mp->extensions == 1) && (cur_cmd() == mp_start_tex))
19106 @<Pass \&{btex} ... \&{etex} to script@>@;
19107 else {
19108
19109 while (cur_cmd() <= mp_max_pre_command) {
19110 if (cur_cmd() == mp_mpx_break) {
19111 if (!file_state || (mp->mpx_name[iindex] == absent))
19112 @<Complain about a misplaced \&{mpxbreak}@>@;
19113 else {
19114 mp_end_mpx_reading (mp);
19115 goto TEX_FLUSH;
19116 }
19117 } else if (cur_cmd() == mp_start_tex) {
19118 if (token_state || (name <= max_spec_src))
19119 @<Complain that we are not reading a file@>@;
19120 else if (mpx_reading)
19121 @<Complain that \.{MPX} files cannot contain \TeX\ material@>@;
19122 else if ((cur_mod() != verbatim_code) &&
19123 (mp->mpx_name[iindex] != mpx_finished)) {
19124 if (!mp_begin_mpx_reading (mp))
19125 mp_start_mpx_input (mp);
19126 } else {
19127 goto TEX_FLUSH;
19128 }
19129 } else
19130 @<Complain about a misplaced \&{etex}@>@;
19131 goto COMMON_ENDING;
19132 TEX_FLUSH:
19133 @<Flush the \TeX\ material@>;
19134 COMMON_ENDING:
19135 mp_get_next (mp);
19136 }
19137 }
19138 }
19139
19140
19141 @ We could be in the middle of an operation such as skipping false conditional
19142 text when \TeX\ material is encountered, so we must be careful to save the
19143 |scanner_status|.
19144
19145 @<Flush the \TeX\ material@>=
19146 old_status = mp->scanner_status;
19147 old_info = mp->warning_line;
19148 mp->scanner_status = tex_flushing;
19149 mp->warning_line = line;
19150 do {
19151 mp_get_next (mp);
19152 } while (cur_cmd() != mp_etex_marker);
19153 mp->scanner_status = old_status;
19154 mp->warning_line = old_info@;
19155
19156 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
19157 {
19158 const char *hlp[] = {
19159 "This file contains picture expressions for btex...etex",
19160 "blocks. Such files are normally generated automatically",
19161 "but this one seems to be messed up. I'll just keep going",
19162 "and hope for the best.",
19163 NULL };
19164 mp_error (mp, "An mpx file cannot contain btex or verbatimtex blocks", hlp, true);
19165 }
19166
19167
19168 @ @<Complain that we are not reading a file@>=
19169 {
19170 const char *hlp[] = {
19171 "I'll have to ignore this preprocessor command because it",
19172 "only works when there is a file to preprocess. You might",
19173 "want to delete everything up to the next `etex`.",
19174 NULL };
19175 mp_error (mp, "You can only use `btex' or `verbatimtex' in a file", hlp, true);
19176 }
19177
19178
19179 @ @<Complain about a misplaced \&{mpxbreak}@>=
19180 {
19181 const char *hlp[] = {
19182 "I'll ignore this preprocessor command because it",
19183 "doesn't belong here",
19184 NULL };
19185 mp_error (mp, "Misplaced mpxbreak", hlp, true);
19186 }
19187
19188
19189 @ @<Complain about a misplaced \&{etex}@>=
19190 {
19191 const char *hlp[] = {
19192 "There is no btex or verbatimtex for this to match",
19193 NULL };
19194 mp_error (mp, "Extra etex will be ignored", hlp, true);
19195 }
19196
19197
19198 @* Scanning macro definitions.
19199 \MP\ has a variety of ways to tuck tokens away into token lists for later
19200 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
19201 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
19202 All such operations are handled by the routines in this part of the program.
19203
19204 The modifier part of each command code is zero for the ``ending delimiters''
19205 like \&{enddef} and \&{endfor}.
19206
19207 @d start_def 1 /* command modifier for \&{def} */
19208 @d var_def 2 /* command modifier for \&{vardef} */
19209 @d end_def 0 /* command modifier for \&{enddef} */
19210 @d start_forever 1 /* command modifier for \&{forever} */
19211 @d start_for 2 /* command modifier for \&{forever} */
19212 @d start_forsuffixes 3 /* command modifier for \&{forever} */
19213 @d end_for 0 /* command modifier for \&{endfor} */
19214
19215 @<Put each...@>=
19216 mp_primitive (mp, "def", mp_macro_def, start_def);
19217 @:def_}{\&{def} primitive@>
19218 mp_primitive (mp, "vardef", mp_macro_def, var_def);
19219 @:var_def_}{\&{vardef} primitive@>
19220 mp_primitive (mp, "primarydef", mp_macro_def, mp_secondary_primary_macro);
19221 @:primary_def_}{\&{primarydef} primitive@>
19222 mp_primitive (mp, "secondarydef", mp_macro_def, mp_tertiary_secondary_macro);
19223 @:secondary_def_}{\&{secondarydef} primitive@>
19224 mp_primitive (mp, "tertiarydef", mp_macro_def, mp_expression_tertiary_macro);
19225 @:tertiary_def_}{\&{tertiarydef} primitive@>
19226 mp_primitive (mp, "enddef", mp_macro_def, end_def);
19227 mp->frozen_end_def = mp_frozen_primitive (mp, "enddef", mp_macro_def, end_def);
19228 @:end_def_}{\&{enddef} primitive@>
19229 mp_primitive (mp, "for", mp_iteration, start_for);
19230 @:for_}{\&{for} primitive@>
19231 mp_primitive (mp, "forsuffixes", mp_iteration, start_forsuffixes);
19232 @:for_suffixes_}{\&{forsuffixes} primitive@>
19233 mp_primitive (mp, "forever", mp_iteration, start_forever);
19234 @:forever_}{\&{forever} primitive@>
19235 mp_primitive (mp, "endfor", mp_iteration, end_for);
19236 mp->frozen_end_for = mp_frozen_primitive (mp, "endfor", mp_iteration, end_for);
19237 @:end_for_}{\&{endfor} primitive@>
19238
19239
19240 @ @<Cases of |print_cmd...@>=
19241 case mp_macro_def:
19242 if (m <= var_def) {
19243 if (m == start_def)
19244 mp_print (mp, "def");
19245 else if (m < start_def)
19246 mp_print (mp, "enddef");
19247 else
19248 mp_print (mp, "vardef");
19249 } else if (m == mp_secondary_primary_macro) {
19250 mp_print (mp, "primarydef");
19251 } else if (m == mp_tertiary_secondary_macro) {
19252 mp_print (mp, "secondarydef");
19253 } else {
19254 mp_print (mp, "tertiarydef");
19255 }
19256 break;
19257 case mp_iteration:
19258 if (m == start_forever)
19259 mp_print (mp, "forever");
19260 else if (m == end_for)
19261 mp_print (mp, "endfor");
19262 else if (m == start_for)
19263 mp_print (mp, "for");
19264 else
19265 mp_print (mp, "forsuffixes");
19266 break;
19267
19268 @ Different macro-absorbing operations have different syntaxes, but they
19269 also have a lot in common. There is a list of special symbols that are to
19270 be replaced by parameter tokens; there is a special command code that
19271 ends the definition; the quotation conventions are identical. Therefore
19272 it makes sense to have most of the work done by a single subroutine. That
19273 subroutine is called |scan_toks|.
19274
19275 The first parameter to |scan_toks| is the command code that will
19276 terminate scanning (either |macro_def| or |iteration|).
19277
19278 The second parameter, |subst_list|, points to a (possibly empty) list
19279 of non-symbolic nodes whose |info| and |value| fields specify symbol tokens
19280 before and after replacement. The list will be returned to free storage
19281 by |scan_toks|.
19282
19283 The third parameter is simply appended to the token list that is built.
19284 And the final parameter tells how many of the special operations
19285 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
19286 When such parameters are present, they are called \.{(SUFFIX0)},
19287 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
19288
19289 @<Types...@>=
19290 typedef struct mp_subst_list_item {
19291 mp_name_type_type info_mod;
19292 quarterword value_mod;
19293 mp_sym info;
19294 halfword value_data;
19295 struct mp_subst_list_item *link;
19296 } mp_subst_list_item;
19297
19298 @ @c
19299 static mp_node mp_scan_toks (MP mp, mp_command_code terminator,
19300 mp_subst_list_item * subst_list, mp_node tail_end,
19301 quarterword suffix_count) {
19302 mp_node p; /* tail of the token list being built */
19303 mp_subst_list_item *q = NULL; /* temporary for link management */
19304 integer balance; /* left delimiters minus right delimiters */
19305 halfword cur_data;
19306 quarterword cur_data_mod = 0;
19307 p = mp->hold_head;
19308 balance = 1;
19309 mp_link (mp->hold_head) = NULL;
19310 while (1) {
19311 get_t_next (mp);
19312 cur_data = -1;
19313 if (cur_sym() != NULL) {
19314 @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
19315 if (cur_cmd() == terminator)
19316 @<Adjust the balance; |break| if it's zero@>@;
19317 else if (cur_cmd() == mp_macro_special) {
19318 /* Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#} */
19319 if (cur_mod() == quote) {
19320 get_t_next (mp);
19321 } else if (cur_mod() <= suffix_count) {
19322 cur_data = cur_mod() - 1;
19323 cur_data_mod = mp_suffix_sym;
19324 }
19325 }
19326 }
19327 if (cur_data != -1) {
19328 mp_node pp = mp_get_symbolic_node (mp);
19329 set_mp_sym_info (pp, cur_data);
19330 mp_name_type (pp) = cur_data_mod;
19331 mp_link (p) = pp;
19332 } else {
19333 mp_link (p) = mp_cur_tok (mp);
19334 }
19335 p = mp_link (p);
19336 }
19337 mp_link (p) = tail_end;
19338 while (subst_list) {
19339 q = subst_list->link;
19340 xfree (subst_list);
19341 subst_list = q;
19342 }
19343 return mp_link (mp->hold_head);
19344 }
19345
19346 @ @c
19347 void mp_print_sym (mp_sym sym) {
19348 printf("{type = %d, v = {type = %d, data = {indep = {scale = %d, serial = %d}, n = %d, str = %p, sym = %p, node = %p, p = %p}}, text = %p}\n",
19349 sym->type, sym->v.type, (int)sym->v.data.indep.scale, (int)sym->v.data.indep.serial,
19350 sym->v.data.n.type, (void*)sym->v.data.str, (void *)sym->v.data.sym, (void *)sym->v.data.node, (void *)sym->v.data.p, (void *)sym->text);
19351 if (is_number(sym->v.data.n)) {
19352 mp_number n = sym->v.data.n;
19353 printf("{data = {dval = %f, val = %"PRId64"}, type = %d}\n", n.data.dval, n.data.val, n.type);
19354 }
19355 if (sym->text != NULL) {
19356 mp_string t = sym->text;
19357 printf ("{str = %p \"%s\", len = %d, refs = %d}\n", t->str, t->str, (int)t->len, t->refs);
19358 }
19359 }
19360
19361 @ @<Declarations@>=
19362 void mp_print_sym (mp_sym sym) ;
19363
19364 @ @<Substitute for |cur_sym|...@>=
19365 {
19366 q = subst_list;
19367 while (q != NULL) {
19368 if (q->info == cur_sym() && q->info_mod == cur_sym_mod()) {
19369 cur_data = q->value_data;
19370 cur_data_mod = q->value_mod;
19371 set_cur_cmd((mp_variable_type)mp_relax);
19372 break;
19373 }
19374 q = q->link;
19375 }
19376 }
19377
19378
19379 @ @<Adjust the balance; |break| if it's zero@>=
19380 {
19381 if (cur_mod() > 0) {
19382 incr (balance);
19383 } else {
19384 decr (balance);
19385 if (balance == 0)
19386 break;
19387 }
19388 }
19389
19390 @ Four commands are intended to be used only within macro texts: \&{quote},
19391 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
19392 code called |macro_special|.
19393
19394 @d quote 0 /* |macro_special| modifier for \&{quote} */
19395 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
19396 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
19397 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
19398
19399 @<Put each...@>=
19400 mp_primitive (mp, "quote", mp_macro_special, quote);
19401 @:quote_}{\&{quote} primitive@>
19402 mp_primitive (mp, "#@@", mp_macro_special, macro_prefix);
19403 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
19404 mp_primitive (mp, "@@", mp_macro_special, macro_at);
19405 @:]]]\AT!_}{\.{\AT!} primitive@>
19406 mp_primitive (mp, "@@#", mp_macro_special, macro_suffix);
19407 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
19408
19409
19410 @ @<Cases of |print_cmd...@>=
19411 case mp_macro_special:
19412 switch (m) {
19413 case macro_prefix:
19414 mp_print (mp, "#@@");
19415 break;
19416 case macro_at:
19417 mp_print_char (mp, xord ('@@'));
19418 break;
19419 case macro_suffix:
19420 mp_print (mp, "@@#");
19421 break;
19422 default:
19423 mp_print (mp, "quote");
19424 break;
19425 }
19426 break;
19427
19428 @ Here is a routine that's used whenever a token will be redefined. If
19429 the user's token is unredefinable, the `|mp->frozen_inaccessible|' token is
19430 substituted; the latter is redefinable but essentially impossible to use,
19431 hence \MP's tables won't get fouled up.
19432
19433 @c
19434 static void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
19435 RESTART:
19436 get_t_next (mp);
19437 if ((cur_sym() == NULL) || mp_is_frozen(mp, cur_sym())) {
19438 const char *hlp[] = {
19439 "Sorry: You can\'t redefine a number, string, or expr.",
19440 "I've inserted an inaccessible symbol so that your",
19441 "definition will be completed without mixing me up too badly.",
19442 NULL };
19443 if (cur_sym() != NULL)
19444 hlp[0] = "Sorry: You can\'t redefine my error-recovery tokens.";
19445 else if (cur_cmd() == mp_string_token)
19446 delete_str_ref (cur_mod_str());
19447 set_cur_sym(mp->frozen_inaccessible);
19448 mp_ins_error (mp, "Missing symbolic token inserted", hlp, true);
19449 @.Missing symbolic token...@>
19450 goto RESTART;
19451 }
19452 }
19453
19454
19455 @ Before we actually redefine a symbolic token, we need to clear away its
19456 former value, if it was a variable. The following stronger version of
19457 |get_symbol| does that.
19458
19459 @c
19460 static void mp_get_clear_symbol (MP mp) {
19461 mp_get_symbol (mp);
19462 mp_clear_symbol (mp, cur_sym(), false);
19463 }
19464
19465
19466 @ Here's another little subroutine; it checks that an equals sign
19467 or assignment sign comes along at the proper place in a macro definition.
19468
19469 @c
19470 static void mp_check_equals (MP mp) {
19471 if (cur_cmd() != mp_equals)
19472 if (cur_cmd() != mp_assignment) {
19473 const char *hlp[] = {
19474 "The next thing in this `def' should have been `=',",
19475 "because I've already looked at the definition heading.",
19476 "But don't worry; I'll pretend that an equals sign",
19477 "was present. Everything from here to `enddef'",
19478 "will be the replacement text of this macro.",
19479 NULL };
19480 mp_back_error (mp, "Missing `=' has been inserted", hlp, true);
19481 @.Missing `='@>
19482 }
19483 }
19484
19485
19486 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
19487 handled now that we have |scan_toks|. In this case there are
19488 two parameters, which will be \.{EXPR0} and \.{EXPR1}.
19489
19490 @c
19491 static void mp_make_op_def (MP mp) {
19492 mp_command_code m; /* the type of definition */
19493 mp_node q, r; /* for list manipulation */
19494 mp_subst_list_item *qm = NULL, *qn = NULL;
19495 m = cur_mod();
19496 mp_get_symbol (mp);
19497 qm = xmalloc (1, sizeof (mp_subst_list_item));
19498 qm->link = NULL;
19499 qm->info = cur_sym();
19500 qm->info_mod = cur_sym_mod();
19501 qm->value_data = 0;
19502 qm->value_mod = mp_expr_sym;
19503 mp_get_clear_symbol (mp);
19504 mp->warning_info = cur_sym();
19505 mp_get_symbol (mp);
19506 qn = xmalloc (1, sizeof (mp_subst_list_item));
19507 qn->link = qm;
19508 qn->info = cur_sym();
19509 qn->info_mod = cur_sym_mod();
19510 qn->value_data = 1;
19511 qn->value_mod = mp_expr_sym;
19512 get_t_next (mp);
19513 mp_check_equals (mp);
19514 mp->scanner_status = op_defining;
19515 q = mp_get_symbolic_node (mp);
19516 set_ref_count (q, 0);
19517 r = mp_get_symbolic_node (mp);
19518 mp_link (q) = r;
19519 set_mp_sym_info (r, mp_general_macro);
19520 mp_name_type (r) = mp_macro_sym;
19521 mp_link (r) = mp_scan_toks (mp, mp_macro_def, qn, NULL, 0);
19522 mp->scanner_status = normal;
19523 set_eq_type (mp->warning_info, m);
19524 set_equiv_node (mp->warning_info, q);
19525 mp_get_x_next (mp);
19526 }
19527
19528
19529 @ Parameters to macros are introduced by the keywords \&{expr},
19530 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
19531
19532 @<Put each...@>=
19533 mp_primitive (mp, "expr", mp_param_type, mp_expr_param);
19534 @:expr_}{\&{expr} primitive@>
19535 mp_primitive (mp, "suffix", mp_param_type, mp_suffix_param);
19536 @:suffix_}{\&{suffix} primitive@>
19537 mp_primitive (mp, "text", mp_param_type, mp_text_param);
19538 @:text_}{\&{text} primitive@>
19539 mp_primitive (mp, "primary", mp_param_type, mp_primary_macro);
19540 @:primary_}{\&{primary} primitive@>
19541 mp_primitive (mp, "secondary", mp_param_type, mp_secondary_macro);
19542 @:secondary_}{\&{secondary} primitive@>
19543 mp_primitive (mp, "tertiary", mp_param_type, mp_tertiary_macro);
19544 @:tertiary_}{\&{tertiary} primitive@>
19545
19546
19547 @ @<Cases of |print_cmd...@>=
19548 case mp_param_type:
19549 if (m == mp_expr_param)
19550 mp_print (mp, "expr");
19551 else if (m == mp_suffix_param)
19552 mp_print (mp, "suffix");
19553 else if (m == mp_text_param)
19554 mp_print (mp, "text");
19555 else if (m == mp_primary_macro)
19556 mp_print (mp, "primary");
19557 else if (m == mp_secondary_macro)
19558 mp_print (mp, "secondary");
19559 else
19560 mp_print (mp, "tertiary");
19561 break;
19562
19563 @ Let's turn next to the more complex processing associated with \&{def}
19564 and \&{vardef}. When the following procedure is called, |cur_mod|
19565 should be either |start_def| or |var_def|.
19566
19567 Note that although the macro scanner allows \&{def} = := \&{enddef} and
19568 \&{def} := = \&{enddef}; \&{def} = = \&{enddef} and \&{def} := := \&{enddef}
19569 will generate an error because by the time the second of the two identical
19570 tokens is seen, its meaning has already become undefined.
19571
19572 @c
19573 static void mp_scan_def (MP mp) {
19574 mpinteger64 m; /* the type of definition */
19575 int n; /* the number of special suffix parameters */
19576 int k; /* the total number of parameters */
19577 mpinteger64 c; /* the kind of macro we're defining */
19578 mp_subst_list_item *r = NULL, *rp = NULL; /* parameter-substitution list */
19579 mp_node q; /* tail of the macro token list */
19580 mp_node p; /* temporary storage */
19581 quarterword sym_type; /* |expr_sym|, |suffix_sym|, or |text_sym| */
19582 mp_sym l_delim, r_delim; /* matching delimiters */
19583 m = cur_mod();
19584 c = mp_general_macro;
19585 mp_link (mp->hold_head) = NULL;
19586 q = mp_get_symbolic_node (mp);
19587 set_ref_count (q, 0);
19588 r = NULL;
19589 /* Scan the token or variable to be defined;
19590 set |n|, |scanner_status|, and |warning_info| */
19591 if (m == start_def) {
19592 mp_get_clear_symbol (mp);
19593 mp->warning_info = cur_sym();
19594 get_t_next (mp);
19595 mp->scanner_status = op_defining;
19596 n = 0;
19597 set_eq_type (mp->warning_info, mp_defined_macro);
19598 set_equiv_node (mp->warning_info, q);
19599 } else { /* |var_def| */
19600 p = mp_scan_declared_variable (mp);
19601 mp_flush_variable (mp, equiv_node (mp_sym_sym (p)), mp_link (p), true);
19602 mp->warning_info_node = mp_find_variable (mp, p);
19603 mp_flush_node_list (mp, p);
19604 if (mp->warning_info_node == NULL) {
19605 /* Change to `\.{a bad variable}' */
19606 const char *hlp[] = {
19607 "After `vardef a' you can\'t say `vardef a.b'.",
19608 "So I'll have to discard this definition.",
19609 NULL };
19610 mp_error (mp, "This variable already starts with a macro", hlp, true);
19611 mp->warning_info_node = mp->bad_vardef;
19612 }
19613 mp->scanner_status = var_defining;
19614 n = 2;
19615 if (cur_cmd() == mp_macro_special && cur_mod() == macro_suffix) { /* \.{\AT!\#} */
19616 n = 3;
19617 get_t_next (mp);
19618 }
19619 mp_type (mp->warning_info_node) = (quarterword) (mp_unsuffixed_macro - 2 + n);
19620 /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
19621 set_value_node (mp->warning_info_node, q);
19622 }
19623
19624 k = n;
19625 if (cur_cmd() == mp_left_delimiter) {
19626 /* Absorb delimited parameters, putting them into lists |q| and |r| */
19627 do {
19628 l_delim = cur_sym();
19629 r_delim = equiv_sym (cur_sym());
19630 get_t_next (mp);
19631 if ((cur_cmd() == mp_param_type) && (cur_mod() == mp_expr_param)) {
19632 sym_type = mp_expr_sym;
19633 } else if ((cur_cmd() == mp_param_type) && (cur_mod() == mp_suffix_param)) {
19634 sym_type = mp_suffix_sym;
19635 } else if ((cur_cmd() == mp_param_type) && (cur_mod() == mp_text_param)) {
19636 sym_type = mp_text_sym;
19637 } else {
19638 const char *hlp[] = { "You should've had `expr' or `suffix' or `text' here.", NULL };
19639 mp_back_error (mp, "Missing parameter type; `expr' will be assumed", hlp, true);
19640 sym_type = mp_expr_sym;
19641 }
19642 /* Absorb parameter tokens for type |sym_type| */
19643 do {
19644 mp_link (q) = mp_get_symbolic_node (mp);
19645 q = mp_link (q);
19646 mp_name_type (q) = sym_type;
19647 set_mp_sym_info (q, k);
19648 mp_get_symbol (mp);
19649 rp = xmalloc (1, sizeof (mp_subst_list_item));
19650 rp->link = NULL;
19651 rp->value_data = k;
19652 rp->value_mod = sym_type;
19653 rp->info = cur_sym();
19654 rp->info_mod = cur_sym_mod();
19655 mp_check_param_size (mp, k);
19656 incr (k);
19657 rp->link = r;
19658 r = rp;
19659 get_t_next (mp);
19660 } while (cur_cmd() == mp_comma);
19661
19662 mp_check_delimiter (mp, l_delim, r_delim);
19663 get_t_next (mp);
19664 } while (cur_cmd() == mp_left_delimiter);
19665
19666 }
19667 if (cur_cmd() == mp_param_type) {
19668 /* Absorb undelimited parameters, putting them into list |r| */
19669 rp = xmalloc (1, sizeof (mp_subst_list_item));
19670 rp->link = NULL;
19671 rp->value_data = k;
19672 if (cur_mod() == mp_expr_param) {
19673 rp->value_mod = mp_expr_sym;
19674 c = mp_expr_macro;
19675 } else if (cur_mod() == mp_suffix_param) {
19676 rp->value_mod = mp_suffix_sym;
19677 c = mp_suffix_macro;
19678 } else if (cur_mod() == mp_text_param) {
19679 rp->value_mod = mp_text_sym;
19680 c = mp_text_macro;
19681 } else {
19682 c = cur_mod();
19683 rp->value_mod = mp_expr_sym;
19684 }
19685 mp_check_param_size (mp, k);
19686 incr (k);
19687 mp_get_symbol (mp);
19688 rp->info = cur_sym();
19689 rp->info_mod = cur_sym_mod();
19690 rp->link = r;
19691 r = rp;
19692 get_t_next (mp);
19693 if (c == mp_expr_macro) {
19694 if (cur_cmd() == mp_of_token) {
19695 c = mp_of_macro;
19696 rp = xmalloc (1, sizeof (mp_subst_list_item));
19697 rp->link = NULL;
19698 mp_check_param_size (mp, k);
19699 rp->value_data = k;
19700 rp->value_mod = mp_expr_sym;
19701 mp_get_symbol (mp);
19702 rp->info = cur_sym();
19703 rp->info_mod = cur_sym_mod();
19704 rp->link = r;
19705 r = rp;
19706 get_t_next (mp);
19707 }
19708 }
19709 }
19710 mp_check_equals (mp);
19711 p = mp_get_symbolic_node (mp);
19712 set_mp_sym_info (p, c);
19713 mp_name_type (p) = mp_macro_sym;
19714 mp_link (q) = p;
19715 /* Attach the replacement text to the tail of node |p| */
19716 /* We don't put `|mp->frozen_end_group|' into the replacement text of
19717 a \&{vardef}, because the user may want to redefine `\.{endgroup}'. */
19718 if (m == start_def) {
19719 mp_link (p) = mp_scan_toks (mp, mp_macro_def, r, NULL, (quarterword) n);
19720 } else {
19721 mp_node qq = mp_get_symbolic_node (mp);
19722 set_mp_sym_sym (qq, mp->bg_loc);
19723 mp_link (p) = qq;
19724 p = mp_get_symbolic_node (mp);
19725 set_mp_sym_sym (p, mp->eg_loc);
19726 mp_link (qq) = mp_scan_toks (mp, mp_macro_def, r, p, (quarterword) n);
19727 }
19728 if (mp->warning_info_node == mp->bad_vardef)
19729 mp_flush_token_list (mp, value_node (mp->bad_vardef));
19730 mp->scanner_status = normal;
19731 mp_get_x_next (mp);
19732 }
19733
19734 @ @<Glob...@>=
19735 mp_sym bg_loc;
19736 mp_sym eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
19737
19738 @ @<Initialize table entries@>=
19739 mp->bad_vardef = mp_get_value_node (mp);
19740 mp_name_type (mp->bad_vardef) = mp_root;
19741 set_value_sym (mp->bad_vardef, mp->frozen_bad_vardef);
19742
19743 @ @<Free table entries@>=
19744 mp_free_value_node (mp, mp->bad_vardef);
19745
19746
19747 @* Expanding the next token.
19748 Only a few command codes |<min_command| can possibly be returned by
19749 |get_t_next|; in increasing order, they are
19750 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
19751 |exit_test|, |relax|, |scan_tokens|, |run_script|, |expand_after|, and |defined_macro|.
19752
19753 \MP\ usually gets the next token of input by saying |get_x_next|. This is
19754 like |get_t_next| except that it keeps getting more tokens until
19755 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
19756 macros and removes conditionals or iterations or input instructions that
19757 might be present.
19758
19759 It follows that |get_x_next| might invoke itself recursively. In fact,
19760 there is massive recursion, since macro expansion can involve the
19761 scanning of arbitrarily complex expressions, which in turn involve
19762 macro expansion and conditionals, etc.
19763 @^recursion@>
19764
19765 Therefore it's necessary to declare a whole bunch of |forward|
19766 procedures at this point, and to insert some other procedures
19767 that will be invoked by |get_x_next|.
19768
19769 @<Declarations@>=
19770 static void mp_scan_primary (MP mp);
19771 static void mp_scan_secondary (MP mp);
19772 static void mp_scan_tertiary (MP mp);
19773 static void mp_scan_expression (MP mp);
19774 static void mp_scan_suffix (MP mp);
19775 static void mp_pass_text (MP mp);
19776 static void mp_conditional (MP mp);
19777 static void mp_start_input (MP mp);
19778 static void mp_begin_iteration (MP mp);
19779 static void mp_resume_iteration (MP mp);
19780 static void mp_stop_iteration (MP mp);
19781
19782 @ A recursion depth counter is used to discover infinite recursions.
19783 (Near) infinite recursion is a problem because it translates into
19784 C function calls that eat up the available call stack. A better solution
19785 would be to depend on signal trapping, but that is problematic when
19786 \MP\ is used as a library.
19787
19788 @<Global...@>=
19789 int expand_depth_count; /* current expansion depth */
19790 int expand_depth; /* current expansion depth */
19791
19792 @ The limit is set at |10000|, which should be enough to allow
19793 normal usages of metapost while preventing the most obvious
19794 crashes on most all operating systems, but the value can be
19795 raised if the runtime system allows a larger C stack.
19796 @^system dependencies@>
19797
19798 @<Set initial...@>=
19799 mp->expand_depth = 10000;
19800
19801 @ Even better would be if the system allows discovery of the amount of
19802 space available on the call stack.
19803 @^system dependencies@>
19804
19805 In any case, when the limit is crossed, that is a fatal error.
19806
19807 @d check_expansion_depth() if (++mp->expand_depth_count >= mp->expand_depth)
19808 mp_expansion_depth_error(mp)
19809
19810 @c
19811 static void mp_expansion_depth_error (MP mp) {
19812 const char *hlp[] = {
19813 "Recursive macro expansion cannot be unlimited because of runtime",
19814 "stack constraints. The limit is 10000 recursion levels in total.",
19815 NULL };
19816 if ( mp->interaction==mp_error_stop_mode )
19817 mp->interaction=mp_scroll_mode; /* no more interaction */
19818 if ( mp->log_opened )
19819 mp_error(mp, "Maximum expansion depth reached", hlp, true);
19820 mp->history=mp_fatal_error_stop;
19821 mp_jump_out(mp);
19822 }
19823
19824
19825 @ An auxiliary subroutine called |expand| is used by |get_x_next|
19826 when it has to do exotic expansion commands.
19827
19828 @c
19829 static void mp_expand (MP mp) {
19830 size_t k; /* something that we hope is |<=buf_size| */
19831 size_t j; /* index into |str_pool| */
19832 check_expansion_depth();
19833 if (number_greater (internal_value (mp_tracing_commands), unity_t))
19834 if (cur_cmd() != mp_defined_macro)
19835 show_cur_cmd_mod;
19836 switch (cur_cmd()) {
19837 case mp_if_test:
19838 mp_conditional (mp); /* this procedure is discussed in Part ``Conditional processing'' below */
19839 break;
19840 case mp_fi_or_else:
19841 @<Terminate the current conditional and skip to \&{fi}@>;
19842 break;
19843 case mp_input:
19844 @<Initiate or terminate input from a file@>;
19845 break;
19846 case mp_iteration:
19847 if (cur_mod() == end_for)
19848 @<Scold the user for having an extra \&{endfor}@>@;
19849 else {
19850 mp_begin_iteration (mp); /* this procedure is discussed in Part ``Iterations'' below */
19851 }
19852 break;
19853 case mp_repeat_loop:
19854 @<Repeat a loop@>;
19855 break;
19856 case mp_exit_test:
19857 @<Exit a loop if the proper time has come@>;
19858 break;
19859 case mp_relax:
19860 break;
19861 case mp_expand_after:
19862 @<Expand the token after the next token@>;
19863 break;
19864 case mp_scan_tokens:
19865 @<Put a string into the input buffer@>;
19866 break;
19867 case mp_runscript:
19868 @<Put a script result string into the input buffer@>;
19869 break;
19870 case mp_maketext:
19871 @<Put a maketext result string into the input buffer@>;
19872 break;
19873 case mp_defined_macro:
19874 mp_macro_call (mp, cur_mod_node(), NULL, cur_sym());
19875 break;
19876 default:
19877 break; /* make the compiler happy */
19878 } /* there are no other cases */
19879 mp->expand_depth_count--;
19880 }
19881
19882
19883 @ @<Scold the user...@>=
19884 {
19885 const char *hlp[] = {
19886 "I'm not currently working on a for loop,",
19887 "so I had better not try to end anything.",
19888 NULL };
19889 mp_error (mp, "Extra `endfor'", hlp, true);
19890 @.Extra `endfor'@>
19891 }
19892
19893
19894 @ The processing of \&{input} involves the |mp_start_input| subroutine,
19895 which will be declared later; the processing of \&{endinput} is trivial.
19896
19897 @<Put each...@>=
19898 mp_primitive (mp, "input", mp_input, 0);
19899 @:input_}{\&{input} primitive@>
19900 mp_primitive (mp, "endinput", mp_input, 1);
19901 @:end_input_}{\&{endinput} primitive@>
19902
19903
19904 @ @<Cases of |print_cmd_mod|...@>=
19905 case mp_input:
19906 if (m == 0)
19907 mp_print (mp, "input");
19908 else
19909 mp_print (mp, "endinput");
19910 break;
19911
19912 @ @<Initiate or terminate input...@>=
19913 if (cur_mod() > 0)
19914 mp->force_eof = true;
19915 else
19916 mp_start_input (mp)
19917
19918
19919 @ We'll discuss the complicated parts of loop operations later. For now
19920 it suffices to know that there's a global variable called |loop_ptr|
19921 that will be |NULL| if no loop is in progress.
19922
19923 @<Repeat a loop@>=
19924 {
19925 while (token_state && (nloc == NULL))
19926 mp_end_token_list (mp); /* conserve stack space */
19927 if (mp->loop_ptr == NULL) {
19928 const char *hlp[] = {
19929 "I'm confused; after exiting from a loop, I still seem",
19930 "to want to repeat it. I'll try to forget the problem.",
19931 NULL };
19932 mp_error (mp, "Lost loop", hlp, true);
19933 @.Lost loop@>
19934 } else {
19935 mp_resume_iteration (mp); /* this procedure is in Part ``Iterations'' below */
19936 }
19937 }
19938
19939
19940 @ @<Exit a loop if the proper time has come@>=
19941 {
19942 mp_get_boolean (mp);
19943 if (number_greater (internal_value (mp_tracing_commands), unity_t))
19944 mp_show_cmd_mod (mp, mp_nullary, cur_exp_value_boolean ());
19945 if (cur_exp_value_boolean () == mp_true_code) {
19946 if (mp->loop_ptr == NULL) {
19947 const char *hlp[] = {
19948 "Why say `exitif' when there's nothing to exit from?",
19949 NULL };
19950 if (cur_cmd() == mp_semicolon)
19951 mp_error (mp, "No loop is in progress", hlp, true);
19952 else
19953 mp_back_error (mp, "No loop is in progress", hlp, true);
19954 @.No loop is in progress@>
19955 } else
19956 @<Exit prematurely from an iteration@>@;
19957 } else if (cur_cmd() != mp_semicolon) {
19958 const char *hlp[] = {
19959 "After `exitif <boolean exp>' I expect to see a semicolon.",
19960 "I shall pretend that one was there.",
19961 NULL };
19962 mp_back_error (mp, "Missing `;' has been inserted", hlp, true);
19963 @.Missing `;'@>
19964 }
19965 }
19966
19967
19968 @ Here we use the fact that |forever_text| is the only |token_type| that
19969 is less than |loop_text|.
19970
19971 @<Exit prematurely...@>=
19972 {
19973 mp_node p = NULL;
19974 do {
19975 if (file_state) {
19976 mp_end_file_reading (mp);
19977 } else {
19978 if (token_type <= loop_text)
19979 p = nstart;
19980 mp_end_token_list (mp);
19981 }
19982 } while (p == NULL);
19983 if (p != mp->loop_ptr->info)
19984 mp_fatal_error (mp, "*** (loop confusion)");
19985 @.loop confusion@>
19986 mp_stop_iteration (mp); /* this procedure is in Part ``Iterations'' below */
19987 }
19988
19989
19990 @ @<Expand the token after the next token@>=
19991 {
19992 mp_node p;
19993 get_t_next (mp);
19994 p = mp_cur_tok (mp);
19995 get_t_next (mp);
19996 if (cur_cmd() < mp_min_command)
19997 mp_expand (mp);
19998 else
19999 mp_back_input (mp);
20000 back_list (p);
20001 }
20002
20003
20004 @ @<Put a string into the input buffer@>=
20005 {
20006 mp_get_x_next (mp);
20007 mp_scan_primary (mp);
20008 if (mp->cur_exp.type != mp_string_type) {
20009 mp_value new_expr;
20010 const char *hlp[] = {
20011 "I'm going to flush this expression, since",
20012 "scantokens should be followed by a known string.",
20013 NULL };
20014 memset(&new_expr,0,sizeof(mp_value));
20015 new_number(new_expr.data.n);
20016 mp_disp_err (mp, NULL);
20017 mp_back_error (mp, "Not a string", hlp, true);
20018 @.Not a string@>
20019 mp_get_x_next (mp);
20020 mp_flush_cur_exp (mp, new_expr);
20021 } else {
20022 mp_back_input (mp);
20023 if (cur_exp_str ()->len > 0)
20024 @<Pretend we're reading a new one-line file@>;
20025 }
20026 }
20027
20028 @ @<Run a script@>=
20029 if (s != NULL) {
20030 int k ;
20031 mp_value new_expr;
20032 size_t size = strlen(s);
20033 memset(&new_expr,0,sizeof(mp_value));
20034 new_number(new_expr.data.n);
20035 mp_begin_file_reading (mp);
20036 name = is_scantok;
20037 mp->last = mp->first;
20038 k = mp->first + size;
20039 if (k >= mp->max_buf_stack) {
20040 while (k >= mp->buf_size) {
20041 mp_reallocate_buffer (mp, (mp->buf_size + (mp->buf_size / 4)));
20042 }
20043 mp->max_buf_stack = k + 1;
20044 }
20045 limit = (halfword) k;
20046 (void) memcpy ((mp->buffer + mp->first), s, size);
20047 mp->buffer[limit] = xord ('%');
20048 mp->first = (size_t) (limit + 1);
20049 loc = start;
20050 mp_flush_cur_exp (mp, new_expr);
20051 }
20052
20053 @ @<Put a script result string into the input buffer@>=
20054 {
20055
20056 if (mp->extensions == 0) {
20057 return ;
20058 }
20059 mp_get_x_next (mp);
20060 mp_scan_primary (mp);
20061 if (mp->cur_exp.type != mp_string_type) {
20062 mp_value new_expr;
20063 const char *hlp[] = {
20064 "I'm going to flush this expression, since",
20065 "runscript should be followed by a known string.",
20066 NULL };
20067 memset(&new_expr,0,sizeof(mp_value));
20068 new_number(new_expr.data.n);
20069 mp_disp_err (mp, NULL);
20070 mp_back_error (mp, "Not a string", hlp, true);
20071 @.Not a string@>
20072 mp_get_x_next (mp);
20073 mp_flush_cur_exp (mp, new_expr);
20074 } else {
20075 mp_back_input (mp);
20076 if (cur_exp_str ()->len > 0) {
20077 char *s = mp->run_script(mp,(const char*) cur_exp_str()->str, cur_exp_str()->len) ;
20078 @<Run a script@>@;
20079 free(s);
20080 }
20081 }
20082 }
20083
20084 @ The |texscriptmode| parameter controls how spaces and newlines get honored in
20085 \&{btex} or \&{verbatimtex} ... \&{etex}. The default value is~1. Possible
20086 values are: 0: no newlines, 1: newlines in \&{verbatimtex}, 2: newlines in
20087 \&{verbatimtex} and \&{etex}, 3: no leading and trailing strip in
20088 \&{verbatimtex}, 4: no leading and trailing strip in \&{verbatimtex} and
20089 \&{btex}. That way the Lua handler can do what it likes. An \&{etex} has to be
20090 followed by a space or |;| or be at the end of a line and preceded by a space
20091 or at the beginning of a line.
20092
20093 @<Pass \&{btex} ... \&{etex} to script@>=
20094 {
20095 char *txt = NULL;
20096 char *ptr = NULL;
20097 mpinteger64 slin = line;
20098 int size = 0;
20099 int done = 0;
20100 mpinteger64 mode = round_unscaled(internal_value(mp_texscriptmode)) ; /* default: 1 */
20101 int verb = cur_mod() == verbatim_code;
20102 int first;
20103 /* we had a (mandate) trailing space */
20104 if (loc <= limit && mp->char_class[mp->buffer[loc]] == space_class) {
20105 incr(loc);
20106 } else {
20107 /* maybe issue an error message and quit */
20108 }
20109 /* we loop over lines */
20110 first = loc;
20111 while (1) {
20112 /* we don't need to check when we have less than 4 characters left */
20113 if (loc < limit - 4) {
20114 if (mp->buffer[loc] == 'e') {
20115 incr(loc);
20116 if (mp->buffer[loc] == 't') {
20117 incr(loc) ;
20118 if (mp->buffer[loc] == 'e') {
20119 incr(loc) ;
20120 if (mp->buffer[loc] == 'x') {
20121 /* let's see if we have the right boundary */
20122 if (first == (loc - 3)) {
20123 /* when we're at the start of a line no leading space is required */
20124 done = 1;
20125 } else if (mp->char_class[mp->buffer[loc - 4]] == space_class) {
20126 /* when we're beyond the start of a line a leading space is required */
20127 done = 2;
20128 }
20129 if (done) {
20130 if ((loc + 1) <= limit) {
20131 quarterword c = mp->char_class[mp->buffer[loc + 1]] ;
20132 if (c != letter_class) {
20133 incr(loc) ;
20134 /* we're past the 'x' */
20135 break;
20136 } else {
20137 /* this is no valid \&{etex} */
20138 done = 0;
20139 }
20140 } else {
20141 /* when we're at the end of a line we're ok */
20142 incr(loc) ;
20143 /* we're past the 'x' */
20144 break;
20145 }
20146 }
20147 }
20148 }
20149 }
20150 }
20151 }
20152 /* no \&{etex} seen (yet) */
20153 if (loc >= limit) {
20154 if (size) {
20155 txt = realloc(txt, size + limit - first + 1);
20156 } else {
20157 txt = malloc(limit - first + 1);
20158 }
20159 (void) memcpy (txt + size, mp->buffer + first, limit - first);
20160 size += limit - first + 1;
20161 if (mode <= 0) {
20162 txt[size - 1] = ' ';
20163 } else if (verb) {
20164 /* modes $\geq 1$ permit a newline in \&{verbatimtex} */
20165 txt[size - 1] = '\n';
20166 } else if (mode >= 2) {
20167 /* modes $\geq 2$ permit a newline in \&{btex} */
20168 txt[size - 1] = '\n';
20169 } else {
20170 txt[size - 1] = ' ';
20171 }
20172 if (move_to_next_line(mp)) {
20173 /* we abort the scanning */
20174 goto FATAL_ERROR;
20175 }
20176 first = loc;
20177 } else {
20178 incr(loc);
20179 }
20180 }
20181 if (done) {
20182 /* we're past the 'x' */
20183 int l = loc - 5 ; // 4
20184 int n = l - first + 1 ;
20185 /* we're before the \&{etex} */
20186 if (done == 2) {
20187 /* we had \&{etex} */
20188 l -= 1;
20189 n -= 1;
20190 /* we're before the \&{etex} */
20191 }
20192 if (size) {
20193 txt = realloc(txt, size + n + 1);
20194 } else {
20195 txt = malloc(n + 1);
20196 }
20197 (void) memcpy (txt + size, mp->buffer + first, n); /* 0 */
20198 size += n;
20199 if (verb && mode >= 3) {
20200 /* don't strip \&{verbatimtex} */
20201 txt[size] = '\0';
20202 ptr = txt;
20203 } else if (mode >= 4) {
20204 /* don't strip \&{btex} */
20205 txt[size] = '\0';
20206 ptr = txt;
20207 } else {
20208 /* strip trailing whitespace, we have a |'\0'| so we are off by one */
20209 /* |while ((size > 1) && (mp->char_class[(ASCII_code) txt[size-2]] == space_class| $\vbv\vbv$ |txt[size-2] == '\n')) | */
20210 while ((size > 1) && (mp->char_class[(ASCII_code) txt[size-1]] == space_class || txt[size-1] == '\n')) {
20211 decr(size);
20212 }
20213 /* prune the string */
20214 txt[size] = '\0';
20215 /* strip leading whitespace */
20216 ptr = txt;
20217 while ((size > 1) && (mp->char_class[(ASCII_code) ptr[0]] == space_class || ptr[0] == '\n')) {
20218 incr(ptr);
20219 decr(size);
20220 }
20221 }
20222 /* action */
20223 {
20224 char *s = mp->make_text(mp,ptr,size,verb) ;
20225 @<Run a script@>@;
20226 free(s);
20227 }
20228 free(txt);
20229 /* really needed */
20230 mp_get_next(mp);
20231 return;
20232 }
20233 /*
20234 we don't recover because in practice the graphic will be broken anyway and
20235 we're not really interacting in mplib .. just fix the input
20236 */
20237 FATAL_ERROR:
20238 {
20239 /* line numbers are not always meaningful so we can get a 0 reported */
20240 char msg[256];
20241 const char *hlp[] = { "An 'etex' is missing at this input level, nothing gets done.", NULL };
20242 if (slin > 0) {
20243 mp_snprintf(msg, 256, "No matching 'etex' for '%stex'.", verb ? "verbatim" : "b");
20244 } else {
20245 mp_snprintf(msg, 256, "No matching 'etex' for '%stex' in line %"PRId64".", verb ? "verbatim" : "b",slin);
20246 }
20247 mp_error (mp, msg, hlp, false);
20248 free(txt);
20249 }
20250 }
20251
20252 @ @<Put a maketext result string into the input buffer@>=
20253 {
20254 if (mp->extensions == 0) {
20255 return ;
20256 }
20257 mp_get_x_next (mp);
20258 mp_scan_primary (mp);
20259 if (mp->cur_exp.type != mp_string_type) {
20260 mp_value new_expr;
20261 const char *hlp[] = {
20262 "I'm going to flush this expression, since",
20263 "maketext should be followed by a known string.",
20264 NULL };
20265 memset(&new_expr,0,sizeof(mp_value));
20266 new_number(new_expr.data.n);
20267 mp_disp_err (mp, NULL);
20268 mp_back_error (mp, "Not a string", hlp, true);
20269 @.Not a string@>
20270 mp_get_x_next (mp);
20271 mp_flush_cur_exp (mp, new_expr);
20272 } else {
20273 mp_back_input (mp);
20274 if (cur_exp_str ()->len > 0) {
20275 char *s = mp->make_text(mp,(const char*) cur_exp_str()->str,cur_exp_str()->len,0) ;
20276 @<Run a script@>@;
20277 free(s);
20278 }
20279 }
20280 }
20281
20282 @ @<Pretend we're reading a new one-line file@>=
20283 {
20284 mp_value new_expr;
20285 memset(&new_expr,0,sizeof(mp_value));
20286 new_number(new_expr.data.n);
20287 mp_begin_file_reading (mp);
20288 name = is_scantok;
20289 k = mp->first + (size_t) cur_exp_str ()->len;
20290 if (k >= mp->max_buf_stack) {
20291 while (k >= mp->buf_size) {
20292 mp_reallocate_buffer (mp, (mp->buf_size + (mp->buf_size / 4)));
20293 }
20294 mp->max_buf_stack = k + 1;
20295 }
20296 j = 0;
20297 limit = (halfword) k;
20298 while (mp->first < (size_t) limit) {
20299 mp->buffer[mp->first] = *(cur_exp_str ()->str + j);
20300 j++;
20301 incr (mp->first);
20302 }
20303 mp->buffer[limit] = xord ('%');
20304 mp->first = (size_t) (limit + 1);
20305 loc = start;
20306 mp_flush_cur_exp (mp, new_expr);
20307 }
20308
20309
20310 @ Here finally is |get_x_next|.
20311
20312 The expression scanning routines to be considered later
20313 communicate via the global quantities |cur_type| and |cur_exp|;
20314 we must be very careful to save and restore these quantities while
20315 macros are being expanded.
20316 @^inner loop@>
20317
20318 @<Declarations@>=
20319 static void mp_get_x_next (MP mp);
20320
20321 @ @c
20322 void mp_get_x_next (MP mp) {
20323 mp_node save_exp; /* a capsule to save |cur_type| and |cur_exp| */
20324 get_t_next (mp);
20325 if (cur_cmd() < mp_min_command) {
20326 save_exp = mp_stash_cur_exp (mp);
20327 do {
20328 if (cur_cmd() == mp_defined_macro)
20329 mp_macro_call (mp, cur_mod_node(), NULL, cur_sym());
20330 else
20331 mp_expand (mp);
20332 get_t_next (mp);
20333 } while (cur_cmd() < mp_min_command);
20334 mp_unstash_cur_exp (mp, save_exp); /* that restores |cur_type| and |cur_exp| */
20335 }
20336 }
20337
20338
20339 @ Now let's consider the |macro_call| procedure, which is used to start up
20340 all user-defined macros. Since the arguments to a macro might be expressions,
20341 |macro_call| is recursive.
20342 @^recursion@>
20343
20344 The first parameter to |macro_call| points to the reference count of the
20345 token list that defines the macro. The second parameter contains any
20346 arguments that have already been parsed (see below). The third parameter
20347 points to the symbolic token that names the macro. If the third parameter
20348 is |NULL|, the macro was defined by \&{vardef}, so its name can be
20349 reconstructed from the prefix and ``at'' arguments found within the
20350 second parameter.
20351
20352 What is this second parameter? It's simply a linked list of symbolic items,
20353 whose |info| fields point to the arguments. In other words, if |arg_list=NULL|,
20354 no arguments have been scanned yet; otherwise |mp_info(arg_list)| points to
20355 the first scanned argument, and |mp_link(arg_list)| points to the list of
20356 further arguments (if any).
20357
20358 Arguments of type \&{expr} are so-called capsules, which we will
20359 discuss later when we concentrate on expressions; they can be
20360 recognized easily because their |link| field is |void|. Arguments of type
20361 \&{suffix} and \&{text} are token lists without reference counts.
20362
20363 @ After argument scanning is complete, the arguments are moved to the
20364 |param_stack|. (They can't be put on that stack any sooner, because
20365 the stack is growing and shrinking in unpredictable ways as more arguments
20366 are being acquired.) Then the macro body is fed to the scanner; i.e.,
20367 the replacement text of the macro is placed at the top of the \MP's
20368 input stack, so that |get_t_next| will proceed to read it next.
20369
20370 @<Declarations@>=
20371 static void mp_macro_call (MP mp, mp_node def_ref, mp_node arg_list,
20372 mp_sym macro_name);
20373
20374 @ @c
20375 void mp_macro_call (MP mp, mp_node def_ref, mp_node arg_list, mp_sym macro_name) {
20376 /* invokes a user-defined control sequence */
20377 mp_node r; /* current node in the macro's token list */
20378 mp_node p, q; /* for list manipulation */
20379 integer n; /* the number of arguments */
20380 mp_node tail = 0; /* tail of the argument list */
20381 mp_sym l_delim = NULL, r_delim = NULL; /* a delimiter pair */
20382 r = mp_link (def_ref);
20383 add_mac_ref (def_ref);
20384 if (arg_list == NULL) {
20385 n = 0;
20386 } else
20387 @<Determine the number |n| of arguments already supplied,
20388 and set |tail| to the tail of |arg_list|@>@;
20389 if (number_positive (internal_value (mp_tracing_macros)))
20390 @<Show the text of the macro being expanded, and the existing arguments@>@;
20391 @<Scan the remaining arguments, if any; set |r| to the first token
20392 of the replacement text@>;
20393 @<Feed the arguments and replacement text to the scanner@>;
20394 }
20395
20396
20397 @ @<Show the text of the macro...@>=
20398 {
20399 mp_begin_diagnostic (mp);
20400 mp_print_ln (mp);
20401 mp_print_macro_name (mp, arg_list, macro_name);
20402 if (n == 3)
20403 mp_print (mp, "@@#"); /* indicate a suffixed macro */
20404 mp_show_macro (mp, def_ref, NULL, 100000);
20405 if (arg_list != NULL) {
20406 n = 0;
20407 p = arg_list;
20408 do {
20409 q = (mp_node)mp_sym_sym (p);
20410 mp_print_arg (mp, q, n, 0, 0);
20411 incr (n);
20412 p = mp_link (p);
20413 } while (p != NULL);
20414 }
20415 mp_end_diagnostic (mp, false);
20416 }
20417
20418 @ @<Declarations@>=
20419 static void mp_print_macro_name (MP mp, mp_node a, mp_sym n);
20420
20421 @ @c
20422 void mp_print_macro_name (MP mp, mp_node a, mp_sym n) {
20423 mp_node p, q; /* they traverse the first part of |a| */
20424 if (n != NULL) {
20425 mp_print_text (n);
20426 } else {
20427 p = (mp_node)mp_sym_sym (a);
20428 if (p == NULL) {
20429 mp_print_text (mp_sym_sym ((mp_node)mp_sym_sym (mp_link (a))));
20430 } else {
20431 q = p;
20432 while (mp_link (q) != NULL)
20433 q = mp_link (q);
20434 mp_link (q) = (mp_node)mp_sym_sym (mp_link (a));
20435 mp_show_token_list (mp, p, NULL, 1000, 0);
20436 mp_link (q) = NULL;
20437 }
20438 }
20439 }
20440
20441
20442 @ @<Declarations@>=
20443 static void mp_print_arg (MP mp, mp_node q, integer n, halfword b,
20444 quarterword bb);
20445
20446 @ @c
20447 void mp_print_arg (MP mp, mp_node q, integer n, halfword b, quarterword bb) {
20448 if (q && mp_link (q) == MP_VOID) {
20449 mp_print_nl (mp, "(EXPR");
20450 } else {
20451 if ((bb < mp_text_sym) && (b != mp_text_macro))
20452 mp_print_nl (mp, "(SUFFIX");
20453 else
20454 mp_print_nl (mp, "(TEXT");
20455 }
20456 mp_print_int (mp, n);
20457 mp_print (mp, ")<-");
20458 if (q && mp_link (q) == MP_VOID)
20459 mp_print_exp (mp, q, 1);
20460 else
20461 mp_show_token_list (mp, q, NULL, 1000, 0);
20462 }
20463
20464
20465 @ @<Determine the number |n| of arguments already supplied...@>=
20466 {
20467 n = 1;
20468 tail = arg_list;
20469 while (mp_link (tail) != NULL) {
20470 incr (n);
20471 tail = mp_link (tail);
20472 }
20473 }
20474
20475
20476 @ @<Scan the remaining arguments, if any; set |r|...@>=
20477 set_cur_cmd(mp_comma + 1); /* anything |<>comma| will do */
20478 while (mp_name_type (r) == mp_expr_sym ||
20479 mp_name_type (r) == mp_suffix_sym || mp_name_type (r) == mp_text_sym) {
20480 @<Scan the delimited argument represented by |mp_sym_info(r)|@>;
20481 r = mp_link (r);
20482 }
20483 if (cur_cmd() == mp_comma) {
20484 char msg[256];
20485 const char *hlp[] = {
20486 "I'm going to assume that the comma I just read was a",
20487 "right delimiter, and then I'll begin expanding the macro.",
20488 "You might want to delete some tokens before continuing.",
20489 NULL };
20490 mp_string rname;
20491 int old_setting = mp->selector;
20492 mp->selector = new_string;
20493 mp_print_macro_name (mp, arg_list, macro_name);
20494 rname = mp_make_string(mp);
20495 mp->selector = old_setting;
20496 mp_snprintf (msg, 256, "Too many arguments to %s; Missing `%s' has been inserted",
20497 mp_str(mp, rname), mp_str(mp, text(r_delim)));
20498 delete_str_ref(rname);
20499 @.Too many arguments...@>
20500 @.Missing `)'...@>
20501 mp_error (mp, msg, hlp, true);
20502 }
20503 if (mp_sym_info (r) != mp_general_macro)
20504 @<Scan undelimited argument(s)@>@;
20505 r = mp_link (r)
20506
20507
20508 @ At this point, the reader will find it advisable to review the explanation
20509 of token list format that was presented earlier, paying special attention to
20510 the conventions that apply only at the beginning of a macro's token list.
20511
20512 On the other hand, the reader will have to take the expression-parsing
20513 aspects of the following program on faith; we will explain |cur_type|
20514 and |cur_exp| later. (Several things in this program depend on each other,
20515 and it's necessary to jump into the circle somewhere.)
20516
20517 @<Scan the delimited argument represented by |mp_sym_info(r)|@>=
20518 if (cur_cmd() != mp_comma) {
20519 mp_get_x_next (mp);
20520 if (cur_cmd() != mp_left_delimiter) {
20521 char msg[256];
20522 const char *hlp[] = {
20523 "That macro has more parameters than you thought.",
20524 "I'll continue by pretending that each missing argument",
20525 "is either zero or null.",
20526 NULL };
20527 mp_string sname;
20528 int old_setting = mp->selector;
20529 mp->selector = new_string;
20530 mp_print_macro_name (mp, arg_list, macro_name);
20531 sname = mp_make_string(mp);
20532 mp->selector = old_setting;
20533 mp_snprintf (msg, 256, "Missing argument to %s", mp_str(mp, sname));
20534 @.Missing argument...@>
20535 delete_str_ref(sname);
20536 if (mp_name_type (r) == mp_suffix_sym || mp_name_type (r) == mp_text_sym) {
20537 set_cur_exp_value_number (zero_t); /* TODO: this was |NULL| */
20538 mp->cur_exp.type = mp_token_list;
20539 } else {
20540 set_cur_exp_value_number (zero_t);
20541 mp->cur_exp.type = mp_known;
20542 }
20543 mp_back_error (mp, msg, hlp, true);
20544 set_cur_cmd((mp_variable_type)mp_right_delimiter);
20545 goto FOUND;
20546 }
20547 l_delim = cur_sym();
20548 r_delim = equiv_sym (cur_sym());
20549 }
20550 @<Scan the argument represented by |mp_sym_info(r)|@>
20551 if (cur_cmd() != mp_comma)
20552 @<Check that the proper right delimiter was present@>@;
20553 FOUND:
20554 @<Append the current expression to |arg_list|@>
20555
20556
20557 @ @<Check that the proper right delim...@>=
20558 if ((cur_cmd() != mp_right_delimiter) || (equiv_sym (cur_sym()) != l_delim)) {
20559 if (mp_name_type (mp_link (r)) == mp_expr_sym ||
20560 mp_name_type (mp_link (r)) == mp_suffix_sym ||
20561 mp_name_type (mp_link (r)) == mp_text_sym) {
20562 const char *hlp[] = {
20563 "I've finished reading a macro argument and am about to",
20564 "read another; the arguments weren't delimited correctly.",
20565 "You might want to delete some tokens before continuing.",
20566 NULL };
20567 mp_back_error (mp, "Missing `,' has been inserted", hlp, true);
20568 @.Missing `,'@>
20569 set_cur_cmd((mp_variable_type)mp_comma);
20570 } else {
20571 char msg[256];
20572 const char *hlp[] = {
20573 "I've gotten to the end of the macro parameter list.",
20574 "You might want to delete some tokens before continuing.",
20575 NULL };
20576 mp_snprintf(msg, 256, "Missing `%s' has been inserted", mp_str(mp, text(r_delim)));
20577 @.Missing `)'@>
20578 mp_back_error (mp, msg, hlp, true);
20579 }
20580 }
20581
20582 @ A \&{suffix} or \&{text} parameter will have been scanned as
20583 a token list pointed to by |cur_exp|, in which case we will have
20584 |cur_type=token_list|.
20585
20586 @<Append the current expression to |arg_list|@>=
20587 {
20588 p = mp_get_symbolic_node (mp);
20589 if (mp->cur_exp.type == mp_token_list)
20590 set_mp_sym_sym (p, mp->cur_exp.data.node);
20591 else
20592 set_mp_sym_sym (p, mp_stash_cur_exp (mp));
20593 if (number_positive (internal_value (mp_tracing_macros))) {
20594 mp_begin_diagnostic (mp);
20595 mp_print_arg (mp, (mp_node)mp_sym_sym (p), n, mp_sym_info (r), mp_name_type (r));
20596 mp_end_diagnostic (mp, false);
20597 }
20598 if (arg_list == NULL) {
20599 arg_list = p;
20600 } else {
20601 mp_link (tail) = p;
20602 }
20603 tail = p;
20604 incr (n);
20605 }
20606
20607
20608 @ @<Scan the argument represented by |mp_sym_info(r)|@>=
20609 if (mp_name_type (r) == mp_text_sym) {
20610 mp_scan_text_arg (mp, l_delim, r_delim);
20611 } else {
20612 mp_get_x_next (mp);
20613 if (mp_name_type (r) == mp_suffix_sym)
20614 mp_scan_suffix (mp);
20615 else
20616 mp_scan_expression (mp);
20617 }
20618
20619
20620 @ The parameters to |scan_text_arg| are either a pair of delimiters
20621 or zero; the latter case is for undelimited text arguments, which
20622 end with the first semicolon or \&{endgroup} or \&{end} that is not
20623 contained in a group.
20624
20625 @<Declarations@>=
20626 static void mp_scan_text_arg (MP mp, mp_sym l_delim, mp_sym r_delim);
20627
20628 @ @c
20629 void mp_scan_text_arg (MP mp, mp_sym l_delim, mp_sym r_delim) {
20630 integer balance; /* excess of |l_delim| over |r_delim| */
20631 mp_node p; /* list tail */
20632 mp->warning_info = l_delim;
20633 mp->scanner_status = absorbing;
20634 p = mp->hold_head;
20635 balance = 1;
20636 mp_link (mp->hold_head) = NULL;
20637 while (1) {
20638 get_t_next (mp);
20639 if (l_delim == NULL)
20640 @<Adjust the balance for an undelimited argument; |break| if done@>@;
20641 else
20642 @<Adjust the balance for a delimited argument; |break| if done@>@;
20643 mp_link (p) = mp_cur_tok (mp);
20644 p = mp_link (p);
20645 }
20646 set_cur_exp_node (mp_link (mp->hold_head));
20647 mp->cur_exp.type = mp_token_list;
20648 mp->scanner_status = normal;
20649 }
20650
20651
20652 @ @<Adjust the balance for a delimited argument...@>=
20653 {
20654 if (cur_cmd() == mp_right_delimiter) {
20655 if (equiv_sym (cur_sym()) == l_delim) {
20656 decr (balance);
20657 if (balance == 0)
20658 break;
20659 }
20660 } else if (cur_cmd() == mp_left_delimiter) {
20661 if (equiv_sym (cur_sym()) == r_delim)
20662 incr (balance);
20663 }
20664 }
20665
20666 @ @<Adjust the balance for an undelimited...@>=
20667 {
20668 if (mp_end_of_statement) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
20669 if (balance == 1) {
20670 break;
20671 } else {
20672 if (cur_cmd() == mp_end_group)
20673 decr (balance);
20674 }
20675 } else if (cur_cmd() == mp_begin_group) {
20676 incr (balance);
20677 }
20678 }
20679
20680 @ @<Scan undelimited argument(s)@>=
20681 {
20682 if (mp_sym_info (r) < mp_text_macro) {
20683 mp_get_x_next (mp);
20684 if (mp_sym_info (r) != mp_suffix_macro) {
20685 if ((cur_cmd() == mp_equals) || (cur_cmd() == mp_assignment))
20686 mp_get_x_next (mp);
20687 }
20688 }
20689 switch (mp_sym_info (r)) {
20690 case mp_primary_macro:
20691 mp_scan_primary (mp);
20692 break;
20693 case mp_secondary_macro:
20694 mp_scan_secondary (mp);
20695 break;
20696 case mp_tertiary_macro:
20697 mp_scan_tertiary (mp);
20698 break;
20699 case mp_expr_macro:
20700 mp_scan_expression (mp);
20701 break;
20702 case mp_of_macro:
20703 @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
20704 break;
20705 case mp_suffix_macro:
20706 @<Scan a suffix with optional delimiters@>;
20707 break;
20708 case mp_text_macro:
20709 mp_scan_text_arg (mp, NULL, NULL);
20710 break;
20711 } /* there are no other cases */
20712 mp_back_input (mp);
20713 @<Append the current expression to |arg_list|@>;
20714 }
20715
20716
20717 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
20718 {
20719 mp_scan_expression (mp);
20720 p = mp_get_symbolic_node (mp);
20721 set_mp_sym_sym (p, mp_stash_cur_exp (mp));
20722 if (number_positive (internal_value (mp_tracing_macros))) {
20723 mp_begin_diagnostic (mp);
20724 mp_print_arg (mp, (mp_node)mp_sym_sym (p), n, 0, 0);
20725 mp_end_diagnostic (mp, false);
20726 }
20727 if (arg_list == NULL)
20728 arg_list = p;
20729 else
20730 mp_link (tail) = p;
20731 tail = p;
20732 incr (n);
20733 if (cur_cmd() != mp_of_token) {
20734 char msg[256];
20735 mp_string sname;
20736 const char *hlp[] = {
20737 "I've got the first argument; will look now for the other.",
20738 NULL };
20739 int old_setting = mp->selector;
20740 mp->selector = new_string;
20741 mp_print_macro_name (mp, arg_list, macro_name);
20742 sname = mp_make_string(mp);
20743 mp->selector = old_setting;
20744 mp_snprintf (msg, 256, "Missing `of' has been inserted for %s", mp_str(mp, sname));
20745 delete_str_ref(sname);
20746 @.Missing `of'@>
20747 mp_back_error (mp, msg, hlp, true);
20748 }
20749 mp_get_x_next (mp);
20750 mp_scan_primary (mp);
20751 }
20752
20753
20754 @ @<Scan a suffix with optional delimiters@>=
20755 {
20756 if (cur_cmd() != mp_left_delimiter) {
20757 l_delim = NULL;
20758 } else {
20759 l_delim = cur_sym();
20760 r_delim = equiv_sym (cur_sym());
20761 mp_get_x_next (mp);
20762 }
20763 mp_scan_suffix (mp);
20764 if (l_delim != NULL) {
20765 if ((cur_cmd() != mp_right_delimiter) || (equiv_sym (cur_sym()) != l_delim)) {
20766 char msg[256];
20767 const char *hlp[] = {
20768 "I've gotten to the end of the macro parameter list.",
20769 "You might want to delete some tokens before continuing.",
20770 NULL };
20771 mp_snprintf(msg, 256, "Missing `%s' has been inserted", mp_str (mp, text (r_delim)));
20772 @.Missing `)'@>
20773 mp_back_error (mp, msg, hlp, true);
20774 }
20775 mp_get_x_next (mp);
20776 }
20777 }
20778
20779
20780 @ Before we put a new token list on the input stack, it is wise to clean off
20781 all token lists that have recently been depleted. Then a user macro that ends
20782 with a call to itself will not require unbounded stack space.
20783
20784 @<Feed the arguments and replacement text to the scanner@>=
20785 while (token_state && (nloc == NULL))
20786 mp_end_token_list (mp); /* conserve stack space */
20787 if (mp->param_ptr + n > mp->max_param_stack) {
20788 mp->max_param_stack = mp->param_ptr + n;
20789 mp_check_param_size (mp, mp->max_param_stack);
20790 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
20791 }
20792 mp_begin_token_list (mp, def_ref, (quarterword) macro);
20793 if (macro_name)
20794 name = text (macro_name);
20795 else
20796 name = NULL;
20797 nloc = r;
20798 if (n > 0) {
20799 p = arg_list;
20800 do {
20801 mp->param_stack[mp->param_ptr] = (mp_node)mp_sym_sym (p);
20802 incr (mp->param_ptr);
20803 p = mp_link (p);
20804 } while (p != NULL);
20805 mp_flush_node_list (mp, arg_list);
20806 }
20807
20808 @ It's sometimes necessary to put a single argument onto |param_stack|.
20809 The |stack_argument| subroutine does this.
20810
20811 @c
20812 static void mp_stack_argument (MP mp, mp_node p) {
20813 if (mp->param_ptr == mp->max_param_stack) {
20814 incr (mp->max_param_stack);
20815 mp_check_param_size (mp, mp->max_param_stack);
20816 }
20817 mp->param_stack[mp->param_ptr] = p;
20818 incr (mp->param_ptr);
20819 }
20820
20821
20822 @* Conditional processing.
20823 Let's consider now the way \&{if} commands are handled.
20824
20825 Conditions can be inside conditions, and this nesting has a stack
20826 that is independent of other stacks.
20827 Four global variables represent the top of the condition stack:
20828 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
20829 we are processing \&{if} or \&{elseif}; |if_limit| specifies
20830 the largest code of a |fi_or_else| command that is syntactically legal;
20831 and |if_line| is the line number at which the current conditional began.
20832
20833 If no conditions are currently in progress, the condition stack has the
20834 special state |cond_ptr=NULL|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
20835 Otherwise |cond_ptr| points to a non-symbolic node; the |type|, |name_type|, and
20836 |link| fields of the first word contain |if_limit|, |cur_if|, and
20837 |cond_ptr| at the next level, and the second word contains the
20838 corresponding |if_line|.
20839
20840 @d if_line_field(A) ((mp_if_node)(A))->if_line_field_
20841 @d if_code 1 /* code for \&{if} being evaluated */
20842 @d fi_code 2 /* code for \&{fi} */
20843 @d else_code 3 /* code for \&{else} */
20844 @d else_if_code 4 /* code for \&{elseif} */
20845
20846 @<MPlib internal header stuff@>=
20847 typedef struct mp_if_node_data {
20848 NODE_BODY;@+@t}\6{@>
20849 mpinteger64 if_line_field_;
20850 } mp_if_node_data;
20851 typedef struct mp_if_node_data *mp_if_node;
20852
20853 @ @d if_node_size sizeof(struct mp_if_node_data) /* number of words in stack entry for conditionals */
20854
20855 @c
20856 static mp_node mp_get_if_node (MP mp) {
20857 mp_if_node p = (mp_if_node) malloc_node (if_node_size);
20858 mp_type (p) = mp_if_node_type;
20859 return (mp_node) p;
20860 }
20861
20862
20863 @ @<Glob...@>=
20864 mp_node cond_ptr; /* top of the condition stack */
20865 integer if_limit; /* upper bound on |fi_or_else| codes */
20866 quarterword cur_if; /* type of conditional being worked on */
20867 mpinteger64 if_line; /* line where that conditional began */
20868
20869 @ @<Set init...@>=
20870 mp->cond_ptr = NULL;
20871 mp->if_limit = normal;
20872 mp->cur_if = 0;
20873 mp->if_line = 0;
20874
20875 @ @<Put each...@>=
20876 mp_primitive (mp, "if", mp_if_test, if_code);
20877 @:if_}{\&{if} primitive@>
20878 mp_primitive (mp, "fi", mp_fi_or_else, fi_code);
20879 mp->frozen_fi = mp_frozen_primitive (mp, "fi", mp_fi_or_else, fi_code);
20880 @:fi_}{\&{fi} primitive@>
20881 mp_primitive (mp, "else", mp_fi_or_else, else_code);
20882 @:else_}{\&{else} primitive@>
20883 mp_primitive (mp, "elseif", mp_fi_or_else, else_if_code);
20884 @:else_if_}{\&{elseif} primitive@>
20885
20886
20887 @ @<Cases of |print_cmd_mod|...@>=
20888 case mp_if_test:
20889 case mp_fi_or_else:
20890 switch (m) {
20891 case if_code:
20892 mp_print (mp, "if");
20893 break;
20894 case fi_code:
20895 mp_print (mp, "fi");
20896 break;
20897 case else_code:
20898 mp_print (mp, "else");
20899 break;
20900 default:
20901 mp_print (mp, "elseif");
20902 break;
20903 }
20904 break;
20905
20906 @ Here is a procedure that ignores text until coming to an \&{elseif},
20907 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
20908 nesting. After it has acted, |cur_mod| will indicate the token that
20909 was found.
20910
20911 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
20912 makes the skipping process a bit simpler.
20913
20914 @c
20915 void mp_pass_text (MP mp) {
20916 integer l = 0;
20917 mp->scanner_status = skipping;
20918 mp->warning_line = mp_true_line (mp);
20919 while (1) {
20920 get_t_next (mp);
20921 if (cur_cmd() <= mp_fi_or_else) {
20922 if (cur_cmd() < mp_fi_or_else) {
20923 incr (l);
20924 } else {
20925 if (l == 0)
20926 break;
20927 if (cur_mod() == fi_code)
20928 decr (l);
20929 }
20930 } else
20931 @<Decrease the string reference count,
20932 if the current token is a string@>@;
20933 }
20934 mp->scanner_status = normal;
20935 }
20936
20937
20938 @ @<Decrease the string reference count...@>=
20939 if ((QUARTERWORD)(cur_cmd()) == (QUARTERWORD)mp_string_token) {
20940 delete_str_ref (cur_mod_str());
20941 }
20942
20943 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
20944 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
20945 condition has been evaluated, a colon will be inserted.
20946 A construction like `\.{if fi}' would otherwise get \MP\ confused.
20947
20948 @<Push the condition stack@>=
20949 {
20950 p = mp_get_if_node (mp);
20951 mp_link (p) = mp->cond_ptr;
20952 mp_type (p) = (quarterword) mp->if_limit;
20953 mp_name_type (p) = mp->cur_if;
20954 if_line_field (p) = mp->if_line;
20955 mp->cond_ptr = p;
20956 mp->if_limit = if_code;
20957 mp->if_line = mp_true_line (mp);
20958 mp->cur_if = if_code;
20959 }
20960
20961
20962 @ @<Pop the condition stack@>=
20963 {
20964 mp_node p = mp->cond_ptr;
20965 mp->if_line = if_line_field (p);
20966 mp->cur_if = mp_name_type (p);
20967 mp->if_limit = mp_type (p);
20968 mp->cond_ptr = mp_link (p);
20969 mp_free_node (mp, p, if_node_size);
20970 }
20971
20972
20973 @ Here's a procedure that changes the |if_limit| code corresponding to
20974 a given value of |cond_ptr|.
20975
20976 @c
20977 static void mp_change_if_limit (MP mp, quarterword l, mp_node p) {
20978 mp_node q;
20979 if (p == mp->cond_ptr) {
20980 mp->if_limit = l; /* that's the easy case */
20981 } else {
20982 q = mp->cond_ptr;
20983 while (1) {
20984 if (q == NULL)
20985 mp_confusion (mp, "if");
20986 @:this can't happen if}{\quad if@>
20987 /* clang: dereference of null pointer */ assert(q);
20988 if (mp_link (q) == p) {
20989 mp_type (q) = l;
20990 return;
20991 }
20992 q = mp_link (q);
20993 }
20994 }
20995 }
20996
20997
20998 @ The user is supposed to put colons into the proper parts of conditional
20999 statements. Therefore, \MP\ has to check for their presence.
21000
21001 @c
21002 static void mp_check_colon (MP mp) {
21003 if (cur_cmd() != mp_colon) {
21004 const char *hlp[] = {
21005 "There should've been a colon after the condition.",
21006 "I shall pretend that one was there.",
21007 NULL };
21008 mp_back_error (mp, "Missing `:' has been inserted", hlp, true);
21009 @.Missing `:'@>
21010 }
21011 }
21012
21013
21014 @ A condition is started when the |get_x_next| procedure encounters
21015 an |if_test| command; in that case |get_x_next| calls |conditional|,
21016 which is a recursive procedure.
21017 @^recursion@>
21018
21019 @c
21020 void mp_conditional (MP mp) {
21021 mp_node save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
21022 int new_if_limit; /* future value of |if_limit| */
21023 mp_node p; /* temporary register */
21024 @<Push the condition stack@>;
21025 save_cond_ptr = mp->cond_ptr;
21026 RESWITCH:
21027 mp_get_boolean (mp);
21028 new_if_limit = else_if_code;
21029 if (number_greater (internal_value (mp_tracing_commands), unity_t)) {
21030 @<Display the boolean value of |cur_exp|@>;
21031 }
21032 FOUND:
21033 mp_check_colon (mp);
21034 if (cur_exp_value_boolean () == mp_true_code) {
21035 mp_change_if_limit (mp, (quarterword) new_if_limit, save_cond_ptr);
21036 return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
21037 }
21038 @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
21039 DONE:
21040 mp->cur_if = (quarterword) cur_mod();
21041 mp->if_line = mp_true_line (mp);
21042 if (cur_mod() == fi_code) {
21043 @<Pop the condition stack@>
21044 } else if (cur_mod() == else_if_code) {
21045 goto RESWITCH;
21046 } else {
21047 set_cur_exp_value_boolean (mp_true_code);
21048 new_if_limit = fi_code;
21049 mp_get_x_next (mp);
21050 goto FOUND;
21051 }
21052 }
21053
21054
21055 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
21056 \&{else}: \\{bar} \&{fi}', the first \&{else}
21057 that we come to after learning that the \&{if} is false is not the
21058 \&{else} we're looking for. Hence the following curious logic is needed.
21059
21060 @<Skip to \&{elseif}...@>=
21061 while (1) {
21062 mp_pass_text (mp);
21063 if (mp->cond_ptr == save_cond_ptr)
21064 goto DONE;
21065 else if (cur_mod() == fi_code)
21066 @<Pop the condition stack@>;
21067 }
21068
21069
21070 @ @<Display the boolean value...@>=
21071 {
21072 mp_begin_diagnostic (mp);
21073 if (cur_exp_value_boolean () == mp_true_code)
21074 mp_print (mp, "{true}");
21075 else
21076 mp_print (mp, "{false}");
21077 mp_end_diagnostic (mp, false);
21078 }
21079
21080
21081 @ The processing of conditionals is complete except for the following
21082 code, which is actually part of |get_x_next|. It comes into play when
21083 \&{elseif}, \&{else}, or \&{fi} is scanned.
21084
21085 @<Terminate the current conditional and skip to \&{fi}@>=
21086 if (cur_mod() > mp->if_limit) {
21087 if (mp->if_limit == if_code) { /* condition not yet evaluated */
21088 const char *hlp[] = { "Something was missing here", NULL };
21089 mp_back_input (mp);
21090 set_cur_sym(mp->frozen_colon);
21091 mp_ins_error (mp, "Missing `:' has been inserted", hlp, true);
21092 @.Missing `:'@>
21093 } else {
21094 const char *hlp[] = {"I'm ignoring this; it doesn't match any if.", NULL};
21095 if (cur_mod() == fi_code) {
21096 mp_error(mp, "Extra fi", hlp, true);
21097 @.Extra fi@>
21098 } else if (cur_mod() == else_code) {
21099 mp_error(mp, "Extra else", hlp, true);
21100 @.Extra else@>
21101 } else {
21102 mp_error(mp, "Extra elseif", hlp, true);
21103 @.Extra elseif@>
21104 }
21105 }
21106 } else {
21107 while (cur_mod() != fi_code)
21108 mp_pass_text (mp); /* skip to \&{fi} */
21109 @<Pop the condition stack@>;
21110 }
21111
21112
21113 @* Iterations.
21114 To bring our treatment of |get_x_next| to a close, we need to consider what
21115 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
21116
21117 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
21118 that are currently active. If |loop_ptr=NULL|, no loops are in progress;
21119 otherwise |loop_ptr.info| points to the iterative text of the current
21120 (innermost) loop, and |loop_ptr.link| points to the data for any other
21121 loops that enclose the current one.
21122
21123 A loop-control node also has two other fields, called |type| and
21124 |list|, whose contents depend on the type of loop:
21125
21126 \yskip\indent|loop_ptr.type=NULL| means that the link of |loop_ptr.list|
21127 points to a list of symbolic nodes whose |info| fields point to the
21128 remaining argument values of a suffix list and expression list.
21129 In this case, an extra field |loop_ptr.start_list| is needed to
21130 make sure that |resume_operation| skips ahead.
21131
21132 \yskip\indent|loop_ptr.type=MP_VOID| means that the current loop is
21133 `\&{forever}'.
21134
21135 \yskip\indent|loop_ptr.type=PROGRESSION_FLAG| means that
21136 |loop_ptr.value|, |loop_ptr.step_size|, and |loop_ptr.final_value|
21137 contain the data for an arithmetic progression.
21138
21139 \yskip\indent|loop_ptr.type=p>PROGRESSION_FLAG| means that |p| points to an edge
21140 header and |loop_ptr.list| points into the graphical object list for
21141 that edge header.
21142
21143 @d PROGRESSION_FLAG (mp_node)(2) /* |NULL+2| */
21144 /* |loop_type| value when |loop_list| points to a progression node */
21145
21146 @<Types...@>=
21147 typedef struct mp_loop_data {
21148 mp_sym var ; /* the var of the loop */
21149 mp_node info; /* iterative text of this loop */
21150 mp_node type; /* the special type of this loop, or a pointer into
21151 mem */
21152 mp_node list; /* the remaining list elements */
21153 mp_node list_start; /* head of the list of elements */
21154 mp_number old_value; /* previous value of current arithmetic value */
21155 mp_number value; /* current arithmetic value */
21156 mp_number step_size; /* arithmetic step size */
21157 mp_number final_value; /* end arithmetic value */
21158 struct mp_loop_data *link; /* the enclosing loop, if any */
21159 } mp_loop_data;
21160
21161 @ @<Glob...@>=
21162 mp_loop_data *loop_ptr; /* top of the loop-control-node stack */
21163
21164 @ @<Set init...@>=
21165 mp->loop_ptr = NULL;
21166
21167 @ If the expressions that define an arithmetic progression in a
21168 \&{for} loop don't have known numeric values, the |bad_for| subroutine
21169 screams at the user.
21170
21171 @c
21172 static void mp_bad_for (MP mp, const char *s) {
21173 char msg[256];
21174 mp_value new_expr;
21175 const char *hlp[] = {"When you say `for x=a step b until c',",
21176 "the initial value `a' and the step size `b'",
21177 "and the final value `c' must have known numeric values.",
21178 "I'm zeroing this one. Proceed, with fingers crossed.",
21179 NULL };
21180 memset(&new_expr,0,sizeof(mp_value));
21181 new_number(new_expr.data.n);
21182 mp_disp_err (mp, NULL);
21183 /* show the bad expression above the message */
21184 mp_snprintf(msg, 256, "Improper %s has been replaced by 0", s);
21185 @.Improper...replaced by 0@>
21186 mp_back_error (mp, msg, hlp, true);
21187 mp_get_x_next (mp);
21188 mp_flush_cur_exp (mp, new_expr);
21189 }
21190
21191
21192 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
21193 has just been scanned. (This code requires slight familiarity with
21194 expression-parsing routines that we have not yet discussed; but it
21195 seems to belong in the present part of the program, even though the
21196 original author didn't write it until later. The reader may wish to
21197 come back to it.)
21198
21199 @c
21200 void mp_begin_iteration (MP mp) {
21201 halfword m; /* |start_for| (\&{for}) or |start_forsuffixes|
21202 (\&{forsuffixes}) */
21203 mp_sym n; /* hash address of the current symbol */
21204 mp_loop_data *s; /* the new loop-control node */
21205 mp_subst_list_item *p = NULL; /* substitution list for |scan_toks|
21206 */
21207 mp_node q; /* link manipulation register */
21208 m = cur_mod();
21209 n = cur_sym();
21210 s = xmalloc (1, sizeof (mp_loop_data));
21211 s->type = s->list = s->info = s->list_start = NULL;
21212 s->link = NULL; s->var = NULL;
21213 new_number (s->value);new_number (s->old_value);
21214 new_number (s->step_size);
21215 new_number (s->final_value);
21216 if (m == start_forever) {
21217 s->type = MP_VOID;
21218 p = NULL;
21219 mp_get_x_next (mp);
21220 } else {
21221 mp_get_symbol (mp);
21222 p = xmalloc (1, sizeof (mp_subst_list_item));
21223 p->link = NULL;
21224 p->info = cur_sym();
21225 s->var = cur_sym();
21226 p->info_mod = cur_sym_mod();
21227 p->value_data = 0;
21228 if (m == start_for) {
21229 p->value_mod = mp_expr_sym;
21230 } else { /* |start_forsuffixes| */
21231 p->value_mod = mp_suffix_sym;
21232 }
21233 mp_get_x_next (mp);
21234 if (p->value_mod == mp_expr_sym && cur_cmd() == mp_within_token)
21235 @<Set up a picture iteration@>@;
21236 else {
21237 @<Check for the assignment in a loop header@>;
21238 @<Scan the values to be used in the loop@>;
21239 }
21240 }
21241 @<Check for the presence of a colon@>;
21242 @<Scan the loop text and put it on the loop control stack@>;
21243 mp_resume_iteration (mp);
21244 }
21245
21246
21247 @ @<Check for the assignment in a loop header@>=
21248 if ((cur_cmd() != mp_equals) && (cur_cmd() != mp_assignment)) {
21249 const char *hlp[] = {
21250 "The next thing in this loop should have been `=' or `:='.",
21251 "But don't worry; I'll pretend that an equals sign",
21252 "was present, and I'll look for the values next.",
21253 NULL };
21254 mp_back_error (mp, "Missing `=' has been inserted", hlp, true);
21255 @.Missing `='@>
21256 }
21257
21258 @ @<Check for the presence of a colon@>=
21259 if (cur_cmd() != mp_colon) {
21260 const char *hlp[] = {
21261 "The next thing in this loop should have been a `:'.",
21262 "So I'll pretend that a colon was present;",
21263 "everything from here to `endfor' will be iterated.",
21264 NULL };
21265 mp_back_error (mp, "Missing `:' has been inserted", hlp, true);
21266 @.Missing `:'@>
21267 }
21268
21269 @ We append a special |mp->frozen_repeat_loop| token in place of the
21270 `\&{endfor}' at the end of the loop. This will come through \MP's
21271 scanner at the proper time to cause the loop to be repeated.
21272
21273 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let}
21274 \&{endfor}', he will be foiled by the |get_symbol| routine, which
21275 keeps frozen tokens unchanged. Furthermore the
21276 |mp->frozen_repeat_loop| is an \&{outer} token, so it won't be lost
21277 accidentally.)
21278
21279 @ @<Scan the loop text...@>=
21280 q = mp_get_symbolic_node (mp);
21281 set_mp_sym_sym (q, mp->frozen_repeat_loop);
21282 mp->scanner_status = loop_defining;
21283 mp->warning_info = n;
21284 s->info = mp_scan_toks (mp, mp_iteration, p, q, 0);
21285 mp->scanner_status = normal;
21286 s->link = mp->loop_ptr;
21287 mp->loop_ptr = s@;
21288
21289 @ @<Initialize table...@>=
21290 mp->frozen_repeat_loop =
21291 mp_frozen_primitive (mp, " ENDFOR", mp_repeat_loop + mp_outer_tag, 0);
21292
21293 @ The loop text is inserted into \MP's scanning apparatus by the
21294 |resume_iteration| routine.
21295
21296 @c
21297 void mp_resume_iteration (MP mp) {
21298 mp_node p, q; /* link registers */
21299 p = mp->loop_ptr->type;
21300 if (p == PROGRESSION_FLAG) {
21301 set_cur_exp_value_number (mp->loop_ptr->value);
21302 if (@<The arithmetic progression has ended@>) {
21303 mp_stop_iteration (mp);
21304 return;
21305 }
21306 mp->cur_exp.type = mp_known;
21307 q = mp_stash_cur_exp (mp); /* make |q| an \&{expr} argument */
21308 number_clone (mp->loop_ptr->old_value, cur_exp_value_number ());
21309 set_number_from_addition (mp->loop_ptr->value, cur_exp_value_number (), mp->loop_ptr->step_size);
21310 /* set |value(p)| for the next iteration */
21311 /* detect numeric overflow */
21312 if (number_positive(mp->loop_ptr->step_size) &&
21313 number_less(mp->loop_ptr->value, cur_exp_value_number ())) {
21314 if (number_positive(mp->loop_ptr->final_value)) {
21315 number_clone (mp->loop_ptr->value, mp->loop_ptr->final_value);
21316 number_add_scaled (mp->loop_ptr->final_value, -1);
21317 } else {
21318 number_clone (mp->loop_ptr->value, mp->loop_ptr->final_value);
21319 number_add_scaled (mp->loop_ptr->value, 1);
21320 }
21321 } else if (number_negative(mp->loop_ptr->step_size) &&
21322 number_greater (mp->loop_ptr->value, cur_exp_value_number ())) {
21323 if (number_negative (mp->loop_ptr->final_value)) {
21324 number_clone (mp->loop_ptr->value, mp->loop_ptr->final_value);
21325 number_add_scaled (mp->loop_ptr->final_value, 1);
21326 } else {
21327 number_clone (mp->loop_ptr->value, mp->loop_ptr->final_value);
21328 number_add_scaled (mp->loop_ptr->value, -1);
21329 }
21330 }
21331 } else if (p == NULL) {
21332 p = mp->loop_ptr->list;
21333 if (p != NULL && p == mp->loop_ptr->list_start) {
21334 q = p;
21335 p = mp_link (p);
21336 mp_free_symbolic_node (mp, q);
21337 mp->loop_ptr->list = p;
21338 }
21339 if (p == NULL) {
21340 mp_stop_iteration (mp);
21341 return;
21342 }
21343 mp->loop_ptr->list = mp_link (p);
21344 q = (mp_node)mp_sym_sym (p);
21345 if (q)
21346 number_clone (mp->loop_ptr->old_value, q->data.n);
21347 mp_free_symbolic_node (mp, p);
21348 } else if (p == MP_VOID) {
21349 mp_begin_token_list (mp, mp->loop_ptr->info, (quarterword) forever_text);
21350 return;
21351 } else
21352 @<Make |q| a capsule containing the next picture component from
21353 |loop_list(loop_ptr)| or |goto not_found|@>@;
21354 mp_begin_token_list (mp, mp->loop_ptr->info, (quarterword) loop_text);
21355 mp_stack_argument (mp, q);
21356 if (number_greater (internal_value (mp_tracing_commands), unity_t)) {
21357 @<Trace the start of a loop@>;
21358 }
21359 return;
21360 NOT_FOUND:
21361 mp_stop_iteration (mp);
21362 }
21363
21364
21365 @ @<The arithmetic progression has ended@>=
21366 (number_positive(mp->loop_ptr->step_size) && number_greater(cur_exp_value_number (), mp->loop_ptr->final_value))
21367 ||
21368 (number_negative(mp->loop_ptr->step_size) && number_less(cur_exp_value_number (), mp->loop_ptr->final_value))
21369
21370
21371 @ @<Trace the start of a loop@>=
21372 {
21373 mp_begin_diagnostic (mp);
21374 mp_print_nl (mp, "{loop value=");
21375 @.loop value=n@>
21376 if ((q != NULL) && (mp_link (q) == MP_VOID))
21377 mp_print_exp (mp, q, 1);
21378 else
21379 mp_show_token_list (mp, q, NULL, 50, 0);
21380 mp_print_char (mp, xord ('}'));
21381 mp_end_diagnostic (mp, false);
21382 }
21383
21384
21385 @ @<Make |q| a capsule containing the next picture component
21386 from...@>=
21387 {
21388 q = mp->loop_ptr->list;
21389 if (q == NULL)
21390 goto NOT_FOUND;
21391 if ( ! is_start_or_stop(q) )
21392 q=mp_link(q);
21393 else if ( ! is_stop(q) )
21394 q=mp_skip_1component(mp, q);
21395 else
21396 goto NOT_FOUND;
21397
21398 set_cur_exp_node ((mp_node)mp_copy_objects (mp, mp->loop_ptr->list, q));
21399 mp_init_bbox (mp, (mp_edge_header_node)cur_exp_node ());
21400 mp->cur_exp.type = mp_picture_type;
21401 mp->loop_ptr->list = q;
21402 q = mp_stash_cur_exp (mp);
21403 }
21404
21405
21406 @ A level of loop control disappears when |resume_iteration| has
21407 decided not to resume, or when an \&{exitif} construction has removed
21408 the loop text from the input stack.
21409
21410 @c
21411 void mp_stop_iteration (MP mp) {
21412 mp_node p, q; /* the usual */
21413 mp_loop_data *tmp; /* for free() */
21414 p = mp->loop_ptr->type;
21415 if (p == PROGRESSION_FLAG) {
21416 mp_free_symbolic_node (mp, mp->loop_ptr->list);
21417 } else if (p == NULL) {
21418 q = mp->loop_ptr->list;
21419 while (q != NULL) {
21420 p = (mp_node)mp_sym_sym (q);
21421 if (p != NULL) {
21422 if (mp_link (p) == MP_VOID) { /* it's an \&{expr} parameter */
21423 mp_recycle_value (mp, p);
21424 mp_free_value_node (mp, p);
21425 } else {
21426 mp_flush_token_list (mp, p); /* it's a \&{suffix} or \&{text}
21427 parameter */
21428 }
21429 }
21430 p = q;
21431 q = mp_link (q);
21432 mp_free_symbolic_node (mp, p);
21433 }
21434 } else if (p > PROGRESSION_FLAG) {
21435 delete_edge_ref (p);
21436 }
21437 tmp = mp->loop_ptr;
21438 mp->loop_ptr = tmp->link;
21439 mp_flush_token_list (mp, tmp->info);
21440 free_number (tmp->value);
21441 free_number (tmp->step_size);
21442 free_number (tmp->final_value);
21443 xfree (tmp);
21444 }
21445
21446
21447 @ Now that we know all about loop control, we can finish up the
21448 missing portion of |begin_iteration| and we'll be done.
21449
21450 The following code is performed after the `\.=' has been scanned in a
21451 \&{for} construction (if |m=start_for|) or a \&{forsuffixes}
21452 construction (if |m=start_forsuffixes|).
21453
21454 @<Scan the values to be used in the loop@>=
21455 s->type = NULL;
21456 s->list = mp_get_symbolic_node (mp);
21457 s->list_start = s->list;
21458 q = s->list;
21459 do {
21460 mp_get_x_next (mp);
21461 if (m != start_for) {
21462 mp_scan_suffix (mp);
21463 } else {
21464 if (cur_cmd() >= mp_colon)
21465 if (cur_cmd() <= mp_comma)
21466 goto CONTINUE;
21467 mp_scan_expression (mp);
21468 if (cur_cmd() == mp_step_token)
21469 if (q == s->list) {
21470 @<Prepare for step-until construction and |break|@>;
21471 }
21472 set_cur_exp_node (mp_stash_cur_exp (mp));
21473 }
21474 mp_link (q) = mp_get_symbolic_node (mp);
21475 q = mp_link (q);
21476 set_mp_sym_sym (q, mp->cur_exp.data.node);
21477 if (m == start_for)
21478 mp_name_type (q) = mp_expr_sym;
21479 else if (m == start_forsuffixes)
21480 mp_name_type (q) = mp_suffix_sym;
21481 mp->cur_exp.type = mp_vacuous;
21482 CONTINUE:
21483 ;
21484 } while (cur_cmd() == mp_comma)@;
21485
21486 @ @<Prepare for step-until construction and |break|@>=
21487 {
21488 if (mp->cur_exp.type != mp_known)
21489 mp_bad_for (mp, "initial value");
21490 number_clone (s->value, cur_exp_value_number ());
21491 number_clone (s->old_value, cur_exp_value_number ());
21492 mp_get_x_next (mp);
21493 mp_scan_expression (mp);
21494 if (mp->cur_exp.type != mp_known)
21495 mp_bad_for (mp, "step size");
21496 number_clone (s->step_size, cur_exp_value_number ());
21497 if (cur_cmd() != mp_until_token) {
21498 const char *hlp[] = {
21499 "I assume you meant to say `until' after `step'.",
21500 "So I'll look for the final value and colon next.",
21501 NULL };
21502 mp_back_error (mp, "Missing `until' has been inserted", hlp, true);
21503 @.Missing `until'@>
21504 }
21505 mp_get_x_next (mp);
21506 mp_scan_expression (mp);
21507 if (mp->cur_exp.type != mp_known)
21508 mp_bad_for (mp, "final value");
21509 number_clone (s->final_value, cur_exp_value_number ());
21510 s->type = PROGRESSION_FLAG;
21511 break;
21512 }
21513
21514
21515 @ The last case is when we have just seen ``\&{within}'', and we need to
21516 parse a picture expression and prepare to iterate over it.
21517
21518 @<Set up a picture iteration@>=
21519 {
21520 mp_get_x_next (mp);
21521 mp_scan_expression (mp);
21522 @<Make sure the current expression is a known picture@>;
21523 s->type = mp->cur_exp.data.node;
21524 mp->cur_exp.type = mp_vacuous;
21525 q = mp_link (edge_list (mp->cur_exp.data.node));
21526 if (q != NULL)
21527 if (is_start_or_stop (q))
21528 if (mp_skip_1component (mp, q) == NULL)
21529 q = mp_link (q);
21530 s->list = q;
21531 }
21532
21533
21534 @ @<Make sure the current expression is a known picture@>=
21535 if (mp->cur_exp.type != mp_picture_type) {
21536 mp_value new_expr;
21537 const char *hlp[] = { "When you say `for x in p', p must be a known picture.", NULL };
21538 memset(&new_expr,0,sizeof(mp_value));
21539 new_number(new_expr.data.n);
21540 new_expr.data.node = (mp_node)mp_get_edge_header_node (mp);
21541 mp_disp_err (mp, NULL);
21542 mp_back_error (mp,"Improper iteration spec has been replaced by nullpicture", hlp, true);
21543 mp_get_x_next (mp);
21544 mp_flush_cur_exp (mp, new_expr);
21545 mp_init_edges (mp, (mp_edge_header_node)mp->cur_exp.data.node);
21546 mp->cur_exp.type = mp_picture_type;
21547 }
21548
21549 @* File names.
21550 It's time now to fret about file names. Besides the fact that different
21551 operating systems treat files in different ways, we must cope with the
21552 fact that completely different naming conventions are used by different
21553 groups of people. The following programs show what is required for one
21554 particular operating system; similar routines for other systems are not
21555 difficult to devise.
21556 @^system dependencies@>
21557
21558 \MP\ assumes that a file name has three parts: the name proper; its
21559 ``extension''; and a ``file area'' where it is found in an external file
21560 system. The extension of an input file is assumed to be
21561 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
21562 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
21563 metric files that describe characters in any fonts created by \MP; it is
21564 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files.
21565 The file area can be arbitrary on input files, but files are usually
21566 output to the user's current area. If an input file cannot be
21567 found on the specified area, \MP\ will look for it on a special system
21568 area; this special area is intended for commonly used input files.
21569
21570 Simple uses of \MP\ refer only to file names that have no explicit
21571 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
21572 instead of `\.{input} \.{cmr10.new}'. Simple file
21573 names are best, because they make the \MP\ source files portable;
21574 whenever a file name consists entirely of letters and digits, it should be
21575 treated in the same way by all implementations of \MP. However, users
21576 need the ability to refer to other files in their environment, especially
21577 when responding to error messages concerning unopenable files; therefore
21578 we want to let them use the syntax that appears in their favorite
21579 operating system.
21580
21581 @ \MP\ uses the same conventions that have proved to be satisfactory for
21582 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
21583 @^system dependencies@>
21584 the system-independent parts of \MP\ are expressed in terms
21585 of three system-dependent
21586 procedures called |begin_name|, |more_name|, and |end_name|. In
21587 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
21588 the system-independent driver program does the operations
21589 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;\,|more_name|(c_n);
21590 \,|end_name|.$$
21591 These three procedures communicate with each other via global variables.
21592 Afterwards the file name will appear in the string pool as three strings
21593 called |cur_name|\penalty10000\hskip-.05em,
21594 |cur_area|, and |cur_ext|; the latter two are NULL (i.e.,
21595 |""|), unless they were explicitly specified by the user.
21596
21597 Actually the situation is slightly more complicated, because \MP\ needs
21598 to know when the file name ends. The |more_name| routine is a function
21599 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
21600 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
21601 returns |false|; or, it returns |true| and $c_n$ is the last character
21602 on the current input line. In other words,
21603 |more_name| is supposed to return |true| unless it is sure that the
21604 file name has been completely scanned; and |end_name| is supposed to be able
21605 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
21606 whether $|more_name|(c_n)$ returned |true| or |false|.
21607
21608 @<Glob...@>=
21609 char *cur_name; /* name of file just scanned */
21610 char *cur_area; /* file area just scanned, or \.{""} */
21611 char *cur_ext; /* file extension just scanned, or \.{""} */
21612
21613 @ It is easier to maintain reference counts if we assign initial values.
21614
21615 @<Set init...@>=
21616 mp->cur_name = xstrdup ("");
21617 mp->cur_area = xstrdup ("");
21618 mp->cur_ext = xstrdup ("");
21619
21620 @ @<Dealloc variables@>=
21621 xfree (mp->cur_area);
21622 xfree (mp->cur_name);
21623 xfree (mp->cur_ext);
21624
21625 @ The file names we shall deal with for illustrative purposes have the
21626 following structure: If the name contains `\.>' or `\.:', the file area
21627 consists of all characters up to and including the final such character;
21628 otherwise the file area is null. If the remaining file name contains
21629 `\..', the file extension consists of all such characters from the first
21630 remaining `\..' to the end, otherwise the file extension is null.
21631 @^system dependencies@>
21632
21633 We can scan such file names easily by using two global variables that keep track
21634 of the occurrences of area and extension delimiters.
21635
21636 @<Glob...@>=
21637 integer area_delimiter;
21638 /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
21639 integer ext_delimiter; /* the relevant `\..', if any */
21640 boolean quoted_filename; /* whether the filename is wrapped in `\."' markers */
21641
21642 @ Here now is the first of the system-dependent routines for file name scanning.
21643 @^system dependencies@>
21644
21645 @<Declarations@>=
21646 static void mp_begin_name (MP mp);
21647 static boolean mp_more_name (MP mp, ASCII_code c);
21648 static void mp_end_name (MP mp);
21649
21650 @ @c
21651 void mp_begin_name (MP mp) {
21652 xfree (mp->cur_name);
21653 xfree (mp->cur_area);
21654 xfree (mp->cur_ext);
21655 mp->area_delimiter = -1;
21656 mp->ext_delimiter = -1;
21657 mp->quoted_filename = false;
21658 }
21659
21660
21661 @ And here's the second.
21662 @^system dependencies@>
21663
21664 @c
21665 #ifndef IS_DIR_SEP
21666 #define IS_DIR_SEP(c) (c=='/' || c=='\\')
21667 #endif
21668 boolean mp_more_name (MP mp, ASCII_code c) {
21669 if (c == '"') {
21670 mp->quoted_filename = !mp->quoted_filename;
21671 } else if ((c == ' ' || c == '\t') && (mp->quoted_filename == false)) {
21672 return false;
21673 } else {
21674 if (IS_DIR_SEP (c)) {
21675 mp->area_delimiter = (integer) mp->cur_length;
21676 mp->ext_delimiter = -1;
21677 } else if (c == '.') {
21678 mp->ext_delimiter = (integer) mp->cur_length;
21679 }
21680 append_char (c); /* contribute |c| to the current string */
21681 }
21682 return true;
21683 }
21684
21685
21686 @ The third.
21687 @^system dependencies@>
21688
21689 @d copy_pool_segment(A,B,C) {
21690 A = xmalloc(C+1,sizeof(char));
21691 (void)memcpy(A,(char *)(mp->cur_string+B),C);
21692 A[C] = 0;}
21693
21694 @c
21695 void mp_end_name (MP mp) {
21696 size_t s = 0; /* length of area, name, and extension */
21697 size_t len;
21698 /* \.{"my/w.mp"} */
21699 if (mp->area_delimiter < 0) {
21700 mp->cur_area = xstrdup ("");
21701 } else {
21702 len = (size_t) mp->area_delimiter - s + 1;
21703 copy_pool_segment (mp->cur_area, s, len);
21704 s += len;
21705 }
21706 if (mp->ext_delimiter < 0) {
21707 mp->cur_ext = xstrdup ("");
21708 len = (unsigned) (mp->cur_length - s);
21709 } else {
21710 copy_pool_segment (mp->cur_ext, mp->ext_delimiter,
21711 (mp->cur_length - (size_t) mp->ext_delimiter));
21712 len = (size_t) mp->ext_delimiter - s;
21713 }
21714 copy_pool_segment (mp->cur_name, s, len);
21715 mp_reset_cur_string (mp);
21716 }
21717
21718
21719 @ Conversely, here is a routine that takes three strings and prints a file
21720 name that might have produced them. (The routine is system dependent, because
21721 some operating systems put the file area last instead of first.)
21722 @^system dependencies@>
21723
21724 @<Basic printing...@>=
21725 static void mp_print_file_name (MP mp, char *n, char *a, char *e) {
21726 boolean must_quote = false;
21727 if (((a != NULL) && (strchr (a, ' ') != NULL)) ||
21728 ((n != NULL) && (strchr (n, ' ') != NULL)) ||
21729 ((e != NULL) && (strchr (e, ' ') != NULL)))
21730 must_quote = true;
21731 if (must_quote)
21732 mp_print_char (mp, (ASCII_code) '"');
21733 mp_print (mp, a);
21734 mp_print (mp, n);
21735 mp_print (mp, e);
21736 if (must_quote)
21737 mp_print_char (mp, (ASCII_code) '"');
21738 }
21739
21740
21741 @ Another system-dependent routine is needed to convert three internal
21742 \MP\ strings
21743 to the |name_of_file| value that is used to open files. The present code
21744 allows both lowercase and uppercase letters in the file name.
21745 @^system dependencies@>
21746
21747 @d append_to_name(A) { mp->name_of_file[k++]=(char)xchr(xord((ASCII_code)(A))); }
21748
21749 @ @c
21750 void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e) {
21751 integer k; /* number of positions filled in |name_of_file| */
21752 const char *j; /* a character index */
21753 size_t slen;
21754 k = 0;
21755 assert (n != NULL);
21756 xfree (mp->name_of_file);
21757 slen = strlen (n) + 1;
21758 if (a != NULL)
21759 slen += strlen (a);
21760 if (e != NULL)
21761 slen += strlen (e);
21762 mp->name_of_file = xmalloc (slen, 1);
21763 if (a != NULL) {
21764 for (j = a; *j != '\0'; j++) {
21765 append_to_name (*j);
21766 }
21767 }
21768 for (j = n; *j != '\0'; j++) {
21769 append_to_name (*j);
21770 }
21771 if (e != NULL) {
21772 for (j = e; *j != '\0'; j++) {
21773 append_to_name (*j);
21774 }
21775 }
21776 mp->name_of_file[k] = 0;
21777 }
21778
21779
21780 @ @<Internal library declarations@>=
21781 void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e);
21782
21783 @ @<Option variables@>=
21784 char *mem_name; /* for commandline */
21785
21786 @ Stripping a |.mem| extension here is for backward compatibility.
21787
21788 @<Find and load preload file, if required@>=
21789 if (!opt->ini_version) {
21790 mp->mem_name = xstrdup (opt->mem_name);
21791 if (mp->mem_name) {
21792 size_t l = strlen (mp->mem_name);
21793 if (l > 4) {
21794 char *test = strstr (mp->mem_name, ".mem");
21795 if (test == mp->mem_name + l - 4) {
21796 *test = 0;
21797 }
21798 }
21799 }
21800 if (mp->mem_name != NULL) {
21801 if (!mp_open_mem_file (mp)) {
21802 mp->history = mp_fatal_error_stop;
21803 mp_jump_out (mp);
21804 }
21805 }
21806 }
21807
21808
21809
21810 @ @<Dealloc variables@>=
21811 xfree (mp->mem_name);
21812
21813 @ This part of the program becomes active when a ``virgin'' \MP\ is
21814 trying to get going, just after the preliminary initialization.
21815 The buffer contains the first line of input in |buffer[loc..(last-1)]|,
21816 where |loc<last| and |buffer[loc]<>""|.
21817
21818 @<Declarations@>=
21819 static boolean mp_open_mem_name (MP mp);
21820 static boolean mp_open_mem_file (MP mp);
21821
21822 @ @c
21823 boolean mp_open_mem_name (MP mp) {
21824 if (mp->mem_name != NULL) {
21825 size_t l = strlen (mp->mem_name);
21826 char *s = xstrdup (mp->mem_name);
21827 if (l > 4) {
21828 char *test = strstr (s, ".mp");
21829 if (test == NULL || test != s + l - 4) {
21830 s = xrealloc (s, l + 5, 1);
21831 strcat (s, ".mp");
21832 }
21833 } else {
21834 s = xrealloc (s, l + 5, 1);
21835 strcat (s, ".mp");
21836 }
21837 s = (mp->find_file) (mp, s, "r", mp_filetype_program);
21838 xfree(mp->name_of_file);
21839 if (s == NULL)
21840 return false;
21841 mp->name_of_file = xstrdup(s);
21842 mp->mem_file = (mp->open_file) (mp, s, "r", mp_filetype_program);
21843 free (s);
21844 if (mp->mem_file)
21845 return true;
21846 }
21847 return false;
21848 }
21849 boolean mp_open_mem_file (MP mp) {
21850 if (mp->mem_file != NULL)
21851 return true;
21852 if (mp_open_mem_name (mp))
21853 return true;
21854 if (mp_xstrcmp (mp->mem_name, "plain")) {
21855 wake_up_terminal();
21856 wterm ("Sorry, I can\'t find the '");
21857 wterm (mp->mem_name);
21858 wterm ("' preload file; will try 'plain'.");
21859 wterm_cr;
21860 @.Sorry, I can't find...@>
21861 update_terminal();
21862 /* now pull out all the stops: try for the system \.{plain} file */
21863 xfree (mp->mem_name);
21864 mp->mem_name = xstrdup ("plain");
21865 if (mp_open_mem_name (mp))
21866 return true;
21867 }
21868 wake_up_terminal();
21869 wterm_ln ("I can't find the 'plain' preload file!\n");
21870 @.I can't find PLAIN...@>
21871 @.plain@>
21872 return false;
21873 }
21874
21875
21876 @ Operating systems often make it possible to determine the exact name (and
21877 possible version number) of a file that has been opened. The following routine,
21878 which simply makes a \MP\ string from the value of |name_of_file|, should
21879 ideally be changed to deduce the full name of file~|f|, which is the file
21880 most recently opened, if it is possible to do this.
21881 @^system dependencies@>
21882
21883 @c
21884 static mp_string mp_make_name_string (MP mp) {
21885 int k; /* index into |name_of_file| */
21886 int name_length = (int) strlen (mp->name_of_file);
21887 str_room (name_length);
21888 for (k = 0; k < name_length; k++) {
21889 append_char (xord ((ASCII_code) mp->name_of_file[k]));
21890 }
21891 return mp_make_string (mp);
21892 }
21893
21894
21895 @ Now let's consider the ``driver''
21896 routines by which \MP\ deals with file names
21897 in a system-independent manner. First comes a procedure that looks for a
21898 file name in the input by taking the information from the input buffer.
21899 (We can't use |get_next|, because the conversion to tokens would
21900 destroy necessary information.)
21901
21902 This procedure doesn't allow semicolons or percent signs to be part of
21903 file names, because of other conventions of \MP.
21904 {\sl The {\logos METAFONT\/}book} doesn't
21905 use semicolons or percents immediately after file names, but some users
21906 no doubt will find it natural to do so; therefore system-dependent
21907 changes to allow such characters in file names should probably
21908 be made with reluctance, and only when an entire file name that
21909 includes special characters is ``quoted'' somehow.
21910 @^system dependencies@>
21911
21912 @c
21913 static void mp_scan_file_name (MP mp) {
21914 mp_begin_name (mp);
21915 while (mp->buffer[loc] == ' ')
21916 incr (loc);
21917 while (1) {
21918 if ((mp->buffer[loc] == ';') || (mp->buffer[loc] == '%'))
21919 break;
21920 if (!mp_more_name (mp, mp->buffer[loc]))
21921 break;
21922 incr (loc);
21923 }
21924 mp_end_name (mp);
21925 }
21926
21927
21928 @ Here is another version that takes its input from a string.
21929
21930 @<Declare subroutines for parsing file names@>=
21931 void mp_str_scan_file (MP mp, mp_string s);
21932
21933 @ @c
21934 void mp_str_scan_file (MP mp, mp_string s) {
21935 size_t p, q; /* current position and stopping point */
21936 mp_begin_name (mp);
21937 p = 0;
21938 q = s->len;
21939 while (p < q) {
21940 if (!mp_more_name (mp, *(s->str + p)))
21941 break;
21942 incr (p);
21943 }
21944 mp_end_name (mp);
21945 }
21946
21947
21948 @ And one that reads from a |char*|.
21949
21950 @<Declare subroutines for parsing file names@>=
21951 extern void mp_ptr_scan_file (MP mp, char *s);
21952
21953 @ @c
21954 void mp_ptr_scan_file (MP mp, char *s) {
21955 char *p, *q; /* current position and stopping point */
21956 mp_begin_name (mp);
21957 p = s;
21958 q = p + strlen (s);
21959 while (p < q) {
21960 if (!mp_more_name (mp, (ASCII_code) (*p)))
21961 break;
21962 p++;
21963 }
21964 mp_end_name (mp);
21965 }
21966
21967
21968 @ The option variable |job_name| contains the file name that was first
21969 \&{input} by the user. This name is used to initialize the |job_name| global
21970 as well as the |mp_job_name| internal, and is extended by `\.{.log}' and
21971 `\.{ps}' and `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's
21972 output files.
21973
21974 @<Glob...@>=
21975 boolean log_opened; /* has the transcript file been opened? */
21976 char *log_name; /* full name of the log file */
21977
21978 @ @<Option variables@>=
21979 char *job_name; /* principal file name */
21980
21981 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
21982 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
21983 except of course for a short time just after |job_name| has become nonzero.
21984
21985 @<Allocate or ...@>=
21986 mp->job_name = mp_xstrdup (mp, opt->job_name);
21987 /*|
21988 if (mp->job_name != NULL) {
21989 char *s = mp->job_name + strlen (mp->job_name);
21990 while (s > mp->job_name) {
21991 if (*s == '.') {
21992 *s = '\0';
21993 }
21994 s--;
21995 }
21996 }
21997 |*/
21998 if (opt->noninteractive) {
21999 if (mp->job_name == NULL)
22000 mp->job_name = mp_xstrdup (mp, mp->mem_name);
22001 }
22002 mp->log_opened = false;
22003
22004 @ Cannot do this earlier because at the |@<Allocate or ...@>| block, the string
22005 pool is not yet initialized.
22006
22007 @<Fix up |mp->internal[mp_job_name]|@>=
22008 if (mp->job_name != NULL) {
22009 if (internal_string (mp_job_name) != 0)
22010 delete_str_ref (internal_string (mp_job_name));
22011 set_internal_string (mp_job_name, mp_rts (mp, mp->job_name));
22012 }
22013
22014 @ @<Dealloc variables@>=
22015 xfree (mp->job_name);
22016
22017 @ Here is a routine that manufactures the output file names, assuming that
22018 |job_name<>0|. It ignores and changes the current settings of |cur_area|
22019 and |cur_ext|.
22020
22021 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
22022
22023 @<Internal library ...@>=
22024 void mp_pack_job_name (MP mp, const char *s);
22025
22026 @ @c
22027 void mp_pack_job_name (MP mp, const char *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
22028 xfree (mp->cur_name);
22029 mp->cur_name = xstrdup (mp->job_name);
22030 xfree (mp->cur_area);
22031 mp->cur_area = xstrdup ("");
22032 xfree (mp->cur_ext);
22033 mp->cur_ext = xstrdup (s);
22034 pack_cur_name;
22035 }
22036
22037
22038 @ If some trouble arises when \MP\ tries to open a file, the following
22039 routine calls upon the user to supply another file name. Parameter~|s|
22040 is used in the error message to identify the type of file; parameter~|e|
22041 is the default extension if none is given. Upon exit from the routine,
22042 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
22043 ready for another attempt at file opening.
22044
22045 @<Internal library ...@>=
22046 void mp_prompt_file_name (MP mp, const char *s, const char *e);
22047
22048 @ @c
22049 void mp_prompt_file_name (MP mp, const char *s, const char *e) {
22050 size_t k; /* index into |buffer| */
22051 char *saved_cur_name;
22052 if (mp->interaction == mp_scroll_mode)
22053 wake_up_terminal();
22054 if (strcmp (s, "input file name") == 0) {
22055 mp_print_err (mp, "I can\'t open file `");
22056 @.I can't find file x@>
22057 } else {
22058 mp_print_err (mp, "I can\'t write on file `");
22059 @.I can't write on file x@>
22060 }
22061 if (strcmp (s, "file name for output") == 0) {
22062 mp_print (mp, mp->name_of_file);
22063 } else {
22064 mp_print_file_name (mp, mp->cur_name, mp->cur_area, mp->cur_ext);
22065 }
22066 mp_print (mp, "'.");
22067 if (strcmp (e, "") == 0)
22068 mp_show_context (mp);
22069 mp_print_nl (mp, "Please type another ");
22070 mp_print (mp, s);
22071 @.Please type...@>
22072 if (mp->noninteractive || mp->interaction < mp_scroll_mode)
22073 mp_fatal_error (mp, "*** (job aborted, file error in nonstop mode)");
22074 @.job aborted, file error...@>
22075 saved_cur_name = xstrdup (mp->cur_name);
22076 clear_terminal();
22077 prompt_input (": ");
22078 @<Scan file name in the buffer@>;
22079 if (strcmp (mp->cur_ext, "") == 0)
22080 mp->cur_ext = xstrdup (e);
22081 if (strlen (mp->cur_name) == 0) {
22082 mp->cur_name = saved_cur_name;
22083 } else {
22084 xfree (saved_cur_name);
22085 }
22086 pack_cur_name;
22087 }
22088
22089
22090 @ @<Scan file name in the buffer@>=
22091 {
22092 mp_begin_name (mp);
22093 k = mp->first;
22094 while ((mp->buffer[k] == ' ') && (k < mp->last))
22095 incr (k);
22096 while (1) {
22097 if (k == mp->last)
22098 break;
22099 if (!mp_more_name (mp, mp->buffer[k]))
22100 break;
22101 incr (k);
22102 }
22103 mp_end_name (mp);
22104 }
22105
22106
22107 @ The |open_log_file| routine is used to open the transcript file and to help
22108 it catch up to what has previously been printed on the terminal.
22109
22110 @c
22111 void mp_open_log_file (MP mp) {
22112 unsigned old_setting; /* previous |selector| setting */
22113 mpinteger64 k; /* index into |months| and |buffer| */
22114 int l; /* end of first input line */
22115 mpinteger64 m; /* the current month */
22116 const char *months = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
22117 /* abbreviations of month names */
22118 if (mp->log_opened)
22119 return;
22120 old_setting = mp->selector;
22121 if (mp->job_name == NULL) {
22122 mp->job_name = xstrdup ("mpout");
22123 @<Fix up |mp->internal[mp_job_name]|@>;
22124 }
22125 mp_pack_job_name (mp, ".log");
22126 while (!mp_open_out (mp, &mp->log_file, mp_filetype_log))
22127 @<Try to get a different log file name@>@;
22128 mp->log_name = xstrdup (mp->name_of_file);
22129 mp->selector = log_only;
22130 mp->log_opened = true;
22131 @<Print the banner line, including the date and time@>;
22132 mp->input_stack[mp->input_ptr] = mp->cur_input;
22133 /* make sure bottom level is in memory */
22134 if (!mp->noninteractive) {
22135 mp_print_nl (mp, "**");
22136 @.**@>
22137 l = mp->input_stack[0].limit_field - 1; /* last position of first line */
22138 for (k = 0; k <= l; k++)
22139 mp_print_char (mp, mp->buffer[k]);
22140 mp_print_ln (mp); /* now the transcript file contains the first line of input */
22141 }
22142 mp->selector = old_setting + 2; /* |log_only| or |term_and_log| */
22143 }
22144
22145
22146 @ @<Dealloc variables@>=
22147 xfree (mp->log_name);
22148
22149 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
22150 unable to print error messages or even to |show_context|.
22151 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
22152 routine will not be invoked because |log_opened| will be false.
22153
22154 The normal idea of |mp_batch_mode| is that nothing at all should be written
22155 on the terminal. However, in the unusual case that
22156 no log file could be opened, we make an exception and allow
22157 an explanatory message to be seen.
22158
22159 Incidentally, the program always refers to the log file as a `\.{transcript
22160 file}', because some systems cannot use the extension `\.{.log}' for
22161 this file.
22162
22163 @<Try to get a different log file name@>=
22164 {
22165 mp->selector = term_only;
22166 mp_prompt_file_name (mp, "transcript file name", ".log");
22167 }
22168
22169
22170 @ @<Print the banner...@>=
22171 {
22172 wlog (mp->banner);
22173 mp_print (mp, " ");
22174 mp_print_int (mp, round_unscaled (internal_value (mp_day)));
22175 mp_print_char (mp, xord (' '));
22176 m = round_unscaled (internal_value (mp_month));
22177 for (k = 3 * m - 3; k < 3 * m; k++) {
22178 wlog_chr ((unsigned char) months[k]);
22179 }
22180 mp_print_char (mp, xord (' '));
22181 mp_print_int (mp, round_unscaled (internal_value (mp_year)));
22182 mp_print_char (mp, xord (' '));
22183 mp_print_dd (mp, round_unscaled (internal_value (mp_hour)));
22184 mp_print_char (mp, xord (':'));
22185 mp_print_dd (mp, round_unscaled (internal_value (mp_minute)));
22186 }
22187
22188
22189 @ The |try_extension| function tries to open an input file determined by
22190 |cur_name|, |cur_area|, and the argument |ext|. It returns |false| if it
22191 can't find the file in |cur_area| or the appropriate system area.
22192
22193 @c
22194 static boolean mp_try_extension (MP mp, const char *ext) {
22195 mp_pack_file_name (mp, mp->cur_name, mp->cur_area, ext);
22196 in_name = xstrdup (mp->cur_name);
22197 in_area = xstrdup (mp->cur_area);
22198 in_ext = xstrdup (ext);
22199 if (mp_open_in (mp, &cur_file, mp_filetype_program)) {
22200 return true;
22201 } else {
22202 mp_pack_file_name (mp, mp->cur_name, NULL, ext);
22203 return mp_open_in (mp, &cur_file, mp_filetype_program);
22204 }
22205 }
22206
22207
22208 @ Let's turn now to the procedure that is used to initiate file reading
22209 when an `\.{input}' command is being processed.
22210
22211 @c
22212 void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
22213 char *fname = NULL;
22214 @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
22215 while (1) {
22216 mp_begin_file_reading (mp); /* set up |cur_file| and new level of input */
22217 if (strlen (mp->cur_ext) == 0) {
22218 if (mp_try_extension (mp, ".mp"))
22219 break;
22220 else if (mp_try_extension (mp, ""))
22221 break;
22222 else if (mp_try_extension (mp, ".mf"))
22223 break;
22224 } else if (mp_try_extension (mp, mp->cur_ext)) {
22225 break;
22226 }
22227 mp_end_file_reading (mp); /* remove the level that didn't work */
22228 mp_prompt_file_name (mp, "input file name", "");
22229 }
22230 name = mp_make_name_string (mp);
22231 fname = xstrdup (mp->name_of_file);
22232 if (mp->job_name == NULL) {
22233 mp->job_name = xstrdup (mp->cur_name);
22234 @<Fix up |mp->internal[mp_job_name]|@>;
22235 }
22236 if (!mp->log_opened) {
22237 mp_open_log_file (mp);
22238 } /* |open_log_file| doesn't |show_context|, so |limit|
22239 and |loc| needn't be set to meaningful values yet */
22240 if (((int) mp->term_offset + (int) strlen (fname)) > (mp->max_print_line - 2))
22241 mp_print_ln (mp);
22242 else if ((mp->term_offset > 0) || (mp->file_offset > 0))
22243 mp_print_char (mp, xord (' '));
22244 mp_print_char (mp, xord ('('));
22245 incr (mp->open_parens);
22246 mp_print (mp, fname);
22247 xfree (fname);
22248 update_terminal();
22249 @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
22250 @<Read the first line of the new file@>;
22251 }
22252
22253
22254 @ This code should be omitted if |make_name_string| returns something other
22255 than just a copy of its argument and the full file name is needed for opening
22256 \.{MPX} files or implementing the switch-to-editor option.
22257 @^system dependencies@>
22258
22259 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
22260 mp_flush_string (mp, name);
22261 name = mp_rts (mp, mp->cur_name);
22262 xfree (mp->cur_name)@;
22263
22264
22265 @ If the file is empty, it is considered to contain a single blank line,
22266 so there is no need to test the return value.
22267
22268 @<Read the first line...@>=
22269 {
22270 line = 1;
22271 (void) mp_input_ln (mp, cur_file);
22272 mp_firm_up_the_line (mp);
22273 mp->buffer[limit] = xord ('%');
22274 mp->first = (size_t) (limit + 1);
22275 loc = start;
22276 }
22277
22278
22279 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
22280 while (token_state && (nloc == NULL))
22281 mp_end_token_list (mp);
22282 if (token_state) {
22283 const char *hlp[] = {
22284 "Sorry...I've converted what follows to tokens,",
22285 "possibly garbaging the name you gave.",
22286 "Please delete the tokens and insert the name again.",
22287 NULL };
22288 mp_error (mp, "File names can't appear within macros", hlp, true);
22289 @.File names can't...@>
22290 }
22291 if (file_state) {
22292 mp_scan_file_name (mp);
22293 } else {
22294 xfree (mp->cur_name);
22295 mp->cur_name = xstrdup ("");
22296 xfree (mp->cur_ext);
22297 mp->cur_ext = xstrdup ("");
22298 xfree (mp->cur_area);
22299 mp->cur_area = xstrdup ("");
22300 }
22301
22302
22303 @ The following simple routine starts reading the \.{MPX} file associated
22304 with the current input file.
22305
22306 @c
22307 void mp_start_mpx_input (MP mp) {
22308 char *origname = NULL; /* a copy of nameoffile */
22309 mp_pack_file_name (mp, in_name, in_area, in_ext);
22310 origname = xstrdup (mp->name_of_file);
22311 mp_pack_file_name (mp, in_name, in_area, ".mpx");
22312 if (!(mp->run_make_mpx) (mp, origname, mp->name_of_file))
22313 goto NOT_FOUND;
22314 mp_begin_file_reading (mp);
22315 if (!mp_open_in (mp, &cur_file, mp_filetype_program)) {
22316 mp_end_file_reading (mp);
22317 goto NOT_FOUND;
22318 }
22319 name = mp_make_name_string (mp);
22320 mp->mpx_name[iindex] = name;
22321 add_str_ref (name);
22322 @<Read the first line of the new file@>;
22323 xfree (origname);
22324 return;
22325 NOT_FOUND:
22326 @<Explain that the \.{MPX} file can't be read and |succumb|@>;
22327 xfree (origname);
22328 }
22329
22330
22331 @ This should ideally be changed to do whatever is necessary to create the
22332 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
22333 of date. This requires invoking \.{MPtoTeX} on the |origname| and passing
22334 the results through \TeX\ and \.{DVItoMP}. (It is possible to use a
22335 completely different typesetting program if suitable postprocessor is
22336 available to perform the function of \.{DVItoMP}.)
22337 @^system dependencies@>
22338
22339 @ @<Exported types@>=
22340 typedef int @[@] (*mp_makempx_cmd) (MP mp, char *origname, char *mtxname);
22341
22342 @ @<Option variables@>=
22343 mp_makempx_cmd run_make_mpx;
22344
22345 @ @<Allocate or initialize ...@>=
22346 set_callback_option (run_make_mpx);
22347
22348 @ @<Declarations@>=
22349 static int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
22350
22351 @ The default does nothing.
22352 @c
22353 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
22354 (void) mp;
22355 (void) origname;
22356 (void) mtxname;
22357 return false;
22358 }
22359
22360
22361 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
22362 {
22363 const char *hlp[] = {
22364 "The two files given above are one of your source files",
22365 "and an auxiliary file I need to read to find out what your",
22366 "btex..etex blocks mean. If you don't know why I had trouble,",
22367 "try running it manually through MPtoTeX, TeX, and DVItoMP",
22368 NULL };
22369 if (mp->interaction == mp_error_stop_mode)
22370 wake_up_terminal();
22371 mp_print_nl (mp, ">> ");
22372 mp_print (mp, origname);
22373 mp_print_nl (mp, ">> ");
22374 mp_print (mp, mp->name_of_file);
22375 xfree (origname);
22376 if ( mp->interaction==mp_error_stop_mode )
22377 mp->interaction=mp_scroll_mode; /* no more interaction */
22378 if ( mp->log_opened )
22379 mp_error(mp, "! Unable to read mpx file", hlp, true);
22380 mp->history=mp_fatal_error_stop;
22381 mp_jump_out(mp); /* irrecoverable error */
22382 }
22383
22384 @ The last file-opening commands are for files accessed via the \&{readfrom}
22385 @:read_from_}{\&{readfrom} primitive@>
22386 operator and the \&{write} command. Such files are stored in separate arrays.
22387 @:write_}{\&{write} primitive@>
22388
22389 @<Types in the outer block@>=
22390 typedef unsigned int readf_index; /* |0..max_read_files| */
22391 typedef unsigned int write_index; /* |0..max_write_files| */
22392
22393 @ @<Glob...@>=
22394 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
22395 void **rd_file; /* \&{readfrom} files */
22396 char **rd_fname; /* corresponding file name or 0 if file not open */
22397 readf_index read_files; /* number of valid entries in the above arrays */
22398 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
22399 void **wr_file; /* \&{write} files */
22400 char **wr_fname; /* corresponding file name or 0 if file not open */
22401 write_index write_files; /* number of valid entries in the above arrays */
22402
22403 @ @<Allocate or initialize ...@>=
22404 mp->max_read_files = 8;
22405 mp->rd_file = xmalloc ((mp->max_read_files + 1), sizeof (void *));
22406 mp->rd_fname = xmalloc ((mp->max_read_files + 1), sizeof (char *));
22407 memset (mp->rd_fname, 0, sizeof (char *) * (mp->max_read_files + 1));
22408 mp->max_write_files = 8;
22409 mp->wr_file = xmalloc ((mp->max_write_files + 1), sizeof (void *));
22410 mp->wr_fname = xmalloc ((mp->max_write_files + 1), sizeof (char *));
22411 memset (mp->wr_fname, 0, sizeof (char *) * (mp->max_write_files + 1));
22412
22413
22414 @ This routine starts reading the file named by string~|s| without setting
22415 |loc|, |limit|, or |name|. It returns |false| if the file is empty or cannot
22416 be opened. Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
22417
22418 @c
22419 static boolean mp_start_read_input (MP mp, char *s, readf_index n) {
22420 mp_ptr_scan_file (mp, s);
22421 pack_cur_name;
22422 mp_begin_file_reading (mp);
22423 if (!mp_open_in (mp, &mp->rd_file[n], (int) (mp_filetype_text + n)))
22424 goto NOT_FOUND;
22425 if (!mp_input_ln (mp, mp->rd_file[n])) {
22426 (mp->close_file) (mp, mp->rd_file[n]);
22427 goto NOT_FOUND;
22428 }
22429 mp->rd_fname[n] = xstrdup (s);
22430 return true;
22431 NOT_FOUND:
22432 mp_end_file_reading (mp);
22433 return false;
22434 }
22435
22436
22437 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
22438
22439 @<Declarations@>=
22440 static void mp_open_write_file (MP mp, char *s, readf_index n);
22441
22442 @ @c
22443 void mp_open_write_file (MP mp, char *s, readf_index n) {
22444 mp_ptr_scan_file (mp, s);
22445 pack_cur_name;
22446 while (!mp_open_out (mp, &mp->wr_file[n], (int) (mp_filetype_text + n)))
22447 mp_prompt_file_name (mp, "file name for write output", "");
22448 mp->wr_fname[n] = xstrdup (s);
22449 }
22450
22451
22452 @* Introduction to the parsing routines.
22453 We come now to the central nervous system that sparks many of \MP's activities.
22454 By evaluating expressions, from their primary constituents to ever larger
22455 subexpressions, \MP\ builds the structures that ultimately define complete
22456 pictures or fonts of type.
22457
22458 Four mutually recursive subroutines are involved in this process: We call them
22459 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
22460 and |scan_expression|.}$$
22461 @^recursion@>
22462 Each of them is parameterless and begins with the first token to be scanned
22463 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
22464 the value of the primary or secondary or tertiary or expression that was
22465 found will appear in the global variables |cur_type| and |cur_exp|. The
22466 token following the expression will be represented in |cur_cmd|, |cur_mod|,
22467 and |cur_sym|.
22468
22469 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
22470 backup mechanisms have been added in order to provide reasonable error
22471 recovery.
22472
22473 @d cur_exp_value_boolean() number_to_int (mp->cur_exp.data.n)
22474 @d cur_exp_value_number() mp->cur_exp.data.n
22475 @d cur_exp_node() mp->cur_exp.data.node
22476 @d cur_exp_str() mp->cur_exp.data.str
22477 @d cur_exp_knot() mp->cur_exp.data.p
22478
22479 @d set_cur_exp_value_scaled(A) do {
22480 if (cur_exp_str()) {
22481 delete_str_ref(cur_exp_str());
22482 }
22483 set_number_from_scaled (mp->cur_exp.data.n, (A));
22484 cur_exp_node() = NULL;
22485 cur_exp_str() = NULL;
22486 cur_exp_knot() = NULL;
22487 } while (0)@;
22488 @d set_cur_exp_value_boolean(A) do {
22489 if (cur_exp_str()) {
22490 delete_str_ref(cur_exp_str());
22491 }
22492 set_number_from_int (mp->cur_exp.data.n, (A));
22493 cur_exp_node() = NULL;
22494 cur_exp_str() = NULL;
22495 cur_exp_knot() = NULL;
22496 } while (0)@;
22497 @d set_cur_exp_value_number(A) do {
22498 if (cur_exp_str()) {
22499 delete_str_ref(cur_exp_str());
22500 }
22501 number_clone (mp->cur_exp.data.n, (A));
22502 cur_exp_node() = NULL;
22503 cur_exp_str() = NULL;
22504 cur_exp_knot() = NULL;
22505 } while (0)@;
22506 @d set_cur_exp_node(A) do {
22507 if (cur_exp_str()) {
22508 delete_str_ref(cur_exp_str());
22509 }
22510 cur_exp_node() = A;
22511 cur_exp_str() = NULL;
22512 cur_exp_knot() = NULL;
22513 set_number_to_zero (mp->cur_exp.data.n);
22514 } while (0)@;
22515 @d set_cur_exp_str(A) do {
22516 if (cur_exp_str()) {
22517 delete_str_ref(cur_exp_str());
22518 }
22519 cur_exp_str() = A;
22520 add_str_ref(cur_exp_str());
22521 cur_exp_node() = NULL;
22522 cur_exp_knot() = NULL;
22523 set_number_to_zero (mp->cur_exp.data.n);
22524 } while (0)@;
22525 @d set_cur_exp_knot(A) do {
22526 if (cur_exp_str()) {
22527 delete_str_ref(cur_exp_str());
22528 }
22529 cur_exp_knot() = A;
22530 cur_exp_node() = NULL;
22531 cur_exp_str() = NULL;
22532 set_number_to_zero (mp->cur_exp.data.n);
22533 } while (0)@;
22534
22535
22536 @ @<Glob...@>=
22537 mp_value cur_exp; /* the value of the expression just found */
22538
22539 @ @<Set init...@>=
22540 memset (&mp->cur_exp.data, 0, sizeof (mp_value));
22541 new_number(mp->cur_exp.data.n);
22542
22543 @ @<Free table ...@>=
22544 free_number(mp->cur_exp.data.n);
22545
22546 @ Many different kinds of expressions are possible, so it is wise to have
22547 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
22548
22549 \smallskip\hang
22550 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
22551 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
22552 construction in which there was no expression before the \&{endgroup}.
22553 In this case |cur_exp| has some irrelevant value.
22554
22555 \smallskip\hang
22556 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
22557 or |false_code|.
22558
22559 \smallskip\hang
22560 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
22561 node that is in
22562 a ring of equivalent booleans whose value has not yet been defined.
22563
22564 \smallskip\hang
22565 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
22566 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
22567 includes this particular reference.
22568
22569 \smallskip\hang
22570 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
22571 node that is in
22572 a ring of equivalent strings whose value has not yet been defined.
22573
22574 \smallskip\hang
22575 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen. Nobody
22576 else points to any of the nodes in this pen. The pen may be polygonal or
22577 elliptical.
22578
22579 \smallskip\hang
22580 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
22581 node that is in
22582 a ring of equivalent pens whose value has not yet been defined.
22583
22584 \smallskip\hang
22585 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
22586 a path; nobody else points to this particular path. The control points of
22587 the path will have been chosen.
22588
22589 \smallskip\hang
22590 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
22591 node that is in
22592 a ring of equivalent paths whose value has not yet been defined.
22593
22594 \smallskip\hang
22595 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
22596 There may be other pointers to this particular set of edges. The header node
22597 contains a reference count that includes this particular reference.
22598
22599 \smallskip\hang
22600 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
22601 node that is in
22602 a ring of equivalent pictures whose value has not yet been defined.
22603
22604 \smallskip\hang
22605 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
22606 capsule node. The |value| part of this capsule
22607 points to a transform node that contains six numeric values,
22608 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
22609
22610 \smallskip\hang
22611 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
22612 capsule node. The |value| part of this capsule
22613 points to a color node that contains three numeric values,
22614 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
22615
22616 \smallskip\hang
22617 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
22618 capsule node. The |value| part of this capsule
22619 points to a color node that contains four numeric values,
22620 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
22621
22622 \smallskip\hang
22623 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
22624 node whose type is |mp_pair_type|. The |value| part of this capsule
22625 points to a pair node that contains two numeric values,
22626 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
22627
22628 \smallskip\hang
22629 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
22630
22631 \smallskip\hang
22632 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
22633 is |dependent|. The |dep_list| field in this capsule points to the associated
22634 dependency list.
22635
22636 \smallskip\hang
22637 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
22638 capsule node. The |dep_list| field in this capsule
22639 points to the associated dependency list.
22640
22641 \smallskip\hang
22642 |cur_type=independent| means that |cur_exp| points to a capsule node
22643 whose type is |independent|. This somewhat unusual case can arise, for
22644 example, in the expression
22645 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
22646
22647 \smallskip\hang
22648 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
22649 tokens.
22650
22651 \smallskip\noindent
22652 The possible settings of |cur_type| have been listed here in increasing
22653 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
22654 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
22655 are allowed. Conversely, \MP\ has no variables of type |mp_vacuous| or
22656 |token_list|.
22657
22658 @ Capsules are non-symbolic nodes that have a similar meaning
22659 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|,
22660 and their |type| field is one of the possibilities for |cur_type| listed above.
22661 Also |link<=void| in capsules that aren't part of a token list.
22662
22663 The |value| field of a capsule is, in most cases, the value that
22664 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
22665 However, when |cur_exp| would point to a capsule,
22666 no extra layer of indirection is present; the |value|
22667 field is what would have been called |value(cur_exp)| if it had not been
22668 encapsulated. Furthermore, if the type is |dependent| or
22669 |mp_proto_dependent|, the |value| field of a capsule is replaced by
22670 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
22671 always part of the general |dep_list| structure.
22672
22673 The |get_x_next| routine is careful not to change the values of |cur_type|
22674 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
22675 call a macro, which might parse an expression, which might execute lots of
22676 commands in a group; hence it's possible that |cur_type| might change
22677 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
22678 |known| or |independent|, during the time |get_x_next| is called. The
22679 programs below are careful to stash sensitive intermediate results in
22680 capsules, so that \MP's generality doesn't cause trouble.
22681
22682 Here's a procedure that illustrates these conventions. It takes
22683 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
22684 and stashes them away in a
22685 capsule. It is not used when |cur_type=mp_token_list|.
22686 After the operation, |cur_type=mp_vacuous|; hence there is no need to
22687 copy path lists or to update reference counts, etc.
22688
22689 The special link |MP_VOID| is put on the capsule returned by
22690 |stash_cur_exp|, because this procedure is used to store macro parameters
22691 that must be easily distinguishable from token lists.
22692
22693 @<Declare the stashing/unstashing routines@>=
22694 static mp_node mp_stash_cur_exp (MP mp) {
22695 mp_node p; /* the capsule that will be returned */
22696 mp_variable_type exp_type = mp->cur_exp.type;
22697 switch (exp_type) {
22698 case unknown_types:
22699 case mp_transform_type:
22700 case mp_color_type:
22701 case mp_pair_type:
22702 case mp_dependent:
22703 case mp_proto_dependent:
22704 case mp_independent:
22705 case mp_cmykcolor_type:
22706 p = cur_exp_node ();
22707 break;
22708 /* |case mp_path_type: case mp_pen_type: case mp_string_type:| */
22709 default:
22710 p = mp_get_value_node (mp);
22711 mp_name_type (p) = mp_capsule;
22712 mp_type (p) = mp->cur_exp.type;
22713 set_value_number (p, cur_exp_value_number ()); /* this also resets the rest to 0/NULL */
22714 if (cur_exp_str ()) {
22715 set_value_str (p, cur_exp_str ());
22716 } else if (cur_exp_knot ()) {
22717 set_value_knot (p, cur_exp_knot ());
22718 } else if (cur_exp_node ()) {
22719 set_value_node (p, cur_exp_node ());
22720 }
22721 break;
22722 }
22723 mp->cur_exp.type = mp_vacuous;
22724 mp_link (p) = MP_VOID;
22725 return p;
22726 }
22727
22728
22729 @ The inverse of |stash_cur_exp| is the following procedure, which
22730 deletes an unnecessary capsule and puts its contents into |cur_type|
22731 and |cur_exp|.
22732
22733 The program steps of \MP\ can be divided into two categories: those in
22734 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
22735 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
22736 information or not. It's important not to ignore them when they're alive,
22737 and it's important not to pay attention to them when they're dead.
22738
22739 There's also an intermediate category: If |cur_type=mp_vacuous|, then
22740 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
22741 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
22742 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
22743 only when they are alive or dormant.
22744
22745 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
22746 are alive or dormant. The \\{unstash} procedure assumes that they are
22747 dead or dormant; it resuscitates them.
22748
22749 @<Declare the stashing/unstashing...@>=
22750 static void mp_unstash_cur_exp (MP mp, mp_node p);
22751
22752 @ @c
22753 void mp_unstash_cur_exp (MP mp, mp_node p) {
22754 mp->cur_exp.type = mp_type (p);
22755 switch (mp->cur_exp.type) {
22756 case unknown_types:
22757 case mp_transform_type:
22758 case mp_color_type:
22759 case mp_pair_type:
22760 case mp_dependent:
22761 case mp_proto_dependent:
22762 case mp_independent:
22763 case mp_cmykcolor_type:
22764 set_cur_exp_node (p);
22765 break;
22766 case mp_token_list: /* this is how symbols are stashed */
22767 set_cur_exp_node (value_node(p));
22768 mp_free_value_node (mp, p);
22769 break;
22770 case mp_path_type:
22771 case mp_pen_type:
22772 set_cur_exp_knot (value_knot (p));
22773 mp_free_value_node (mp, p);
22774 break;
22775 case mp_string_type:
22776 set_cur_exp_str (value_str (p));
22777 mp_free_value_node (mp, p);
22778 break;
22779 case mp_picture_type:
22780 set_cur_exp_node (value_node (p));
22781 mp_free_value_node (mp, p);
22782 break;
22783 case mp_boolean_type:
22784 case mp_known:
22785 set_cur_exp_value_number (value_number (p));
22786 mp_free_value_node (mp, p);
22787 break;
22788 default:
22789 set_cur_exp_value_number (value_number (p));
22790 if (value_knot(p)) {
22791 set_cur_exp_knot (value_knot (p));
22792 } else if (value_node(p)) {
22793 set_cur_exp_node (value_node (p));
22794 } else if (value_str(p)) {
22795 set_cur_exp_str (value_str (p));
22796 }
22797 mp_free_value_node (mp, p);
22798 break;
22799 }
22800 }
22801
22802
22803 @ The following procedure prints the values of expressions in an
22804 abbreviated format. If its first parameter |p| is NULL, the value of
22805 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
22806 containing the desired value. The second parameter controls the amount of
22807 output. If it is~0, dependency lists will be abbreviated to
22808 `\.{linearform}' unless they consist of a single term. If it is greater
22809 than~1, complicated structures (pens, pictures, and paths) will be displayed
22810 in full.
22811 @.linearform@>
22812
22813 @<Declarations@>=
22814 @<Declare the procedure called |print_dp|@>
22815 @<Declare the stashing/unstashing routines@>
22816 static void mp_print_exp (MP mp, mp_node p, quarterword verbosity);
22817
22818 @ @c
22819 void mp_print_exp (MP mp, mp_node p, quarterword verbosity) {
22820 boolean restore_cur_exp; /* should |cur_exp| be restored? */
22821 mp_variable_type t; /* the type of the expression */
22822 mp_number vv; /* the value of the expression */
22823 mp_node v = NULL;
22824 new_number (vv);
22825 if (p != NULL) {
22826 restore_cur_exp = false;
22827 } else {
22828 p = mp_stash_cur_exp (mp);
22829 restore_cur_exp = true;
22830 }
22831 t = mp_type (p);
22832 if (t < mp_dependent) { /* no dep list, could be a capsule */
22833 if (t != mp_vacuous && t != mp_known && value_node (p) != NULL)
22834 v = value_node (p);
22835 else
22836 number_clone (vv, value_number (p));
22837 } else if (t < mp_independent) {
22838 v = (mp_node) dep_list ((mp_value_node) p);
22839 }
22840 @<Print an abbreviated value of |v| or |vv| with format depending on |t|@>;
22841 if (restore_cur_exp)
22842 mp_unstash_cur_exp (mp, p);
22843 free_number (vv);
22844 }
22845
22846
22847 @ @<Print an abbreviated value of |v| or |vv| with format depending on |t|@>=
22848 switch (t) {
22849 case mp_vacuous:
22850 mp_print (mp, "vacuous");
22851 break;
22852 case mp_boolean_type:
22853 if (number_to_boolean (vv) == mp_true_code)
22854 mp_print (mp, "true");
22855 else
22856 mp_print (mp, "false");
22857 break;
22858 case unknown_types:
22859 case mp_numeric_type:
22860 @<Display a variable that's been declared but not defined@>;
22861 break;
22862 case mp_string_type:
22863 mp_print_char (mp, xord ('"'));
22864 mp_print_str (mp, value_str (p));
22865 mp_print_char (mp, xord ('"'));
22866 break;
22867 case mp_pen_type:
22868 case mp_path_type:
22869 case mp_picture_type:
22870 @<Display a complex type@>;
22871 break;
22872 case mp_transform_type:
22873 if (number_zero (vv) && v == NULL)
22874 mp_print_type (mp, t);
22875 else
22876 @<Display a transform node@>;
22877 break;
22878 case mp_color_type:
22879 if (number_zero (vv) && v == NULL)
22880 mp_print_type (mp, t);
22881 else
22882 @<Display a color node@>;
22883 break;
22884 case mp_pair_type:
22885 if (number_zero (vv) && v == NULL)
22886 mp_print_type (mp, t);
22887 else
22888 @<Display a pair node@>;
22889 break;
22890 case mp_cmykcolor_type:
22891 if (number_zero (vv) && v == NULL)
22892 mp_print_type (mp, t);
22893 else
22894 @<Display a cmykcolor node@>;
22895 break;
22896 case mp_known:
22897 print_number (vv);
22898 break;
22899 case mp_dependent:
22900 case mp_proto_dependent:
22901 mp_print_dp (mp, t, (mp_value_node) v, verbosity);
22902 break;
22903 case mp_independent:
22904 mp_print_variable_name (mp, p);
22905 break;
22906 default:
22907 mp_confusion (mp, "exp");
22908 break;
22909 @:this can't happen exp}{\quad exp@>
22910 }
22911
22912
22913 @ @<Display big node item |v|@>=
22914 {
22915 if (mp_type (v) == mp_known)
22916 print_number (value_number (v));
22917 else if (mp_type (v) == mp_independent)
22918 mp_print_variable_name (mp, v);
22919 else
22920 mp_print_dp (mp, mp_type (v), (mp_value_node) dep_list ((mp_value_node) v),
22921 verbosity);
22922 }
22923
22924
22925 @ In these cases, |v| starts as the big node.
22926
22927 @<Display a pair node@>=
22928 {
22929 mp_node vvv = v;
22930 mp_print_char (mp, xord ('('));
22931 /* clang: dereference of null pointer */ assert(vvv);
22932 v = x_part (vvv);
22933 @<Display big node item |v|@>;
22934 mp_print_char (mp, xord (','));
22935 v = y_part (vvv);
22936 @<Display big node item |v|@>;
22937 mp_print_char (mp, xord (')'));
22938 }
22939
22940
22941 @ @<Display a transform node@>=
22942 {
22943 mp_node vvv = v;
22944 mp_print_char (mp, xord ('('));
22945 /* clang: dereference of null pointer */ assert(vvv);
22946 v = tx_part (vvv);
22947 @<Display big node item |v|@>;
22948 mp_print_char (mp, xord (','));
22949 v = ty_part (vvv);
22950 @<Display big node item |v|@>;
22951 mp_print_char (mp, xord (','));
22952 v = xx_part (vvv);
22953 @<Display big node item |v|@>;
22954 mp_print_char (mp, xord (','));
22955 v = xy_part (vvv);
22956 @<Display big node item |v|@>;
22957 mp_print_char (mp, xord (','));
22958 v = yx_part (vvv);
22959 @<Display big node item |v|@>;
22960 mp_print_char (mp, xord (','));
22961 v = yy_part (vvv);
22962 @<Display big node item |v|@>;
22963 mp_print_char (mp, xord (')'));
22964 }
22965
22966
22967 @ @<Display a color node@>=
22968 {
22969 mp_node vvv = v;
22970 mp_print_char (mp, xord ('('));
22971 /* clang: dereference of null pointer */ assert(vvv);
22972 v = red_part (vvv);
22973 @<Display big node item |v|@>;
22974 mp_print_char (mp, xord (','));
22975 v = green_part (vvv);
22976 @<Display big node item |v|@>;
22977 mp_print_char (mp, xord (','));
22978 v = blue_part (vvv);
22979 @<Display big node item |v|@>;
22980 mp_print_char (mp, xord (')'));
22981 }
22982
22983
22984 @ @<Display a cmykcolor node@>=
22985 {
22986 mp_node vvv = v;
22987 mp_print_char (mp, xord ('('));
22988 /* clang: dereference of null pointer */ assert(vvv);
22989 v = cyan_part (vvv);
22990 @<Display big node item |v|@>;
22991 mp_print_char (mp, xord (','));
22992 v = magenta_part (vvv);
22993 @<Display big node item |v|@>;
22994 mp_print_char (mp, xord (','));
22995 v = yellow_part (vvv);
22996 @<Display big node item |v|@>;
22997 mp_print_char (mp, xord (','));
22998 v = black_part (vvv);
22999 @<Display big node item |v|@>;
23000 mp_print_char (mp, xord (')'));
23001 }
23002
23003
23004 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
23005 in the log file only, unless the user has given a positive value to
23006 \\{tracingonline}.
23007
23008 @<Display a complex type@>=
23009 if (verbosity <= 1) {
23010 mp_print_type (mp, t);
23011 } else {
23012 if (mp->selector == term_and_log)
23013 if (number_nonpositive (internal_value (mp_tracing_online))) {
23014 mp->selector = term_only;
23015 mp_print_type (mp, t);
23016 mp_print (mp, " (see the transcript file)");
23017 mp->selector = term_and_log;
23018 }
23019 switch (t) {
23020 case mp_pen_type:
23021 mp_print_pen (mp, value_knot (p), "", false);
23022 break;
23023 case mp_path_type:
23024 mp_print_path (mp, value_knot (p), "", false);
23025 break;
23026 case mp_picture_type:
23027 mp_print_edges (mp, v, "", false);
23028 break;
23029 default:
23030 break;
23031 }
23032 }
23033
23034
23035 @ @<Declare the procedure called |print_dp|@>=
23036 static void mp_print_dp (MP mp, quarterword t, mp_value_node p,
23037 quarterword verbosity) {
23038 mp_value_node q; /* the node following |p| */
23039 q = (mp_value_node) mp_link (p);
23040 if ((dep_info (q) == NULL) || (verbosity > 0))
23041 mp_print_dependency (mp, p, t);
23042 else
23043 mp_print (mp, "linearform");
23044 }
23045
23046
23047 @ The displayed name of a variable in a ring will not be a capsule unless
23048 the ring consists entirely of capsules.
23049
23050 @<Display a variable that's been declared but not defined@>=
23051 {
23052 mp_print_type (mp, t);
23053 if (v != NULL) {
23054 mp_print_char (mp, xord (' '));
23055 while ((mp_name_type (v) == mp_capsule) && (v != p))
23056 v = value_node (v);
23057 mp_print_variable_name (mp, v);
23058 }
23059 }
23060
23061
23062 @ When errors are detected during parsing, it is often helpful to
23063 display an expression just above the error message, using |disp_err|
23064 just before |mp_error|.
23065
23066 @<Declarations@>=
23067 static void mp_disp_err (MP mp, mp_node p);
23068
23069 @ @c
23070 void mp_disp_err (MP mp, mp_node p) {
23071 if (mp->interaction == mp_error_stop_mode)
23072 wake_up_terminal();
23073 mp_print_nl (mp, ">> ");
23074 @.>>@>
23075 mp_print_exp (mp, p, 1); /* ``medium verbose'' printing of the expression */
23076 }
23077
23078
23079 @ If |cur_type| and |cur_exp| contain relevant information that should
23080 be recycled, we will use the following procedure, which changes |cur_type|
23081 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
23082 and |cur_exp| as either alive or dormant after this has been done,
23083 because |cur_exp| will not contain a pointer value.
23084
23085 @c
23086 void mp_flush_cur_exp (MP mp, mp_value v) {
23087 if (is_number(mp->cur_exp.data.n)) {
23088 free_number(mp->cur_exp.data.n);
23089 }
23090 switch (mp->cur_exp.type) {
23091 case unknown_types:
23092 case mp_transform_type:
23093 case mp_color_type:
23094 case mp_pair_type:
23095 case mp_dependent:
23096 case mp_proto_dependent:
23097 case mp_independent:
23098 case mp_cmykcolor_type:
23099 mp_recycle_value (mp, cur_exp_node ());
23100 mp_free_value_node (mp, cur_exp_node ());
23101 break;
23102 case mp_string_type:
23103 delete_str_ref (cur_exp_str ());
23104 break;
23105 case mp_pen_type:
23106 case mp_path_type:
23107 mp_toss_knot_list (mp, cur_exp_knot ());
23108 break;
23109 case mp_picture_type:
23110 delete_edge_ref (cur_exp_node ());
23111 break;
23112 default:
23113 break;
23114 }
23115 mp->cur_exp = v;
23116 mp->cur_exp.type = mp_known;
23117 }
23118
23119
23120 @ There's a much more general procedure that is capable of releasing
23121 the storage associated with any non-symbolic value packet.
23122
23123 @<Declarations@>=
23124 static void mp_recycle_value (MP mp, mp_node p);
23125
23126 @ @c
23127 static void mp_recycle_value (MP mp, mp_node p) {
23128 mp_variable_type t; /* a type code */
23129 FUNCTION_TRACE2 ("mp_recycle_value(%p)\n", p);
23130 if (p==NULL || p==MP_VOID)
23131 return;
23132 t = mp_type (p);
23133 switch (t) {
23134 case mp_vacuous:
23135 case mp_boolean_type:
23136 case mp_known:
23137 case mp_numeric_type:
23138 break;
23139 case unknown_types:
23140 mp_ring_delete (mp, p);
23141 break;
23142 case mp_string_type:
23143 delete_str_ref (value_str (p));
23144 break;
23145 case mp_path_type:
23146 case mp_pen_type:
23147 mp_toss_knot_list (mp, value_knot (p));
23148 break;
23149 case mp_picture_type:
23150 delete_edge_ref (value_node (p));
23151 break;
23152 case mp_cmykcolor_type:
23153 if (value_node (p) != NULL) {
23154 mp_recycle_value (mp, cyan_part (value_node (p)));
23155 mp_recycle_value (mp, magenta_part (value_node (p)));
23156 mp_recycle_value (mp, yellow_part (value_node (p)));
23157 mp_recycle_value (mp, black_part (value_node (p)));
23158 mp_free_value_node (mp, cyan_part (value_node (p)));
23159 mp_free_value_node (mp, magenta_part (value_node (p)));
23160 mp_free_value_node (mp, black_part (value_node (p)));
23161 mp_free_value_node (mp, yellow_part (value_node (p)));
23162 mp_free_node (mp, value_node (p), cmykcolor_node_size);
23163 }
23164 break;
23165 case mp_pair_type:
23166 if (value_node (p) != NULL) {
23167 mp_recycle_value (mp, x_part (value_node (p)));
23168 mp_recycle_value (mp, y_part (value_node (p)));
23169 mp_free_value_node (mp, x_part (value_node (p)));
23170 mp_free_value_node (mp, y_part (value_node (p)));
23171 mp_free_pair_node (mp, value_node (p));
23172 }
23173 break;
23174 case mp_color_type:
23175 if (value_node (p) != NULL) {
23176 mp_recycle_value (mp, red_part (value_node (p)));
23177 mp_recycle_value (mp, green_part (value_node (p)));
23178 mp_recycle_value (mp, blue_part (value_node (p)));
23179 mp_free_value_node (mp, red_part (value_node (p)));
23180 mp_free_value_node (mp, green_part (value_node (p)));
23181 mp_free_value_node (mp, blue_part (value_node (p)));
23182 mp_free_node (mp, value_node (p), color_node_size);
23183 }
23184 break;
23185 case mp_transform_type:
23186 if (value_node (p) != NULL) {
23187 mp_recycle_value (mp, tx_part (value_node (p)));
23188 mp_recycle_value (mp, ty_part (value_node (p)));
23189 mp_recycle_value (mp, xx_part (value_node (p)));
23190 mp_recycle_value (mp, xy_part (value_node (p)));
23191 mp_recycle_value (mp, yx_part (value_node (p)));
23192 mp_recycle_value (mp, yy_part (value_node (p)));
23193 mp_free_value_node (mp, tx_part (value_node (p)));
23194 mp_free_value_node (mp, ty_part (value_node (p)));
23195 mp_free_value_node (mp, xx_part (value_node (p)));
23196 mp_free_value_node (mp, xy_part (value_node (p)));
23197 mp_free_value_node (mp, yx_part (value_node (p)));
23198 mp_free_value_node (mp, yy_part (value_node (p)));
23199 mp_free_node (mp, value_node (p), transform_node_size);
23200 }
23201 break;
23202 case mp_dependent:
23203 case mp_proto_dependent:
23204 /* Recycle a dependency list */
23205 {
23206 mp_value_node qq = (mp_value_node) dep_list ((mp_value_node) p);
23207 while (dep_info (qq) != NULL)
23208 qq = (mp_value_node) mp_link (qq);
23209 set_mp_link (prev_dep ((mp_value_node) p), mp_link (qq));
23210 set_prev_dep (mp_link (qq), prev_dep ((mp_value_node) p));
23211 set_mp_link (qq, NULL);
23212 mp_flush_node_list (mp, (mp_node) dep_list ((mp_value_node) p));
23213 }
23214 break;
23215 case mp_independent:
23216 @<Recycle an independent variable@>;
23217 break;
23218 case mp_token_list:
23219 case mp_structured:
23220 mp_confusion (mp, "recycle");
23221 break;
23222 case mp_unsuffixed_macro:
23223 case mp_suffixed_macro:
23224 mp_delete_mac_ref (mp, value_node (p));
23225 break;
23226 default: /* there are no other valid cases, but please the compiler */
23227 break;
23228 }
23229 mp_type (p) = mp_undefined;
23230 }
23231
23232 @ When an independent variable disappears, it simply fades away, unless
23233 something depends on it. In the latter case, a dependent variable whose
23234 coefficient of dependence is maximal will take its place.
23235 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
23236 as part of his Ph.n->data. thesis (Stanford University, December 1982).
23237 @^Zabala Salelles, Ignacio Andr\'es@>
23238
23239 For example, suppose that variable $x$ is being recycled, and that the
23240 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
23241 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
23242 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
23243 we will print `\.{\#\#\# -2x=-y+a}'.
23244
23245 There's a slight complication, however: An independent variable $x$
23246 can occur both in dependency lists and in proto-dependency lists.
23247 This makes it necessary to be careful when deciding which coefficient
23248 is maximal.
23249
23250 Furthermore, this complication is not so slight when
23251 a proto-dependent variable is chosen to become independent. For example,
23252 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
23253 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
23254 large coefficient `50'.
23255
23256 In order to deal with these complications without wasting too much time,
23257 we shall link together the occurrences of~$x$ among all the linear
23258 dependencies, maintaining separate lists for the dependent and
23259 proto-dependent cases.
23260
23261 @<Recycle an independent variable@>=
23262 {
23263 mp_value_node q, r, s;
23264 mp_node pp; /* link manipulation register */
23265 mp_number v ; /* a value */
23266 mp_number test; /* a temporary value */
23267 new_number (test);
23268 new_number (v);
23269 if (t < mp_dependent)
23270 number_clone (v, value_number (p));
23271 set_number_to_zero(mp->max_c[mp_dependent]);
23272 set_number_to_zero(mp->max_c[mp_proto_dependent]);
23273 mp->max_link[mp_dependent] = NULL;
23274 mp->max_link[mp_proto_dependent] = NULL;
23275 q = (mp_value_node) mp_link (mp->dep_head);
23276 while (q != mp->dep_head) {
23277 s = (mp_value_node) mp->temp_head;
23278 set_mp_link (s, dep_list (q));
23279 while (1) {
23280 r = (mp_value_node) mp_link (s);
23281 if (dep_info (r) == NULL)
23282 break;
23283 if (dep_info (r) != p) {
23284 s = r;
23285 } else {
23286 t = mp_type (q);
23287 if (mp_link (s) == dep_list (q)) { /* reset the |dep_list| */
23288 set_dep_list (q, mp_link (r));
23289 }
23290 set_mp_link (s, mp_link (r));
23291 set_dep_info (r, (mp_node) q);
23292 number_clone (test, dep_value (r));
23293 number_abs (test);
23294 if (number_greater (test, mp->max_c[t])) {
23295 /* Record a new maximum coefficient of type |t| */
23296 if (number_positive(mp->max_c[t])) {
23297 set_mp_link (mp->max_ptr[t], (mp_node) mp->max_link[t]);
23298 mp->max_link[t] = mp->max_ptr[t];
23299 }
23300 number_clone (mp->max_c[t], test);
23301 mp->max_ptr[t] = r;
23302 } else {
23303 set_mp_link (r, (mp_node) mp->max_link[t]);
23304 mp->max_link[t] = r;
23305 }
23306 }
23307 }
23308 q = (mp_value_node) mp_link (r);
23309 }
23310 if (number_positive(mp->max_c[mp_dependent]) || number_positive(mp->max_c[mp_proto_dependent])) {
23311 /* Choose a dependent variable to take the place of the disappearing
23312 independent variable, and change all remaining dependencies
23313 accordingly */
23314 mp_number test, ret; /* temporary use */
23315 new_number (ret);
23316 new_number (test);
23317 number_clone (test, mp->max_c[mp_dependent]);
23318 number_divide_int (test, 4096);
23319 if (number_greaterequal(test, mp->max_c[mp_proto_dependent]))
23320 t = mp_dependent;
23321 else
23322 t = mp_proto_dependent;
23323
23324 /* Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
23325 and |dep_info(s)| points to the dependent variable~|pp| of type~|t| from
23326 whose dependency list we have removed node~|s|. We must reinsert
23327 node~|s| into the dependency list, with coefficient $-1.0$, and with
23328 |pp| as the new independent variable. Since |pp| will have a larger serial
23329 number than any other variable, we can put node |s| at the head of the
23330 list. */
23331 /* Determine the dependency list |s| to substitute for the independent
23332 variable~|p| */
23333
23334 s = mp->max_ptr[t];
23335 pp = (mp_node) dep_info (s);
23336 number_clone (v, dep_value (s));
23337 if (t == mp_dependent) {
23338 set_dep_value (s, fraction_one_t);
23339 } else {
23340 set_dep_value (s, unity_t);
23341 }
23342 number_negate(dep_value(s));
23343 r = (mp_value_node) dep_list ((mp_value_node) pp);
23344 set_mp_link (s, (mp_node) r);
23345 while (dep_info (r) != NULL)
23346 r = (mp_value_node) mp_link (r);
23347 q = (mp_value_node) mp_link (r);
23348 set_mp_link (r, NULL);
23349 set_prev_dep (q, prev_dep ((mp_value_node) pp));
23350 set_mp_link (prev_dep ((mp_value_node) pp), (mp_node) q);
23351 mp_new_indep (mp, pp);
23352 if (cur_exp_node () == pp && mp->cur_exp.type == t)
23353 mp->cur_exp.type = mp_independent;
23354 if (number_positive (internal_value (mp_tracing_equations))) {
23355 /* Show the transformed dependency */
23356 if (mp_interesting (mp, p)) {
23357 mp_begin_diagnostic (mp);
23358 mp_show_transformed_dependency(mp, v, t, p);
23359 mp_print_dependency (mp, s, t);
23360 mp_end_diagnostic (mp, false);
23361 }
23362 }
23363
23364 t = (quarterword) (mp_dependent + mp_proto_dependent - t); /* complement |t| */
23365 if (number_positive(mp->max_c[t])) {
23366 /* we need to pick up an unchosen dependency */
23367 set_mp_link (mp->max_ptr[t], (mp_node) mp->max_link[t]);
23368 mp->max_link[t] = mp->max_ptr[t];
23369 }
23370 /* Finally, there are dependent and proto-dependent variables whose
23371 dependency lists must be brought up to date. */
23372 if (t != mp_dependent) {
23373 /* Substitute new dependencies in place of |p| */
23374 for (t = mp_dependent; t <= mp_proto_dependent; t=t+1) {
23375 r = mp->max_link[t];
23376 while (r != NULL) {
23377 q = (mp_value_node) dep_info (r);
23378 number_clone (test, v);
23379 number_negate (test);
23380 make_fraction (ret, dep_value (r), test);
23381 set_dep_list (q, mp_p_plus_fq (mp, (mp_value_node) dep_list (q), ret, s, t, mp_dependent));
23382 if (dep_list (q) == (mp_node) mp->dep_final)
23383 mp_make_known (mp, q, mp->dep_final);
23384 q = r;
23385 r = (mp_value_node) mp_link (r);
23386 mp_free_dep_node (mp, q);
23387 }
23388 }
23389 } else {
23390 /* Substitute new proto-dependencies in place of |p| */
23391 for (t = mp_dependent; t <= mp_proto_dependent; t=t+1) {
23392 r = mp->max_link[t];
23393 while (r != NULL) {
23394 q = (mp_value_node) dep_info (r);
23395 if (t == mp_dependent) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
23396 if (cur_exp_node () == (mp_node) q && mp->cur_exp.type == mp_dependent)
23397 mp->cur_exp.type = mp_proto_dependent;
23398 set_dep_list (q, mp_p_over_v (mp, (mp_value_node) dep_list (q),
23399 unity_t, mp_dependent,
23400 mp_proto_dependent));
23401 mp_type (q) = mp_proto_dependent;
23402 fraction_to_round_scaled (dep_value (r));
23403 }
23404 number_clone (test, v);
23405 number_negate (test);
23406 make_scaled (ret, dep_value (r), test);
23407 set_dep_list (q, mp_p_plus_fq (mp, (mp_value_node) dep_list (q),
23408 ret, s,
23409 mp_proto_dependent,
23410 mp_proto_dependent));
23411 if (dep_list (q) == (mp_node) mp->dep_final)
23412 mp_make_known (mp, q, mp->dep_final);
23413 q = r;
23414 r = (mp_value_node) mp_link (r);
23415 mp_free_dep_node (mp, q);
23416 }
23417 }
23418 }
23419 mp_flush_node_list (mp, (mp_node) s);
23420 if (mp->fix_needed)
23421 mp_fix_dependencies (mp);
23422 check_arith();
23423 free_number (ret);
23424 }
23425 free_number (v);
23426 free_number(test);
23427 }
23428
23429 @ @<Declarations@>=
23430 static void mp_show_transformed_dependency(MP mp, mp_number v, mp_variable_type t, mp_node p);
23431
23432 @ @c
23433 static void mp_show_transformed_dependency(MP mp, mp_number v, mp_variable_type t, mp_node p)
23434 {
23435 mp_number vv; /* for temp use */
23436 new_number (vv);
23437 mp_print_nl (mp, "### ");
23438 if (number_positive(v))
23439 mp_print_char (mp, xord ('-'));
23440 if (t == mp_dependent) {
23441 number_clone (vv, mp->max_c[mp_dependent]);
23442 fraction_to_round_scaled (vv);
23443 } else {
23444 number_clone (vv, mp->max_c[mp_proto_dependent]);
23445 }
23446 if (!number_equal(vv, unity_t)) {
23447 print_number (vv);
23448 }
23449 mp_print_variable_name (mp, p);
23450 while (indep_scale (p) > 0) {
23451 mp_print (mp, "*4");
23452 set_indep_scale(p, indep_scale(p)-2);
23453 }
23454 if (t == mp_dependent)
23455 mp_print_char (mp, xord ('='));
23456 else
23457 mp_print (mp, " = ");
23458 free_number (vv);
23459 }
23460
23461
23462 @ The code for independency removal makes use of three non-symbolic arrays.
23463
23464 @<Glob...@>=
23465 mp_number max_c[mp_proto_dependent + 1]; /* max coefficient magnitude */
23466 mp_value_node max_ptr[mp_proto_dependent + 1]; /* where |p| occurs with |max_c| */
23467 mp_value_node max_link[mp_proto_dependent + 1]; /* other occurrences of |p| */
23468
23469
23470 @ @<Initialize table ... @>=
23471 {
23472 int i;
23473 for (i=0;i<mp_proto_dependent + 1;i++) {
23474 new_number (mp->max_c[i]);
23475 }
23476 }
23477
23478 @ @<Dealloc...@>=
23479 {
23480 int i;
23481 for (i=0;i<mp_proto_dependent + 1;i++) {
23482 free_number (mp->max_c[i]);
23483 }
23484 }
23485
23486 @ A global variable |var_flag| is set to a special command code
23487 just before \MP\ calls |scan_expression|, if the expression should be
23488 treated as a variable when this command code immediately follows. For
23489 example, |var_flag| is set to |assignment| at the beginning of a
23490 statement, because we want to know the {\sl location\/} of a variable at
23491 the left of `\.{:=}', not the {\sl value\/} of that variable.
23492
23493 The |scan_expression| subroutine calls |scan_tertiary|,
23494 which calls |scan_secondary|, which calls |scan_primary|, which sets
23495 |var_flag:=0|. In this way each of the scanning routines ``knows''
23496 when it has been called with a special |var_flag|, but |var_flag| is
23497 usually zero.
23498
23499 A variable preceding a command that equals |var_flag| is converted to a
23500 token list rather than a value. Furthermore, an `\.{=}' sign following an
23501 expression with |var_flag=assignment| is not considered to be a relation
23502 that produces boolean expressions.
23503
23504
23505 @<Glob...@>=
23506 int var_flag; /* command that wants a variable */
23507
23508 @ @<Set init...@>=
23509 mp->var_flag = 0;
23510
23511 @* Parsing primary expressions.
23512 The first parsing routine, |scan_primary|, is also the most complicated one,
23513 since it involves so many different cases. But each case---with one
23514 exception---is fairly simple by itself.
23515
23516 When |scan_primary| begins, the first token of the primary to be scanned
23517 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
23518 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
23519 earlier. If |cur_cmd| is not between |min_primary_command| and
23520 |max_primary_command|, inclusive, a syntax error will be signaled.
23521
23522 Later we'll come to procedures that perform actual operations like
23523 addition, square root, and so on; our purpose now is to do the parsing.
23524 But we might as well mention those future procedures now, so that the
23525 suspense won't be too bad:
23526
23527 \smallskip
23528 |do_nullary(c)| does primitive operations that have no operands (e.g.,
23529 `\&{true}' or `\&{pencircle}');
23530
23531 \smallskip
23532 |do_unary(c)| applies a primitive operation to the current expression;
23533
23534 \smallskip
23535 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
23536 and the current expression.
23537
23538 @<Declare the basic parsing subroutines@>=
23539 static void check_for_mediation (MP mp);
23540 void mp_scan_primary (MP mp) {
23541 mp_command_code my_var_flag; /* initial value of |my_var_flag| */
23542 my_var_flag = mp->var_flag;
23543 mp->var_flag = 0;
23544 RESTART:
23545 check_arith();
23546 /* Supply diagnostic information, if requested */
23547 if (mp->interrupt != 0) {
23548 if (mp->OK_to_interrupt) {
23549 mp_back_input (mp);
23550 check_interrupt;
23551 mp_get_x_next (mp);
23552 }
23553 }
23554 switch (cur_cmd()) {
23555 case mp_left_delimiter:
23556 {
23557 /* Scan a delimited primary */
23558 mp_node p, q, r; /* for list manipulation */
23559 mp_sym l_delim, r_delim; /* hash addresses of a delimiter pair */
23560 l_delim = cur_sym();
23561 r_delim = equiv_sym (cur_sym());
23562 mp_get_x_next (mp);
23563 mp_scan_expression (mp);
23564 if ((cur_cmd() == mp_comma) && (mp->cur_exp.type >= mp_known)) {
23565 /* Scan the rest of a delimited set of numerics */
23566 /* This code uses the fact that |red_part| and |green_part|
23567 are synonymous with |x_part| and |y_part|. */
23568 p = mp_stash_cur_exp (mp);
23569 mp_get_x_next (mp);
23570 mp_scan_expression (mp);
23571 /* Make sure the second part of a pair or color has a numeric type */
23572 if (mp->cur_exp.type < mp_known) {
23573 const char *hlp[] = {
23574 "I've started to scan a pair `(a,b)' or a color `(a,b,c)';",
23575 "but after finding a nice `a' I found a `b' that isn't",
23576 "of numeric type. So I've changed that part to zero.",
23577 "(The b that I didn't like appears above the error message.)",
23578 NULL };
23579 mp_value new_expr;
23580 memset(&new_expr,0,sizeof(mp_value));
23581 mp_disp_err(mp, NULL);
23582 new_number(new_expr.data.n);
23583 set_number_to_zero(new_expr.data.n);
23584 mp_back_error (mp,"Nonnumeric ypart has been replaced by 0", hlp, true);
23585 mp_get_x_next (mp);
23586 mp_flush_cur_exp (mp, new_expr);
23587 }
23588
23589 q = mp_get_value_node (mp);
23590 mp_name_type (q) = mp_capsule;
23591 if (cur_cmd() == mp_comma) {
23592 mp_init_color_node (mp, q);
23593 r = value_node (q);
23594 mp_stash_in (mp, y_part (r));
23595 mp_unstash_cur_exp (mp, p);
23596 mp_stash_in (mp, x_part (r));
23597 /* Scan the last of a triplet of numerics */
23598 mp_get_x_next (mp);
23599 mp_scan_expression (mp);
23600 if (mp->cur_exp.type < mp_known) {
23601 mp_value new_expr;
23602 const char *hlp[] = {
23603 "I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'",
23604 "isn't of numeric type. So I've changed that part to zero.",
23605 "(The c that I didn't like appears above the error message.)",
23606 NULL };
23607 memset(&new_expr,0,sizeof(mp_value));
23608 mp_disp_err(mp, NULL);
23609 new_number(new_expr.data.n);
23610 set_number_to_zero(new_expr.data.n);
23611 mp_back_error (mp,"Nonnumeric third part has been replaced by 0", hlp, true);
23612 mp_get_x_next (mp);
23613 mp_flush_cur_exp (mp, new_expr);
23614 }
23615 mp_stash_in (mp, blue_part (r));
23616
23617 if (cur_cmd() == mp_comma) {
23618 mp_node t; /* a token */
23619 mp_init_cmykcolor_node (mp, q);
23620 t = value_node (q);
23621 mp_type (cyan_part (t)) = mp_type (red_part (r));
23622 set_value_number (cyan_part (t), value_number (red_part (r)));
23623 mp_type (magenta_part (t)) = mp_type (green_part (r));
23624 set_value_number (magenta_part (t), value_number (green_part (r)));
23625 mp_type (yellow_part (t)) = mp_type (blue_part (r));
23626 set_value_number (yellow_part (t), value_number (blue_part (r)));
23627 /*see |mp_stash_in| */
23628 if ( ((mp_type (cyan_part (t))) != mp_independent) && ((mp_type (cyan_part (t))) != mp_known) ) {
23629 /* Copy the dep list */
23630 set_dep_list (cyan_part(t),dep_list ((mp_value_node) red_part(r)));
23631 set_prev_dep (cyan_part(t),prev_dep ((mp_value_node) red_part(r)));
23632 set_mp_link (prev_dep (cyan_part(t)), (mp_node) cyan_part(t));
23633 }
23634 if ( ((mp_type (magenta_part (t))) != mp_independent) && ((mp_type (magenta_part (t))) != mp_known) ) {
23635 /* Copy the dep list */
23636 set_dep_list (magenta_part(t),dep_list ((mp_value_node) green_part(r)));
23637 set_prev_dep (magenta_part(t),prev_dep ((mp_value_node) green_part(r)));
23638 set_mp_link (prev_dep (magenta_part(t)), (mp_node) magenta_part(t));
23639 }
23640 if ( ((mp_type (yellow_part (t))) != mp_independent) && ((mp_type (yellow_part (t))) != mp_known)) {
23641 /* Copy the dep list */
23642 set_dep_list (yellow_part(t),dep_list ((mp_value_node) blue_part(r)));
23643 set_prev_dep (yellow_part(t),prev_dep ((mp_value_node) blue_part(r)));
23644 set_mp_link (prev_dep (yellow_part(t)), (mp_node) yellow_part(t));
23645 }
23646 mp_recycle_value (mp, r);
23647 r = t;
23648 /* Scan the last of a quartet of numerics */
23649 mp_get_x_next (mp);
23650 mp_scan_expression (mp);
23651 if (mp->cur_exp.type < mp_known) {
23652 const char *hlp[] = {
23653 "I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't",
23654 "of numeric type. So I've changed that part to zero.",
23655 "(The k that I didn't like appears above the error message.)",
23656 NULL };
23657 mp_value new_expr;
23658 memset(&new_expr,0,sizeof(mp_value));
23659 new_number(new_expr.data.n);
23660 mp_disp_err(mp, NULL);
23661 set_number_to_zero(new_expr.data.n);
23662 mp_back_error (mp,"Nonnumeric blackpart has been replaced by 0", hlp, true);
23663 mp_get_x_next (mp);
23664 mp_flush_cur_exp (mp, new_expr);
23665 }
23666 mp_stash_in (mp, black_part (r));
23667 }
23668 } else {
23669 mp_init_pair_node (mp, q);
23670 r = value_node (q);
23671 mp_stash_in (mp, y_part (r));
23672 mp_unstash_cur_exp (mp, p);
23673 mp_stash_in (mp, x_part (r));
23674 }
23675 mp_check_delimiter (mp, l_delim, r_delim);
23676 mp->cur_exp.type = mp_type (q);
23677 set_cur_exp_node (q);
23678
23679 } else {
23680 mp_check_delimiter (mp, l_delim, r_delim);
23681 }
23682 }
23683 break;
23684 case mp_begin_group:
23685 /* Scan a grouped primary */
23686 /* The local variable |group_line| keeps track of the line
23687 where a \&{begingroup} command occurred; this will be useful
23688 in an error message if the group doesn't actually end. */
23689 {
23690 integer group_line; /* where a group began */
23691 group_line = mp_true_line (mp);
23692 if (number_positive (internal_value (mp_tracing_commands)))
23693 show_cur_cmd_mod;
23694 mp_save_boundary (mp);
23695 do {
23696 mp_do_statement (mp); /* ends with |cur_cmd>=semicolon| */
23697 } while (cur_cmd() == mp_semicolon);
23698 if (cur_cmd() != mp_end_group) {
23699 char msg[256];
23700 const char *hlp[] = {
23701 "I saw a `begingroup' back there that hasn't been matched",
23702 "by `endgroup'. So I've inserted `endgroup' now.",
23703 NULL };
23704 mp_snprintf(msg, 256, "A group begun on line %d never ended", (int)group_line);
23705 mp_back_error (mp, msg, hlp, true);
23706 set_cur_cmd((mp_variable_type)mp_end_group);
23707 }
23708 mp_unsave (mp);
23709 /* this might change |cur_type|, if independent variables are recycled */
23710 if (number_positive (internal_value (mp_tracing_commands)))
23711 show_cur_cmd_mod;
23712 }
23713 break;
23714 case mp_string_token:
23715 /* Scan a string constant */
23716 mp->cur_exp.type = mp_string_type;
23717 set_cur_exp_str (cur_mod_str());
23718 break;
23719 case mp_numeric_token:
23720 {
23721 /* Scan a primary that starts with a numeric token */
23722 /* A numeric token might be a primary by itself, or it might be the
23723 numerator of a fraction composed solely of numeric tokens, or it might
23724 multiply the primary that follows (provided that the primary doesn't begin
23725 with a plus sign or a minus sign). The code here uses the facts that
23726 |max_primary_command=plus_or_minus| and
23727 |max_primary_command-1=numeric_token|. If a fraction is found that is less
23728 than unity, we try to retain higher precision when we use it in scalar
23729 multiplication. */
23730 mp_number num, denom; /* for primaries that are fractions, like `1/2' */
23731 new_number (num);
23732 new_number (denom);
23733 set_cur_exp_value_number (cur_mod_number());
23734 mp->cur_exp.type = mp_known;
23735 mp_get_x_next (mp);
23736 if (cur_cmd() != mp_slash) {
23737 set_number_to_zero(num);
23738 set_number_to_zero(denom);
23739 } else {
23740 mp_get_x_next (mp);
23741 if (cur_cmd() != mp_numeric_token) {
23742 mp_back_input (mp);
23743 set_cur_cmd((mp_variable_type)mp_slash);
23744 set_cur_mod(mp_over);
23745 set_cur_sym(mp->frozen_slash);
23746 free_number (num);
23747 free_number (denom);
23748 goto DONE;
23749 }
23750 number_clone (num, cur_exp_value_number ());
23751 number_clone (denom, cur_mod_number());
23752 if (number_zero(denom)) {
23753 /* Protest division by zero */
23754 const char *hlp[] = { "I'll pretend that you meant to divide by 1.", NULL };
23755 mp_error (mp, "Division by zero", hlp, true);
23756 } else {
23757 mp_number ret;
23758 new_number (ret);
23759 make_scaled (ret, num, denom);
23760 set_cur_exp_value_number (ret);
23761 free_number (ret);
23762 }
23763 check_arith();
23764 mp_get_x_next (mp);
23765 }
23766 if (cur_cmd() >= mp_min_primary_command) {
23767 if (cur_cmd() < mp_numeric_token) { /* in particular, |cur_cmd<>plus_or_minus| */
23768 mp_node p; /* for list manipulation */
23769 mp_number absnum, absdenom;
23770 new_number (absnum);
23771 new_number (absdenom);
23772 p = mp_stash_cur_exp (mp);
23773 mp_scan_primary (mp);
23774 number_clone (absnum, num);
23775 number_abs (absnum);
23776 number_clone (absdenom, denom);
23777 number_abs (absdenom);
23778 if (number_greaterequal(absnum, absdenom) || (mp->cur_exp.type < mp_color_type)) {
23779 mp_do_binary (mp, p, mp_times);
23780 } else {
23781 mp_frac_mult (mp, num, denom);
23782 mp_free_value_node (mp, p);
23783 }
23784 free_number (absnum);
23785 free_number (absdenom);
23786 }
23787 }
23788 free_number (num);
23789 free_number (denom);
23790 goto DONE;
23791 }
23792 break;
23793 case mp_nullary:
23794 /* Scan a nullary operation */
23795 mp_do_nullary (mp, (quarterword) cur_mod());
23796 break;
23797 case mp_unary:
23798 case mp_type_name:
23799 case mp_cycle:
23800 case mp_plus_or_minus:
23801 {
23802 /* Scan a unary operation */
23803 quarterword c; /* a primitive operation code */
23804 c = (quarterword) cur_mod();
23805 mp_get_x_next (mp);
23806 mp_scan_primary (mp);
23807 mp_do_unary (mp, c);
23808 goto DONE;
23809 }
23810 break;
23811 case mp_primary_binary:
23812 {
23813 /* Scan a binary operation with `\&{of}' between its operands */
23814 mp_node p; /* for list manipulation */
23815 quarterword c; /* a primitive operation code */
23816 c = (quarterword) cur_mod();
23817 mp_get_x_next (mp);
23818 mp_scan_expression (mp);
23819 if (cur_cmd() != mp_of_token) {
23820 char msg[256];
23821 mp_string sname;
23822 const char *hlp[] = {
23823 "I've got the first argument; will look now for the other.",
23824 NULL };
23825 int old_setting = mp->selector;
23826 mp->selector = new_string;
23827 mp_print_cmd_mod (mp, mp_primary_binary, c);
23828 mp->selector = old_setting;
23829 sname = mp_make_string(mp);
23830 mp_snprintf (msg, 256, "Missing `of' has been inserted for %s", mp_str(mp, sname));
23831 delete_str_ref(sname);
23832 mp_back_error (mp, msg, hlp, true);
23833 }
23834 p = mp_stash_cur_exp (mp);
23835 mp_get_x_next (mp);
23836 mp_scan_primary (mp);
23837 mp_do_binary (mp, p, c);
23838 goto DONE;
23839 }
23840 break;
23841 case mp_str_op:
23842 /* Convert a suffix to a string */
23843 mp_get_x_next (mp);
23844 mp_scan_suffix (mp);
23845 mp->old_setting = mp->selector;
23846 mp->selector = new_string;
23847 mp_show_token_list (mp, cur_exp_node (), NULL, 100000, 0);
23848 mp_flush_token_list (mp, cur_exp_node ());
23849 set_cur_exp_str (mp_make_string (mp));
23850 mp->selector = mp->old_setting;
23851 mp->cur_exp.type = mp_string_type;
23852 goto DONE;
23853 break;
23854 case mp_void_op:
23855 {
23856 /* Convert a suffix to a boolean */
23857 mp_value new_expr;
23858 memset(&new_expr,0,sizeof(mp_value));
23859 new_number(new_expr.data.n);
23860 mp_get_x_next (mp);
23861 mp_scan_suffix (mp);
23862 if (cur_exp_node() == NULL) {
23863 set_number_from_boolean (new_expr.data.n, mp_true_code);
23864 } else {
23865 set_number_from_boolean (new_expr.data.n, mp_false_code);
23866 }
23867 mp_flush_cur_exp (mp, new_expr);
23868 cur_exp_node() = NULL; /* !! do not replace with |set_cur_exp_node()| !! */
23869 mp->cur_exp.type = mp_boolean_type;
23870 goto DONE;
23871 }
23872 break;
23873 case mp_internal_quantity:
23874 /* Scan an internal numeric quantity */
23875 /* If an internal quantity appears all by itself on the left of an
23876 assignment, we return a token list of length one, containing the address
23877 of the internal quantity, with |name_type| equal to |mp_internal_sym|.
23878 (This accords with the conventions of the save stack, as described earlier.) */
23879 {
23880 halfword qq = cur_mod();
23881 if (my_var_flag == mp_assignment) {
23882 mp_get_x_next (mp);
23883 if (cur_cmd() == mp_assignment) {
23884 set_cur_exp_node (mp_get_symbolic_node (mp));
23885 set_mp_sym_info (cur_exp_node (), qq);
23886 mp_name_type (cur_exp_node ()) = mp_internal_sym;
23887 mp->cur_exp.type = mp_token_list;
23888 goto DONE;
23889 }
23890 mp_back_input (mp);
23891 }
23892 if (internal_type (qq) == mp_string_type) {
23893 set_cur_exp_str (internal_string (qq));
23894 } else {
23895 set_cur_exp_value_number (internal_value (qq));
23896 }
23897 mp->cur_exp.type = internal_type (qq);
23898 }
23899 break;
23900 case mp_capsule_token:
23901 mp_make_exp_copy (mp, cur_mod_node());
23902 break;
23903 case mp_tag_token:
23904 @<Scan a variable primary; |goto restart| if it turns out to be a macro@>;
23905 break;
23906 default:
23907 mp_bad_exp (mp, "A primary");
23908 goto RESTART;
23909 break;
23910 }
23911 mp_get_x_next (mp); /* the routines |goto done| if they don't want this */
23912 DONE:
23913 check_for_mediation (mp);
23914 }
23915
23916 @ Expressions of the form `\.{a[b,c]}' are converted into
23917 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
23918 provided that \.a is numeric.
23919
23920 @<Declare the basic parsing subroutines@>=
23921 static void check_for_mediation (MP mp) {
23922 mp_node p, q, r; /* for list manipulation */
23923 if (cur_cmd() == mp_left_bracket) {
23924 if (mp->cur_exp.type >= mp_known) {
23925 /* Scan a mediation construction */
23926 p = mp_stash_cur_exp (mp);
23927 mp_get_x_next (mp);
23928 mp_scan_expression (mp);
23929 if (cur_cmd() != mp_comma) {
23930 /* Put the left bracket and the expression back to be rescanned */
23931 /* The left bracket that we thought was introducing a subscript might have
23932 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
23933 So we don't issue an error message at this point; but we do want to back up
23934 so as to avoid any embarrassment about our incorrect assumption. */
23935 mp_back_input (mp); /* that was the token following the current expression */
23936 mp_back_expr (mp);
23937 set_cur_cmd((mp_variable_type)mp_left_bracket);
23938 set_cur_mod_number(zero_t);
23939 set_cur_sym(mp->frozen_left_bracket);
23940 mp_unstash_cur_exp (mp, p);
23941 } else {
23942 q = mp_stash_cur_exp (mp);
23943 mp_get_x_next (mp);
23944 mp_scan_expression (mp);
23945 if (cur_cmd() != mp_right_bracket) {
23946 const char *hlp[] = {
23947 "I've scanned an expression of the form `a[b,c',",
23948 "so a right bracket should have come next.",
23949 "I shall pretend that one was there.",
23950 NULL };
23951 mp_back_error (mp, "Missing `]' has been inserted", hlp, true);
23952 }
23953 r = mp_stash_cur_exp (mp);
23954 mp_make_exp_copy (mp, q);
23955 mp_do_binary (mp, r, mp_minus);
23956 mp_do_binary (mp, p, mp_times);
23957 mp_do_binary (mp, q, mp_plus);
23958 mp_get_x_next (mp);
23959 }
23960 }
23961 }
23962 }
23963
23964
23965 @ Errors at the beginning of expressions are flagged by |bad_exp|.
23966
23967 @c
23968 static void mp_bad_exp (MP mp, const char *s) {
23969 char msg[256];
23970 int save_flag;
23971 const char *hlp[] = {
23972 "I'm afraid I need some sort of value in order to continue,",
23973 "so I've tentatively inserted `0'. You may want to",
23974 "delete this zero and insert something else;",
23975 "see Chapter 27 of The METAFONTbook for an example.",
23976 NULL };
23977 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
23978 {
23979 mp_string cm;
23980 int old_selector = mp->selector;
23981 mp->selector = new_string;
23982 mp_print_cmd_mod (mp, cur_cmd(), cur_mod());
23983 mp->selector = old_selector;
23984 cm = mp_make_string(mp);
23985 mp_snprintf(msg, 256, "%s expression can't begin with `%s'", s, mp_str(mp, cm));
23986 delete_str_ref(cm);
23987 }
23988 mp_back_input (mp);
23989 set_cur_sym(NULL);
23990 set_cur_cmd((mp_variable_type)mp_numeric_token);
23991 set_cur_mod_number (zero_t);
23992 mp_ins_error (mp, msg, hlp, true);
23993 save_flag = mp->var_flag;
23994 mp->var_flag = 0;
23995 mp_get_x_next (mp);
23996 mp->var_flag = save_flag;
23997 }
23998
23999
24000 @ The |stash_in| subroutine puts the current (numeric) expression into a field
24001 within a ``big node.''
24002
24003 @c
24004 static void mp_stash_in (MP mp, mp_node p) {
24005 mp_value_node q; /* temporary register */
24006 mp_type (p) = mp->cur_exp.type;
24007 if (mp->cur_exp.type == mp_known) {
24008 set_value_number (p, cur_exp_value_number ());
24009 } else {
24010 if (mp->cur_exp.type == mp_independent) {
24011 /* Stash an independent |cur_exp| into a big node */
24012 /* In rare cases the current expression can become |independent|. There
24013 may be many dependency lists pointing to such an independent capsule,
24014 so we can't simply move it into place within a big node. Instead,
24015 we copy it, then recycle it. */
24016 q = mp_single_dependency (mp, cur_exp_node ());
24017 if (q == mp->dep_final) {
24018 mp_type (p) = mp_known;
24019 set_value_number (p, zero_t);
24020 mp_free_dep_node (mp, q);
24021 } else {
24022 mp_new_dep (mp, p, mp_dependent, q);
24023 }
24024 mp_recycle_value (mp, cur_exp_node ());
24025 mp_free_value_node (mp, cur_exp_node ());
24026 } else {
24027 set_dep_list ((mp_value_node) p,
24028 dep_list ((mp_value_node) cur_exp_node ()));
24029 set_prev_dep ((mp_value_node) p,
24030 prev_dep ((mp_value_node) cur_exp_node ()));
24031 set_mp_link (prev_dep ((mp_value_node) p), p);
24032 mp_free_dep_node (mp, (mp_value_node) cur_exp_node ());
24033 }
24034 }
24035 mp->cur_exp.type = mp_vacuous;
24036 }
24037
24038 @ The most difficult part of |scan_primary| has been saved for last, since
24039 it was necessary to build up some confidence first. We can now face the task
24040 of scanning a variable.
24041
24042 As we scan a variable, we build a token list containing the relevant
24043 names and subscript values, simultaneously following along in the
24044 ``collective'' structure to see if we are actually dealing with a macro
24045 instead of a value.
24046
24047 The local variables |pre_head| and |post_head| will point to the beginning
24048 of the prefix and suffix lists; |tail| will point to the end of the list
24049 that is currently growing.
24050
24051 Another local variable, |tt|, contains partial information about the
24052 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
24053 relation |tt=mp_type(q)| will always hold. If |tt=undefined|, the routine
24054 doesn't bother to update its information about type. And if
24055 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
24056
24057 @<Scan a variable primary...@>=
24058 {
24059 mp_node p, q; /* for list manipulation */
24060 mp_node t; /* a token */
24061 mp_node pre_head, post_head, tail; /* prefix and suffix list variables */
24062 quarterword tt; /* approximation to the type of the variable-so-far */
24063 mp_node macro_ref = 0; /* reference count for a suffixed macro */
24064 pre_head = mp_get_symbolic_node (mp);
24065 tail = pre_head;
24066 post_head = NULL;
24067 tt = mp_vacuous;
24068 while (1) {
24069 t = mp_cur_tok (mp);
24070 mp_link (tail) = t;
24071 if (tt != mp_undefined) {
24072 /* Find the approximate type |tt| and corresponding~|q| */
24073 /* Every time we call |get_x_next|, there's a chance that the variable we've
24074 been looking at will disappear. Thus, we cannot safely keep |q| pointing
24075 into the variable structure; we need to start searching from the root each
24076 time. */
24077 mp_sym qq;
24078 p = mp_link (pre_head);
24079 qq = mp_sym_sym (p);
24080 tt = mp_undefined;
24081 if (eq_type (qq) % mp_outer_tag == mp_tag_token) {
24082 q = equiv_node (qq);
24083 if (q == NULL)
24084 goto DONE2;
24085 while (1) {
24086 p = mp_link (p);
24087 if (p == NULL) {
24088 tt = mp_type (q);
24089 goto DONE2;
24090 }
24091 if (mp_type (q) != mp_structured)
24092 goto DONE2;
24093 q = mp_link (attr_head (q)); /* the |collective_subscript| attribute */
24094 if (mp_type (p) == mp_symbol_node) { /* it's not a subscript */
24095 do {
24096 q = mp_link (q);
24097 } while (!(hashloc (q) >= mp_sym_sym (p)));
24098 if (hashloc (q) > mp_sym_sym (p))
24099 goto DONE2;
24100 }
24101 }
24102 }
24103 DONE2:
24104
24105 if (tt >= mp_unsuffixed_macro) {
24106 /* Either begin an unsuffixed macro call or
24107 prepare for a suffixed one */
24108 mp_link (tail) = NULL;
24109 if (tt > mp_unsuffixed_macro) { /* |tt=mp_suffixed_macro| */
24110 post_head = mp_get_symbolic_node (mp);
24111 tail = post_head;
24112 mp_link (tail) = t;
24113 tt = mp_undefined;
24114 macro_ref = value_node (q);
24115 add_mac_ref (macro_ref);
24116 } else {
24117 /* Set up unsuffixed macro call and |goto restart| */
24118 /* The only complication associated with macro calling is that the prefix
24119 and ``at'' parameters must be packaged in an appropriate list of lists. */
24120 p = mp_get_symbolic_node (mp);
24121 set_mp_sym_sym (pre_head, mp_link (pre_head));
24122 mp_link (pre_head) = p;
24123 set_mp_sym_sym (p, t);
24124 mp_macro_call (mp, value_node (q), pre_head, NULL);
24125 mp_get_x_next (mp);
24126 goto RESTART;
24127 }
24128 }
24129 }
24130 mp_get_x_next (mp);
24131 tail = t;
24132 if (cur_cmd() == mp_left_bracket) {
24133 /* Scan for a subscript; replace |cur_cmd| by |numeric_token| if found */
24134 mp_get_x_next (mp);
24135 mp_scan_expression (mp);
24136 if (cur_cmd() != mp_right_bracket) {
24137 /* Put the left bracket and the expression back to be rescanned */
24138 /* The left bracket that we thought was introducing a subscript might have
24139 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
24140 So we don't issue an error message at this point; but we do want to back up
24141 so as to avoid any embarrassment about our incorrect assumption. */
24142 mp_back_input (mp); /* that was the token following the current expression */
24143 mp_back_expr (mp);
24144 set_cur_cmd((mp_variable_type)mp_left_bracket);
24145 set_cur_mod_number(zero_t);
24146 set_cur_sym(mp->frozen_left_bracket);
24147
24148 } else {
24149 if (mp->cur_exp.type != mp_known)
24150 mp_bad_subscript (mp);
24151 set_cur_cmd((mp_variable_type)mp_numeric_token);
24152 set_cur_mod_number(cur_exp_value_number ());
24153 set_cur_sym(NULL);
24154 }
24155 }
24156 if (cur_cmd() > mp_max_suffix_token)
24157 break;
24158 if (cur_cmd() < mp_min_suffix_token)
24159 break;
24160 } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
24161 /* Handle unusual cases that masquerade as variables, and |goto restart| or
24162 |goto done| if appropriate; otherwise make a copy of the variable and |goto done| */
24163 /* If the variable does exist, we also need to check
24164 for a few other special cases before deciding that a plain old ordinary
24165 variable has, indeed, been scanned. */
24166 if (post_head != NULL) {
24167 /* Set up suffixed macro call and |goto restart| */
24168 /* If the ``variable'' that turned out to be a suffixed macro no longer exists,
24169 we don't care, because we have reserved a pointer (|macro_ref|) to its
24170 token list. */
24171 mp_back_input (mp);
24172 p = mp_get_symbolic_node (mp);
24173 q = mp_link (post_head);
24174 set_mp_sym_sym (pre_head, mp_link (pre_head));
24175 mp_link (pre_head) = post_head;
24176 set_mp_sym_sym (post_head, q);
24177 mp_link (post_head) = p;
24178 set_mp_sym_sym (p, mp_link (q));
24179 mp_link (q) = NULL;
24180 mp_macro_call (mp, macro_ref, pre_head, NULL);
24181 decr_mac_ref (macro_ref);
24182 mp_get_x_next (mp);
24183 goto RESTART;
24184 }
24185 q = mp_link (pre_head);
24186 mp_free_symbolic_node (mp, pre_head);
24187 if (cur_cmd() == my_var_flag) {
24188 mp->cur_exp.type = mp_token_list;
24189 set_cur_exp_node (q);
24190 goto DONE;
24191 }
24192 p = mp_find_variable (mp, q);
24193 if (p != NULL) {
24194 mp_make_exp_copy (mp, p);
24195 } else {
24196 mp_value new_expr;
24197 const char *hlp[] = {
24198 "While I was evaluating the suffix of this variable,",
24199 "something was redefined, and it's no longer a variable!",
24200 "In order to get back on my feet, I've inserted `0' instead.",
24201 NULL };
24202 char *msg = mp_obliterated (mp, q);
24203 memset(&new_expr,0,sizeof(mp_value));
24204 new_number(new_expr.data.n);
24205 set_number_to_zero(new_expr.data.n);
24206 mp_back_error (mp, msg, hlp, true);
24207 free(msg);
24208 mp_get_x_next (mp);
24209 mp_flush_cur_exp (mp, new_expr);
24210 }
24211 mp_flush_node_list (mp, q);
24212 goto DONE;
24213 }
24214
24215
24216 @ Here's a routine that puts the current expression back to be read again.
24217
24218 @c
24219 static void mp_back_expr (MP mp) {
24220 mp_node p; /* capsule token */
24221 p = mp_stash_cur_exp (mp);
24222 mp_link (p) = NULL;
24223 back_list (p);
24224 }
24225
24226
24227 @ Unknown subscripts lead to the following error message.
24228
24229 @c
24230 static void mp_bad_subscript (MP mp) {
24231 mp_value new_expr;
24232 const char *hlp[] = {
24233 "A bracketed subscript must have a known numeric value;",
24234 "unfortunately, what I found was the value that appears just",
24235 "above this error message. So I'll try a zero subscript.",
24236 NULL };
24237 memset(&new_expr,0,sizeof(mp_value));
24238 new_number(new_expr.data.n);
24239 mp_disp_err(mp, NULL);
24240 mp_error (mp, "Improper subscript has been replaced by zero", hlp, true);
24241 @.Improper subscript...@>
24242 mp_flush_cur_exp (mp, new_expr);
24243 }
24244
24245
24246 @ How do things stand now? Well, we have scanned an entire variable name,
24247 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
24248 |cur_sym| represent the token that follows. If |post_head=NULL|, a
24249 token list for this variable name starts at |mp_link(pre_head)|, with all
24250 subscripts evaluated. But if |post_head<>NULL|, the variable turned out
24251 to be a suffixed macro; |pre_head| is the head of the prefix list, while
24252 |post_head| is the head of a token list containing both `\.{\AT!}' and
24253 the suffix.
24254
24255 Our immediate problem is to see if this variable still exists. (Variable
24256 structures can change drastically whenever we call |get_x_next|; users
24257 aren't supposed to do this, but the fact that it is possible means that
24258 we must be cautious.)
24259
24260 The following procedure creates an error message for when a variable
24261 unexpectedly disappears.
24262
24263 @c
24264 static char *mp_obliterated (MP mp, mp_node q) {
24265 char msg[256];
24266 mp_string sname;
24267 int old_setting = mp->selector;
24268 mp->selector = new_string;
24269 mp_show_token_list (mp, q, NULL, 1000, 0);
24270 sname = mp_make_string(mp);
24271 mp->selector = old_setting;
24272 mp_snprintf(msg, 256, "Variable %s has been obliterated", mp_str(mp, sname));
24273 @.Variable...obliterated@>
24274 delete_str_ref(sname);
24275 return xstrdup(msg);
24276 }
24277
24278
24279 @ Our remaining job is simply to make a copy of the value that has been
24280 found. Some cases are harder than others, but complexity arises solely
24281 because of the multiplicity of possible cases.
24282
24283 @<Declare the procedure called |make_exp_copy|@>=
24284 @<Declare subroutines needed by |make_exp_copy|@>
24285 static void mp_make_exp_copy (MP mp, mp_node p) {
24286 mp_node t; /* register(s) for list manipulation */
24287 mp_value_node q;
24288 RESTART:
24289 mp->cur_exp.type = mp_type (p);
24290 switch (mp->cur_exp.type) {
24291 case mp_vacuous:
24292 case mp_boolean_type:
24293 case mp_known:
24294 set_cur_exp_value_number (value_number (p));
24295 break;
24296 case unknown_types:
24297 t = mp_new_ring_entry (mp, p);
24298 set_cur_exp_node (t);
24299 break;
24300 case mp_string_type:
24301 set_cur_exp_str (value_str (p));
24302 break;
24303 case mp_picture_type:
24304 set_cur_exp_node (value_node (p));
24305 add_edge_ref (cur_exp_node ());
24306 break;
24307 case mp_pen_type:
24308 set_cur_exp_knot (copy_pen (value_knot (p)));
24309 break;
24310 case mp_path_type:
24311 set_cur_exp_knot (mp_copy_path (mp, value_knot (p)));
24312 break;
24313 case mp_transform_type:
24314 case mp_color_type:
24315 case mp_cmykcolor_type:
24316 case mp_pair_type:
24317 /* Copy the big node |p| */
24318 /* The most tedious case arises when the user refers to a
24319 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
24320 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
24321 or |known|. */
24322 if (value_node (p) == NULL) {
24323 switch (mp_type (p)) {
24324 case mp_pair_type:
24325 mp_init_pair_node (mp, p);
24326 break;
24327 case mp_color_type:
24328 mp_init_color_node (mp, p);
24329 break;
24330 case mp_cmykcolor_type:
24331 mp_init_cmykcolor_node (mp, p);
24332 break;
24333 case mp_transform_type:
24334 mp_init_transform_node (mp, p);
24335 break;
24336 default: /* there are no other valid cases, but please the compiler */
24337 break;
24338 }
24339 }
24340 t = mp_get_value_node (mp);
24341 mp_name_type (t) = mp_capsule;
24342 q = (mp_value_node)value_node (p);
24343 switch (mp->cur_exp.type) {
24344 case mp_pair_type:
24345 mp_init_pair_node (mp, t);
24346 mp_install (mp, y_part (value_node (t)), y_part (q));
24347 mp_install (mp, x_part (value_node (t)), x_part (q));
24348 break;
24349 case mp_color_type:
24350 mp_init_color_node (mp, t);
24351 mp_install (mp, blue_part (value_node (t)), blue_part (q));
24352 mp_install (mp, green_part (value_node (t)), green_part (q));
24353 mp_install (mp, red_part (value_node (t)), red_part (q));
24354 break;
24355 case mp_cmykcolor_type:
24356 mp_init_cmykcolor_node (mp, t);
24357 mp_install (mp, black_part (value_node (t)), black_part (q));
24358 mp_install (mp, yellow_part (value_node (t)), yellow_part (q));
24359 mp_install (mp, magenta_part (value_node (t)), magenta_part (q));
24360 mp_install (mp, cyan_part (value_node (t)), cyan_part (q));
24361 break;
24362 case mp_transform_type:
24363 mp_init_transform_node (mp, t);
24364 mp_install (mp, yy_part (value_node (t)), yy_part (q));
24365 mp_install (mp, yx_part (value_node (t)), yx_part (q));
24366 mp_install (mp, xy_part (value_node (t)), xy_part (q));
24367 mp_install (mp, xx_part (value_node (t)), xx_part (q));
24368 mp_install (mp, ty_part (value_node (t)), ty_part (q));
24369 mp_install (mp, tx_part (value_node (t)), tx_part (q));
24370 break;
24371 default: /* there are no other valid cases, but please the compiler */
24372 break;
24373 }
24374 set_cur_exp_node (t);
24375 break;
24376 case mp_dependent:
24377 case mp_proto_dependent:
24378 mp_encapsulate (mp,
24379 mp_copy_dep_list (mp,
24380 (mp_value_node) dep_list ((mp_value_node)
24381 p)));
24382 break;
24383 case mp_numeric_type:
24384 mp_new_indep (mp, p);
24385 goto RESTART;
24386 break;
24387 case mp_independent:
24388 q = mp_single_dependency (mp, p);
24389 if (q == mp->dep_final) {
24390 mp->cur_exp.type = mp_known;
24391 set_cur_exp_value_number (zero_t);
24392 mp_free_dep_node (mp, q);
24393 } else {
24394 mp->cur_exp.type = mp_dependent;
24395 mp_encapsulate (mp, q);
24396 }
24397 break;
24398 default:
24399 mp_confusion (mp, "copy");
24400 @:this can't happen copy}{\quad copy@>
24401 break;
24402 }
24403 }
24404
24405
24406 @ The |encapsulate| subroutine assumes that |dep_final| is the
24407 tail of dependency list~|p|.
24408
24409 @<Declare subroutines needed by |make_exp_copy|@>=
24410 static void mp_encapsulate (MP mp, mp_value_node p) {
24411 mp_node q = mp_get_value_node (mp);
24412 FUNCTION_TRACE2 ("mp_encapsulate(%p)\n", p);
24413 mp_name_type (q) = mp_capsule;
24414 mp_new_dep (mp, q, mp->cur_exp.type, p);
24415 set_cur_exp_node (q);
24416 }
24417
24418 @ The |install| procedure copies a numeric field~|q| into field~|r| of
24419 a big node that will be part of a capsule.
24420
24421 @<Declare subroutines needed by |make_exp_copy|@>=
24422 static void mp_install (MP mp, mp_node r, mp_node q) {
24423 mp_value_node p; /* temporary register */
24424 if (mp_type (q) == mp_known) {
24425 mp_type (r) = mp_known;
24426 set_value_number (r, value_number (q));
24427 } else if (mp_type (q) == mp_independent) {
24428 p = mp_single_dependency (mp, q);
24429 if (p == mp->dep_final) {
24430 mp_type (r) = mp_known;
24431 set_value_number (r, zero_t);
24432 mp_free_dep_node (mp, p);
24433 } else {
24434 mp_new_dep (mp, r, mp_dependent, p);
24435 }
24436 } else {
24437 mp_new_dep (mp, r, mp_type (q),
24438 mp_copy_dep_list (mp, (mp_value_node) dep_list ((mp_value_node)
24439 q)));
24440 }
24441 }
24442
24443
24444 @ Here is a comparatively simple routine that is used to scan the
24445 \&{suffix} parameters of a macro.
24446
24447 @<Declare the basic parsing subroutines@>=
24448 static void mp_scan_suffix (MP mp) {
24449 mp_node h, t; /* head and tail of the list being built */
24450 mp_node p; /* temporary register */
24451 h = mp_get_symbolic_node (mp);
24452 t = h;
24453 while (1) {
24454 if (cur_cmd() == mp_left_bracket) {
24455 /* Scan a bracketed subscript and set |cur_cmd:=numeric_token| */
24456 mp_get_x_next (mp);
24457 mp_scan_expression (mp);
24458 if (mp->cur_exp.type != mp_known)
24459 mp_bad_subscript (mp);
24460 if (cur_cmd() != mp_right_bracket) {
24461 const char *hlp[] = {
24462 "I've seen a `[' and a subscript value, in a suffix,",
24463 "so a right bracket should have come next.",
24464 "I shall pretend that one was there.",
24465 NULL };
24466 mp_back_error (mp, "Missing `]' has been inserted", hlp, true);
24467 }
24468 set_cur_cmd((mp_variable_type)mp_numeric_token);
24469 set_cur_mod_number(cur_exp_value_number ());
24470
24471 }
24472 if (cur_cmd() == mp_numeric_token) {
24473 mp_number arg1;
24474 new_number (arg1);
24475 number_clone (arg1, cur_mod_number());
24476 p = mp_new_num_tok (mp, arg1);
24477 free_number (arg1);
24478 } else if ((cur_cmd() == mp_tag_token) || (cur_cmd() == mp_internal_quantity)) {
24479 p = mp_get_symbolic_node (mp);
24480 set_mp_sym_sym (p, cur_sym());
24481 mp_name_type (p) = cur_sym_mod();
24482 } else {
24483 break;
24484 }
24485 mp_link (t) = p;
24486 t = p;
24487 mp_get_x_next (mp);
24488 }
24489 set_cur_exp_node (mp_link (h));
24490 mp_free_symbolic_node (mp, h);
24491 mp->cur_exp.type = mp_token_list;
24492 }
24493
24494 @* Parsing secondary and higher expressions.
24495
24496 After the intricacies of |scan_primary|\kern-1pt,
24497 the |scan_secondary| routine is
24498 refreshingly simple. It's not trivial, but the operations are relatively
24499 straightforward; the main difficulty is, again, that expressions and data
24500 structures might change drastically every time we call |get_x_next|, so a
24501 cautious approach is mandatory. For example, a macro defined by
24502 \&{primarydef} might have disappeared by the time its second argument has
24503 been scanned; we solve this by increasing the reference count of its token
24504 list, so that the macro can be called even after it has been clobbered.
24505
24506 @<Declare the basic parsing subroutines@>=
24507 static void mp_scan_secondary (MP mp) {
24508 mp_node p; /* for list manipulation */
24509 halfword c, d; /* operation codes or modifiers */
24510 mp_node cc = NULL;
24511 mp_sym mac_name = NULL; /* token defined with \&{primarydef} */
24512 RESTART:
24513 if ((cur_cmd() < mp_min_primary_command) ||
24514 (cur_cmd() > mp_max_primary_command))
24515 mp_bad_exp (mp, "A secondary");
24516 @.A secondary expression...@>
24517 mp_scan_primary (mp);
24518 CONTINUE:
24519 if (cur_cmd() <= mp_max_secondary_command &&
24520 cur_cmd() >= mp_min_secondary_command) {
24521 p = mp_stash_cur_exp (mp);
24522 d = cur_cmd();
24523 c = cur_mod();
24524 if (d == mp_secondary_primary_macro) {
24525 cc = cur_mod_node();
24526 mac_name = cur_sym();
24527 add_mac_ref (cc);
24528 }
24529 mp_get_x_next (mp);
24530 mp_scan_primary (mp);
24531 if (d != mp_secondary_primary_macro) {
24532 mp_do_binary (mp, p, c);
24533 } else {
24534 mp_back_input (mp);
24535 mp_binary_mac (mp, p, cc, mac_name);
24536 decr_mac_ref (cc);
24537 mp_get_x_next (mp);
24538 goto RESTART;
24539 }
24540 goto CONTINUE;
24541 }
24542 }
24543
24544
24545 @ The following procedure calls a macro that has two parameters,
24546 |p| and |cur_exp|.
24547
24548 @c
24549 static void mp_binary_mac (MP mp, mp_node p, mp_node c, mp_sym n) {
24550 mp_node q, r; /* nodes in the parameter list */
24551 q = mp_get_symbolic_node (mp);
24552 r = mp_get_symbolic_node (mp);
24553 mp_link (q) = r;
24554 set_mp_sym_sym (q, p);
24555 set_mp_sym_sym (r, mp_stash_cur_exp (mp));
24556 mp_macro_call (mp, c, q, n);
24557 }
24558
24559
24560 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
24561
24562 @<Declare the basic parsing subroutines@>=
24563 static void mp_scan_tertiary (MP mp) {
24564 mp_node p; /* for list manipulation */
24565 halfword c, d; /* operation codes or modifiers */
24566 mp_node cc = NULL;
24567 mp_sym mac_name = NULL; /* token defined with \&{secondarydef} */
24568 RESTART:
24569 if ((cur_cmd() < mp_min_primary_command) ||
24570 (cur_cmd() > mp_max_primary_command))
24571 mp_bad_exp (mp, "A tertiary");
24572 @.A tertiary expression...@>
24573 mp_scan_secondary (mp);
24574 CONTINUE:
24575 if (cur_cmd() <= mp_max_tertiary_command) {
24576 if (cur_cmd() >= mp_min_tertiary_command) {
24577 p = mp_stash_cur_exp (mp);
24578 c = cur_mod();
24579 d = cur_cmd();
24580 if (d == mp_tertiary_secondary_macro) {
24581 cc = cur_mod_node();
24582 mac_name = cur_sym();
24583 add_mac_ref (cc);
24584 }
24585 mp_get_x_next (mp);
24586 mp_scan_secondary (mp);
24587 if (d != mp_tertiary_secondary_macro) {
24588 mp_do_binary (mp, p, c);
24589 } else {
24590 mp_back_input (mp);
24591 mp_binary_mac (mp, p, cc, mac_name);
24592 decr_mac_ref (cc);
24593 mp_get_x_next (mp);
24594 goto RESTART;
24595 }
24596 goto CONTINUE;
24597 }
24598 }
24599 }
24600
24601
24602 @ Finally we reach the deepest level in our quartet of parsing routines.
24603 This one is much like the others; but it has an extra complication from
24604 paths, which materialize here.
24605
24606 @<Declare the basic parsing subroutines@>=
24607 static int mp_scan_path (MP mp);
24608 static void mp_scan_expression (MP mp) {
24609 int my_var_flag; /* initial value of |var_flag| */
24610 my_var_flag = mp->var_flag;
24611 check_expansion_depth();
24612 RESTART:
24613 if ((cur_cmd() < mp_min_primary_command) ||
24614 (cur_cmd() > mp_max_primary_command))
24615 mp_bad_exp (mp, "An");
24616 @.An expression...@>
24617 mp_scan_tertiary (mp);
24618 CONTINUE:
24619 if (cur_cmd() <= mp_max_expression_command) {
24620 if (cur_cmd() >= mp_min_expression_command) {
24621 if ((cur_cmd() != mp_equals) || (my_var_flag != mp_assignment)) {
24622 mp_node p; /* for list manipulation */
24623 mp_node cc = NULL;
24624 halfword c;
24625 halfword d; /* operation codes or modifiers */
24626 mp_sym mac_name; /* token defined with \&{tertiarydef} */
24627 mac_name = NULL;
24628 p = mp_stash_cur_exp (mp);
24629 d = cur_cmd();
24630 c = cur_mod();
24631 if (d == mp_expression_tertiary_macro) {
24632 cc = cur_mod_node();
24633 mac_name = cur_sym();
24634 add_mac_ref (cc);
24635 }
24636 if ((d < mp_ampersand) || ((d == mp_ampersand) &&
24637 ((mp_type (p) == mp_pair_type)
24638 || (mp_type (p) == mp_path_type)))) {
24639 /* Scan a path construction operation; but |return| if |p| has the wrong type */
24640
24641 mp_unstash_cur_exp (mp, p);
24642 if (!mp_scan_path(mp)) {
24643 mp->expand_depth_count--;
24644 return;
24645 }
24646 } else {
24647 mp_get_x_next (mp);
24648 mp_scan_tertiary (mp);
24649 if (d != mp_expression_tertiary_macro) {
24650 mp_do_binary (mp, p, c);
24651 } else {
24652 mp_back_input (mp);
24653 mp_binary_mac (mp, p, cc, mac_name);
24654 decr_mac_ref (cc);
24655 mp_get_x_next (mp);
24656 goto RESTART;
24657 }
24658 }
24659 goto CONTINUE;
24660 }
24661 }
24662 }
24663 mp->expand_depth_count--;
24664 }
24665
24666
24667 @ The reader should review the data structure conventions for paths before
24668 hoping to understand the next part of this code.
24669
24670 @d min_tension three_quarter_unit_t
24671
24672 @<Declare the basic parsing subroutines@>=
24673 static void force_valid_tension_setting(MP mp) {
24674 if ((mp->cur_exp.type != mp_known) || number_less(cur_exp_value_number (), min_tension)) {
24675 mp_value new_expr;
24676 const char *hlp[] = {
24677 "The expression above should have been a number >=3/4.",
24678 NULL };
24679 memset(&new_expr,0,sizeof(mp_value));
24680 new_number(new_expr.data.n);
24681 mp_disp_err(mp, NULL);
24682 number_clone(new_expr.data.n, unity_t);
24683 mp_back_error (mp, "Improper tension has been set to 1", hlp, true);
24684 mp_get_x_next (mp);
24685 mp_flush_cur_exp (mp, new_expr);
24686 }
24687 }
24688 static int mp_scan_path (MP mp) {
24689 mp_knot path_p, path_q, r;
24690 mp_knot pp, qq;
24691 halfword d; /* operation code or modifier */
24692 boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
24693 mp_number x, y; /* explicit coordinates or tension at a path join */
24694 int t; /* knot type following a path join */
24695 t = 0;
24696 cycle_hit = false;
24697 /* Convert the left operand, |p|, into a partial path ending at~|q|;
24698 but |return| if |p| doesn't have a suitable type */
24699 if (mp->cur_exp.type == mp_pair_type)
24700 path_p = mp_pair_to_knot (mp);
24701 else if (mp->cur_exp.type == mp_path_type)
24702 path_p = cur_exp_knot ();
24703 else
24704 return 0;
24705 path_q = path_p;
24706 while (mp_next_knot (path_q) != path_p)
24707 path_q = mp_next_knot (path_q);
24708 if (mp_left_type (path_p) != mp_endpoint) { /* open up a cycle */
24709 r = mp_copy_knot (mp, path_p);
24710 mp_next_knot (path_q) = r;
24711 path_q = r;
24712 }
24713 mp_left_type (path_p) = mp_open;
24714 mp_right_type (path_q) = mp_open;
24715
24716 new_number (y);
24717 new_number (x);
24718
24719 CONTINUE_PATH:
24720 /* Determine the path join parameters;
24721 but |goto finish_path| if there's only a direction specifier */
24722 /* At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|. */
24723
24724 if (cur_cmd() == mp_left_brace) {
24725 /* Put the pre-join direction information into node |q| */
24726 /* At this point |mp_right_type(q)| is usually |open|, but it may have been
24727 set to some other value by a previous operation. We must maintain
24728 the value of |mp_right_type(q)| in cases such as
24729 `\.{..\{curl2\}z\{0,0\}..}'. */
24730 t = mp_scan_direction (mp);
24731 if (t != mp_open) {
24732 mp_right_type (path_q) = (unsigned short) t;
24733 number_clone(path_q->right_given, cur_exp_value_number ());
24734 if (mp_left_type (path_q) == mp_open) {
24735 mp_left_type (path_q) = (unsigned short) t;
24736 number_clone(path_q->left_given, cur_exp_value_number ());
24737 } /* note that |left_given(q)=left_curl(q)| */
24738 }
24739 }
24740 d = cur_cmd();
24741 if (d == mp_path_join) {
24742 /* Determine the tension and/or control points */
24743 mp_get_x_next (mp);
24744 if (cur_cmd() == mp_tension) {
24745 /* Set explicit tensions */
24746 mp_get_x_next (mp);
24747 set_number_from_scaled (y, cur_cmd());
24748 if (cur_cmd() == mp_at_least)
24749 mp_get_x_next (mp);
24750 mp_scan_primary (mp);
24751 force_valid_tension_setting(mp);
24752 if (number_to_scaled (y) == mp_at_least) {
24753 if (is_number(cur_exp_value_number()))
24754 number_negate (cur_exp_value_number());
24755 }
24756 number_clone(path_q->right_tension, cur_exp_value_number ());
24757 if (cur_cmd() == mp_and_command) {
24758 mp_get_x_next (mp);
24759 set_number_from_scaled (y, cur_cmd());
24760 if (cur_cmd() == mp_at_least)
24761 mp_get_x_next (mp);
24762 mp_scan_primary (mp);
24763 force_valid_tension_setting(mp);
24764 if (number_to_scaled (y) == mp_at_least) {
24765 if (is_number(cur_exp_value_number()))
24766 number_negate (cur_exp_value_number());
24767 }
24768 }
24769 number_clone (y, cur_exp_value_number ());
24770
24771 } else if (cur_cmd() == mp_controls) {
24772 /* Set explicit control points */
24773 mp_right_type (path_q) = mp_explicit;
24774 t = mp_explicit;
24775 mp_get_x_next (mp);
24776 mp_scan_primary (mp);
24777 mp_known_pair (mp);
24778 number_clone (path_q->right_x, mp->cur_x);
24779 number_clone (path_q->right_y, mp->cur_y);
24780 if (cur_cmd() != mp_and_command) {
24781 number_clone (x, path_q->right_x);
24782 number_clone (y, path_q->right_y);
24783 } else {
24784 mp_get_x_next (mp);
24785 mp_scan_primary (mp);
24786 mp_known_pair (mp);
24787 number_clone (x, mp->cur_x);
24788 number_clone (y, mp->cur_y);
24789 }
24790
24791 } else {
24792 set_number_to_unity(path_q->right_tension);
24793 set_number_to_unity(y);
24794 mp_back_input (mp); /* default tension */
24795 goto DONE;
24796 }
24797 if (cur_cmd() != mp_path_join) {
24798 const char *hlp[] = { "A path join command should end with two dots.", NULL};
24799 mp_back_error (mp, "Missing `..' has been inserted", hlp, true);
24800 }
24801 DONE:
24802 ;
24803 } else if (d != mp_ampersand) {
24804 goto FINISH_PATH;
24805 }
24806 mp_get_x_next (mp);
24807 if (cur_cmd() == mp_left_brace) {
24808 /* Put the post-join direction information into |x| and |t| */
24809 /* Since |left_tension| and |mp_left_y| share the same position in knot nodes,
24810 and since |left_given| is similarly equivalent to |left_x|, we use
24811 |x| and |y| to hold the given direction and tension information when
24812 there are no explicit control points. */
24813 t = mp_scan_direction (mp);
24814 if (mp_right_type (path_q) != mp_explicit)
24815 number_clone (x, cur_exp_value_number ());
24816 else
24817 t = mp_explicit; /* the direction information is superfluous */
24818
24819 } else if (mp_right_type (path_q) != mp_explicit) {
24820 t = mp_open;
24821 set_number_to_zero(x);
24822 }
24823
24824 if (cur_cmd() == mp_cycle) {
24825 /* Get ready to close a cycle */
24826 /* If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
24827 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
24828 shouldn't have length zero. */
24829 cycle_hit = true;
24830 mp_get_x_next (mp);
24831 pp = path_p;
24832 qq = path_p;
24833 if (d == mp_ampersand) {
24834 if (path_p == path_q) {
24835 d = mp_path_join;
24836 set_number_to_unity(path_q->right_tension);
24837 set_number_to_unity(y);
24838 }
24839 }
24840 } else {
24841 mp_scan_tertiary (mp);
24842 /* Convert the right operand, |cur_exp|,
24843 into a partial path from |pp| to~|qq| */
24844 if (mp->cur_exp.type != mp_path_type)
24845 pp = mp_pair_to_knot (mp);
24846 else
24847 pp = cur_exp_knot ();
24848 qq = pp;
24849 while (mp_next_knot (qq) != pp)
24850 qq = mp_next_knot (qq);
24851 if (mp_left_type (pp) != mp_endpoint) { /* open up a cycle */
24852 r = mp_copy_knot (mp, pp);
24853 mp_next_knot (qq) = r;
24854 qq = r;
24855 }
24856 mp_left_type (pp) = mp_open;
24857 mp_right_type (qq) = mp_open;
24858 }
24859 /* Join the partial paths and reset |p| and |q| to the head and tail
24860 of the result */
24861 if (d == mp_ampersand) {
24862 if (!(number_equal (path_q->x_coord, pp->x_coord)) ||
24863 !(number_equal (path_q->y_coord, pp->y_coord))) {
24864 const char *hlp[] = {
24865 "When you join paths `p&q', the ending point of p",
24866 "must be exactly equal to the starting point of q.",
24867 "So I'm going to pretend that you said `p..q' instead.",
24868 NULL };
24869 mp_back_error (mp, "Paths don't touch; `&' will be changed to `..'", hlp, true);
24870 @.Paths don't touch@>
24871 mp_get_x_next (mp);
24872 d = mp_path_join;
24873 set_number_to_unity (path_q->right_tension);
24874 set_number_to_unity (y);
24875 }
24876 }
24877 /* Plug an opening in |mp_right_type(pp)|, if possible */
24878 if (mp_right_type (pp) == mp_open) {
24879 if ((t == mp_curl) || (t == mp_given)) {
24880 mp_right_type (pp) = (unsigned short) t;
24881 number_clone (pp->right_given, x);
24882 }
24883 }
24884 if (d == mp_ampersand) {
24885 /* Splice independent paths together */
24886 if (mp_left_type (path_q) == mp_open)
24887 if (mp_right_type (path_q) == mp_open) {
24888 mp_left_type (path_q) = mp_curl;
24889 set_number_to_unity(path_q->left_curl);
24890 }
24891 if (mp_right_type (pp) == mp_open)
24892 if (t == mp_open) {
24893 mp_right_type (pp) = mp_curl;
24894 set_number_to_unity(pp->right_curl);
24895 }
24896 mp_right_type (path_q) = mp_right_type (pp);
24897 mp_next_knot (path_q) = mp_next_knot (pp);
24898 number_clone (path_q->right_x, pp->right_x);
24899 number_clone (path_q->right_y, pp->right_y);
24900 mp_xfree (pp);
24901 if (qq == pp)
24902 qq = path_q;
24903
24904 } else {
24905 /* Plug an opening in |mp_right_type(q)|, if possible */
24906 if (mp_right_type (path_q) == mp_open) {
24907 if ((mp_left_type (path_q) == mp_curl) || (mp_left_type (path_q) == mp_given)) {
24908 mp_right_type (path_q) = mp_left_type (path_q);
24909 number_clone(path_q->right_given, path_q->left_given);
24910 }
24911 }
24912
24913 mp_next_knot (path_q) = pp;
24914 number_clone (pp->left_y, y);
24915 if (t != mp_open) {
24916 number_clone (pp->left_x, x);
24917 mp_left_type (pp) = (unsigned short) t;
24918 }
24919 }
24920 path_q = qq;
24921
24922 if (cur_cmd() >= mp_min_expression_command)
24923 if (cur_cmd() <= mp_ampersand)
24924 if (!cycle_hit)
24925 goto CONTINUE_PATH;
24926 FINISH_PATH:
24927 /* Choose control points for the path and put the result into |cur_exp| */
24928 if (cycle_hit) {
24929 if (d == mp_ampersand)
24930 path_p = path_q;
24931 } else {
24932 mp_left_type (path_p) = mp_endpoint;
24933 if (mp_right_type (path_p) == mp_open) {
24934 mp_right_type (path_p) = mp_curl;
24935 set_number_to_unity(path_p->right_curl);
24936 }
24937 mp_right_type (path_q) = mp_endpoint;
24938 if (mp_left_type (path_q) == mp_open) {
24939 mp_left_type (path_q) = mp_curl;
24940 set_number_to_unity(path_q->left_curl);
24941 }
24942 mp_next_knot (path_q) = path_p;
24943 }
24944 mp_make_choices (mp, path_p);
24945 mp->cur_exp.type = mp_path_type;
24946 set_cur_exp_knot (path_p);
24947
24948 free_number (x);
24949 free_number (y);
24950 return 1;
24951 }
24952
24953
24954 @ A pair of numeric values is changed into a knot node for a one-point path
24955 when \MP\ discovers that the pair is part of a path.
24956
24957 @c
24958 static mp_knot mp_pair_to_knot (MP mp) { /* convert a pair to a knot with two endpoints */
24959 mp_knot q; /* the new node */
24960 q = mp_new_knot(mp);
24961 mp_left_type (q) = mp_endpoint;
24962 mp_right_type (q) = mp_endpoint;
24963 mp_originator (q) = mp_metapost_user;
24964 mp_next_knot (q) = q;
24965 mp_known_pair (mp);
24966 number_clone (q->x_coord, mp->cur_x);
24967 number_clone (q->y_coord, mp->cur_y);
24968 return q;
24969 }
24970
24971
24972 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
24973 of the current expression, assuming that the current expression is a
24974 pair of known numerics. Unknown components are zeroed, and the
24975 current expression is flushed.
24976
24977 @<Declarations@>=
24978 static void mp_known_pair (MP mp);
24979
24980 @ @c
24981 void mp_known_pair (MP mp) {
24982 mp_value new_expr;
24983 mp_node p; /* the pair node */
24984 memset(&new_expr,0,sizeof(mp_value));
24985 new_number(new_expr.data.n);
24986 if (mp->cur_exp.type != mp_pair_type) {
24987 const char *hlp[] = {
24988 "I need x and y numbers for this part of the path.",
24989 "The value I found (see above) was no good;",
24990 "so I'll try to keep going by using zero instead.",
24991 "(Chapter 27 of The METAFONTbook explains that",
24992 "you might want to type `I ??" "?' now.)",
24993 NULL };
24994 mp_disp_err(mp, NULL);
24995 mp_back_error (mp, "Undefined coordinates have been replaced by (0,0)", hlp, true);
24996 mp_get_x_next (mp);
24997 mp_flush_cur_exp (mp, new_expr);
24998 set_number_to_zero(mp->cur_x);
24999 set_number_to_zero(mp->cur_y);
25000 } else {
25001 p = value_node (cur_exp_node ());
25002 /* Make sure that both |x| and |y| parts of |p| are known;
25003 copy them into |cur_x| and |cur_y| */
25004 if (mp_type (x_part (p)) == mp_known) {
25005 number_clone(mp->cur_x, value_number (x_part (p)));
25006 } else {
25007 const char *hlp[] = {
25008 "I need a `known' x value for this part of the path.",
25009 "The value I found (see above) was no good;",
25010 "so I'll try to keep going by using zero instead.",
25011 "(Chapter 27 of The METAFONTbook explains that",
25012 "you might want to type `I ??" "?' now.)",
25013 NULL };
25014 mp_disp_err (mp, x_part (p));
25015 mp_back_error (mp, "Undefined x coordinate has been replaced by 0", hlp, true);
25016 mp_get_x_next (mp);
25017 mp_recycle_value (mp, x_part (p));
25018 set_number_to_zero(mp->cur_x);
25019 }
25020 if (mp_type (y_part (p)) == mp_known) {
25021 number_clone(mp->cur_y, value_number (y_part (p)));
25022 } else {
25023 const char *hlp[] = {
25024 "I need a `known' y value for this part of the path.",
25025 "The value I found (see above) was no good;",
25026 "so I'll try to keep going by using zero instead.",
25027 "(Chapter 27 of The METAFONTbook explains that",
25028 "you might want to type `I ??" "?' now.)",
25029 NULL };
25030 mp_disp_err (mp, y_part (p));
25031 mp_back_error (mp, "Undefined y coordinate has been replaced by 0", hlp, true);
25032 mp_get_x_next (mp);
25033 mp_recycle_value (mp, y_part (p));
25034 set_number_to_zero(mp->cur_y);
25035 }
25036 mp_flush_cur_exp (mp, new_expr);
25037 }
25038 }
25039
25040 @ The |scan_direction| subroutine looks at the directional information
25041 that is enclosed in braces, and also scans ahead to the following character.
25042 A type code is returned, either |open| (if the direction was $(0,0)$),
25043 or |curl| (if the direction was a curl of known value |cur_exp|), or
25044 |given| (if the direction is given by the |angle| value that now
25045 appears in |cur_exp|).
25046
25047 There's nothing difficult about this subroutine, but the program is rather
25048 lengthy because a variety of potential errors need to be nipped in the bud.
25049
25050 @c
25051 static quarterword mp_scan_direction (MP mp) {
25052 int t; /* the type of information found */
25053 mp_get_x_next (mp);
25054 if (cur_cmd() == mp_curl_command) {
25055 /* Scan a curl specification */
25056 mp_get_x_next (mp);
25057 mp_scan_expression (mp);
25058 if ((mp->cur_exp.type != mp_known) || (number_negative(cur_exp_value_number ()))) {
25059 mp_value new_expr;
25060 const char *hlp[] = { "A curl must be a known, nonnegative number.", NULL };
25061 memset(&new_expr,0,sizeof(mp_value));
25062 new_number(new_expr.data.n);
25063 set_number_to_unity(new_expr.data.n);
25064 mp_disp_err(mp, NULL);
25065 mp_back_error (mp, "Improper curl has been replaced by 1", hlp, true);
25066 mp_get_x_next (mp);
25067 mp_flush_cur_exp (mp, new_expr);
25068 }
25069 t = mp_curl;
25070
25071 } else {
25072 /* Scan a given direction */
25073 mp_scan_expression (mp);
25074 if (mp->cur_exp.type > mp_pair_type) {
25075 /* Get given directions separated by commas */
25076 mp_number xx;
25077 new_number(xx);
25078 if (mp->cur_exp.type != mp_known) {
25079 mp_value new_expr;
25080 const char *hlp[] = {
25081 "I need a `known' x value for this part of the path.",
25082 "The value I found (see above) was no good;",
25083 "so I'll try to keep going by using zero instead.",
25084 "(Chapter 27 of The METAFONTbook explains that",
25085 "you might want to type `I ??" "?' now.)",
25086 NULL };
25087 memset(&new_expr,0,sizeof(mp_value));
25088 new_number(new_expr.data.n);
25089 set_number_to_zero(new_expr.data.n);
25090 mp_disp_err(mp, NULL);
25091 mp_back_error (mp, "Undefined x coordinate has been replaced by 0", hlp, true);
25092 mp_get_x_next (mp);
25093 mp_flush_cur_exp (mp, new_expr);
25094 }
25095 number_clone(xx, cur_exp_value_number ());
25096 if (cur_cmd() != mp_comma) {
25097 const char *hlp[] = {
25098 "I've got the x coordinate of a path direction;",
25099 "will look for the y coordinate next.",
25100 NULL };
25101 mp_back_error (mp, "Missing `,' has been inserted", hlp, true);
25102 }
25103 mp_get_x_next (mp);
25104 mp_scan_expression (mp);
25105 if (mp->cur_exp.type != mp_known) {
25106 mp_value new_expr;
25107 const char *hlp[] = {
25108 "I need a `known' y value for this part of the path.",
25109 "The value I found (see above) was no good;",
25110 "so I'll try to keep going by using zero instead.",
25111 "(Chapter 27 of The METAFONTbook explains that",
25112 "you might want to type `I ??" "?' now.)",
25113 NULL };
25114 memset(&new_expr,0,sizeof(mp_value));
25115 new_number(new_expr.data.n);
25116 set_number_to_zero(new_expr.data.n);
25117 mp_disp_err(mp, NULL);
25118 mp_back_error (mp, "Undefined y coordinate has been replaced by 0", hlp, true);
25119 mp_get_x_next (mp);
25120 mp_flush_cur_exp (mp, new_expr);
25121 }
25122 number_clone(mp->cur_y, cur_exp_value_number ());
25123 number_clone(mp->cur_x, xx);
25124 free_number(xx);
25125
25126 } else {
25127 mp_known_pair (mp);
25128 }
25129 if (number_zero(mp->cur_x) && number_zero(mp->cur_y))
25130 t = mp_open;
25131 else {
25132 mp_number narg;
25133 new_angle (narg);
25134 n_arg (narg, mp->cur_x, mp->cur_y);
25135 t = mp_given;
25136 set_cur_exp_value_number (narg);
25137 free_number (narg);
25138 }
25139 }
25140 if (cur_cmd() != mp_right_brace) {
25141 const char *hlp[] = {
25142 "I've scanned a direction spec for part of a path,",
25143 "so a right brace should have come next.",
25144 "I shall pretend that one was there.",
25145 NULL };
25146 mp_back_error (mp, "Missing `}' has been inserted", hlp, true);
25147 }
25148 mp_get_x_next (mp);
25149 return (quarterword) t;
25150 }
25151
25152
25153 @ Finally, we sometimes need to scan an expression whose value is
25154 supposed to be either |true_code| or |false_code|.
25155
25156 @d mp_get_boolean(mp) do {
25157 mp_get_x_next (mp);
25158 mp_scan_expression (mp);
25159 if (mp->cur_exp.type != mp_boolean_type) {
25160 do_boolean_error(mp);
25161 }
25162 } while (0)@;
25163
25164 @<Declare the basic parsing subroutines@>=
25165 static void do_boolean_error (MP mp) {
25166 mp_value new_expr;
25167 const char *hlp[] = {
25168 "The expression shown above should have had a definite",
25169 "true-or-false value. I'm changing it to `false'.",
25170 NULL };
25171 memset(&new_expr,0,sizeof(mp_value));
25172 new_number(new_expr.data.n);
25173 mp_disp_err(mp, NULL);
25174 set_number_from_boolean (new_expr.data.n, mp_false_code);
25175 mp_back_error (mp, "Undefined condition will be treated as `false'", hlp, true);
25176 mp_get_x_next (mp);
25177 mp_flush_cur_exp (mp, new_expr);
25178 mp->cur_exp.type = mp_boolean_type;
25179 }
25180
25181 @ @<Declarations@>=
25182 static void do_boolean_error (MP mp);
25183
25184 @* Doing the operations.
25185 The purpose of parsing is primarily to permit people to avoid piles of
25186 parentheses. But the real work is done after the structure of an expression
25187 has been recognized; that's when new expressions are generated. We
25188 turn now to the guts of \MP, which handles individual operators that
25189 have come through the parsing mechanism.
25190
25191 We'll start with the easy ones that take no operands, then work our way
25192 up to operators with one and ultimately two arguments. In other words,
25193 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
25194 that are invoked periodically by the expression scanners.
25195
25196 First let's make sure that all of the primitive operators are in the
25197 hash table. Although |scan_primary| and its relatives made use of the
25198 \\{cmd} code for these operators, the \\{do} routines base everything
25199 on the \\{mod} code. For example, |do_binary| doesn't care whether the
25200 operation it performs is a |primary_binary| or |secondary_binary|, etc.
25201
25202 @<Put each...@>=
25203 mp_primitive (mp, "true", mp_nullary, mp_true_code);
25204 @:true_}{\&{true} primitive@>
25205 mp_primitive (mp, "false", mp_nullary, mp_false_code);
25206 @:false_}{\&{false} primitive@>
25207 mp_primitive (mp, "nullpicture", mp_nullary, mp_null_picture_code);
25208 @:null_picture_}{\&{nullpicture} primitive@>
25209 mp_primitive (mp, "nullpen", mp_nullary, mp_null_pen_code);
25210 @:null_pen_}{\&{nullpen} primitive@>
25211 mp_primitive (mp, "readstring", mp_nullary, mp_read_string_op);
25212 @:read_string_}{\&{readstring} primitive@>
25213 mp_primitive (mp, "pencircle", mp_nullary, mp_pen_circle);
25214 @:pen_circle_}{\&{pencircle} primitive@>
25215 mp_primitive (mp, "normaldeviate", mp_nullary, mp_normal_deviate);
25216 @:normal_deviate_}{\&{normaldeviate} primitive@>
25217 mp_primitive (mp, "readfrom", mp_unary, mp_read_from_op);
25218 @:read_from_}{\&{readfrom} primitive@>
25219 mp_primitive (mp, "closefrom", mp_unary, mp_close_from_op);
25220 @:close_from_}{\&{closefrom} primitive@>
25221 mp_primitive (mp, "odd", mp_unary, mp_odd_op);
25222 @:odd_}{\&{odd} primitive@>
25223 mp_primitive (mp, "known", mp_unary, mp_known_op);
25224 @:known_}{\&{known} primitive@>
25225 mp_primitive (mp, "unknown", mp_unary, mp_unknown_op);
25226 @:unknown_}{\&{unknown} primitive@>
25227 mp_primitive (mp, "not", mp_unary, mp_not_op);
25228 @:not_}{\&{not} primitive@>
25229 mp_primitive (mp, "decimal", mp_unary, mp_decimal);
25230 @:decimal_}{\&{decimal} primitive@>
25231 mp_primitive (mp, "reverse", mp_unary, mp_reverse);
25232 @:reverse_}{\&{reverse} primitive@>
25233 mp_primitive (mp, "makepath", mp_unary, mp_make_path_op);
25234 @:make_path_}{\&{makepath} primitive@>
25235 mp_primitive (mp, "makepen", mp_unary, mp_make_pen_op);
25236 @:make_pen_}{\&{makepen} primitive@>
25237 mp_primitive (mp, "oct", mp_unary, mp_oct_op);
25238 @:oct_}{\&{oct} primitive@>
25239 mp_primitive (mp, "hex", mp_unary, mp_hex_op);
25240 @:hex_}{\&{hex} primitive@>
25241 mp_primitive (mp, "ASCII", mp_unary, mp_ASCII_op);
25242 @:ASCII_}{\&{ASCII} primitive@>
25243 mp_primitive (mp, "char", mp_unary, mp_char_op);
25244 @:char_}{\&{char} primitive@>
25245 mp_primitive (mp, "length", mp_unary, mp_length_op);
25246 @:length_}{\&{length} primitive@>
25247 mp_primitive (mp, "turningnumber", mp_unary, mp_turning_op);
25248 @:turning_number_}{\&{turningnumber} primitive@>
25249 mp_primitive (mp, "xpart", mp_unary, mp_x_part);
25250 @:x_part_}{\&{xpart} primitive@>
25251 mp_primitive (mp, "ypart", mp_unary, mp_y_part);
25252 @:y_part_}{\&{ypart} primitive@>
25253 mp_primitive (mp, "xxpart", mp_unary, mp_xx_part);
25254 @:xx_part_}{\&{xxpart} primitive@>
25255 mp_primitive (mp, "xypart", mp_unary, mp_xy_part);
25256 @:xy_part_}{\&{xypart} primitive@>
25257 mp_primitive (mp, "yxpart", mp_unary, mp_yx_part);
25258 @:yx_part_}{\&{yxpart} primitive@>
25259 mp_primitive (mp, "yypart", mp_unary, mp_yy_part);
25260 @:yy_part_}{\&{yypart} primitive@>
25261 mp_primitive (mp, "redpart", mp_unary, mp_red_part);
25262 @:red_part_}{\&{redpart} primitive@>
25263 mp_primitive (mp, "greenpart", mp_unary, mp_green_part);
25264 @:green_part_}{\&{greenpart} primitive@>
25265 mp_primitive (mp, "bluepart", mp_unary, mp_blue_part);
25266 @:blue_part_}{\&{bluepart} primitive@>
25267 mp_primitive (mp, "cyanpart", mp_unary, mp_cyan_part);
25268 @:cyan_part_}{\&{cyanpart} primitive@>
25269 mp_primitive (mp, "magentapart", mp_unary, mp_magenta_part);
25270 @:magenta_part_}{\&{magentapart} primitive@>
25271 mp_primitive (mp, "yellowpart", mp_unary, mp_yellow_part);
25272 @:yellow_part_}{\&{yellowpart} primitive@>
25273 mp_primitive (mp, "blackpart", mp_unary, mp_black_part);
25274 @:black_part_}{\&{blackpart} primitive@>
25275 mp_primitive (mp, "greypart", mp_unary, mp_grey_part);
25276 @:grey_part_}{\&{greypart} primitive@>
25277 mp_primitive (mp, "colormodel", mp_unary, mp_color_model_part);
25278 @:color_model_part_}{\&{colormodel} primitive@>
25279 mp_primitive (mp, "fontpart", mp_unary, mp_font_part);
25280 @:font_part_}{\&{fontpart} primitive@>
25281 mp_primitive (mp, "textpart", mp_unary, mp_text_part);
25282 @:text_part_}{\&{textpart} primitive@>
25283 mp_primitive (mp, "prescriptpart", mp_unary, mp_prescript_part);
25284 @:prescript_part_}{\&{prescriptpart} primitive@>
25285 mp_primitive (mp, "postscriptpart", mp_unary, mp_postscript_part);
25286 @:postscript_part_}{\&{postscriptpart} primitive@>
25287 mp_primitive (mp, "pathpart", mp_unary, mp_path_part);
25288 @:path_part_}{\&{pathpart} primitive@>
25289 mp_primitive (mp, "penpart", mp_unary, mp_pen_part);
25290 @:pen_part_}{\&{penpart} primitive@>
25291 mp_primitive (mp, "dashpart", mp_unary, mp_dash_part);
25292 @:dash_part_}{\&{dashpart} primitive@>
25293 mp_primitive (mp, "sqrt", mp_unary, mp_sqrt_op);
25294 @:sqrt_}{\&{sqrt} primitive@>
25295 mp_primitive (mp, "mexp", mp_unary, mp_m_exp_op);
25296 @:m_exp_}{\&{mexp} primitive@>
25297 mp_primitive (mp, "mlog", mp_unary, mp_m_log_op);
25298 @:m_log_}{\&{mlog} primitive@>
25299 mp_primitive (mp, "sind", mp_unary, mp_sin_d_op);
25300 @:sin_d_}{\&{sind} primitive@>
25301 mp_primitive (mp, "cosd", mp_unary, mp_cos_d_op);
25302 @:cos_d_}{\&{cosd} primitive@>
25303 mp_primitive (mp, "floor", mp_unary, mp_floor_op);
25304 @:floor_}{\&{floor} primitive@>
25305 mp_primitive (mp, "uniformdeviate", mp_unary, mp_uniform_deviate);
25306 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
25307 mp_primitive (mp, "charexists", mp_unary, mp_char_exists_op);
25308 @:char_exists_}{\&{charexists} primitive@>
25309 mp_primitive (mp, "fontsize", mp_unary, mp_font_size);
25310 @:font_size_}{\&{fontsize} primitive@>
25311 mp_primitive (mp, "llcorner", mp_unary, mp_ll_corner_op);
25312 @:ll_corner_}{\&{llcorner} primitive@>
25313 mp_primitive (mp, "lrcorner", mp_unary, mp_lr_corner_op);
25314 @:lr_corner_}{\&{lrcorner} primitive@>
25315 mp_primitive (mp, "ulcorner", mp_unary, mp_ul_corner_op);
25316 @:ul_corner_}{\&{ulcorner} primitive@>
25317 mp_primitive (mp, "urcorner", mp_unary, mp_ur_corner_op);
25318 @:ur_corner_}{\&{urcorner} primitive@>
25319 mp_primitive (mp, "arclength", mp_unary, mp_arc_length);
25320 @:arc_length_}{\&{arclength} primitive@>
25321 mp_primitive (mp, "angle", mp_unary, mp_angle_op);
25322 @:angle_}{\&{angle} primitive@>
25323 mp_primitive (mp, "cycle", mp_cycle, mp_cycle_op);
25324 @:cycle_}{\&{cycle} primitive@>
25325 mp_primitive (mp, "stroked", mp_unary, mp_stroked_op);
25326 @:stroked_}{\&{stroked} primitive@>
25327 mp_primitive (mp, "filled", mp_unary, mp_filled_op);
25328 @:filled_}{\&{filled} primitive@>
25329 mp_primitive (mp, "textual", mp_unary, mp_textual_op);
25330 @:textual_}{\&{textual} primitive@>
25331 mp_primitive (mp, "clipped", mp_unary, mp_clipped_op);
25332 @:clipped_}{\&{clipped} primitive@>
25333 mp_primitive (mp, "bounded", mp_unary, mp_bounded_op);
25334 @:bounded_}{\&{bounded} primitive@>
25335 mp_primitive (mp, "+", mp_plus_or_minus, mp_plus);
25336 @:+ }{\.{+} primitive@>
25337 mp_primitive (mp, "-", mp_plus_or_minus, mp_minus);
25338 @:- }{\.{-} primitive@>
25339 mp_primitive (mp, "*", mp_secondary_binary, mp_times);
25340 @:* }{\.{*} primitive@>
25341 mp_primitive (mp, "/", mp_slash, mp_over);
25342 mp->frozen_slash = mp_frozen_primitive (mp, "/", mp_slash, mp_over);
25343 @:/ }{\.{/} primitive@>
25344 mp_primitive (mp, "++", mp_tertiary_binary, mp_pythag_add);
25345 @:++_}{\.{++} primitive@>
25346 mp_primitive (mp, "+-+", mp_tertiary_binary, mp_pythag_sub);
25347 @:+-+_}{\.{+-+} primitive@>
25348 mp_primitive (mp, "or", mp_tertiary_binary, mp_or_op);
25349 @:or_}{\&{or} primitive@>
25350 mp_primitive (mp, "and", mp_and_command, mp_and_op);
25351 @:and_}{\&{and} primitive@>
25352 mp_primitive (mp, "<", mp_expression_binary, mp_less_than);
25353 @:< }{\.{<} primitive@>
25354 mp_primitive (mp, "<=", mp_expression_binary, mp_less_or_equal);
25355 @:<=_}{\.{<=} primitive@>
25356 mp_primitive (mp, ">", mp_expression_binary, mp_greater_than);
25357 @:> }{\.{>} primitive@>
25358 mp_primitive (mp, ">=", mp_expression_binary, mp_greater_or_equal);
25359 @:>=_}{\.{>=} primitive@>
25360 mp_primitive (mp, "=", mp_equals, mp_equal_to);
25361 @:= }{\.{=} primitive@>
25362 mp_primitive (mp, "<>", mp_expression_binary, mp_unequal_to);
25363 @:<>_}{\.{<>} primitive@>
25364 mp_primitive (mp, "substring", mp_primary_binary, mp_substring_of);
25365 @:substring_}{\&{substring} primitive@>
25366 mp_primitive (mp, "subpath", mp_primary_binary, mp_subpath_of);
25367 @:subpath_}{\&{subpath} primitive@>
25368 mp_primitive (mp, "directiontime", mp_primary_binary, mp_direction_time_of);
25369 @:direction_time_}{\&{directiontime} primitive@>
25370 mp_primitive (mp, "point", mp_primary_binary, mp_point_of);
25371 @:point_}{\&{point} primitive@>
25372 mp_primitive (mp, "precontrol", mp_primary_binary, mp_precontrol_of);
25373 @:precontrol_}{\&{precontrol} primitive@>
25374 mp_primitive (mp, "postcontrol", mp_primary_binary, mp_postcontrol_of);
25375 @:postcontrol_}{\&{postcontrol} primitive@>
25376 mp_primitive (mp, "penoffset", mp_primary_binary, mp_pen_offset_of);
25377 @:pen_offset_}{\&{penoffset} primitive@>
25378 mp_primitive (mp, "arctime", mp_primary_binary, mp_arc_time_of);
25379 @:arc_time_of_}{\&{arctime} primitive@>
25380 mp_primitive (mp, "mpversion", mp_nullary, mp_version);
25381 @:mp_verison_}{\&{mpversion} primitive@>
25382 mp_primitive (mp, "&", mp_ampersand, mp_concatenate);
25383 @:!!!}{\.{\&} primitive@>
25384 mp_primitive (mp, "rotated", mp_secondary_binary, mp_rotated_by);
25385 @:rotated_}{\&{rotated} primitive@>
25386 mp_primitive (mp, "slanted", mp_secondary_binary, mp_slanted_by);
25387 @:slanted_}{\&{slanted} primitive@>
25388 mp_primitive (mp, "scaled", mp_secondary_binary, mp_scaled_by);
25389 @:scaled_}{\&{scaled} primitive@>
25390 mp_primitive (mp, "shifted", mp_secondary_binary, mp_shifted_by);
25391 @:shifted_}{\&{shifted} primitive@>
25392 mp_primitive (mp, "transformed", mp_secondary_binary, mp_transformed_by);
25393 @:transformed_}{\&{transformed} primitive@>
25394 mp_primitive (mp, "xscaled", mp_secondary_binary, mp_x_scaled);
25395 @:x_scaled_}{\&{xscaled} primitive@>
25396 mp_primitive (mp, "yscaled", mp_secondary_binary, mp_y_scaled);
25397 @:y_scaled_}{\&{yscaled} primitive@>
25398 mp_primitive (mp, "zscaled", mp_secondary_binary, mp_z_scaled);
25399 @:z_scaled_}{\&{zscaled} primitive@>
25400 mp_primitive (mp, "infont", mp_secondary_binary, mp_in_font);
25401 @:in_font_}{\&{infont} primitive@>
25402 mp_primitive (mp, "intersectiontimes", mp_tertiary_binary, mp_intersect);
25403 @:intersection_times_}{\&{intersectiontimes} primitive@>
25404 mp_primitive (mp, "envelope", mp_primary_binary, mp_envelope_of);
25405 @:envelope_}{\&{envelope} primitive@>
25406 mp_primitive (mp, "boundingpath", mp_primary_binary, mp_boundingpath_of);
25407 @:boundingpath_}{\&{boundingpath} primitive@>
25408 mp_primitive (mp, "glyph", mp_primary_binary, mp_glyph_infont);
25409 @:glyph_infont_}{\&{glyph} primitive@>
25410 mp_primitive (mp, "interval_get_left_endpoint", mp_unary, mp_m_get_left_endpoint_op); /* math interval new primitives */
25411 @:m_get_left_endpoint_}{\&{mget\_left\_endpoint} primitive@>
25412 mp_primitive (mp, "interval_get_right_endpoint", mp_unary, mp_m_get_right_endpoint_op); /* math interval new primitives */
25413 @:m_get_right_endpoint_}{\&{mget\_right\_endpoint} primitive@>
25414 mp_primitive (mp, "interval_set", mp_unary, mp_interval_set_op); /* math interval new primitives */
25415 @:interval_set}{\&{interval\_set} primitive@>
25416
25417
25418 @ @<Cases of |print_cmd...@>=
25419 case mp_nullary:
25420 case mp_unary:
25421 case mp_primary_binary:
25422 case mp_secondary_binary:
25423 case mp_tertiary_binary:
25424 case mp_expression_binary:
25425 case mp_cycle:
25426 case mp_plus_or_minus:
25427 case mp_slash:
25428 case mp_ampersand:
25429 case mp_equals:
25430 case mp_and_command:
25431 mp_print_op (mp, (quarterword) m);
25432 break;
25433
25434 @ OK, let's look at the simplest \\{do} procedure first.
25435
25436 @c
25437 @<Declare nullary action procedure@>
25438 static void mp_do_nullary (MP mp, quarterword c) {
25439 check_arith();
25440 if (number_greater (internal_value (mp_tracing_commands), two_t))
25441 mp_show_cmd_mod (mp, mp_nullary, c);
25442 switch (c) {
25443 case mp_true_code:
25444 case mp_false_code:
25445 mp->cur_exp.type = mp_boolean_type;
25446 set_cur_exp_value_boolean (c);
25447 break;
25448 case mp_null_picture_code:
25449 mp->cur_exp.type = mp_picture_type;
25450 set_cur_exp_node ((mp_node)mp_get_edge_header_node (mp));
25451 mp_init_edges (mp, (mp_edge_header_node)cur_exp_node ());
25452 break;
25453 case mp_null_pen_code:
25454 mp->cur_exp.type = mp_pen_type;
25455 set_cur_exp_knot (mp_get_pen_circle (mp, zero_t));
25456 break;
25457 case mp_normal_deviate:
25458 {
25459 mp_number r;
25460 new_number (r);
25461 /*|mp_norm_rand (mp, &r)|;*/
25462 m_norm_rand (r);
25463 mp->cur_exp.type = mp_known;
25464 set_cur_exp_value_number (r);
25465 free_number (r);
25466 }
25467 break;
25468 case mp_pen_circle:
25469 mp->cur_exp.type = mp_pen_type;
25470 set_cur_exp_knot (mp_get_pen_circle (mp, unity_t));
25471 break;
25472 case mp_version:
25473 mp->cur_exp.type = mp_string_type;
25474 set_cur_exp_str (mp_intern (mp, metapost_version));
25475 break;
25476 case mp_read_string_op:
25477 /* Read a string from the terminal */
25478 if (mp->noninteractive || mp->interaction <= mp_nonstop_mode)
25479 mp_fatal_error (mp, "*** (cannot readstring in nonstop modes)");
25480 mp_begin_file_reading (mp);
25481 name = is_read;
25482 limit = start;
25483 prompt_input ("");
25484 mp_finish_read (mp);
25485 break;
25486 } /* there are no other cases */
25487 check_arith();
25488 }
25489
25490
25491 @ @<Declare nullary action procedure@>=
25492 static void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
25493 size_t k;
25494 str_room (((int) mp->last - (int) start));
25495 for (k = (size_t) start; k < mp->last; k++) {
25496 append_char (mp->buffer[k]);
25497 }
25498 mp_end_file_reading (mp);
25499 mp->cur_exp.type = mp_string_type;
25500 set_cur_exp_str (mp_make_string (mp));
25501 }
25502
25503
25504 @ Things get a bit more interesting when there's an operand. The
25505 operand to |do_unary| appears in |cur_type| and |cur_exp|.
25506
25507 This complicated if test makes sure that any |bounds| or |clip|
25508 picture objects that get passed into \&{within} do not raise an
25509 error when queried using the color part primitives (this is needed
25510 for backward compatibility) .
25511
25512 @d cur_pic_item mp_link(edge_list(cur_exp_node()))
25513 @d pict_color_type(A) ((cur_pic_item!=NULL) &&
25514 ((!has_color(cur_pic_item))
25515 || @|
25516 (((mp_color_model(cur_pic_item)==A)
25517 || @|
25518 ((mp_color_model(cur_pic_item)==mp_uninitialized_model) && @|
25519 (number_to_scaled (internal_value(mp_default_color_model))/ @| number_to_scaled (unity_t))==(A))))))
25520
25521 @d boolean_reset(A) if ( (A) ) set_cur_exp_value_boolean(mp_true_code); else set_cur_exp_value_boolean(mp_false_code)
25522
25523 @d type_range(A,B) {
25524 if ( (mp->cur_exp.type>=(A)) && (mp->cur_exp.type<=(B)) )
25525 set_number_from_boolean (new_expr.data.n, mp_true_code);
25526 else
25527 set_number_from_boolean (new_expr.data.n, mp_false_code);
25528 mp_flush_cur_exp(mp, new_expr);
25529 mp->cur_exp.type=mp_boolean_type;
25530 }
25531 @d type_test(A) {
25532 if ( mp->cur_exp.type==(mp_variable_type)(A) )
25533 set_number_from_boolean (new_expr.data.n, mp_true_code);
25534 else
25535 set_number_from_boolean (new_expr.data.n, mp_false_code);
25536 mp_flush_cur_exp(mp, new_expr);
25537 mp->cur_exp.type=mp_boolean_type;
25538 }
25539
25540
25541 @c
25542 @<Declare unary action procedures@>
25543 static void mp_do_unary (MP mp, quarterword c) {
25544 mp_node p; /* for list manipulation */
25545 mp_value new_expr;
25546 check_arith();
25547 if (number_greater (internal_value (mp_tracing_commands), two_t)) {
25548 /* Trace the current unary operation */
25549 mp_begin_diagnostic (mp);
25550 mp_print_nl (mp, "{");
25551 mp_print_op (mp, c);
25552 mp_print_char (mp, xord ('('));
25553 mp_print_exp (mp, NULL, 0); /* show the operand, but not verbosely */
25554 mp_print (mp, ")}");
25555 mp_end_diagnostic (mp, false);
25556 }
25557 switch (c) {
25558 case mp_plus:
25559 if (mp->cur_exp.type < mp_color_type)
25560 mp_bad_unary (mp, mp_plus);
25561 break;
25562 case mp_minus:
25563 negate_cur_expr(mp);
25564 break;
25565 case mp_not_op:
25566 if (mp->cur_exp.type != mp_boolean_type) {
25567 mp_bad_unary (mp, mp_not_op);
25568 } else {
25569 halfword bb;
25570 if (cur_exp_value_boolean () == mp_true_code)
25571 bb = mp_false_code;
25572 else
25573 bb = mp_true_code;
25574 set_cur_exp_value_boolean (bb);
25575 }
25576 break;
25577 case mp_sqrt_op:
25578 case mp_m_exp_op:
25579 case mp_m_log_op:
25580 case mp_sin_d_op:
25581 case mp_cos_d_op:
25582 case mp_floor_op:
25583 case mp_uniform_deviate:
25584 case mp_odd_op:
25585 case mp_char_exists_op:
25586 case mp_m_get_left_endpoint_op: /* math interval new primitives */
25587 case mp_m_get_right_endpoint_op:/* math interval new primitives */
25588 if (mp->cur_exp.type != mp_known) {
25589 mp_bad_unary (mp, c);
25590 } else {
25591 switch (c) {
25592 case mp_sqrt_op:
25593 {
25594 mp_number r1;
25595 new_number (r1);
25596 square_rt (r1, cur_exp_value_number ());
25597 set_cur_exp_value_number (r1);
25598 free_number (r1);
25599 }
25600 break;
25601 case mp_m_exp_op:
25602 {
25603 mp_number r1;
25604 new_number (r1);
25605 m_exp (r1, cur_exp_value_number ());
25606 set_cur_exp_value_number (r1);
25607 free_number (r1);
25608 }
25609 break;
25610 case mp_m_log_op:
25611 {
25612 mp_number r1;
25613 new_number (r1);
25614 m_log (r1, cur_exp_value_number ());
25615 set_cur_exp_value_number (r1);
25616 free_number (r1);
25617 }
25618 break;
25619 case mp_sin_d_op:
25620 case mp_cos_d_op:
25621 {
25622 mp_number n_sin, n_cos, arg1, arg2;
25623 new_number (arg1);
25624 new_number (arg2);
25625 new_fraction (n_sin);
25626 new_fraction (n_cos); /* results computed by |n_sin_cos| */
25627 number_clone (arg1, cur_exp_value_number());
25628 number_clone (arg2, unity_t);
25629 number_multiply_int (arg2, 360);
25630 number_modulo (arg1, arg2);
25631 convert_scaled_to_angle (arg1);
25632 n_sin_cos (arg1, n_cos, n_sin);
25633 if (c == mp_sin_d_op) {
25634 fraction_to_round_scaled (n_sin);
25635 set_cur_exp_value_number (n_sin);
25636 } else {
25637 fraction_to_round_scaled (n_cos);
25638 set_cur_exp_value_number (n_cos);
25639 }
25640 free_number (arg1);
25641 free_number (arg2);
25642 free_number (n_sin);
25643 free_number (n_cos);
25644 }
25645 break;
25646 case mp_floor_op:
25647 {
25648 mp_number vvx;
25649 new_number (vvx);
25650 number_clone (vvx, cur_exp_value_number ());
25651 floor_scaled (vvx);
25652 set_cur_exp_value_number (vvx);
25653 free_number (vvx);
25654 }
25655 break;
25656 case mp_uniform_deviate:
25657 {
25658 mp_number vvx;
25659 new_number (vvx);
25660 /*|mp_unif_rand (mp, &vvx, cur_exp_value_number ());|*/
25661 m_unif_rand (vvx, cur_exp_value_number ());
25662 set_cur_exp_value_number (vvx);
25663 free_number (vvx);
25664 }
25665 break;
25666 case mp_odd_op:
25667 {
25668 integer vvx = odd (round_unscaled (cur_exp_value_number ()));
25669 boolean_reset (vvx);
25670 mp->cur_exp.type = mp_boolean_type;
25671 }
25672 break;
25673 case mp_char_exists_op:
25674 /* Determine if a character has been shipped out */
25675 set_cur_exp_value_scaled (round_unscaled (cur_exp_value_number ()) % 256);
25676 if (number_negative(cur_exp_value_number ())) {
25677 halfword vv = number_to_scaled(cur_exp_value_number ());
25678 set_cur_exp_value_scaled (vv + 256);
25679 }
25680 boolean_reset (mp->char_exists[number_to_scaled(cur_exp_value_number ())]);
25681 mp->cur_exp.type = mp_boolean_type;
25682 break;
25683 case mp_m_get_left_endpoint_op: /* math interval new primitives */
25684 {
25685 mp_number r1;
25686 new_number (r1);
25687 m_get_left_endpoint (r1, cur_exp_value_number ());
25688 set_cur_exp_value_number (r1);
25689 free_number (r1);
25690 }
25691 break;
25692 case mp_m_get_right_endpoint_op: /* math interval new primitives */
25693 {
25694 mp_number r1;
25695 new_number (r1);
25696 m_get_right_endpoint (r1, cur_exp_value_number ());
25697 set_cur_exp_value_number (r1);
25698 free_number (r1);
25699 }
25700 break;
25701
25702 } /* there are no other cases */
25703 }
25704 break;
25705 case mp_interval_set_op: /* math interval new primitives */
25706 if (mp_nice_pair (mp, cur_exp_node (), mp->cur_exp.type)) {
25707 mp_number ret_val;
25708 memset(&new_expr,0,sizeof(mp_value));
25709 new_number(new_expr.data.n);
25710 new_number(ret_val);
25711 p = value_node (cur_exp_node ());
25712 m_interval_set(ret_val, value_number (x_part (p)), value_number (y_part (p)));
25713 number_clone (new_expr.data.n, ret_val);
25714 free_number (ret_val);
25715 mp_flush_cur_exp (mp, new_expr);
25716 } else {
25717 mp_bad_unary (mp, mp_interval_set_op);
25718 }
25719 break;
25720 case mp_angle_op:
25721 if (mp_nice_pair (mp, cur_exp_node (), mp->cur_exp.type)) {
25722 mp_number narg;
25723 memset(&new_expr,0,sizeof(mp_value));
25724 new_number(new_expr.data.n);
25725 new_angle (narg);
25726 p = value_node (cur_exp_node ());
25727 n_arg (narg, value_number (x_part (p)), value_number (y_part (p)));
25728 number_clone (new_expr.data.n, narg);
25729 convert_angle_to_scaled (new_expr.data.n);
25730 free_number (narg);
25731 mp_flush_cur_exp (mp, new_expr);
25732 } else {
25733 mp_bad_unary (mp, mp_angle_op);
25734 }
25735 break;
25736 case mp_x_part:
25737 case mp_y_part:
25738 if ((mp->cur_exp.type == mp_pair_type)
25739 || (mp->cur_exp.type == mp_transform_type))
25740 mp_take_part (mp, c);
25741 else if (mp->cur_exp.type == mp_picture_type)
25742 mp_take_pict_part (mp, c);
25743 else
25744 mp_bad_unary (mp, c);
25745 break;
25746 case mp_xx_part:
25747 case mp_xy_part:
25748 case mp_yx_part:
25749 case mp_yy_part:
25750 if (mp->cur_exp.type == mp_transform_type)
25751 mp_take_part (mp, c);
25752 else if (mp->cur_exp.type == mp_picture_type)
25753 mp_take_pict_part (mp, c);
25754 else
25755 mp_bad_unary (mp, c);
25756 break;
25757 case mp_red_part:
25758 case mp_green_part:
25759 case mp_blue_part:
25760 if (mp->cur_exp.type == mp_color_type)
25761 mp_take_part (mp, c);
25762 else if (mp->cur_exp.type == mp_picture_type) {
25763 if pict_color_type
25764 (mp_rgb_model) mp_take_pict_part (mp, c);
25765 else
25766 mp_bad_color_part (mp, c);
25767 } else
25768 mp_bad_unary (mp, c);
25769 break;
25770 case mp_cyan_part:
25771 case mp_magenta_part:
25772 case mp_yellow_part:
25773 case mp_black_part:
25774 if (mp->cur_exp.type == mp_cmykcolor_type)
25775 mp_take_part (mp, c);
25776 else if (mp->cur_exp.type == mp_picture_type) {
25777 if pict_color_type
25778 (mp_cmyk_model) mp_take_pict_part (mp, c);
25779 else
25780 mp_bad_color_part (mp, c);
25781 } else
25782 mp_bad_unary (mp, c);
25783 break;
25784 case mp_grey_part:
25785 if (mp->cur_exp.type == mp_known);
25786 else if (mp->cur_exp.type == mp_picture_type) {
25787 if pict_color_type
25788 (mp_grey_model) mp_take_pict_part (mp, c);
25789 else
25790 mp_bad_color_part (mp, c);
25791 } else
25792 mp_bad_unary (mp, c);
25793 break;
25794 case mp_color_model_part:
25795 if (mp->cur_exp.type == mp_picture_type)
25796 mp_take_pict_part (mp, c);
25797 else
25798 mp_bad_unary (mp, c);
25799 break;
25800 case mp_font_part:
25801 case mp_text_part:
25802 case mp_path_part:
25803 case mp_pen_part:
25804 case mp_dash_part:
25805 case mp_prescript_part:
25806 case mp_postscript_part:
25807 if (mp->cur_exp.type == mp_picture_type)
25808 mp_take_pict_part (mp, c);
25809 else
25810 mp_bad_unary (mp, c);
25811 break;
25812 case mp_char_op:
25813 if (mp->cur_exp.type != mp_known) {
25814 mp_bad_unary (mp, mp_char_op);
25815 } else {
25816 mpinteger64 vv = round_unscaled (cur_exp_value_number ()) % 256;
25817 set_cur_exp_value_scaled (vv);
25818 mp->cur_exp.type = mp_string_type;
25819 if (number_negative(cur_exp_value_number ())) {
25820 vv = number_to_scaled(cur_exp_value_number ()) + 256;
25821 set_cur_exp_value_scaled (vv);
25822 }
25823 {
25824 unsigned char ss[2];
25825 ss[0] = (unsigned char) number_to_scaled(cur_exp_value_number ());
25826 ss[1] = '\0';
25827 set_cur_exp_str (mp_rtsl (mp, (char *) ss, 1));
25828 }
25829 }
25830 break;
25831 case mp_decimal:
25832 if (mp->cur_exp.type != mp_known) {
25833 mp_bad_unary (mp, mp_decimal);
25834 } else {
25835 mp->old_setting = mp->selector;
25836 mp->selector = new_string;
25837 print_number (cur_exp_value_number ());
25838 set_cur_exp_str (mp_make_string (mp));
25839 mp->selector = mp->old_setting;
25840 mp->cur_exp.type = mp_string_type;
25841 }
25842 break;
25843 case mp_oct_op:
25844 case mp_hex_op:
25845 case mp_ASCII_op:
25846 if (mp->cur_exp.type != mp_string_type)
25847 mp_bad_unary (mp, c);
25848 else
25849 mp_str_to_num (mp, c);
25850 break;
25851 case mp_font_size:
25852 if (mp->cur_exp.type != mp_string_type) {
25853 mp_bad_unary (mp, mp_font_size);
25854 } else {
25855 /* Find the design size of the font whose name is |cur_exp| */
25856 /* One simple application of |find_font| is the implementation of the |font_size|
25857 operator that gets the design size for a given font name. */
25858 memset(&new_expr,0,sizeof(mp_value));
25859 new_number(new_expr.data.n);
25860 set_number_from_scaled (new_expr.data.n,
25861 (mp->font_dsize[mp_find_font (mp, mp_str (mp, cur_exp_str ()))] + 8) / 16);
25862 mp_flush_cur_exp (mp, new_expr);
25863 }
25864 break;
25865 case mp_length_op:
25866 /* The length operation is somewhat unusual in that it applies to a variety
25867 of different types of operands. */
25868 switch (mp->cur_exp.type) {
25869 case mp_string_type:
25870 memset(&new_expr,0,sizeof(mp_value));
25871 new_number(new_expr.data.n);
25872 number_clone (new_expr.data.n, unity_t);
25873 number_multiply_int(new_expr.data.n, cur_exp_str ()->len);
25874 mp_flush_cur_exp (mp, new_expr);
25875 break;
25876 case mp_path_type:
25877 memset(&new_expr,0,sizeof(mp_value));
25878 new_number(new_expr.data.n);
25879 mp_path_length (mp, &new_expr.data.n);
25880 mp_flush_cur_exp (mp, new_expr);
25881 break;
25882 case mp_known:
25883 set_cur_exp_value_number (cur_exp_value_number ());
25884 number_abs (cur_exp_value_number ());
25885 break;
25886 case mp_picture_type:
25887 memset(&new_expr,0,sizeof(mp_value));
25888 new_number(new_expr.data.n);
25889 mp_pict_length (mp, &new_expr.data.n);
25890 mp_flush_cur_exp (mp, new_expr);
25891 break;
25892 default:
25893 if (mp_nice_pair (mp, cur_exp_node (), mp->cur_exp.type)) {
25894 memset(&new_expr,0,sizeof(mp_value));
25895 new_number(new_expr.data.n);
25896 pyth_add (new_expr.data.n, value_number (x_part (value_node (cur_exp_node ()))),
25897 value_number (y_part (value_node (cur_exp_node ()))));
25898 mp_flush_cur_exp (mp, new_expr);
25899 } else
25900 mp_bad_unary (mp, c);
25901 break;
25902 }
25903 break;
25904 case mp_turning_op:
25905 if (mp->cur_exp.type == mp_pair_type) {
25906 memset(&new_expr,0,sizeof(mp_value));
25907 new_number(new_expr.data.n);
25908 set_number_to_zero(new_expr.data.n);
25909 mp_flush_cur_exp (mp, new_expr);
25910 } else if (mp->cur_exp.type != mp_path_type) {
25911 mp_bad_unary (mp, mp_turning_op);
25912 } else if (mp_left_type (cur_exp_knot ()) == mp_endpoint) {
25913 memset(&new_expr,0,sizeof(mp_value));
25914 new_number(new_expr.data.n);
25915 new_expr.data.p = NULL;
25916 mp_flush_cur_exp (mp, new_expr); /* not a cyclic path */
25917 } else {
25918 memset(&new_expr,0,sizeof(mp_value));
25919 new_number(new_expr.data.n);
25920 mp_turn_cycles_wrapper (mp, &new_expr.data.n, cur_exp_knot ());
25921 mp_flush_cur_exp (mp, new_expr);
25922 }
25923 break;
25924 case mp_boolean_type:
25925 memset(&new_expr,0,sizeof(mp_value));
25926 new_number(new_expr.data.n);
25927 type_range (mp_boolean_type, mp_unknown_boolean);
25928 break;
25929 case mp_string_type:
25930 memset(&new_expr,0,sizeof(mp_value));
25931 new_number(new_expr.data.n);
25932 type_range (mp_string_type, mp_unknown_string);
25933 break;
25934 case mp_pen_type:
25935 memset(&new_expr,0,sizeof(mp_value));
25936 new_number(new_expr.data.n);
25937 type_range (mp_pen_type, mp_unknown_pen);
25938 break;
25939 case mp_path_type:
25940 memset(&new_expr,0,sizeof(mp_value));
25941 new_number(new_expr.data.n);
25942 type_range (mp_path_type, mp_unknown_path);
25943 break;
25944 case mp_picture_type:
25945 memset(&new_expr,0,sizeof(mp_value));
25946 new_number(new_expr.data.n);
25947 type_range (mp_picture_type, mp_unknown_picture);
25948 break;
25949 case mp_transform_type:
25950 case mp_color_type:
25951 case mp_cmykcolor_type:
25952 case mp_pair_type:
25953 memset(&new_expr,0,sizeof(mp_value));
25954 new_number(new_expr.data.n);
25955 type_test (c);
25956 break;
25957 case mp_numeric_type:
25958 memset(&new_expr,0,sizeof(mp_value));
25959 new_number(new_expr.data.n);
25960 type_range (mp_known, mp_independent);
25961 break;
25962 case mp_known_op:
25963 case mp_unknown_op:
25964 mp_test_known (mp, c);
25965 break;
25966 case mp_cycle_op:
25967 memset(&new_expr,0,sizeof(mp_value));
25968 new_number(new_expr.data.n);
25969 if (mp->cur_exp.type != mp_path_type)
25970 set_number_from_boolean (new_expr.data.n, mp_false_code);
25971 else if (mp_left_type (cur_exp_knot ()) != mp_endpoint)
25972 set_number_from_boolean (new_expr.data.n, mp_true_code);
25973 else
25974 set_number_from_boolean (new_expr.data.n, mp_false_code);
25975 mp_flush_cur_exp (mp, new_expr);
25976 mp->cur_exp.type = mp_boolean_type;
25977 break;
25978 case mp_arc_length:
25979 if (mp->cur_exp.type == mp_pair_type)
25980 mp_pair_to_path (mp);
25981 if (mp->cur_exp.type != mp_path_type) {
25982 mp_bad_unary (mp, mp_arc_length);
25983 } else {
25984 memset(&new_expr,0,sizeof(mp_value));
25985 new_number(new_expr.data.n);
25986 mp_get_arc_length (mp, &new_expr.data.n, cur_exp_knot ());
25987 mp_flush_cur_exp (mp, new_expr);
25988 }
25989 break;
25990 case mp_filled_op:
25991 case mp_stroked_op:
25992 case mp_textual_op:
25993 case mp_clipped_op:
25994 case mp_bounded_op:
25995 /* Here we use the fact that |c-filled_op+fill_code| is the desired graphical
25996 object |type|. */
25997 @^data structure assumptions@>
25998 memset(&new_expr,0,sizeof(mp_value));
25999 new_number(new_expr.data.n);
26000 if (mp->cur_exp.type != mp_picture_type) {
26001 set_number_from_boolean (new_expr.data.n, mp_false_code);
26002 } else if (mp_link (edge_list (cur_exp_node ())) == NULL) {
26003 set_number_from_boolean (new_expr.data.n, mp_false_code);
26004 } else if (mp_type (mp_link (edge_list (cur_exp_node ()))) ==
26005 (mp_variable_type) (c + mp_fill_node_type - mp_filled_op)) {
26006 set_number_from_boolean (new_expr.data.n, mp_true_code);
26007 } else {
26008 set_number_from_boolean (new_expr.data.n, mp_false_code);
26009 }
26010 mp_flush_cur_exp (mp, new_expr);
26011 mp->cur_exp.type = mp_boolean_type;
26012 break;
26013 case mp_make_pen_op:
26014 if (mp->cur_exp.type == mp_pair_type)
26015 mp_pair_to_path (mp);
26016 if (mp->cur_exp.type != mp_path_type)
26017 mp_bad_unary (mp, mp_make_pen_op);
26018 else {
26019 mp->cur_exp.type = mp_pen_type;
26020 set_cur_exp_knot (mp_make_pen (mp, cur_exp_knot (), true));
26021 }
26022 break;
26023 case mp_make_path_op:
26024 if (mp->cur_exp.type != mp_pen_type) {
26025 mp_bad_unary (mp, mp_make_path_op);
26026 } else {
26027 mp->cur_exp.type = mp_path_type;
26028 mp_make_path (mp, cur_exp_knot ());
26029 }
26030 break;
26031 case mp_reverse:
26032 if (mp->cur_exp.type == mp_path_type) {
26033 mp_knot pk = mp_htap_ypoc (mp, cur_exp_knot ());
26034 if (mp_right_type (pk) == mp_endpoint)
26035 pk = mp_next_knot (pk);
26036 mp_toss_knot_list (mp, cur_exp_knot ());
26037 set_cur_exp_knot (pk);
26038 } else if (mp->cur_exp.type == mp_pair_type) {
26039 mp_pair_to_path (mp);
26040 } else {
26041 mp_bad_unary (mp, mp_reverse);
26042 }
26043 break;
26044 case mp_ll_corner_op:
26045 if (!mp_get_cur_bbox (mp))
26046 mp_bad_unary (mp, mp_ll_corner_op);
26047 else
26048 mp_pair_value (mp, mp_minx, mp_miny);
26049 break;
26050 case mp_lr_corner_op:
26051 if (!mp_get_cur_bbox (mp))
26052 mp_bad_unary (mp, mp_lr_corner_op);
26053 else
26054 mp_pair_value (mp, mp_maxx, mp_miny);
26055 break;
26056 case mp_ul_corner_op:
26057 if (!mp_get_cur_bbox (mp))
26058 mp_bad_unary (mp, mp_ul_corner_op);
26059 else
26060 mp_pair_value (mp, mp_minx, mp_maxy);
26061 break;
26062 case mp_ur_corner_op:
26063 if (!mp_get_cur_bbox (mp))
26064 mp_bad_unary (mp, mp_ur_corner_op);
26065 else
26066 mp_pair_value (mp, mp_maxx, mp_maxy);
26067 break;
26068 case mp_read_from_op:
26069 case mp_close_from_op:
26070 if (mp->cur_exp.type != mp_string_type)
26071 mp_bad_unary (mp, c);
26072 else
26073 mp_do_read_or_close (mp, c);
26074 break;
26075
26076 } /* there are no other cases */
26077 check_arith();
26078 }
26079
26080
26081 @ The |nice_pair| function returns |true| if both components of a pair
26082 are known.
26083
26084 @<Declare unary action procedures@>=
26085 static boolean mp_nice_pair (MP mp, mp_node p, quarterword t) {
26086 (void) mp;
26087 if (t == mp_pair_type) {
26088 p = value_node (p);
26089 if (mp_type (x_part (p)) == mp_known)
26090 if (mp_type (y_part (p)) == mp_known)
26091 return true;
26092 }
26093 return false;
26094 }
26095
26096
26097 @ The |nice_color_or_pair| function is analogous except that it also accepts
26098 fully known colors.
26099
26100 @<Declare unary action procedures@>=
26101 static boolean mp_nice_color_or_pair (MP mp, mp_node p, quarterword t) {
26102 mp_node q;
26103 (void) mp;
26104 switch (t) {
26105 case mp_pair_type:
26106 q = value_node (p);
26107 if (mp_type (x_part (q)) == mp_known)
26108 if (mp_type (y_part (q)) == mp_known)
26109 return true;
26110 break;
26111 case mp_color_type:
26112 q = value_node (p);
26113 if (mp_type (red_part (q)) == mp_known)
26114 if (mp_type (green_part (q)) == mp_known)
26115 if (mp_type (blue_part (q)) == mp_known)
26116 return true;
26117 break;
26118 case mp_cmykcolor_type:
26119 q = value_node (p);
26120 if (mp_type (cyan_part (q)) == mp_known)
26121 if (mp_type (magenta_part (q)) == mp_known)
26122 if (mp_type (yellow_part (q)) == mp_known)
26123 if (mp_type (black_part (q)) == mp_known)
26124 return true;
26125 break;
26126 }
26127 return false;
26128 }
26129
26130
26131 @ @<Declare unary action...@>=
26132 static void mp_print_known_or_unknown_type (MP mp, quarterword t, mp_node v) {
26133 mp_print_char (mp, xord ('('));
26134 if (t > mp_known)
26135 mp_print (mp, "unknown numeric");
26136 else {
26137 if ((t == mp_pair_type) || (t == mp_color_type) || (t == mp_cmykcolor_type))
26138 if (!mp_nice_color_or_pair (mp, v, t))
26139 mp_print (mp, "unknown ");
26140 mp_print_type (mp, t);
26141 }
26142 mp_print_char (mp, xord (')'));
26143 }
26144
26145
26146 @ @<Declare unary action...@>=
26147 static void mp_bad_unary (MP mp, quarterword c) {
26148 char msg[256];
26149 mp_string sname;
26150 int old_setting = mp->selector;
26151 const char *hlp[] = {
26152 "I'm afraid I don't know how to apply that operation to that",
26153 "particular type. Continue, and I'll simply return the",
26154 "argument (shown above) as the result of the operation.",
26155 NULL };
26156 mp->selector = new_string;
26157 mp_print_op (mp, c);
26158 mp_print_known_or_unknown_type (mp, mp->cur_exp.type, cur_exp_node ());
26159 sname = mp_make_string(mp);
26160 mp->selector = old_setting;
26161 mp_snprintf (msg, 256, "Not implemented: %s", mp_str(mp, sname));
26162 delete_str_ref(sname);
26163 mp_disp_err(mp, NULL);
26164 mp_back_error (mp, msg, hlp, true);
26165 @.Not implemented...@>
26166 mp_get_x_next (mp);
26167 }
26168
26169
26170
26171 @ Negation is easy except when the current expression
26172 is of type |independent|, or when it is a pair with one or more
26173 |independent| components.
26174
26175 @<Declare unary action...@>=
26176 static void mp_negate_dep_list (MP mp, mp_value_node p) {
26177 (void) mp;
26178 while (1) {
26179 number_negate (dep_value (p));
26180 if (dep_info (p) == NULL)
26181 return;
26182 p = (mp_value_node) mp_link (p);
26183 }
26184 }
26185
26186
26187 @ It is tempting to argue that the negative of an independent variable
26188 is an independent variable, hence we don't have to do anything when
26189 negating it. The fallacy is that other dependent variables pointing
26190 to the current expression must change the sign of their
26191 coefficients if we make no change to the current expression.
26192
26193 Instead, we work around the problem by copying the current expression
26194 and recycling it afterwards (cf.~the |stash_in| routine).
26195
26196 @d negate_value(A) if (mp_type (A) == mp_known) {
26197 set_value_number(A, (value_number (A))); /* to clear the rest */
26198 number_negate (value_number (A));
26199 } else {
26200 mp_negate_dep_list (mp, (mp_value_node) dep_list ((mp_value_node) A));
26201 }
26202
26203 @<Declare unary action...@>=
26204 static void negate_cur_expr(MP mp) {
26205 mp_node p, q, r; /* for list manipulation */
26206 switch (mp->cur_exp.type) {
26207 case mp_color_type:
26208 case mp_cmykcolor_type:
26209 case mp_pair_type:
26210 case mp_independent:
26211 q = cur_exp_node ();
26212 mp_make_exp_copy (mp, q);
26213 if (mp->cur_exp.type == mp_dependent) {
26214 mp_negate_dep_list (mp, (mp_value_node) dep_list ((mp_value_node)
26215 cur_exp_node ()));
26216 } else if (mp->cur_exp.type <= mp_pair_type) {
26217 /* |mp_color_type| |mp_cmykcolor_type|, or |mp_pair_type| */
26218 p = value_node (cur_exp_node ());
26219 switch (mp->cur_exp.type) {
26220 case mp_pair_type:
26221 r = x_part (p);
26222 negate_value (r);
26223 r = y_part (p);
26224 negate_value (r);
26225 break;
26226 case mp_color_type:
26227 r = red_part (p);
26228 negate_value (r);
26229 r = green_part (p);
26230 negate_value (r);
26231 r = blue_part (p);
26232 negate_value (r);
26233 break;
26234 case mp_cmykcolor_type:
26235 r = cyan_part (p);
26236 negate_value (r);
26237 r = magenta_part (p);
26238 negate_value (r);
26239 r = yellow_part (p);
26240 negate_value (r);
26241 r = black_part (p);
26242 negate_value (r);
26243 break;
26244 default: /* there are no other valid cases, but please the compiler */
26245 break;
26246 }
26247 } /* if |cur_type=mp_known| then |cur_exp=0| */
26248 mp_recycle_value (mp, q);
26249 mp_free_value_node (mp, q);
26250 break;
26251 case mp_dependent:
26252 case mp_proto_dependent:
26253 mp_negate_dep_list (mp, (mp_value_node) dep_list ((mp_value_node)
26254 cur_exp_node ()));
26255 break;
26256 case mp_known:
26257 if (is_number(cur_exp_value_number()))
26258 number_negate (cur_exp_value_number());
26259 break;
26260 default:
26261 mp_bad_unary (mp, mp_minus);
26262 break;
26263 }
26264 }
26265
26266 @ If the current expression is a pair, but the context wants it to
26267 be a path, we call |pair_to_path|.
26268
26269 @<Declare unary action...@>=
26270 static void mp_pair_to_path (MP mp) {
26271 set_cur_exp_knot (mp_pair_to_knot (mp));
26272 mp->cur_exp.type = mp_path_type;
26273 }
26274
26275
26276
26277 @ @<Declarations@>=
26278 static void mp_bad_color_part (MP mp, quarterword c);
26279
26280 @ @c
26281 static void mp_bad_color_part (MP mp, quarterword c) {
26282 mp_node p; /* the big node */
26283 mp_value new_expr;
26284 char msg[256];
26285 int old_setting;
26286 mp_string sname;
26287 const char *hlp[] = {@|
26288 "You can only ask for the redpart, greenpart, bluepart of a rgb object,",
26289 "the cyanpart, magentapart, yellowpart or blackpart of a cmyk object, ",
26290 "or the greypart of a grey object. No mixing and matching, please.",
26291 NULL };
26292 memset(&new_expr,0,sizeof(mp_value));
26293 new_number(new_expr.data.n);
26294 p = mp_link (edge_list (cur_exp_node ()));
26295 mp_disp_err(mp, NULL);
26296 old_setting = mp->selector;
26297 mp->selector = new_string;
26298 mp_print_op (mp, c);
26299 sname = mp_make_string(mp);
26300 mp->selector = old_setting;
26301 @.Wrong picture color model...@>
26302 if (mp_color_model (p) == mp_grey_model)
26303 mp_snprintf (msg, 256, "Wrong picture color model: %s of grey object", mp_str(mp, sname));
26304 else if (mp_color_model (p) == mp_cmyk_model)
26305 mp_snprintf (msg, 256, "Wrong picture color model: %s of cmyk object", mp_str(mp, sname));
26306 else if (mp_color_model (p) == mp_rgb_model)
26307 mp_snprintf (msg, 256, "Wrong picture color model: %s of rgb object", mp_str(mp, sname));
26308 else if (mp_color_model (p) == mp_no_model)
26309 mp_snprintf (msg, 256, "Wrong picture color model: %s of marking object", mp_str(mp, sname));
26310 else
26311 mp_snprintf (msg, 256, "Wrong picture color model: %s of defaulted object", mp_str(mp, sname));
26312 delete_str_ref(sname);
26313 mp_error (mp, msg, hlp, true);
26314 if (c == mp_black_part)
26315 number_clone (new_expr.data.n, unity_t);
26316 else
26317 set_number_to_zero(new_expr.data.n);
26318 mp_flush_cur_exp (mp, new_expr);
26319 }
26320
26321
26322 @ In the following procedure, |cur_exp| points to a capsule, which points to
26323 a big node. We want to delete all but one part of the big node.
26324
26325 @<Declare unary action...@>=
26326 static void mp_take_part (MP mp, quarterword c) {
26327 mp_node p; /* the big node */
26328 p = value_node (cur_exp_node ());
26329 set_value_node (mp->temp_val, p);
26330 mp_type (mp->temp_val) = mp->cur_exp.type;
26331 mp_link (p) = mp->temp_val;
26332 mp_free_value_node (mp, cur_exp_node ());
26333 switch (c) {
26334 case mp_x_part:
26335 if (mp->cur_exp.type == mp_pair_type)
26336 mp_make_exp_copy (mp, x_part (p));
26337 else
26338 mp_make_exp_copy (mp, tx_part (p));
26339 break;
26340 case mp_y_part:
26341 if (mp->cur_exp.type == mp_pair_type)
26342 mp_make_exp_copy (mp, y_part (p));
26343 else
26344 mp_make_exp_copy (mp, ty_part (p));
26345 break;
26346 case mp_xx_part:
26347 mp_make_exp_copy (mp, xx_part (p));
26348 break;
26349 case mp_xy_part:
26350 mp_make_exp_copy (mp, xy_part (p));
26351 break;
26352 case mp_yx_part:
26353 mp_make_exp_copy (mp, yx_part (p));
26354 break;
26355 case mp_yy_part:
26356 mp_make_exp_copy (mp, yy_part (p));
26357 break;
26358 case mp_red_part:
26359 mp_make_exp_copy (mp, red_part (p));
26360 break;
26361 case mp_green_part:
26362 mp_make_exp_copy (mp, green_part (p));
26363 break;
26364 case mp_blue_part:
26365 mp_make_exp_copy (mp, blue_part (p));
26366 break;
26367 case mp_cyan_part:
26368 mp_make_exp_copy (mp, cyan_part (p));
26369 break;
26370 case mp_magenta_part:
26371 mp_make_exp_copy (mp, magenta_part (p));
26372 break;
26373 case mp_yellow_part:
26374 mp_make_exp_copy (mp, yellow_part (p));
26375 break;
26376 case mp_black_part:
26377 mp_make_exp_copy (mp, black_part (p));
26378 break;
26379 }
26380 mp_recycle_value (mp, mp->temp_val);
26381 }
26382
26383
26384 @ @<Initialize table entries@>=
26385 mp->temp_val = mp_get_value_node (mp);
26386 mp_name_type (mp->temp_val) = mp_capsule;
26387
26388 @ @<Free table entries@>=
26389 mp_free_value_node (mp, mp->temp_val);
26390
26391
26392 @ @<Declarations@>=
26393 static mp_edge_header_node mp_scale_edges (MP mp, mp_number se_sf, mp_edge_header_node se_pic);
26394
26395 @ @<Declare unary action...@>=
26396 static void mp_take_pict_part (MP mp, quarterword c) {
26397 mp_node p; /* first graphical object in |cur_exp| */
26398 mp_value new_expr;
26399 memset(&new_expr,0,sizeof(mp_value));
26400 new_number(new_expr.data.n);
26401 p = mp_link (edge_list (cur_exp_node ()));
26402 if (p != NULL) {
26403 switch (c) {
26404 case mp_x_part:
26405 case mp_y_part:
26406 case mp_xx_part:
26407 case mp_xy_part:
26408 case mp_yx_part:
26409 case mp_yy_part:
26410 if (mp_type (p) == mp_text_node_type) {
26411 mp_text_node p0 = (mp_text_node)p;
26412 switch (c) {
26413 case mp_x_part:
26414 number_clone(new_expr.data.n, p0->tx);
26415 break;
26416 case mp_y_part:
26417 number_clone(new_expr.data.n, p0->ty);
26418 break;
26419 case mp_xx_part:
26420 number_clone(new_expr.data.n, p0->txx);
26421 break;
26422 case mp_xy_part:
26423 number_clone(new_expr.data.n, p0->txy);
26424 break;
26425 case mp_yx_part:
26426 number_clone(new_expr.data.n, p0->tyx);
26427 break;
26428 case mp_yy_part:
26429 number_clone(new_expr.data.n, p0->tyy);
26430 break;
26431 }
26432 mp_flush_cur_exp (mp, new_expr);
26433 } else
26434 goto NOT_FOUND;
26435 break;
26436 case mp_red_part:
26437 case mp_green_part:
26438 case mp_blue_part:
26439 if (has_color (p)) {
26440 switch (c) {
26441 case mp_red_part:
26442 number_clone(new_expr.data.n,((mp_stroked_node)p)->red);
26443 break;
26444 case mp_green_part:
26445 number_clone(new_expr.data.n,((mp_stroked_node)p)->green);
26446 break;
26447 case mp_blue_part:
26448 number_clone(new_expr.data.n,((mp_stroked_node)p)->blue);
26449 break;
26450 }
26451 mp_flush_cur_exp (mp, new_expr);
26452 } else
26453 goto NOT_FOUND;
26454 break;
26455 case mp_cyan_part:
26456 case mp_magenta_part:
26457 case mp_yellow_part:
26458 case mp_black_part:
26459 if (has_color (p)) {
26460 if (mp_color_model (p) == mp_uninitialized_model && c == mp_black_part) {
26461 set_number_to_unity(new_expr.data.n);
26462 } else {
26463 switch (c) {
26464 case mp_cyan_part:
26465 number_clone(new_expr.data.n,((mp_stroked_node)p)->cyan);
26466 break;
26467 case mp_magenta_part:
26468 number_clone(new_expr.data.n,((mp_stroked_node)p)->magenta);
26469 break;
26470 case mp_yellow_part:
26471 number_clone(new_expr.data.n,((mp_stroked_node)p)->yellow);
26472 break;
26473 case mp_black_part:
26474 number_clone(new_expr.data.n,((mp_stroked_node)p)->black);
26475 break;
26476 }
26477 }
26478 mp_flush_cur_exp (mp, new_expr);
26479 } else
26480 goto NOT_FOUND;
26481 break;
26482 case mp_grey_part:
26483 if (has_color (p)) {
26484 number_clone(new_expr.data.n,((mp_stroked_node)p)->grey);
26485 mp_flush_cur_exp (mp, new_expr);
26486 } else
26487 goto NOT_FOUND;
26488 break;
26489 case mp_color_model_part:
26490 if (has_color (p)) {
26491 if (mp_color_model (p) == mp_uninitialized_model) {
26492 number_clone (new_expr.data.n, internal_value (mp_default_color_model));
26493 } else {
26494 number_clone (new_expr.data.n, unity_t);
26495 number_multiply_int (new_expr.data.n, mp_color_model (p));
26496 }
26497 mp_flush_cur_exp (mp, new_expr);
26498 } else
26499 goto NOT_FOUND;
26500 break;
26501 case mp_text_part:
26502 if (mp_type (p) != mp_text_node_type)
26503 goto NOT_FOUND;
26504 else {
26505 new_expr.data.str = mp_text_p (p);
26506 add_str_ref (new_expr.data.str);
26507 mp_flush_cur_exp (mp, new_expr);
26508 mp->cur_exp.type = mp_string_type;
26509 }
26510 break;
26511 case mp_prescript_part:
26512 if (!has_color (p)) {
26513 goto NOT_FOUND;
26514 } else {
26515 if (mp_pre_script(p)) {
26516 new_expr.data.str = mp_pre_script(p);
26517 add_str_ref (new_expr.data.str);
26518 } else {
26519 new_expr.data.str = mp_rts(mp,"");
26520 }
26521 mp_flush_cur_exp (mp, new_expr);
26522 mp->cur_exp.type = mp_string_type;
26523 }
26524 break;
26525 case mp_postscript_part:
26526 if (!has_color (p)) {
26527 goto NOT_FOUND;
26528 } else {
26529 if (mp_post_script(p)) {
26530 new_expr.data.str = mp_post_script(p);
26531 add_str_ref (new_expr.data.str);
26532 } else {
26533 new_expr.data.str = mp_rts(mp,"");
26534 }
26535 mp_flush_cur_exp (mp, new_expr);
26536 mp->cur_exp.type = mp_string_type;
26537 }
26538 break;
26539 case mp_font_part:
26540 if (mp_type (p) != mp_text_node_type)
26541 goto NOT_FOUND;
26542 else {
26543 new_expr.data.str = mp_rts (mp, mp->font_name[mp_font_n (p)]);
26544 add_str_ref (new_expr.data.str);
26545 mp_flush_cur_exp (mp, new_expr);
26546 mp->cur_exp.type = mp_string_type;
26547 }
26548 break;
26549 case mp_path_part:
26550 if (mp_type (p) == mp_text_node_type) {
26551 goto NOT_FOUND;
26552 } else if (is_stop (p)) {
26553 mp_confusion (mp, "pict");
26554 } else {
26555 new_expr.data.node = NULL;
26556 switch (mp_type (p)) {
26557 case mp_fill_node_type:
26558 new_expr.data.p = mp_copy_path (mp, mp_path_p ((mp_fill_node) p));
26559 break;
26560 case mp_stroked_node_type:
26561 new_expr.data.p = mp_copy_path (mp, mp_path_p ((mp_stroked_node) p));
26562 break;
26563 case mp_start_bounds_node_type:
26564 new_expr.data.p = mp_copy_path (mp, mp_path_p ((mp_start_bounds_node) p));
26565 break;
26566 case mp_start_clip_node_type:
26567 new_expr.data.p = mp_copy_path (mp, mp_path_p ((mp_start_clip_node) p));
26568 break;
26569 default:
26570 assert (0);
26571 break;
26572 }
26573 mp_flush_cur_exp (mp, new_expr);
26574 mp->cur_exp.type = mp_path_type;
26575 }
26576 break;
26577 case mp_pen_part:
26578 if (!has_pen (p)) {
26579 goto NOT_FOUND;
26580 } else {
26581 switch (mp_type (p)) {
26582 case mp_fill_node_type:
26583 if (mp_pen_p ((mp_fill_node) p) == NULL)
26584 goto NOT_FOUND;
26585 else {
26586 new_expr.data.p = copy_pen (mp_pen_p ((mp_fill_node) p));
26587 mp_flush_cur_exp (mp, new_expr);
26588 mp->cur_exp.type = mp_pen_type;
26589 }
26590 break;
26591 case mp_stroked_node_type:
26592 if (mp_pen_p ((mp_stroked_node) p) == NULL)
26593 goto NOT_FOUND;
26594 else {
26595 new_expr.data.p = copy_pen (mp_pen_p ((mp_stroked_node) p));
26596 mp_flush_cur_exp (mp, new_expr);
26597 mp->cur_exp.type = mp_pen_type;
26598 }
26599 break;
26600 default:
26601 assert (0);
26602 break;
26603 }
26604 }
26605 break;
26606 case mp_dash_part:
26607 if (mp_type (p) != mp_stroked_node_type) {
26608 goto NOT_FOUND;
26609 } else {
26610 if (mp_dash_p (p) == NULL) {
26611 goto NOT_FOUND;
26612 } else {
26613 add_edge_ref (mp_dash_p (p));
26614 new_expr.data.node = (mp_node)mp_scale_edges (mp, ((mp_stroked_node)p)->dash_scale,
26615 (mp_edge_header_node)mp_dash_p (p));
26616 mp_flush_cur_exp (mp, new_expr);
26617 mp->cur_exp.type = mp_picture_type;
26618 }
26619 }
26620 break;
26621 } /* all cases have been enumerated */
26622 return;
26623 }
26624 NOT_FOUND:
26625 /* Convert the current expression to a NULL value appropriate for |c| */
26626 switch (c) {
26627 case mp_text_part:
26628 case mp_font_part:
26629 case mp_prescript_part:
26630 case mp_postscript_part:
26631 new_expr.data.str = mp_rts(mp,"");
26632 mp_flush_cur_exp (mp, new_expr);
26633 mp->cur_exp.type = mp_string_type;
26634 break;
26635 case mp_path_part:
26636 new_expr.data.p = mp_new_knot (mp);
26637 mp_flush_cur_exp (mp, new_expr);
26638 mp_left_type (cur_exp_knot ()) = mp_endpoint;
26639 mp_right_type (cur_exp_knot ()) = mp_endpoint;
26640 mp_next_knot (cur_exp_knot ()) = cur_exp_knot ();
26641 set_number_to_zero(cur_exp_knot ()->x_coord);
26642 set_number_to_zero(cur_exp_knot ()->y_coord);
26643 mp_originator (cur_exp_knot ()) = mp_metapost_user;
26644 mp->cur_exp.type = mp_path_type;
26645 break;
26646 case mp_pen_part:
26647 new_expr.data.p = mp_get_pen_circle (mp, zero_t);
26648 mp_flush_cur_exp (mp, new_expr);
26649 mp->cur_exp.type = mp_pen_type;
26650 break;
26651 case mp_dash_part:
26652 new_expr.data.node = (mp_node)mp_get_edge_header_node (mp);
26653 mp_flush_cur_exp (mp, new_expr);
26654 mp_init_edges (mp, (mp_edge_header_node)cur_exp_node ());
26655 mp->cur_exp.type = mp_picture_type;
26656 break;
26657 default:
26658 set_number_to_zero(new_expr.data.n);
26659 mp_flush_cur_exp (mp, new_expr);
26660 break;
26661 }
26662 }
26663
26664 @ @<Declare unary action...@>=
26665 static void mp_str_to_num (MP mp, quarterword c) { /* converts a string to a number */
26666 integer n; /* accumulator */
26667 ASCII_code m; /* current character */
26668 unsigned k; /* index into |str_pool| */
26669 int b; /* radix of conversion */
26670 boolean bad_char; /* did the string contain an invalid digit? */
26671 mp_value new_expr;
26672 memset(&new_expr,0,sizeof(mp_value));
26673 new_number(new_expr.data.n);
26674 if (c == mp_ASCII_op) {
26675 if (cur_exp_str ()->len == 0)
26676 n = -1;
26677 else
26678 n = cur_exp_str ()->str[0];
26679 } else {
26680 if (c == mp_oct_op)
26681 b = 8;
26682 else
26683 b = 16;
26684 n = 0;
26685 bad_char = false;
26686 for (k = 0; k < cur_exp_str ()->len; k++) {
26687 m = (ASCII_code) (*(cur_exp_str ()->str + k));
26688 if ((m >= '0') && (m <= '9'))
26689 m = (ASCII_code) (m - '0');
26690 else if ((m >= 'A') && (m <= 'F'))
26691 m = (ASCII_code) (m - 'A' + 10);
26692 else if ((m >= 'a') && (m <= 'f'))
26693 m = (ASCII_code) (m - 'a' + 10);
26694 else {
26695 bad_char = true;
26696 m = 0;
26697 }
26698 if ((int) m >= b) {
26699 bad_char = true;
26700 m = 0;
26701 }
26702 if (n < 32768 / b)
26703 n = n * b + m;
26704 else
26705 n = 32767;
26706 }
26707 /* Give error messages if |bad_char| or |n>=4096| */
26708 if (bad_char) {
26709 const char *hlp[] = {"I zeroed out characters that weren't hex digits.", NULL};
26710 if (c == mp_oct_op) {
26711 hlp[0] = "I zeroed out characters that weren't in the range 0..7.";
26712 }
26713 mp_disp_err(mp, NULL);
26714 mp_back_error (mp, "String contains illegal digits", hlp, true);
26715 mp_get_x_next (mp);
26716 }
26717 if ((n > 4095)) { /* TODO: this is scaled specific */
26718 if (number_positive (internal_value (mp_warning_check))) {
26719 char msg[256];
26720 const char *hlp[] = {
26721 "I have trouble with numbers greater than 4095; watch out.",
26722 "(Set warningcheck:=0 to suppress this message.)",
26723 NULL };
26724 mp_snprintf (msg, 256,"Number too large (%d)", (int)n);
26725 mp_back_error (mp, msg, hlp, true);
26726 mp_get_x_next (mp);
26727 }
26728 }
26729 }
26730 number_clone (new_expr.data.n, unity_t);
26731 number_multiply_int(new_expr.data.n, n);
26732 mp_flush_cur_exp (mp, new_expr);
26733 }
26734
26735 @ @<Declare unary action...@>=
26736 static void mp_path_length (MP mp, mp_number *n) { /* computes the length of the current path */
26737 mp_knot p; /* traverser */
26738 set_number_to_zero (*n);
26739 p = cur_exp_knot ();
26740 if (mp_left_type (p) == mp_endpoint) {
26741 number_substract(*n, unity_t); /* -unity */
26742 }
26743 do {
26744 p = mp_next_knot (p);
26745 number_add(*n, unity_t);
26746 } while (p != cur_exp_knot ());
26747 }
26748
26749
26750 @ @<Declare unary action...@>=
26751 static void mp_pict_length (MP mp, mp_number *n) {
26752 /* counts interior components in picture |cur_exp| */
26753 mp_node p; /* traverser */
26754 set_number_to_zero (*n);
26755 p = mp_link (edge_list (cur_exp_node ()));
26756 if (p != NULL) {
26757 if (is_start_or_stop (p))
26758 if (mp_skip_1component (mp, p) == NULL)
26759 p = mp_link (p);
26760 while (p != NULL) {
26761 if ( ! is_start_or_stop(p) )
26762 p = mp_link(p);
26763 else if ( ! is_stop(p))
26764 p = mp_skip_1component(mp, p);
26765 else
26766 return;
26767 number_add(*n, unity_t);
26768 }
26769 }
26770 }
26771
26772
26773 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
26774 argument is |origin|.
26775
26776 @<Declare unary action...@>=
26777 static void mp_an_angle (MP mp, mp_number *ret, mp_number xpar, mp_number ypar) {
26778 set_number_to_zero (*ret);
26779 if ((!(number_zero(xpar) && number_zero(ypar)))) {
26780 n_arg (*ret, xpar, ypar);
26781 }
26782 }
26783
26784
26785 @ The actual turning number is (for the moment) computed in a C function
26786 that receives eight integers corresponding to the four controlling points,
26787 and returns a single angle. Besides those, we have to account for discrete
26788 moves at the actual points.
26789
26790 @d mp_floor(a) ((a)>=0 ? (int)(a) : -(int)(-(a)))
26791 @d bezier_error (720*(256*256*16))+1
26792 @d mp_sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
26793 @d mp_out(A) (double)((A)/16)
26794
26795 @<Declare unary action...@>=
26796 static void mp_bezier_slope (MP mp, mp_number *ret, mp_number AX, mp_number AY, mp_number BX,
26797 mp_number BY, mp_number CX, mp_number CY, mp_number DX,
26798 mp_number DY);
26799
26800 @ @c
26801 static void mp_bezier_slope (MP mp, mp_number *ret, mp_number AX, mp_number AY, mp_number BX,
26802 mp_number BY, mp_number CX, mp_number CY, mp_number DX,
26803 mp_number DY) {
26804 double a, b, c;
26805 mp_number deltax, deltay;
26806 double ax, ay, bx, by, cx, cy, dx, dy;
26807 mp_number xi, xo, xm;
26808 double res = 0;
26809 ax = number_to_double (AX);
26810 ay = number_to_double (AY);
26811 bx = number_to_double (BX);
26812 by = number_to_double (BY);
26813 cx = number_to_double (CX);
26814 cy = number_to_double (CY);
26815 dx = number_to_double (DX);
26816 dy = number_to_double (DY);
26817 new_number (deltax);
26818 new_number (deltay);
26819 set_number_from_substraction(deltax, BX, AX);
26820 set_number_from_substraction(deltay, BY, AY);
26821 if (number_zero(deltax) && number_zero(deltay)) {
26822 set_number_from_substraction(deltax, CX, AX);
26823 set_number_from_substraction(deltay, CY, AY);
26824 }
26825 if (number_zero(deltax) && number_zero(deltay)) {
26826 set_number_from_substraction(deltax, DX, AX);
26827 set_number_from_substraction(deltay, DY, AY);
26828 }
26829 new_number (xi);
26830 new_number (xm);
26831 new_number (xo);
26832 mp_an_angle (mp, &xi, deltax, deltay);
26833 set_number_from_substraction(deltax, CX, BX);
26834 set_number_from_substraction(deltay, CY, BY);
26835 mp_an_angle (mp, &xm, deltax, deltay); /* !!! never used? */
26836 set_number_from_substraction(deltax, DX, CX);
26837 set_number_from_substraction(deltay, DY, CY);
26838 if (number_zero(deltax) && number_zero(deltay)) {
26839 set_number_from_substraction(deltax, DX, BX);
26840 set_number_from_substraction(deltay, DY, BY);
26841 }
26842 if (number_zero(deltax) && number_zero(deltay)) {
26843 set_number_from_substraction(deltax, DX, AX);
26844 set_number_from_substraction(deltay, DY, AY);
26845 }
26846 mp_an_angle (mp, &xo, deltax, deltay);
26847 a = (bx - ax) * (cy - by) - (cx - bx) * (by - ay); /* a = (bp-ap)x(cp-bp); */
26848 b = (bx - ax) * (dy - cy) - (by - ay) * (dx - cx); /* b = (bp-ap)x(dp-cp); */
26849 c = (cx - bx) * (dy - cy) - (dx - cx) * (cy - by); /* c = (cp-bp)x(dp-cp); */
26850 if ((a == 0) && (c == 0)) {
26851 res = (b == 0 ? 0 : (mp_out (number_to_double(xo)) - mp_out (number_to_double(xi))));
26852 } else if ((a == 0) || (c == 0)) {
26853 if ((mp_sign (b) == mp_sign (a)) || (mp_sign (b) == mp_sign (c))) {
26854 res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi)); /* ? */
26855 if (res < -180.0)
26856 res += 360.0;
26857 else if (res > 180.0)
26858 res -= 360.0;
26859 } else {
26860 res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi)); /* ? */
26861 }
26862 } else if ((mp_sign (a) * mp_sign (c)) < 0) {
26863 res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi)); /* ? */
26864 if (res < -180.0)
26865 res += 360.0;
26866 else if (res > 180.0)
26867 res -= 360.0;
26868 } else {
26869 if (mp_sign (a) == mp_sign (b)) {
26870 res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi)); /* ? */
26871 if (res < -180.0)
26872 res += 360.0;
26873 else if (res > 180.0)
26874 res -= 360.0;
26875 } else {
26876 if ((b * b) == (4 * a * c)) {
26877 res = (double) bezier_error;
26878 } else if ((b * b) < (4 * a * c)) {
26879 res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi)); /* ? */
26880 if (res <= 0.0 && res > -180.0)
26881 res += 360.0;
26882 else if (res >= 0.0 && res < 180.0)
26883 res -= 360.0;
26884 } else {
26885 res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi));
26886 if (res < -180.0)
26887 res += 360.0;
26888 else if (res > 180.0)
26889 res -= 360.0;
26890 }
26891 }
26892 }
26893 free_number (deltax);
26894 free_number (deltay);
26895 free_number (xi);
26896 free_number (xo);
26897 free_number (xm);
26898 set_number_from_double(*ret, res);
26899 convert_scaled_to_angle (*ret);
26900 }
26901
26902
26903 @
26904 @d p_nextnext mp_next_knot(mp_next_knot(p))
26905 @d p_next mp_next_knot(p)
26906
26907 @<Declare unary action...@>=
26908 static void mp_turn_cycles (MP mp, mp_number *turns, mp_knot c) {
26909 mp_angle res, ang; /* the angles of intermediate results */
26910 mp_knot p; /* for running around the path */
26911 mp_number xp, yp; /* coordinates of next point */
26912 mp_number x, y; /* helper coordinates */
26913 mp_number arg1, arg2;
26914 mp_angle in_angle, out_angle; /* helper angles */
26915 mp_angle seven_twenty_deg_t, neg_one_eighty_deg_t;
26916 unsigned old_setting; /* saved |selector| setting */
26917 set_number_to_zero(*turns);
26918 new_number(arg1);
26919 new_number(arg2);
26920 new_number(xp);
26921 new_number(yp);
26922 new_number(x);
26923 new_number(y);
26924 new_angle(in_angle);
26925 new_angle(out_angle);
26926 new_angle(ang);
26927 new_angle(res);
26928 new_angle(seven_twenty_deg_t);
26929 new_angle(neg_one_eighty_deg_t);
26930 number_clone(seven_twenty_deg_t, three_sixty_deg_t);
26931 number_double(seven_twenty_deg_t);
26932 number_clone(neg_one_eighty_deg_t, one_eighty_deg_t);
26933 number_negate(neg_one_eighty_deg_t);
26934 p = c;
26935 old_setting = mp->selector;
26936 mp->selector = term_only;
26937 if (number_greater (internal_value (mp_tracing_commands), unity_t)) {
26938 mp_begin_diagnostic (mp);
26939 mp_print_nl (mp, "");
26940 mp_end_diagnostic (mp, false);
26941 }
26942 do {
26943 number_clone (xp, p_next->x_coord);
26944 number_clone (yp, p_next->y_coord);
26945 mp_bezier_slope (mp, &ang, p->x_coord, p->y_coord, p->right_x, p->right_y,
26946 p_next->left_x, p_next->left_y, xp, yp);
26947 if (number_greater(ang, seven_twenty_deg_t)) {
26948 mp_error (mp, "Strange path", NULL, true);
26949 mp->selector = old_setting;
26950 set_number_to_zero(*turns);
26951 goto DONE;
26952 }
26953 number_add(res, ang);
26954 if (number_greater(res, one_eighty_deg_t)) {
26955 number_substract(res, three_sixty_deg_t);
26956 number_add(*turns, unity_t);
26957 }
26958 if (number_lessequal(res, neg_one_eighty_deg_t)) {
26959 number_add(res, three_sixty_deg_t);
26960 number_substract(*turns, unity_t);
26961 }
26962 /* incoming angle at next point */
26963 number_clone (x, p_next->left_x);
26964 number_clone (y, p_next->left_y);
26965 if (number_equal(xp, x) && number_equal(yp, y)) {
26966 number_clone (x, p->right_x);
26967 number_clone (y, p->right_y);
26968 }
26969 if (number_equal(xp, x) && number_equal(yp, y)) {
26970 number_clone (x, p->x_coord);
26971 number_clone (y, p->y_coord);
26972 }
26973 set_number_from_substraction(arg1, xp, x);
26974 set_number_from_substraction(arg2, yp, y);
26975 mp_an_angle (mp, &in_angle, arg1, arg2);
26976 /* outgoing angle at next point */
26977 number_clone (x, p_next->right_x);
26978 number_clone (y, p_next->right_y);
26979 if (number_equal(xp, x) && number_equal(yp, y)) {
26980 number_clone (x, p_nextnext->left_x);
26981 number_clone (y, p_nextnext->left_y);
26982 }
26983 if (number_equal(xp, x) && number_equal(yp, y)) {
26984 number_clone (x, p_nextnext->x_coord);
26985 number_clone (y, p_nextnext->y_coord);
26986 }
26987 set_number_from_substraction(arg1, x, xp);
26988 set_number_from_substraction(arg2, y, yp);
26989 mp_an_angle (mp, &out_angle, arg1, arg2);
26990 set_number_from_substraction(ang, out_angle, in_angle);
26991 mp_reduce_angle (mp, &ang);
26992 if (number_nonzero(ang)) {
26993 number_add(res, ang);
26994 if (number_greaterequal(res, one_eighty_deg_t)) {
26995 number_substract(res, three_sixty_deg_t);
26996 number_add(*turns, unity_t);
26997 }
26998 if (number_lessequal(res, neg_one_eighty_deg_t)) {
26999 number_add(res, three_sixty_deg_t);
27000 number_substract(*turns, unity_t);
27001 }
27002 }
27003 p = mp_next_knot (p);
27004 } while (p != c);
27005 mp->selector = old_setting;
27006 DONE:
27007 free_number(xp);
27008 free_number(yp);
27009 free_number(x);
27010 free_number(y);
27011 free_number(seven_twenty_deg_t);
27012 free_number(neg_one_eighty_deg_t);
27013 free_number(in_angle);
27014 free_number(out_angle);
27015 free_number(ang);
27016 free_number(res);
27017 free_number(arg1);
27018 free_number(arg2);
27019 }
27020
27021 @ @<Declare unary action...@>=
27022 static void mp_turn_cycles_wrapper (MP mp, mp_number *ret, mp_knot c) {
27023 if (mp_next_knot (c) == c) {
27024 /* one-knot paths always have a turning number of 1 */
27025 set_number_to_unity(*ret);
27026 } else {
27027 mp_turn_cycles (mp, ret, c);
27028 }
27029 }
27030
27031 @ @<Declare unary action procedures@>=
27032 static void mp_test_known (MP mp, quarterword c) {
27033 int b; /* is the current expression known? */
27034 mp_node p; /* location in a big node */
27035 mp_value new_expr;
27036 memset(&new_expr,0,sizeof(mp_value));
27037 new_number(new_expr.data.n);
27038 b = mp_false_code;
27039 switch (mp->cur_exp.type) {
27040 case mp_vacuous:
27041 case mp_boolean_type:
27042 case mp_string_type:
27043 case mp_pen_type:
27044 case mp_path_type:
27045 case mp_picture_type:
27046 case mp_known:
27047 b = mp_true_code;
27048 break;
27049 case mp_transform_type:
27050 p = value_node (cur_exp_node ());
27051 if (mp_type (tx_part (p)) != mp_known)
27052 break;
27053 if (mp_type (ty_part (p)) != mp_known)
27054 break;
27055 if (mp_type (xx_part (p)) != mp_known)
27056 break;
27057 if (mp_type (xy_part (p)) != mp_known)
27058 break;
27059 if (mp_type (yx_part (p)) != mp_known)
27060 break;
27061 if (mp_type (yy_part (p)) != mp_known)
27062 break;
27063 b = mp_true_code;
27064 break;
27065 case mp_color_type:
27066 p = value_node (cur_exp_node ());
27067 if (mp_type (red_part (p)) != mp_known)
27068 break;
27069 if (mp_type (green_part (p)) != mp_known)
27070 break;
27071 if (mp_type (blue_part (p)) != mp_known)
27072 break;
27073 b = mp_true_code;
27074 break;
27075 case mp_cmykcolor_type:
27076 p = value_node (cur_exp_node ());
27077 if (mp_type (cyan_part (p)) != mp_known)
27078 break;
27079 if (mp_type (magenta_part (p)) != mp_known)
27080 break;
27081 if (mp_type (yellow_part (p)) != mp_known)
27082 break;
27083 if (mp_type (black_part (p)) != mp_known)
27084 break;
27085 b = mp_true_code;
27086 break;
27087 case mp_pair_type:
27088 p = value_node (cur_exp_node ());
27089 if (mp_type (x_part (p)) != mp_known)
27090 break;
27091 if (mp_type (y_part (p)) != mp_known)
27092 break;
27093 b = mp_true_code;
27094 break;
27095 default:
27096 break;
27097 }
27098 if (c == mp_known_op) {
27099 set_number_from_boolean (new_expr.data.n, b);
27100 } else {
27101 if (b==mp_true_code) {
27102 set_number_from_boolean (new_expr.data.n, mp_false_code);
27103 } else {
27104 set_number_from_boolean (new_expr.data.n, mp_true_code);
27105 }
27106 }
27107 mp_flush_cur_exp (mp, new_expr);
27108 cur_exp_node() = NULL; /* !! do not replace with |set_cur_exp_node()| !! */
27109 mp->cur_exp.type = mp_boolean_type;
27110 }
27111
27112 @ The |pair_value| routine changes the current expression to a
27113 given ordered pair of values.
27114
27115 @<Declare unary action procedures@>=
27116 static void mp_pair_value (MP mp, mp_number x, mp_number y) {
27117 mp_node p; /* a pair node */
27118 mp_value new_expr;
27119 mp_number x1, y1;
27120 new_number(x1);
27121 new_number(y1);
27122 number_clone (x1, x);
27123 number_clone (y1, y);
27124 memset(&new_expr,0,sizeof(mp_value));
27125 new_number(new_expr.data.n);
27126 p = mp_get_value_node (mp);
27127 new_expr.type = mp_type (p);
27128 new_expr.data.node = p;
27129 mp_flush_cur_exp (mp, new_expr);
27130 mp->cur_exp.type = mp_pair_type;
27131 mp_name_type (p) = mp_capsule;
27132 mp_init_pair_node (mp, p);
27133 p = value_node (p);
27134 mp_type (x_part (p)) = mp_known;
27135 set_value_number (x_part (p), x1);
27136 mp_type (y_part (p)) = mp_known;
27137 set_value_number (y_part (p), y1);
27138 free_number(x1);
27139 free_number(y1);
27140 }
27141
27142
27143 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
27144 box of the current expression. The boolean result is |false| if the expression
27145 has the wrong type.
27146
27147 @<Declare unary action procedures@>=
27148 static boolean mp_get_cur_bbox (MP mp) {
27149 switch (mp->cur_exp.type) {
27150 case mp_picture_type:
27151 {
27152 mp_edge_header_node p0 = (mp_edge_header_node)cur_exp_node ();
27153 mp_set_bbox (mp, p0, true);
27154 if (number_greater(p0->minx, p0->maxx)) {
27155 set_number_to_zero(mp_minx);
27156 set_number_to_zero(mp_maxx);
27157 set_number_to_zero(mp_miny);
27158 set_number_to_zero(mp_maxy);
27159 } else {
27160 number_clone (mp_minx, p0->minx);
27161 number_clone (mp_maxx, p0->maxx);
27162 number_clone (mp_miny, p0->miny);
27163 number_clone (mp_maxy, p0->maxy);
27164 }
27165 }
27166 break;
27167 case mp_path_type:
27168 mp_path_bbox (mp, cur_exp_knot ());
27169 break;
27170 case mp_pen_type:
27171 mp_pen_bbox (mp, cur_exp_knot ());
27172 break;
27173 default:
27174 return false;
27175 }
27176 return true;
27177 }
27178
27179
27180 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
27181 a line from the file or to close the file.
27182
27183 @<Declare unary action procedures@>=
27184 static void mp_do_read_or_close (MP mp, quarterword c) {
27185 mp_value new_expr;
27186 readf_index n, n0; /* indices for searching |rd_fname| */
27187 memset(&new_expr,0,sizeof(mp_value));
27188 new_number(new_expr.data.n);
27189 /* Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
27190 call |start_read_input| and |goto found| or |not_found| */
27191 /* Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
27192 |rd_fname|. */
27193 {
27194 char *fn;
27195 n = mp->read_files;
27196 n0 = mp->read_files;
27197 fn = mp_xstrdup (mp, mp_str (mp, cur_exp_str ()));
27198 while (mp_xstrcmp (fn, mp->rd_fname[n]) != 0) {
27199 if (n > 0) {
27200 decr (n);
27201 } else if (c == mp_close_from_op) {
27202 goto CLOSE_FILE;
27203 } else {
27204 if (n0 == mp->read_files) {
27205 if (mp->read_files < mp->max_read_files) {
27206 incr (mp->read_files);
27207 } else {
27208 void **rd_file;
27209 char **rd_fname;
27210 readf_index l, k;
27211 l = mp->max_read_files + (mp->max_read_files / 4);
27212 rd_file = xmalloc ((l + 1), sizeof (void *));
27213 rd_fname = xmalloc ((l + 1), sizeof (char *));
27214 for (k = 0; k <= l; k++) {
27215 if (k <= mp->max_read_files) {
27216 rd_file[k] = mp->rd_file[k];
27217 rd_fname[k] = mp->rd_fname[k];
27218 } else {
27219 rd_file[k] = 0;
27220 rd_fname[k] = NULL;
27221 }
27222 }
27223 xfree (mp->rd_file);
27224 xfree (mp->rd_fname);
27225 mp->max_read_files = l;
27226 mp->rd_file = rd_file;
27227 mp->rd_fname = rd_fname;
27228 }
27229 }
27230 n = n0;
27231 if (mp_start_read_input (mp, fn, n))
27232 goto FOUND;
27233 else
27234 goto NOT_FOUND;
27235 }
27236 if (mp->rd_fname[n] == NULL) {
27237 n0 = n;
27238 }
27239 }
27240 if (c == mp_close_from_op) {
27241 (mp->close_file) (mp, mp->rd_file[n]);
27242 goto NOT_FOUND;
27243 }
27244 }
27245 mp_begin_file_reading (mp);
27246 name = is_read;
27247 if (mp_input_ln (mp, mp->rd_file[n]))
27248 goto FOUND;
27249 mp_end_file_reading (mp);
27250 NOT_FOUND:
27251 /* Record the end of file and set |cur_exp| to a dummy value */
27252 xfree (mp->rd_fname[n]);
27253 mp->rd_fname[n] = NULL;
27254 if (n == mp->read_files - 1)
27255 mp->read_files = n;
27256 if (c == mp_close_from_op)
27257 goto CLOSE_FILE;
27258 new_expr.data.str = mp->eof_line;
27259 add_str_ref (new_expr.data.str);
27260 mp_flush_cur_exp (mp, new_expr);
27261 mp->cur_exp.type = mp_string_type;
27262 return;
27263 CLOSE_FILE:
27264 mp_flush_cur_exp (mp, new_expr);
27265 mp->cur_exp.type = mp_vacuous;
27266 return;
27267 FOUND:
27268 mp_flush_cur_exp (mp, new_expr);
27269 mp_finish_read (mp);
27270 }
27271
27272 @ The string denoting end-of-file is a one-byte string at position zero, by definition.
27273 I have to cheat a little here because
27274
27275 @<Glob...@>=
27276 mp_string eof_line;
27277
27278 @ @<Set init...@>=
27279 mp->eof_line = mp_rtsl (mp, "\0", 1);
27280 mp->eof_line->refs = MAX_STR_REF;
27281
27282 @ Finally, we have the operations that combine a capsule~|p|
27283 with the current expression.
27284
27285 Several of the binary operations are potentially complicated by the
27286 fact that |independent| values can sneak into capsules. For example,
27287 we've seen an instance of this difficulty in the unary operation
27288 of negation. In order to reduce the number of cases that need to be
27289 handled, we first change the two operands (if necessary)
27290 to rid them of |independent| components. The original operands are
27291 put into capsules called |old_p| and |old_exp|, which will be
27292 recycled after the binary operation has been safely carried out.
27293
27294 @d binary_return { mp_finish_binary(mp, old_p, old_exp); return; }
27295
27296 @c
27297 @<Declare binary action procedures@>
27298 static void mp_finish_binary (MP mp, mp_node old_p, mp_node old_exp) {
27299 check_arith();
27300 /* Recycle any sidestepped |independent| capsules */
27301 if (old_p != NULL) {
27302 mp_recycle_value (mp, old_p);
27303 mp_free_value_node (mp, old_p);
27304 }
27305 if (old_exp != NULL) {
27306 mp_recycle_value (mp, old_exp);
27307 mp_free_value_node (mp, old_exp);
27308 }
27309 }
27310 static void mp_do_binary (MP mp, mp_node p, integer c) {
27311 mp_node q, r, rr; /* for list manipulation */
27312 mp_node old_p, old_exp; /* capsules to recycle */
27313 mp_value new_expr;
27314 check_arith();
27315 if (number_greater (internal_value (mp_tracing_commands), two_t)) {
27316 /* Trace the current binary operation */
27317 mp_begin_diagnostic (mp);
27318 mp_print_nl (mp, "{(");
27319 mp_print_exp (mp, p, 0); /* show the operand, but not verbosely */
27320 mp_print_char (mp, xord (')'));
27321 mp_print_op (mp, (quarterword) c);
27322 mp_print_char (mp, xord ('('));
27323 mp_print_exp (mp, NULL, 0);
27324 mp_print (mp, ")}");
27325 mp_end_diagnostic (mp, false);
27326 }
27327 /* Sidestep |independent| cases in capsule |p| */
27328 /* A big node is considered to be ``tarnished'' if it contains at least one
27329 independent component. We will define a simple function called `|tarnished|'
27330 that returns |NULL| if and only if its argument is not tarnished. */
27331 switch (mp_type (p)) {
27332 case mp_transform_type:
27333 case mp_color_type:
27334 case mp_cmykcolor_type:
27335 case mp_pair_type:
27336 old_p = mp_tarnished (mp, p);
27337 break;
27338 case mp_independent:
27339 old_p = MP_VOID;
27340 break;
27341 default:
27342 old_p = NULL;
27343 break;
27344 }
27345 if (old_p != NULL) {
27346 q = mp_stash_cur_exp (mp);
27347 old_p = p;
27348 mp_make_exp_copy (mp, old_p);
27349 p = mp_stash_cur_exp (mp);
27350 mp_unstash_cur_exp (mp, q);
27351 }
27352
27353 /* Sidestep |independent| cases in the current expression */
27354 switch (mp->cur_exp.type) {
27355 case mp_transform_type:
27356 case mp_color_type:
27357 case mp_cmykcolor_type:
27358 case mp_pair_type:
27359 old_exp = mp_tarnished (mp, cur_exp_node ());
27360 break;
27361 case mp_independent:
27362 old_exp = MP_VOID;
27363 break;
27364 default:
27365 old_exp = NULL;
27366 break;
27367 }
27368 if (old_exp != NULL) {
27369 old_exp = cur_exp_node ();
27370 mp_make_exp_copy (mp, old_exp);
27371 }
27372
27373 switch (c) {
27374 case mp_plus:
27375 case mp_minus:
27376 /* Add or subtract the current expression from |p| */
27377 if ((mp->cur_exp.type < mp_color_type) || (mp_type (p) < mp_color_type)) {
27378 mp_bad_binary (mp, p, (quarterword) c);
27379 } else {
27380 quarterword cc = (quarterword)c;
27381 if ((mp->cur_exp.type > mp_pair_type) && (mp_type (p) > mp_pair_type)) {
27382 mp_add_or_subtract (mp, p, NULL, cc);
27383 } else {
27384 if (mp->cur_exp.type != mp_type (p)) {
27385 mp_bad_binary (mp, p, cc);
27386 } else {
27387 q = value_node (p);
27388 r = value_node (cur_exp_node ());
27389 switch (mp->cur_exp.type) {
27390 case mp_pair_type:
27391 mp_add_or_subtract (mp, x_part (q), x_part (r),cc);
27392 mp_add_or_subtract (mp, y_part (q), y_part (r),cc);
27393 break;
27394 case mp_color_type:
27395 mp_add_or_subtract (mp, red_part (q), red_part (r),cc);
27396 mp_add_or_subtract (mp, green_part (q), green_part (r),cc);
27397 mp_add_or_subtract (mp, blue_part (q), blue_part (r),cc);
27398 break;
27399 case mp_cmykcolor_type:
27400 mp_add_or_subtract (mp, cyan_part (q), cyan_part (r),cc);
27401 mp_add_or_subtract (mp, magenta_part (q), magenta_part (r),cc);
27402 mp_add_or_subtract (mp, yellow_part (q), yellow_part (r),cc);
27403 mp_add_or_subtract (mp, black_part (q), black_part (r),cc);
27404 break;
27405 case mp_transform_type:
27406 mp_add_or_subtract (mp, tx_part (q), tx_part (r),cc);
27407 mp_add_or_subtract (mp, ty_part (q), ty_part (r),cc);
27408 mp_add_or_subtract (mp, xx_part (q), xx_part (r),cc);
27409 mp_add_or_subtract (mp, xy_part (q), xy_part (r),cc);
27410 mp_add_or_subtract (mp, yx_part (q), yx_part (r),cc);
27411 mp_add_or_subtract (mp, yy_part (q), yy_part (r),cc);
27412 break;
27413 default: /* there are no other valid cases, but please the compiler */
27414 break;
27415 }
27416 }
27417 }
27418 }
27419 break;
27420 case mp_less_than:
27421 case mp_less_or_equal:
27422 case mp_greater_than:
27423 case mp_greater_or_equal:
27424 case mp_equal_to:
27425 case mp_unequal_to:
27426 check_arith(); /* at this point |arith_error| should be |false|? */
27427 if ((mp->cur_exp.type > mp_pair_type) && (mp_type (p) > mp_pair_type)) {
27428 mp_add_or_subtract (mp, p, NULL, mp_minus); /* |cur_exp:=(p)-cur_exp| */
27429 } else if (mp->cur_exp.type != mp_type (p)) {
27430 mp_bad_binary (mp, p, (quarterword) c);
27431 goto DONE;
27432 } else if (mp->cur_exp.type == mp_string_type) {
27433 memset(&new_expr,0,sizeof(mp_value));
27434 new_number(new_expr.data.n);
27435 set_number_from_scaled (new_expr.data.n, mp_str_vs_str (mp, value_str (p), cur_exp_str ()));
27436 mp_flush_cur_exp (mp, new_expr);
27437 } else if ((mp->cur_exp.type == mp_unknown_string) ||
27438 (mp->cur_exp.type == mp_unknown_boolean)) {
27439 /* Check if unknowns have been equated */
27440 /* When two unknown strings are in the same ring, we know that they are
27441 equal. Otherwise, we don't know whether they are equal or not, so we
27442 make no change. */
27443 q = value_node (cur_exp_node ());
27444 while ((q != cur_exp_node ()) && (q != p))
27445 q = value_node (q);
27446 if (q == p) {
27447 memset(&new_expr,0,sizeof(mp_value));
27448 new_number(new_expr.data.n);
27449 set_cur_exp_node (NULL);
27450 mp_flush_cur_exp (mp, new_expr);
27451 }
27452
27453 } else if ((mp->cur_exp.type <= mp_pair_type)
27454 && (mp->cur_exp.type >= mp_transform_type)) {
27455 /* Reduce comparison of big nodes to comparison of scalars */
27456 /* In the following, the |while| loops exist just so that |break| can be used,
27457 each loop runs exactly once. */
27458 quarterword part_type;
27459 q = value_node (p);
27460 r = value_node (cur_exp_node ());
27461 part_type = 0;
27462 switch (mp->cur_exp.type) {
27463 case mp_pair_type:
27464 while (part_type==0) {
27465 rr = x_part (r);
27466 part_type = mp_x_part;
27467 mp_add_or_subtract (mp, x_part (q), rr, mp_minus);
27468 if (mp_type (rr) != mp_known || ! number_zero(value_number (rr)))
27469 break;
27470 rr = y_part (r);
27471 part_type = mp_y_part;
27472 mp_add_or_subtract (mp, y_part (q), rr, mp_minus);
27473 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27474 break;
27475 }
27476 mp_take_part (mp, part_type);
27477 break;
27478 case mp_color_type:
27479 while (part_type==0) {
27480 rr = red_part (r);
27481 part_type = mp_red_part;
27482 mp_add_or_subtract (mp, red_part (q), rr, mp_minus);
27483 if (mp_type (rr) != mp_known || ! number_zero(value_number (rr)))
27484 break;
27485 rr = green_part (r);
27486 part_type = mp_green_part;
27487 mp_add_or_subtract (mp, green_part (q), rr, mp_minus);
27488 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27489 break;
27490 rr = blue_part (r);
27491 part_type = mp_blue_part;
27492 mp_add_or_subtract (mp, blue_part (q), rr, mp_minus);
27493 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27494 break;
27495 }
27496 mp_take_part (mp, part_type);
27497 break;
27498 case mp_cmykcolor_type:
27499 while (part_type==0) {
27500 rr = cyan_part (r);
27501 part_type = mp_cyan_part;
27502 mp_add_or_subtract (mp, cyan_part (q), rr, mp_minus);
27503 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27504 break;
27505 rr = magenta_part (r);
27506 part_type = mp_magenta_part;
27507 mp_add_or_subtract (mp, magenta_part (q), rr, mp_minus);
27508 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27509 break;
27510 rr = yellow_part (r);
27511 part_type = mp_yellow_part;
27512 mp_add_or_subtract (mp, yellow_part (q), rr, mp_minus);
27513 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27514 break;
27515 rr = black_part (r);
27516 part_type = mp_black_part;
27517 mp_add_or_subtract (mp, black_part (q), rr, mp_minus);
27518 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27519 break;
27520 }
27521 mp_take_part (mp, part_type);
27522 break;
27523 case mp_transform_type:
27524 while (part_type==0) {
27525 rr = tx_part (r);
27526 part_type = mp_x_part;
27527 mp_add_or_subtract (mp, tx_part (q), rr, mp_minus);
27528 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27529 break;
27530 rr = ty_part (r);
27531 part_type = mp_y_part;
27532 mp_add_or_subtract (mp, ty_part (q), rr, mp_minus);
27533 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27534 break;
27535 rr = xx_part (r);
27536 part_type = mp_xx_part;
27537 mp_add_or_subtract (mp, xx_part (q), rr, mp_minus);
27538 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27539 break;
27540 rr = xy_part (r);
27541 part_type = mp_xy_part;
27542 mp_add_or_subtract (mp, xy_part (q), rr, mp_minus);
27543 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27544 break;
27545 rr = yx_part (r);
27546 part_type = mp_yx_part;
27547 mp_add_or_subtract (mp, yx_part (q), rr, mp_minus);
27548 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27549 break;
27550 rr = yy_part (r);
27551 part_type = mp_yy_part;
27552 mp_add_or_subtract (mp, yy_part (q), rr, mp_minus);
27553 if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
27554 break;
27555 }
27556 mp_take_part (mp, part_type);
27557 break;
27558 default:
27559 assert (0); /* TODO: |mp->cur_exp.type>mp_transform_node_type| ? */
27560 break;
27561 }
27562
27563 } else if (mp->cur_exp.type == mp_boolean_type) {
27564 memset(&new_expr,0,sizeof(mp_value));
27565 new_number(new_expr.data.n);
27566 set_number_from_boolean (new_expr.data.n, number_to_scaled(cur_exp_value_number ()) -
27567 number_to_scaled (value_number (p)));
27568 mp_flush_cur_exp (mp, new_expr);
27569 } else {
27570 mp_bad_binary (mp, p, (quarterword) c);
27571 goto DONE;
27572 }
27573 /* Compare the current expression with zero */
27574 if (mp->cur_exp.type != mp_known) {
27575 const char *hlp[] = {
27576 "Oh dear. I can\'t decide if the expression above is positive,",
27577 "negative, or zero. So this comparison test won't be `true'.",
27578 NULL };
27579 if (mp->cur_exp.type < mp_known) {
27580 mp_disp_err (mp, p);
27581 hlp[0] = "The quantities shown above have not been equated.";
27582 hlp[1] = NULL;
27583 }
27584 mp_disp_err(mp, NULL);
27585 memset(&new_expr,0,sizeof(mp_value));
27586 new_number(new_expr.data.n);
27587 set_number_from_boolean (new_expr.data.n, mp_false_code);
27588 mp_back_error (mp,"Unknown relation will be considered false", hlp, true);
27589 @.Unknown relation...@>
27590 mp_get_x_next (mp);
27591 mp_flush_cur_exp (mp, new_expr);
27592 } else {
27593 switch (c) {
27594 case mp_less_than:
27595 boolean_reset (number_negative(cur_exp_value_number ()));
27596 break;
27597 case mp_less_or_equal:
27598 boolean_reset (number_nonpositive(cur_exp_value_number ()));
27599 break;
27600 case mp_greater_than:
27601 boolean_reset (number_positive(cur_exp_value_number ()));
27602 break;
27603 case mp_greater_or_equal:
27604 boolean_reset (number_nonnegative(cur_exp_value_number ()));
27605 break;
27606 case mp_equal_to:
27607 boolean_reset (number_zero(cur_exp_value_number ()));
27608 break;
27609 case mp_unequal_to:
27610 boolean_reset (number_nonzero(cur_exp_value_number ()));
27611 break;
27612 } /* there are no other cases */
27613 }
27614 mp->cur_exp.type = mp_boolean_type;
27615 DONE:
27616 mp->arith_error = false; /* ignore overflow in comparisons */
27617 break;
27618 case mp_and_op:
27619 case mp_or_op:
27620 /* Here we use the sneaky fact that |and_op-false_code=or_op-true_code| */
27621 if ((mp_type (p) != mp_boolean_type) || (mp->cur_exp.type != mp_boolean_type))
27622 mp_bad_binary (mp, p, (quarterword) c);
27623 else if (number_to_boolean (p->data.n) == c + mp_false_code - mp_and_op) {
27624 set_cur_exp_value_boolean (number_to_boolean (p->data.n));
27625 }
27626 break;
27627 case mp_times:
27628 if ((mp->cur_exp.type < mp_color_type) || (mp_type (p) < mp_color_type)) {
27629 mp_bad_binary (mp, p, mp_times);
27630 } else if ((mp->cur_exp.type == mp_known) || (mp_type (p) == mp_known)) {
27631 /* Multiply when at least one operand is known */
27632 mp_number vv;
27633 new_fraction (vv);
27634 if (mp_type (p) == mp_known) {
27635 number_clone(vv, value_number (p));
27636 mp_free_value_node (mp, p);
27637 } else {
27638 number_clone(vv, cur_exp_value_number ());
27639 mp_unstash_cur_exp (mp, p);
27640 }
27641 if (mp->cur_exp.type == mp_known) {
27642 mp_number ret;
27643 new_number (ret);
27644 take_scaled (ret, cur_exp_value_number (), vv);
27645 set_cur_exp_value_number (ret);
27646 free_number (ret);
27647 } else if (mp->cur_exp.type == mp_pair_type) {
27648 mp_dep_mult (mp, (mp_value_node) x_part (value_node (cur_exp_node ())), vv, true);
27649 mp_dep_mult (mp, (mp_value_node) y_part (value_node (cur_exp_node ())), vv, true);
27650 } else if (mp->cur_exp.type == mp_color_type) {
27651 mp_dep_mult (mp, (mp_value_node) red_part (value_node (cur_exp_node ())), vv, true);
27652 mp_dep_mult (mp, (mp_value_node) green_part (value_node (cur_exp_node ())), vv, true);
27653 mp_dep_mult (mp, (mp_value_node) blue_part (value_node (cur_exp_node ())), vv, true);
27654 } else if (mp->cur_exp.type == mp_cmykcolor_type) {
27655 mp_dep_mult (mp, (mp_value_node) cyan_part (value_node (cur_exp_node ())), vv, true);
27656 mp_dep_mult (mp, (mp_value_node) magenta_part (value_node (cur_exp_node ())), vv, true);
27657 mp_dep_mult (mp, (mp_value_node) yellow_part (value_node (cur_exp_node ())), vv, true);
27658 mp_dep_mult (mp, (mp_value_node) black_part (value_node (cur_exp_node ())), vv, true);
27659 } else {
27660 mp_dep_mult (mp, NULL, vv, true);
27661 }
27662 free_number (vv);
27663 binary_return;
27664
27665 } else if ((mp_nice_color_or_pair (mp, p, mp_type (p))
27666 && (mp->cur_exp.type > mp_pair_type))
27667 || (mp_nice_color_or_pair (mp, cur_exp_node (), mp->cur_exp.type)
27668 && (mp_type (p) > mp_pair_type))) {
27669 mp_hard_times (mp, p);
27670 binary_return;
27671 } else {
27672 mp_bad_binary (mp, p, mp_times);
27673 }
27674 break;
27675 case mp_over:
27676 if ((mp->cur_exp.type != mp_known) || (mp_type (p) < mp_color_type)) {
27677 mp_bad_binary (mp, p, mp_over);
27678 } else {
27679 mp_number v_n;
27680 new_number (v_n);
27681 number_clone (v_n, cur_exp_value_number ());
27682 mp_unstash_cur_exp (mp, p);
27683 if (number_zero(v_n)) {
27684 /* Squeal about division by zero */
27685 const char *hlp[] = {
27686 "You're trying to divide the quantity shown above the error",
27687 "message by zero. I'm going to divide it by one instead.",
27688 NULL };
27689 mp_disp_err(mp, NULL);
27690 mp_back_error (mp, "Division by zero", hlp, true);
27691 mp_get_x_next (mp);
27692
27693 } else {
27694 if (mp->cur_exp.type == mp_known) {
27695 mp_number ret;
27696 new_number (ret);
27697 make_scaled (ret, cur_exp_value_number (), v_n);
27698 set_cur_exp_value_number (ret);
27699 free_number (ret);
27700 } else if (mp->cur_exp.type == mp_pair_type) {
27701 mp_dep_div (mp, (mp_value_node) x_part (value_node (cur_exp_node ())),
27702 v_n);
27703 mp_dep_div (mp, (mp_value_node) y_part (value_node (cur_exp_node ())),
27704 v_n);
27705 } else if (mp->cur_exp.type == mp_color_type) {
27706 mp_dep_div (mp,
27707 (mp_value_node) red_part (value_node (cur_exp_node ())),
27708 v_n);
27709 mp_dep_div (mp,
27710 (mp_value_node) green_part (value_node (cur_exp_node ())),
27711 v_n);
27712 mp_dep_div (mp,
27713 (mp_value_node) blue_part (value_node (cur_exp_node ())),
27714 v_n);
27715 } else if (mp->cur_exp.type == mp_cmykcolor_type) {
27716 mp_dep_div (mp,
27717 (mp_value_node) cyan_part (value_node (cur_exp_node ())),
27718 v_n);
27719 mp_dep_div (mp, (mp_value_node)
27720 magenta_part (value_node (cur_exp_node ())), v_n);
27721 mp_dep_div (mp, (mp_value_node)
27722 yellow_part (value_node (cur_exp_node ())), v_n);
27723 mp_dep_div (mp,
27724 (mp_value_node) black_part (value_node (cur_exp_node ())),
27725 v_n);
27726 } else {
27727 mp_dep_div (mp, NULL, v_n);
27728 }
27729 }
27730 free_number(v_n);
27731 binary_return;
27732 }
27733 break;
27734 case mp_pythag_add:
27735 case mp_pythag_sub:
27736 if ((mp->cur_exp.type == mp_known) && (mp_type (p) == mp_known)) {
27737 mp_number r;
27738 new_number (r);
27739 if (c == mp_pythag_add) {
27740 pyth_add (r, value_number (p), cur_exp_value_number ());
27741 } else {
27742 pyth_sub (r, value_number (p), cur_exp_value_number ());
27743 }
27744 set_cur_exp_value_number (r);
27745 free_number (r);
27746 } else
27747 mp_bad_binary (mp, p, (quarterword) c);
27748 break;
27749 case mp_rotated_by:
27750 case mp_slanted_by:
27751 case mp_scaled_by:
27752 case mp_shifted_by:
27753 case mp_transformed_by:
27754 case mp_x_scaled:
27755 case mp_y_scaled:
27756 case mp_z_scaled:
27757 /* The next few sections of the program deal with affine transformations
27758 of coordinate data. */
27759 if (mp_type (p) == mp_path_type) {
27760 path_trans ((quarterword) c, p);
27761 binary_return;
27762 } else if (mp_type (p) == mp_pen_type) {
27763 pen_trans ((quarterword) c, p);
27764 set_cur_exp_knot (mp_convex_hull (mp, cur_exp_knot ()));
27765 /* rounding error could destroy convexity */
27766 binary_return;
27767 } else if ((mp_type (p) == mp_pair_type) || (mp_type (p) == mp_transform_type)) {
27768 mp_big_trans (mp, p, (quarterword) c);
27769 } else if (mp_type (p) == mp_picture_type) {
27770 mp_do_edges_trans (mp, p, (quarterword) c);
27771 binary_return;
27772 } else {
27773 mp_bad_binary (mp, p, (quarterword) c);
27774 }
27775 break;
27776 case mp_concatenate:
27777 if ((mp->cur_exp.type == mp_string_type) && (mp_type (p) == mp_string_type)) {
27778 mp_string str = mp_cat (mp, value_str (p), cur_exp_str());
27779 delete_str_ref (cur_exp_str ()) ;
27780 set_cur_exp_str (str);
27781 } else
27782 mp_bad_binary (mp, p, mp_concatenate);
27783 break;
27784 case mp_substring_of:
27785 if (mp_nice_pair (mp, p, mp_type (p)) && (mp->cur_exp.type == mp_string_type)) {
27786 mp_string str = mp_chop_string (mp,
27787 cur_exp_str (),
27788 round_unscaled (value_number (x_part (value_node(p)))),
27789 round_unscaled (value_number (y_part (value_node(p)))));
27790 delete_str_ref (cur_exp_str ()) ;
27791 set_cur_exp_str (str);
27792 } else
27793 mp_bad_binary (mp, p, mp_substring_of);
27794 break;
27795 case mp_subpath_of:
27796 if (mp->cur_exp.type == mp_pair_type)
27797 mp_pair_to_path (mp);
27798 if (mp_nice_pair (mp, p, mp_type (p)) && (mp->cur_exp.type == mp_path_type))
27799 mp_chop_path (mp, value_node (p));
27800 else
27801 mp_bad_binary (mp, p, mp_subpath_of);
27802 break;
27803 case mp_point_of:
27804 case mp_precontrol_of:
27805 case mp_postcontrol_of:
27806 if (mp->cur_exp.type == mp_pair_type)
27807 mp_pair_to_path (mp);
27808 if ((mp->cur_exp.type == mp_path_type) && (mp_type (p) == mp_known))
27809 mp_find_point (mp, value_number (p), (quarterword) c);
27810 else
27811 mp_bad_binary (mp, p, (quarterword) c);
27812 break;
27813 case mp_pen_offset_of:
27814 if ((mp->cur_exp.type == mp_pen_type) && mp_nice_pair (mp, p, mp_type (p)))
27815 mp_set_up_offset (mp, value_node (p));
27816 else
27817 mp_bad_binary (mp, p, mp_pen_offset_of);
27818 break;
27819 case mp_direction_time_of:
27820 if (mp->cur_exp.type == mp_pair_type)
27821 mp_pair_to_path (mp);
27822 if ((mp->cur_exp.type == mp_path_type) && mp_nice_pair (mp, p, mp_type (p)))
27823 mp_set_up_direction_time (mp, value_node (p));
27824 else
27825 mp_bad_binary (mp, p, mp_direction_time_of);
27826 break;
27827 case mp_envelope_of:
27828 if ((mp_type (p) != mp_pen_type) || (mp->cur_exp.type != mp_path_type))
27829 mp_bad_binary (mp, p, mp_envelope_of);
27830 else
27831 mp_set_up_envelope (mp, p);
27832 break;
27833 case mp_boundingpath_of:
27834 if ((mp_type (p) != mp_pen_type) || (mp->cur_exp.type != mp_path_type))
27835 mp_bad_binary (mp, p, mp_boundingpath_of);
27836 else
27837 mp_set_up_boundingpath (mp, p);
27838 break;
27839 case mp_glyph_infont:
27840 if ((mp_type (p) != mp_string_type &&
27841 mp_type (p) != mp_known) || (mp->cur_exp.type != mp_string_type))
27842 mp_bad_binary (mp, p, mp_glyph_infont);
27843 else
27844 mp_set_up_glyph_infont (mp, p);
27845 break;
27846 case mp_arc_time_of:
27847 if (mp->cur_exp.type == mp_pair_type)
27848 mp_pair_to_path (mp);
27849 if ((mp->cur_exp.type == mp_path_type) && (mp_type (p) == mp_known)) {
27850 memset(&new_expr,0,sizeof(mp_value));
27851 new_number(new_expr.data.n);
27852 mp_get_arc_time (mp, &new_expr.data.n, cur_exp_knot (), value_number (p));
27853 mp_flush_cur_exp (mp, new_expr);
27854 } else {
27855 mp_bad_binary (mp, p, (quarterword) c);
27856 }
27857 break;
27858 case mp_intersect:
27859 if (mp_type (p) == mp_pair_type) {
27860 q = mp_stash_cur_exp (mp);
27861 mp_unstash_cur_exp (mp, p);
27862 mp_pair_to_path (mp);
27863 p = mp_stash_cur_exp (mp);
27864 mp_unstash_cur_exp (mp, q);
27865 }
27866 if (mp->cur_exp.type == mp_pair_type)
27867 mp_pair_to_path (mp);
27868 if ((mp->cur_exp.type == mp_path_type) && (mp_type (p) == mp_path_type)) {
27869 mp_number arg1, arg2;
27870 new_number (arg1);
27871 new_number (arg2);
27872 mp_path_intersection (mp, value_knot (p), cur_exp_knot ());
27873 number_clone (arg1, mp->cur_t);
27874 number_clone (arg2, mp->cur_tt);
27875 mp_pair_value (mp, arg1, arg2);
27876 free_number (arg1);
27877 free_number (arg2);
27878 } else {
27879 mp_bad_binary (mp, p, mp_intersect);
27880 }
27881 break;
27882 case mp_in_font:
27883 if ((mp->cur_exp.type != mp_string_type) || mp_type (p) != mp_string_type) {
27884 mp_bad_binary (mp, p, mp_in_font);
27885 } else {
27886 mp_do_infont (mp, p);
27887 binary_return;
27888 }
27889 break;
27890 } /* there are no other cases */
27891 mp_recycle_value (mp, p);
27892 mp_free_value_node (mp, p); /* |return| to avoid this */
27893 mp_finish_binary (mp, old_p, old_exp);
27894 }
27895
27896
27897 @ @<Declare binary action...@>=
27898 static void mp_bad_binary (MP mp, mp_node p, quarterword c) {
27899 char msg[256];
27900 mp_string sname;
27901 int old_setting = mp->selector;
27902 const char *hlp[] = {
27903 "I'm afraid I don't know how to apply that operation to that",
27904 "combination of types. Continue, and I'll return the second",
27905 "argument (see above) as the result of the operation.",
27906 NULL };
27907 mp->selector = new_string;
27908 if (c >= mp_min_of)
27909 mp_print_op (mp, c);
27910 mp_print_known_or_unknown_type (mp, mp_type (p), p);
27911 if (c >= mp_min_of)
27912 mp_print (mp, "of");
27913 else
27914 mp_print_op (mp, c);
27915 mp_print_known_or_unknown_type (mp, mp->cur_exp.type, cur_exp_node ());
27916 sname = mp_make_string(mp);
27917 mp->selector = old_setting;
27918 mp_snprintf (msg, 256, "Not implemented: %s", mp_str(mp, sname));
27919 @.Not implemented...@>
27920 delete_str_ref(sname);
27921 mp_disp_err (mp, p);
27922 mp_disp_err (mp, NULL);
27923 mp_back_error (mp, msg, hlp, true);
27924 mp_get_x_next (mp);
27925 }
27926 static void mp_bad_envelope_pen (MP mp) {
27927 const char *hlp[] = {
27928 "I'm afraid I don't know how to apply that operation to that",
27929 "combination of types. Continue, and I'll return the second",
27930 "argument (see above) as the result of the operation.",
27931 NULL };
27932 mp_disp_err (mp, NULL);
27933 mp_disp_err (mp, NULL);
27934 mp_back_error (mp, "Not implemented: envelope(elliptical pen)of(path)", hlp, true);
27935 @.Not implemented...@>
27936 mp_get_x_next (mp);
27937 }
27938
27939 @ @<Declare binary action...@>=
27940 static mp_node mp_tarnished (MP mp, mp_node p) {
27941 mp_node q; /* beginning of the big node */
27942 mp_node r; /* moving value node pointer */
27943 (void) mp;
27944 q = value_node (p);
27945 switch (mp_type (p)) {
27946 case mp_pair_type:
27947 r = x_part (q);
27948 if (mp_type (r) == mp_independent)
27949 return MP_VOID;
27950 r = y_part (q);
27951 if (mp_type (r) == mp_independent)
27952 return MP_VOID;
27953 break;
27954 case mp_color_type:
27955 r = red_part (q);
27956 if (mp_type (r) == mp_independent)
27957 return MP_VOID;
27958 r = green_part (q);
27959 if (mp_type (r) == mp_independent)
27960 return MP_VOID;
27961 r = blue_part (q);
27962 if (mp_type (r) == mp_independent)
27963 return MP_VOID;
27964 break;
27965 case mp_cmykcolor_type:
27966 r = cyan_part (q);
27967 if (mp_type (r) == mp_independent)
27968 return MP_VOID;
27969 r = magenta_part (q);
27970 if (mp_type (r) == mp_independent)
27971 return MP_VOID;
27972 r = yellow_part (q);
27973 if (mp_type (r) == mp_independent)
27974 return MP_VOID;
27975 r = black_part (q);
27976 if (mp_type (r) == mp_independent)
27977 return MP_VOID;
27978 break;
27979 case mp_transform_type:
27980 r = tx_part (q);
27981 if (mp_type (r) == mp_independent)
27982 return MP_VOID;
27983 r = ty_part (q);
27984 if (mp_type (r) == mp_independent)
27985 return MP_VOID;
27986 r = xx_part (q);
27987 if (mp_type (r) == mp_independent)
27988 return MP_VOID;
27989 r = xy_part (q);
27990 if (mp_type (r) == mp_independent)
27991 return MP_VOID;
27992 r = yx_part (q);
27993 if (mp_type (r) == mp_independent)
27994 return MP_VOID;
27995 r = yy_part (q);
27996 if (mp_type (r) == mp_independent)
27997 return MP_VOID;
27998 break;
27999 default: /* there are no other valid cases, but please the compiler */
28000 break;
28001 }
28002 return NULL;
28003 }
28004
28005 @ The first argument to |add_or_subtract| is the location of a value node
28006 in a capsule or pair node that will soon be recycled. The second argument
28007 is either a location within a pair or transform node of |cur_exp|,
28008 or it is NULL (which means that |cur_exp| itself should be the second
28009 argument). The third argument is either |plus| or |minus|.
28010
28011 The sum or difference of the numeric quantities will replace the second
28012 operand. Arithmetic overflow may go undetected; users aren't supposed to
28013 be monkeying around with really big values.
28014 @^overflow in arithmetic@>
28015
28016 @<Declare binary action...@>=
28017 @<Declare the procedure called |dep_finish|@>
28018 static void mp_add_or_subtract (MP mp, mp_node p, mp_node q, quarterword c) {
28019 mp_variable_type s, t; /* operand types */
28020 mp_value_node r; /* dependency list traverser */
28021 mp_value_node v = NULL; /* second operand value for dep lists */
28022 mp_number vv; /* second operand value for known values */
28023 new_number (vv);
28024 if (q == NULL) {
28025 t = mp->cur_exp.type;
28026 if (t < mp_dependent)
28027 number_clone (vv, cur_exp_value_number ());
28028 else
28029 v = (mp_value_node) dep_list ((mp_value_node) cur_exp_node ());
28030 } else {
28031 t = mp_type (q);
28032 if (t < mp_dependent)
28033 number_clone (vv, value_number (q));
28034 else
28035 v = (mp_value_node) dep_list ((mp_value_node) q);
28036 }
28037 if (t == mp_known) {
28038 mp_value_node qq = (mp_value_node) q;
28039 if (c == mp_minus)
28040 number_negate (vv);
28041 if (mp_type (p) == mp_known) {
28042 slow_add (vv, value_number (p), vv);
28043 if (q == NULL)
28044 set_cur_exp_value_number (vv);
28045 else
28046 set_value_number (q, vv);
28047 free_number (vv);
28048 return;
28049 }
28050 /* Add a known value to the constant term of |dep_list(p)| */
28051 r = (mp_value_node) dep_list ((mp_value_node) p);
28052 while (dep_info (r) != NULL)
28053 r = (mp_value_node) mp_link (r);
28054 slow_add (vv, dep_value (r), vv);
28055 set_dep_value (r, vv);
28056 if (qq == NULL) {
28057 qq = mp_get_dep_node (mp);
28058 set_cur_exp_node ((mp_node) qq);
28059 mp->cur_exp.type = mp_type (p);
28060 mp_name_type (qq) = mp_capsule;
28061 /* clang: never read: |q = (mp_node) qq;| */
28062 }
28063 set_dep_list (qq, dep_list ((mp_value_node) p));
28064 mp_type (qq) = mp_type (p);
28065 set_prev_dep (qq, prev_dep ((mp_value_node) p));
28066 mp_link (prev_dep ((mp_value_node) p)) = (mp_node) qq;
28067 mp_type (p) = mp_known; /* this will keep the recycler from collecting non-garbage */
28068 } else {
28069 if (c == mp_minus)
28070 mp_negate_dep_list (mp, v);
28071 /* Add operand |p| to the dependency list |v| */
28072 /* We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
28073 nice to retain the extra accuracy of |fraction| coefficients.
28074 But we have to handle both kinds, and mixtures too. */
28075 if (mp_type (p) == mp_known) {
28076 /* Add the known |value(p)| to the constant term of |v| */
28077 while (dep_info (v) != NULL) {
28078 v = (mp_value_node) mp_link (v);
28079 }
28080 slow_add (vv, value_number (p), dep_value (v));
28081 set_dep_value (v, vv);
28082 } else {
28083 s = mp_type (p);
28084 r = (mp_value_node) dep_list ((mp_value_node) p);
28085 if (t == mp_dependent) {
28086 if (s == mp_dependent) {
28087 mp_number ret1, ret2;
28088 new_fraction (ret1);
28089 new_fraction (ret2);
28090 mp_max_coef (mp, &ret1, r);
28091 mp_max_coef (mp, &ret2, v);
28092 number_add (ret1, ret2);
28093 free_number (ret2);
28094 if (number_less (ret1, coef_bound_k)) {
28095 v = mp_p_plus_q (mp, v, r, mp_dependent);
28096 free_number (ret1);
28097 goto DONE;
28098 }
28099 free_number (ret1);
28100 } /* |fix_needed| will necessarily be false */
28101 t = mp_proto_dependent;
28102 v = mp_p_over_v (mp, v, unity_t, mp_dependent, mp_proto_dependent);
28103 }
28104 if (s == mp_proto_dependent)
28105 v = mp_p_plus_q (mp, v, r, mp_proto_dependent);
28106 else
28107 v = mp_p_plus_fq (mp, v, unity_t, r, mp_proto_dependent, mp_dependent);
28108 DONE:
28109 /* Output the answer, |v| (which might have become |known|) */
28110 if (q != NULL) {
28111 mp_dep_finish (mp, v, (mp_value_node) q, t);
28112 } else {
28113 mp->cur_exp.type = t;
28114 mp_dep_finish (mp, v, NULL, t);
28115 }
28116 }
28117 }
28118 free_number (vv);
28119 }
28120
28121
28122 @ Here's the current situation: The dependency list |v| of type |t|
28123 should either be put into the current expression (if |q=NULL|) or
28124 into location |q| within a pair node (otherwise). The destination (|cur_exp|
28125 or |q|) formerly held a dependency list with the same
28126 final pointer as the list |v|.
28127
28128 @<Declare the procedure called |dep_finish|@>=
28129 static void mp_dep_finish (MP mp, mp_value_node v, mp_value_node q,
28130 quarterword t) {
28131 mp_value_node p; /* the destination */
28132 if (q == NULL)
28133 p = (mp_value_node) cur_exp_node ();
28134 else
28135 p = q;
28136 set_dep_list (p, v);
28137 mp_type (p) = t;
28138 if (dep_info (v) == NULL) {
28139 mp_number vv; /* the value, if it is |known| */
28140 new_number (vv);
28141 number_clone (vv, value_number (v));
28142 if (q == NULL) {
28143 mp_value new_expr;
28144 memset(&new_expr,0,sizeof(mp_value));
28145 new_number(new_expr.data.n);
28146 number_clone (new_expr.data.n, vv);
28147 mp_flush_cur_exp (mp, new_expr);
28148 } else {
28149 mp_recycle_value (mp, (mp_node) p);
28150 mp_type (q) = mp_known;
28151 set_value_number (q, vv);
28152 }
28153 free_number (vv);
28154 } else if (q == NULL) {
28155 mp->cur_exp.type = t;
28156 }
28157 if (mp->fix_needed)
28158 mp_fix_dependencies (mp);
28159 }
28160
28161 @ @<Declare binary action...@>=
28162 static void mp_dep_mult (MP mp, mp_value_node p, mp_number v, boolean v_is_scaled) {
28163 mp_value_node q; /* the dependency list being multiplied by |v| */
28164 quarterword s, t; /* its type, before and after */
28165 if (p == NULL) {
28166 q = (mp_value_node) cur_exp_node ();
28167 } else if (mp_type (p) != mp_known) {
28168 q = p;
28169 } else {
28170 {
28171 mp_number r1, arg1;
28172 new_number (arg1);
28173 number_clone (arg1, dep_value (p));
28174 if (v_is_scaled) {
28175 new_number (r1);
28176 take_scaled (r1, arg1, v);
28177 } else {
28178 new_fraction (r1);
28179 take_fraction (r1, arg1, v);
28180 }
28181 set_dep_value (p, r1);
28182 free_number (r1);
28183 free_number (arg1);
28184 }
28185 return;
28186 }
28187 t = mp_type (q);
28188 q = (mp_value_node) dep_list (q);
28189 s = t;
28190 if (t == mp_dependent) {
28191 if (v_is_scaled) {
28192 mp_number ab_vs_cd;
28193 mp_number arg1, arg2;
28194 new_number (ab_vs_cd);
28195 new_number (arg2);
28196 new_fraction (arg1);
28197 mp_max_coef (mp, &arg1, q);
28198 number_clone (arg2, v);
28199 number_abs (arg2);
28200 ab_vs_cd (ab_vs_cd, arg1, arg2, coef_bound_minus_1, unity_t);
28201 free_number (arg1);
28202 free_number (arg2);
28203 if (number_nonnegative(ab_vs_cd)) {
28204 t = mp_proto_dependent;
28205 }
28206 free_number (ab_vs_cd);
28207 }
28208 }
28209 q = mp_p_times_v (mp, q, v, s, t, v_is_scaled);
28210 mp_dep_finish (mp, q, p, t);
28211 }
28212
28213
28214 @ Here is a routine that is similar to |times|; but it is invoked only
28215 internally, when |v| is a |fraction| whose magnitude is at most~1,
28216 and when |cur_type>=mp_color_type|.
28217
28218 @c
28219 static void mp_frac_mult (MP mp, mp_number n, mp_number d) {
28220 /* multiplies |cur_exp| by |n/d| */
28221 mp_node old_exp; /* a capsule to recycle */
28222 mp_number v; /* |n/d| */
28223 new_fraction (v);
28224 if (number_greater (internal_value (mp_tracing_commands), two_t))
28225 @<Trace the fraction multiplication@>@;
28226 switch (mp->cur_exp.type) {
28227 case mp_transform_type:
28228 case mp_color_type:
28229 case mp_cmykcolor_type:
28230 case mp_pair_type:
28231 old_exp = mp_tarnished (mp, cur_exp_node ());
28232 break;
28233 case mp_independent:
28234 old_exp = MP_VOID;
28235 break;
28236 default:
28237 old_exp = NULL;
28238 break;
28239 }
28240 if (old_exp != NULL) {
28241 old_exp = cur_exp_node ();
28242 mp_make_exp_copy (mp, old_exp);
28243 }
28244 make_fraction (v, n, d);
28245 if (mp->cur_exp.type == mp_known) {
28246 mp_number r1, arg1;
28247 new_fraction (r1);
28248 new_number (arg1);
28249 number_clone (arg1, cur_exp_value_number ());
28250 take_fraction (r1, arg1, v);
28251 set_cur_exp_value_number (r1);
28252 free_number (r1);
28253 free_number (arg1);
28254 } else if (mp->cur_exp.type == mp_pair_type) {
28255 mp_dep_mult (mp, (mp_value_node) x_part (value_node (cur_exp_node ())), v, false);
28256 mp_dep_mult (mp, (mp_value_node) y_part (value_node (cur_exp_node ())), v, false);
28257 } else if (mp->cur_exp.type == mp_color_type) {
28258 mp_dep_mult (mp, (mp_value_node) red_part (value_node (cur_exp_node ())), v, false);
28259 mp_dep_mult (mp, (mp_value_node) green_part (value_node (cur_exp_node ())), v, false);
28260 mp_dep_mult (mp, (mp_value_node) blue_part (value_node (cur_exp_node ())), v, false);
28261 } else if (mp->cur_exp.type == mp_cmykcolor_type) {
28262 mp_dep_mult (mp, (mp_value_node) cyan_part (value_node (cur_exp_node ())), v, false);
28263 mp_dep_mult (mp, (mp_value_node) magenta_part (value_node (cur_exp_node ())), v, false);
28264 mp_dep_mult (mp, (mp_value_node) yellow_part (value_node (cur_exp_node ())), v, false);
28265 mp_dep_mult (mp, (mp_value_node) black_part (value_node (cur_exp_node ())), v, false);
28266 } else {
28267 mp_dep_mult (mp, NULL, v, false);
28268 }
28269 if (old_exp != NULL) {
28270 mp_recycle_value (mp, old_exp);
28271 mp_free_value_node (mp, old_exp);
28272 }
28273 free_number (v);
28274 }
28275
28276
28277 @ @<Trace the fraction multiplication@>=
28278 {
28279 mp_begin_diagnostic (mp);
28280 mp_print_nl (mp, "{(");
28281 print_number (n);
28282 mp_print_char (mp, xord ('/'));
28283 print_number (d);
28284 mp_print (mp, ")*(");
28285 mp_print_exp (mp, NULL, 0);
28286 mp_print (mp, ")}");
28287 mp_end_diagnostic (mp, false);
28288 }
28289
28290 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
28291
28292 @<Declare binary action procedures@>=
28293 static void mp_hard_times(MP mp, mp_node p)
28294 {
28295 if (p->type <= mp_pair_type) {
28296 mp_value_node q = (mp_value_node) mp_stash_cur_exp(mp);
28297 mp_unstash_cur_exp(mp, p);
28298 p = (mp_node) q;
28299 }
28300 switch (mp->cur_exp.type) {
28301 case mp_pair_type:
28302 {
28303 mp_node e = value_node(cur_exp_node());
28304 mp_number x, y;
28305 new_number(x);
28306 new_number(y);
28307 number_clone(x, value_number(x_part(e)));
28308 number_clone(y, value_number(y_part(e)));
28309 mp_new_dep(mp, y_part(e), p->type, mp_copy_dep_list(mp, (mp_value_node) dep_list((mp_value_node) p)));
28310 mp_free_value_node(mp, x_part(e));
28311 x_part(e) = p;
28312 set_mp_link(prev_dep(p), x_part(e));
28313 mp_dep_mult(mp, (mp_value_node) x_part(e), x, true);
28314 mp_dep_mult(mp, (mp_value_node) y_part(e), y, true);
28315 free_number(x);
28316 free_number(y);
28317 }
28318 break;
28319 case mp_color_type:
28320 {
28321 mp_node e = value_node(cur_exp_node());
28322 mp_number r, g, b;
28323 new_number(r);
28324 new_number(g);
28325 new_number(b);
28326 number_clone(r, value_number(red_part(e)));
28327 number_clone(g, value_number(green_part(e)));
28328 number_clone(b, value_number(blue_part(e)));
28329 mp_new_dep(mp, blue_part(e), p->type, mp_copy_dep_list(mp, (mp_value_node) dep_list((mp_value_node) p)));
28330 mp_new_dep(mp, green_part(e), p->type, mp_copy_dep_list(mp, (mp_value_node) dep_list((mp_value_node) p)));
28331 mp_free_value_node(mp, red_part(e));
28332 red_part(e) = p;
28333 set_mp_link(prev_dep(p), red_part(e));
28334 mp_dep_mult(mp, (mp_value_node) red_part(e), r, true);
28335 mp_dep_mult(mp, (mp_value_node) green_part(e), g, true);
28336 mp_dep_mult(mp, (mp_value_node) blue_part(e), b, true);
28337 free_number(r);
28338 free_number(g);
28339 free_number(b);
28340 }
28341 break;
28342 case mp_cmykcolor_type:
28343 {
28344 mp_node e = value_node(cur_exp_node());
28345 mp_number c, m, y, k;
28346 new_number(c);
28347 new_number(m);
28348 new_number(y);
28349 new_number(k);
28350 number_clone(c, value_number(cyan_part(e)));
28351 number_clone(m, value_number(magenta_part(e)));
28352 number_clone(y, value_number(yellow_part(e)));
28353 number_clone(k, value_number(black_part(e)));
28354 mp_new_dep(mp, black_part(e), p->type, mp_copy_dep_list(mp, (mp_value_node) dep_list((mp_value_node) p)));
28355 mp_new_dep(mp, yellow_part(e), p->type, mp_copy_dep_list(mp, (mp_value_node) dep_list((mp_value_node) p)));
28356 mp_new_dep(mp, magenta_part(e), p->type, mp_copy_dep_list(mp, (mp_value_node) dep_list((mp_value_node) p)));
28357 mp_free_value_node(mp, cyan_part(e));
28358 cyan_part(e) = p;
28359 set_mp_link(prev_dep(p), cyan_part(e));
28360 mp_dep_mult(mp, (mp_value_node) cyan_part(e), c, true);
28361 mp_dep_mult(mp, (mp_value_node) magenta_part(e), m, true);
28362 mp_dep_mult(mp, (mp_value_node) yellow_part(e), y, true);
28363 mp_dep_mult(mp, (mp_value_node) black_part(e), k, true);
28364 free_number(c);
28365 free_number(m);
28366 free_number(y);
28367 free_number(k);
28368 }
28369 break;
28370 default:
28371 break;
28372 }
28373 }
28374
28375 @ @<Declare binary action...@>=
28376 static void mp_dep_div (MP mp, mp_value_node p, mp_number v) {
28377 mp_value_node q; /* the dependency list being divided by |v| */
28378 quarterword s, t; /* its type, before and after */
28379 if (p == NULL)
28380 q = (mp_value_node) cur_exp_node ();
28381 else if (mp_type (p) != mp_known)
28382 q = p;
28383 else {
28384 mp_number ret;
28385 new_number (ret);
28386 make_scaled (ret, value_number (p), v);
28387 set_value_number (p, ret);
28388 free_number (ret);
28389 return;
28390 }
28391 t = mp_type (q);
28392 q = (mp_value_node) dep_list (q);
28393 s = t;
28394 if (t == mp_dependent) {
28395 mp_number ab_vs_cd;
28396 mp_number arg1, arg2;
28397 new_number (ab_vs_cd);
28398 new_number (arg2);
28399 new_fraction (arg1);
28400 mp_max_coef (mp, &arg1, q);
28401 number_clone (arg2, v);
28402 number_abs (arg2);
28403 ab_vs_cd (ab_vs_cd, arg1, unity_t, coef_bound_minus_1, arg2);
28404 free_number (arg1);
28405 free_number (arg2);
28406 if (number_nonnegative(ab_vs_cd)) {
28407 t = mp_proto_dependent;
28408 }
28409 free_number (ab_vs_cd);
28410 }
28411 q = mp_p_over_v (mp, q, v, s, t);
28412 mp_dep_finish (mp, q, p, t);
28413 }
28414
28415 @ Let |c| be one of the eight transform operators. The procedure call
28416 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
28417 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
28418 change at all if |c=transformed_by|.)
28419
28420 Then, if all components of the resulting transform are |known|, they are
28421 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
28422 and |cur_exp| is changed to the known value zero.
28423
28424 @<Declare binary action...@>=
28425 static void mp_set_up_trans (MP mp, quarterword c) {
28426 mp_node p, q, r; /* list manipulation registers */
28427 mp_value new_expr;
28428 memset(&new_expr,0,sizeof(mp_value));
28429 if ((c != mp_transformed_by) || (mp->cur_exp.type != mp_transform_type)) {
28430 /* Put the current transform into |cur_exp| */
28431 const char *hlp[] = {
28432 "The expression shown above has the wrong type,",
28433 "so I can\'t transform anything using it.",
28434 "Proceed, and I'll omit the transformation.",
28435 NULL };
28436 p = mp_stash_cur_exp (mp);
28437 set_cur_exp_node (mp_id_transform (mp));
28438 mp->cur_exp.type = mp_transform_type;
28439 q = value_node (cur_exp_node ());
28440 switch (c) {
28441 @<For each of the eight cases, change the relevant fields of |cur_exp|
28442 and |goto done|;
28443 but do nothing if capsule |p| doesn't have the appropriate type@>;
28444 } /* there are no other cases */
28445 mp_disp_err (mp, p);
28446 mp_back_error (mp, "Improper transformation argument", hlp, true);
28447 mp_get_x_next (mp);
28448 DONE:
28449 mp_recycle_value (mp, p);
28450 mp_free_value_node (mp, p);
28451
28452 }
28453 /* If the current transform is entirely known, stash it in global variables;
28454 otherwise |return| */
28455 q = value_node (cur_exp_node ());
28456 if (mp_type (tx_part (q)) != mp_known)
28457 return;
28458 if (mp_type (ty_part (q)) != mp_known)
28459 return;
28460 if (mp_type (xx_part (q)) != mp_known)
28461 return;
28462 if (mp_type (xy_part (q)) != mp_known)
28463 return;
28464 if (mp_type (yx_part (q)) != mp_known)
28465 return;
28466 if (mp_type (yy_part (q)) != mp_known)
28467 return;
28468 number_clone(mp->txx, value_number (xx_part (q)));
28469 number_clone(mp->txy, value_number (xy_part (q)));
28470 number_clone(mp->tyx, value_number (yx_part (q)));
28471 number_clone(mp->tyy, value_number (yy_part (q)));
28472 number_clone(mp->tx, value_number (tx_part (q)));
28473 number_clone(mp->ty, value_number (ty_part (q)));
28474 new_number(new_expr.data.n);
28475 set_number_to_zero (new_expr.data.n);
28476 mp_flush_cur_exp (mp, new_expr);
28477 }
28478
28479
28480 @ @<Glob...@>=
28481 mp_number txx;
28482 mp_number txy;
28483 mp_number tyx;
28484 mp_number tyy;
28485 mp_number tx;
28486 mp_number ty; /* current transform coefficients */
28487
28488 @ @<Initialize table...@>=
28489 new_number(mp->txx);
28490 new_number(mp->txy);
28491 new_number(mp->tyx);
28492 new_number(mp->tyy);
28493 new_number(mp->tx);
28494 new_number(mp->ty);
28495
28496 @ @<Free table...@>=
28497 free_number(mp->txx);
28498 free_number(mp->txy);
28499 free_number(mp->tyx);
28500 free_number(mp->tyy);
28501 free_number(mp->tx);
28502 free_number(mp->ty);
28503
28504
28505 @ @<For each of the eight cases...@>=
28506 case mp_rotated_by:
28507 if (mp_type (p) == mp_known)
28508 @<Install sines and cosines, then |goto done|@>;
28509 break;
28510 case mp_slanted_by:
28511 if (mp_type (p) > mp_pair_type) {
28512 mp_install (mp, xy_part (q), p);
28513 goto DONE;
28514 }
28515 break;
28516 case mp_scaled_by:
28517 if (mp_type (p) > mp_pair_type) {
28518 mp_install (mp, xx_part (q), p);
28519 mp_install (mp, yy_part (q), p);
28520 goto DONE;
28521 }
28522 break;
28523 case mp_shifted_by:
28524 if (mp_type (p) == mp_pair_type) {
28525 r = value_node (p);
28526 mp_install (mp, tx_part (q), x_part (r));
28527 mp_install (mp, ty_part (q), y_part (r));
28528 goto DONE;
28529 }
28530 break;
28531 case mp_x_scaled:
28532 if (mp_type (p) > mp_pair_type) {
28533 mp_install (mp, xx_part (q), p);
28534 goto DONE;
28535 }
28536 break;
28537 case mp_y_scaled:
28538 if (mp_type (p) > mp_pair_type) {
28539 mp_install (mp, yy_part (q), p);
28540 goto DONE;
28541 }
28542 break;
28543 case mp_z_scaled:
28544 if (mp_type (p) == mp_pair_type)
28545 @<Install a complex multiplier, then |goto done|@>;
28546 break;
28547 case mp_transformed_by:
28548 break;
28549
28550
28551 @ @<Install sines and cosines, then |goto done|@>=
28552 {
28553 mp_number n_sin, n_cos, arg1, arg2;
28554 new_number (arg1);
28555 new_number (arg2);
28556 new_fraction (n_sin);
28557 new_fraction (n_cos); /* results computed by |n_sin_cos| */
28558 number_clone (arg2, unity_t);
28559 number_clone (arg1, value_number (p));
28560 number_multiply_int (arg2, 360);
28561 number_modulo (arg1, arg2);
28562 convert_scaled_to_angle (arg1);
28563 n_sin_cos (arg1, n_cos, n_sin);
28564 fraction_to_round_scaled (n_sin);
28565 fraction_to_round_scaled (n_cos);
28566 set_value_number (xx_part (q), n_cos);
28567 set_value_number (yx_part (q), n_sin);
28568 set_value_number (xy_part (q), value_number (yx_part (q)));
28569 number_negate (value_number (xy_part (q)));
28570 set_value_number (yy_part (q), value_number (xx_part (q)));
28571 free_number (arg1);
28572 free_number (arg2);
28573 free_number (n_sin);
28574 free_number (n_cos);
28575 goto DONE;
28576 }
28577
28578
28579 @ @<Install a complex multiplier, then |goto done|@>=
28580 {
28581 r = value_node (p);
28582 mp_install (mp, xx_part (q), x_part (r));
28583 mp_install (mp, yy_part (q), x_part (r));
28584 mp_install (mp, yx_part (q), y_part (r));
28585 if (mp_type (y_part (r)) == mp_known) {
28586 set_value_number (y_part (r), value_number (y_part (r)));
28587 number_negate (value_number (y_part (r)));
28588 } else {
28589 mp_negate_dep_list (mp, (mp_value_node) dep_list ((mp_value_node)
28590 y_part (r)));
28591 }
28592 mp_install (mp, xy_part (q), y_part (r));
28593 goto DONE;
28594 }
28595
28596
28597 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
28598 insists that the transformation be entirely known.
28599
28600 @<Declare binary action...@>=
28601 static void mp_set_up_known_trans (MP mp, quarterword c) {
28602 mp_set_up_trans (mp, c);
28603 if (mp->cur_exp.type != mp_known) {
28604 mp_value new_expr;
28605 const char *hlp[] = {
28606 "I'm unable to apply a partially specified transformation",
28607 "except to a fully known pair or transform.",
28608 "Proceed, and I'll omit the transformation.",
28609 NULL };
28610 memset(&new_expr,0,sizeof(mp_value));
28611 new_number(new_expr.data.n);
28612 mp_disp_err(mp, NULL);
28613 set_number_to_zero (new_expr.data.n);
28614 mp_back_error (mp,"Transform components aren't all known", hlp, true);
28615 mp_get_x_next (mp);
28616 mp_flush_cur_exp (mp, new_expr);
28617 set_number_to_unity(mp->txx);
28618 set_number_to_zero(mp->txy);
28619 set_number_to_zero(mp->tyx);
28620 set_number_to_unity(mp->tyy);
28621 set_number_to_zero(mp->tx);
28622 set_number_to_zero(mp->ty);
28623 }
28624 }
28625
28626
28627 @ Here's a procedure that applies the transform |txx..ty| to a pair of
28628 coordinates in locations |p| and~|q|.
28629
28630 @<Declare binary action...@>=
28631 static void mp_number_trans (MP mp, mp_number *p, mp_number *q) {
28632 mp_number r1, r2, v;
28633 new_number (r1);
28634 new_number (r2);
28635 new_number (v);
28636 take_scaled (r1, *p, mp->txx);
28637 take_scaled (r2, *q, mp->txy);
28638 number_add (r1, r2);
28639 set_number_from_addition(v, r1, mp->tx);
28640 take_scaled (r1, *p, mp->tyx);
28641 take_scaled (r2, *q, mp->tyy);
28642 number_add (r1, r2);
28643 set_number_from_addition(*q, r1, mp->ty);
28644 number_clone(*p,v);
28645 free_number (r1);
28646 free_number (r2);
28647 free_number(v);
28648 }
28649
28650
28651 @ The simplest transformation procedure applies a transform to all
28652 coordinates of a path. The |path_trans(c)(p)| macro applies
28653 a transformation defined by |cur_exp| and the transform operator |c|
28654 to the path~|p|.
28655
28656 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A));
28657 mp_unstash_cur_exp(mp, (B));
28658 mp_do_path_trans(mp, cur_exp_knot()); }
28659
28660 @<Declare binary action...@>=
28661 static void mp_do_path_trans (MP mp, mp_knot p) {
28662 mp_knot q; /* list traverser */
28663 q = p;
28664 do {
28665 if (mp_left_type (q) != mp_endpoint)
28666 mp_number_trans (mp, &q->left_x, &q->left_y);
28667 mp_number_trans (mp, &q->x_coord, &q->y_coord);
28668 if (mp_right_type (q) != mp_endpoint)
28669 mp_number_trans (mp, &q->right_x, &q->right_y);
28670 q = mp_next_knot (q);
28671 } while (q != p);
28672 }
28673
28674
28675 @ Transforming a pen is very similar, except that there are no |mp_left_type|
28676 and |mp_right_type| fields.
28677
28678 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A));
28679 mp_unstash_cur_exp(mp, (B));
28680 mp_do_pen_trans(mp, cur_exp_knot()); }
28681
28682 @<Declare binary action...@>=
28683 static void mp_do_pen_trans (MP mp, mp_knot p) {
28684 mp_knot q; /* list traverser */
28685 if (pen_is_elliptical (p)) {
28686 mp_number_trans (mp, &p->left_x, &p->left_y);
28687 mp_number_trans (mp, &p->right_x, &p->right_y);
28688 }
28689 q = p;
28690 do {
28691 mp_number_trans (mp, &q->x_coord, &q->y_coord);
28692 q = mp_next_knot (q);
28693 } while (q != p);
28694 }
28695
28696
28697 @ The next transformation procedure applies to edge structures. It will do
28698 any transformation, but the results may be substandard if the picture contains
28699 text that uses downloaded bitmap fonts. The binary action procedure is
28700 |do_edges_trans|, but we also need a function that just scales a picture.
28701 That routine is |scale_edges|. Both it and the underlying routine |edges_trans|
28702 should be thought of as procedures that update an edge structure |h|, except
28703 that they have to return a (possibly new) structure because of the need to call
28704 |private_edges|.
28705
28706 @<Declare binary action...@>=
28707 static mp_edge_header_node mp_edges_trans (MP mp, mp_edge_header_node h) {
28708 mp_node q; /* the object being transformed */
28709 mp_dash_node r, s; /* for list manipulation */
28710 mp_number sx, sy; /* saved transformation parameters */
28711 mp_number sqdet; /* square root of determinant for |dash_scale| */
28712 mp_number sgndet; /* sign of the determinant */
28713 h = mp_private_edges (mp, h);
28714 new_number(sx);
28715 new_number(sy);
28716 new_number(sqdet);
28717 new_number(sgndet);
28718 mp_sqrt_det (mp, &sqdet, mp->txx, mp->txy, mp->tyx, mp->tyy);
28719 ab_vs_cd (sgndet, mp->txx, mp->tyy, mp->txy, mp->tyx);
28720 if (dash_list (h) != mp->null_dash) {
28721 @<Try to transform the dash list of |h|@>;
28722 }
28723 @<Make the bounding box of |h| unknown if it can't be updated properly
28724 without scanning the whole structure@>;
28725 q = mp_link (edge_list (h));
28726 while (q != NULL) {
28727 @<Transform graphical object |q|@>;
28728 q = mp_link (q);
28729 }
28730 free_number (sx);
28731 free_number (sy);
28732 free_number (sqdet);
28733 free_number(sgndet);
28734 return h;
28735 }
28736 static void mp_do_edges_trans (MP mp, mp_node p, quarterword c) {
28737 mp_set_up_known_trans (mp, c);
28738 set_value_node (p, (mp_node)mp_edges_trans (mp, (mp_edge_header_node)value_node (p)));
28739 mp_unstash_cur_exp (mp, p);
28740 }
28741 static mp_edge_header_node mp_scale_edges (MP mp, mp_number se_sf, mp_edge_header_node se_pic) {
28742 number_clone(mp->txx, se_sf);
28743 number_clone(mp->tyy, se_sf);
28744 set_number_to_zero(mp->txy);
28745 set_number_to_zero(mp->tyx);
28746 set_number_to_zero(mp->tx);
28747 set_number_to_zero(mp->ty);
28748 return mp_edges_trans (mp, se_pic);
28749 }
28750
28751
28752 @ @<Try to transform the dash list of |h|@>=
28753 if (number_nonzero(mp->txy) || number_nonzero(mp->tyx) ||
28754 number_nonzero(mp->ty) || number_nonequalabs (mp->txx, mp->tyy)) {
28755 mp_flush_dash_list (mp, h);
28756 } else {
28757 mp_number abs_tyy, ret;
28758 new_number (abs_tyy);
28759 if (number_negative(mp->txx))
28760 @<Reverse the dash list of |h|@>@;
28761 @<Scale the dash list by |txx| and shift it by |tx|@>;
28762 number_clone(abs_tyy, mp->tyy);
28763 number_abs (abs_tyy);
28764 new_number (ret);
28765 take_scaled (ret, h->dash_y, abs_tyy);
28766 number_clone(h->dash_y, ret);
28767 free_number (ret);
28768 free_number (abs_tyy);
28769 }
28770
28771
28772 @ @<Reverse the dash list of |h|@>=
28773 {
28774 r = dash_list (h);
28775 set_dash_list (h, mp->null_dash);
28776 while (r != mp->null_dash) {
28777 s = r;
28778 r = (mp_dash_node)mp_link (r);
28779 number_swap(s->start_x, s->stop_x );
28780 mp_link (s) = (mp_node)dash_list (h);
28781 set_dash_list (h, s);
28782 }
28783 }
28784
28785
28786 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
28787 r = dash_list (h);
28788 {
28789 mp_number arg1;
28790 new_number (arg1);
28791 while (r != mp->null_dash) {
28792 take_scaled (arg1, r->start_x, mp->txx);
28793 set_number_from_addition(r->start_x, arg1, mp->tx);
28794 take_scaled (arg1, r->stop_x, mp->txx);
28795 set_number_from_addition(r->stop_x, arg1, mp->tx);
28796 r = (mp_dash_node)mp_link (r);
28797 }
28798 free_number (arg1);
28799 }
28800
28801
28802 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
28803 if (number_zero(mp->txx) && number_zero(mp->tyy))
28804 @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>@;
28805 else if (number_nonzero(mp->txy) || number_nonzero(mp->tyx)) {
28806 mp_init_bbox (mp, h);
28807 goto DONE1;
28808 }
28809 if (number_lessequal (h->minx, h->maxx))
28810 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
28811 |(tx,ty)|@>@;
28812 DONE1:
28813
28814
28815 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
28816 {
28817 number_swap(h->minx, h->miny);
28818 number_swap(h->maxx, h->maxy);
28819 }
28820
28821
28822 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero. The other
28823 sum is similar.
28824
28825 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
28826 {
28827 mp_number tot, ret;
28828 new_number(tot);
28829 new_number (ret);
28830 set_number_from_addition(tot,mp->txx,mp->txy);
28831 take_scaled (ret, h->minx, tot);
28832 set_number_from_addition(h->minx,ret, mp->tx);
28833 take_scaled (ret, h->maxx, tot);
28834 set_number_from_addition(h->maxx,ret, mp->tx);
28835
28836 set_number_from_addition(tot,mp->tyx,mp->tyy);
28837 take_scaled (ret, h->miny, tot);
28838 set_number_from_addition(h->miny, ret, mp->ty);
28839 take_scaled (ret, h->maxy, tot);
28840 set_number_from_addition(h->maxy, ret, mp->ty);
28841
28842 set_number_from_addition(tot, mp->txx, mp->txy);
28843 if (number_negative(tot)) {
28844 number_swap(h->minx, h->maxx);
28845 }
28846 set_number_from_addition(tot, mp->tyx, mp->tyy);
28847 if (number_negative(tot)) {
28848 number_swap(h->miny, h->maxy);
28849 }
28850 free_number (ret);
28851 free_number (tot);
28852 }
28853
28854
28855 @ Now we ready for the main task of transforming the graphical objects in edge
28856 structure~|h|.
28857
28858 @<Transform graphical object |q|@>=
28859 switch (mp_type (q)) {
28860 case mp_fill_node_type:
28861 {
28862 mp_fill_node qq = (mp_fill_node) q;
28863 mp_do_path_trans (mp, mp_path_p (qq));
28864 @<Transform |mp_pen_p(qq)|, making sure polygonal pens stay counter-clockwise@>;
28865 }
28866 break;
28867 case mp_stroked_node_type:
28868 {
28869 mp_stroked_node qq = (mp_stroked_node) q;
28870 mp_do_path_trans (mp, mp_path_p (qq));
28871 @<Transform |mp_pen_p(qq)|, making sure polygonal pens stay counter-clockwise@>;
28872 }
28873 break;
28874 case mp_start_clip_node_type:
28875 mp_do_path_trans (mp, mp_path_p ((mp_start_clip_node) q));
28876 break;
28877 case mp_start_bounds_node_type:
28878 mp_do_path_trans (mp, mp_path_p ((mp_start_bounds_node) q));
28879 break;
28880 case mp_text_node_type:
28881 @<Transform the compact transformation@>;
28882 break;
28883 case mp_stop_clip_node_type:
28884 case mp_stop_bounds_node_type:
28885 break;
28886 default: /* there are no other valid cases, but please the compiler */
28887 break;
28888 }
28889
28890
28891 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
28892 The |dash_scale| has to be adjusted to scale the dash lengths in |mp_dash_p(q)|
28893 since the \ps\ output procedures will try to compensate for the transformation
28894 we are applying to |mp_pen_p(q)|. Since this compensation is based on the square
28895 root of the determinant, |sqdet| is the appropriate factor.
28896
28897 We pass the mptrap test only if |dash_scale| is not adjusted, nowadays
28898 (backend is changed?)
28899
28900 @<Transform |mp_pen_p(qq)|, making sure...@>=
28901 if (mp_pen_p (qq) != NULL) {
28902 number_clone(sx, mp->tx);
28903 number_clone(sy, mp->ty);
28904 set_number_to_zero(mp->tx);
28905 set_number_to_zero(mp->ty);
28906 mp_do_pen_trans (mp, mp_pen_p (qq));
28907 if (number_nonzero(sqdet)
28908 && ((mp_type (q) == mp_stroked_node_type) && (mp_dash_p (q) != NULL))) {
28909 mp_number ret;
28910 new_number (ret);
28911 take_scaled (ret, ((mp_stroked_node)q)->dash_scale, sqdet);
28912 number_clone(((mp_stroked_node)q)->dash_scale, ret);
28913 free_number (ret);
28914 }
28915 if (!pen_is_elliptical (mp_pen_p (qq)))
28916 if (number_negative(sgndet))
28917 mp_pen_p (qq) = mp_make_pen (mp, mp_copy_path (mp, mp_pen_p (qq)), true);
28918 /* this unreverses the pen */
28919 number_clone(mp->tx, sx);
28920 number_clone(mp->ty, sy);
28921 }
28922
28923 @ @<Transform the compact transformation@>=
28924 mp_number_trans (mp, &((mp_text_node)q)->tx, &((mp_text_node)q)->ty);
28925 number_clone(sx, mp->tx);
28926 number_clone(sy, mp->ty);
28927 set_number_to_zero(mp->tx);
28928 set_number_to_zero(mp->ty);
28929 mp_number_trans (mp, &((mp_text_node)q)->txx, &((mp_text_node)q)->tyx);
28930 mp_number_trans (mp, &((mp_text_node)q)->txy, &((mp_text_node)q)->tyy);
28931 number_clone(mp->tx, sx);
28932 number_clone(mp->ty, sy)@;
28933
28934 @ The hard cases of transformation occur when big nodes are involved,
28935 and when some of their components are unknown.
28936
28937 @<Declare binary action...@>=
28938 @<Declare subroutines needed by |big_trans|@>
28939 static void mp_big_trans (MP mp, mp_node p, quarterword c) {
28940 mp_node q, r, pp, qq; /* list manipulation registers */
28941 q = value_node (p);
28942 if (mp_type (q) == mp_pair_node_type) {
28943 if (mp_type (x_part (q)) != mp_known ||
28944 mp_type (y_part (q)) != mp_known) {
28945 @<Transform an unknown big node and |return|@>;
28946 }
28947 } else { /* |mp_transform_type| */
28948 if (mp_type (tx_part (q)) != mp_known ||
28949 mp_type (ty_part (q)) != mp_known ||
28950 mp_type (xx_part (q)) != mp_known ||
28951 mp_type (xy_part (q)) != mp_known ||
28952 mp_type (yx_part (q)) != mp_known ||
28953 mp_type (yy_part (q)) != mp_known) {
28954 @<Transform an unknown big node and |return|@>;
28955 }
28956 }
28957 @<Transform a known big node@>;
28958 } /* node |p| will now be recycled by |do_binary| */
28959
28960
28961 @ @<Transform an unknown big node and |return|@>=
28962 {
28963 mp_set_up_known_trans (mp, c);
28964 mp_make_exp_copy (mp, p);
28965 r = value_node (cur_exp_node ());
28966 if (mp->cur_exp.type == mp_transform_type) {
28967 mp_bilin1 (mp, yy_part (r), mp->tyy, xy_part (q), mp->tyx, zero_t);
28968 mp_bilin1 (mp, yx_part (r), mp->tyy, xx_part (q), mp->tyx, zero_t);
28969 mp_bilin1 (mp, xy_part (r), mp->txx, yy_part (q), mp->txy, zero_t);
28970 mp_bilin1 (mp, xx_part (r), mp->txx, yx_part (q), mp->txy, zero_t);
28971 }
28972 mp_bilin1 (mp, y_part (r), mp->tyy, x_part (q), mp->tyx, mp->ty);
28973 mp_bilin1 (mp, x_part (r), mp->txx, y_part (q), mp->txy, mp->tx);
28974 return;
28975 }
28976
28977
28978 @ Let |p| point to a value field inside a big node of |cur_exp|,
28979 and let |q| point to a another value field. The |bilin1| procedure
28980 replaces |p| by $p\cdot t+q\cdot u+\delta$.
28981
28982 @<Declare subroutines needed by |big_trans|@>=
28983 static void mp_bilin1 (MP mp, mp_node p, mp_number t, mp_node q,
28984 mp_number u, mp_number delta_orig) {
28985 mp_number delta;
28986 new_number (delta);
28987 number_clone (delta, delta_orig);
28988 if (!number_equal(t, unity_t)) {
28989 mp_dep_mult (mp, (mp_value_node) p, t, true);
28990 }
28991 if (number_nonzero(u)) {
28992 if (mp_type (q) == mp_known) {
28993 mp_number tmp;
28994 new_number (tmp);
28995 take_scaled (tmp, value_number (q), u);
28996 number_add (delta, tmp);
28997 free_number (tmp);
28998 } else {
28999 /* Ensure that |type(p)=mp_proto_dependent| */
29000 if (mp_type (p) != mp_proto_dependent) {
29001 if (mp_type (p) == mp_known) {
29002 mp_new_dep (mp, p, mp_type (p), mp_const_dependency (mp, value_number (p)));
29003 } else {
29004 set_dep_list ((mp_value_node) p,
29005 mp_p_times_v (mp,
29006 (mp_value_node) dep_list ((mp_value_node)
29007 p), unity_t,
29008 mp_dependent, mp_proto_dependent, true));
29009 }
29010 mp_type (p) = mp_proto_dependent;
29011 }
29012 set_dep_list ((mp_value_node) p,
29013 mp_p_plus_fq (mp,
29014 (mp_value_node) dep_list ((mp_value_node) p), u,
29015 (mp_value_node) dep_list ((mp_value_node) q),
29016 mp_proto_dependent, mp_type (q)));
29017 }
29018 }
29019 if (mp_type (p) == mp_known) {
29020 set_value_number (p, value_number (p));
29021 number_add (value_number (p), delta);
29022 } else {
29023 mp_number tmp;
29024 mp_value_node r; /* list traverser */
29025 new_number (tmp);
29026 r = (mp_value_node) dep_list ((mp_value_node) p);
29027 while (dep_info (r) != NULL)
29028 r = (mp_value_node) mp_link (r);
29029 number_clone (tmp, value_number(r));
29030 number_add (delta, tmp);
29031 if (r != (mp_value_node) dep_list ((mp_value_node) p))
29032 set_value_number (r, delta);
29033 else {
29034 mp_recycle_value (mp, p);
29035 mp_type (p) = mp_known;
29036 set_value_number (p, delta);
29037 }
29038 free_number (tmp);
29039 }
29040 if (mp->fix_needed)
29041 mp_fix_dependencies (mp);
29042 free_number (delta);
29043 }
29044
29045
29046 @ @<Transform a known big node@>=
29047 mp_set_up_trans (mp, c);
29048 if (mp->cur_exp.type == mp_known)
29049 @<Transform known by known@>@;
29050 else {
29051 pp = mp_stash_cur_exp (mp);
29052 qq = value_node (pp);
29053 mp_make_exp_copy (mp, p);
29054 r = value_node (cur_exp_node ());
29055 if (mp->cur_exp.type == mp_transform_type) {
29056 mp_bilin2 (mp, yy_part (r), yy_part (qq), value_number (xy_part (q)),
29057 yx_part (qq), NULL);
29058 mp_bilin2 (mp, yx_part (r), yy_part (qq), value_number (xx_part (q)),
29059 yx_part (qq), NULL);
29060 mp_bilin2 (mp, xy_part (r), xx_part (qq), value_number (yy_part (q)),
29061 xy_part (qq), NULL);
29062 mp_bilin2 (mp, xx_part (r), xx_part (qq), value_number (yx_part (q)),
29063 xy_part (qq), NULL);
29064 }
29065 mp_bilin2 (mp, y_part (r), yy_part (qq), value_number (x_part (q)),
29066 yx_part (qq), y_part (qq));
29067 mp_bilin2 (mp, x_part (r), xx_part (qq), value_number (y_part (q)),
29068 xy_part (qq), x_part (qq));
29069 mp_recycle_value (mp, pp);
29070 mp_free_value_node (mp, pp);
29071 }
29072
29073
29074 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
29075 at |dep_final|. The following procedure adds |v| times another
29076 numeric quantity to~|p|.
29077
29078 @<Declare subroutines needed by |big_trans|@>=
29079 static void mp_add_mult_dep (MP mp, mp_value_node p, mp_number v, mp_node r) {
29080 if (mp_type (r) == mp_known) {
29081 mp_number ret;
29082 new_number (ret);
29083 take_scaled (ret, value_number (r), v);
29084 set_dep_value (mp->dep_final, dep_value (mp->dep_final));
29085 number_add (dep_value (mp->dep_final), ret);
29086 free_number (ret);
29087 } else {
29088 set_dep_list (p,
29089 mp_p_plus_fq (mp, (mp_value_node) dep_list (p), v,
29090 (mp_value_node) dep_list ((mp_value_node) r),
29091 mp_proto_dependent, mp_type (r)));
29092 if (mp->fix_needed)
29093 mp_fix_dependencies (mp);
29094 }
29095 }
29096
29097
29098 @ The |bilin2| procedure is something like |bilin1|, but with known
29099 and unknown quantities reversed. Parameter |p| points to a value field
29100 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
29101 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
29102 unless it is |NULL| (which stands for zero). Location~|p| will be
29103 replaced by $p\cdot t+v\cdot u+q$.
29104
29105 @<Declare subroutines needed by |big_trans|@>=
29106 static void mp_bilin2 (MP mp, mp_node p, mp_node t, mp_number v,
29107 mp_node u, mp_node q) {
29108 mp_number vv; /* temporary storage for |value(p)| */
29109 new_number (vv);
29110 number_clone (vv, value_number (p));
29111 mp_new_dep (mp, p, mp_proto_dependent, mp_const_dependency (mp, zero_t)); /* this sets |dep_final| */
29112 if (number_nonzero(vv)) {
29113 mp_add_mult_dep (mp, (mp_value_node) p, vv, t); /* |dep_final| doesn't change */
29114 }
29115 if (number_nonzero(v)) {
29116 mp_number arg1;
29117 new_number (arg1);
29118 number_clone (arg1, v);
29119 mp_add_mult_dep (mp, (mp_value_node) p, arg1, u);
29120 free_number (arg1);
29121 }
29122 if (q != NULL)
29123 mp_add_mult_dep (mp, (mp_value_node) p, unity_t, q);
29124 if (dep_list ((mp_value_node) p) == (mp_node) mp->dep_final) {
29125 number_clone (vv, dep_value (mp->dep_final));
29126 mp_recycle_value (mp, p);
29127 mp_type (p) = mp_known;
29128 set_value_number (p, vv);
29129 }
29130 free_number (vv);
29131 }
29132
29133
29134 @ @<Transform known by known@>=
29135 {
29136 mp_make_exp_copy (mp, p);
29137 r = value_node (cur_exp_node ());
29138 if (mp->cur_exp.type == mp_transform_type) {
29139 mp_bilin3 (mp, yy_part (r), mp->tyy, value_number (xy_part (q)), mp->tyx, zero_t);
29140 mp_bilin3 (mp, yx_part (r), mp->tyy, value_number (xx_part (q)), mp->tyx, zero_t);
29141 mp_bilin3 (mp, xy_part (r), mp->txx, value_number (yy_part (q)), mp->txy, zero_t);
29142 mp_bilin3 (mp, xx_part (r), mp->txx, value_number (yx_part (q)), mp->txy, zero_t);
29143 }
29144 mp_bilin3 (mp, y_part (r), mp->tyy, value_number (x_part (q)), mp->tyx, mp->ty);
29145 mp_bilin3 (mp, x_part (r), mp->txx, value_number (y_part (q)), mp->txy, mp->tx);
29146 }
29147
29148
29149 @ Finally, in |bilin3| everything is |known|.
29150
29151 @<Declare subroutines needed by |big_trans|@>=
29152 static void mp_bilin3 (MP mp, mp_node p, mp_number t,
29153 mp_number v, mp_number u, mp_number delta_orig) {
29154 mp_number delta;
29155 mp_number tmp;
29156 new_number (tmp);
29157 new_number (delta);
29158 number_clone (delta, delta_orig);
29159 if (!number_equal(t, unity_t)) {
29160 take_scaled (tmp, value_number (p), t);
29161 } else {
29162 number_clone (tmp, value_number (p));
29163 }
29164 number_add (delta, tmp);
29165 if (number_nonzero(u)) {
29166 mp_number ret;
29167 new_number (ret);
29168 take_scaled (ret, v, u);
29169 set_value_number (p, delta);
29170 number_add (value_number (p), ret);
29171 free_number (ret);
29172 } else
29173 set_value_number (p, delta);
29174 free_number (tmp);
29175 free_number (delta);
29176 }
29177
29178
29179 @ @<Declare binary action...@>=
29180 static void mp_chop_path (MP mp, mp_node p) {
29181 mp_knot q; /* a knot in the original path */
29182 mp_knot pp, qq, rr, ss; /* link variables for copies of path nodes */
29183 mp_number a, b; /* indices for chopping */
29184 mp_number l;
29185 boolean reversed; /* was |a>b|? */
29186 new_number (a);
29187 new_number (b);
29188 new_number (l);
29189 mp_path_length (mp, &l);
29190 number_clone (a, value_number (x_part (p)));
29191 number_clone (b, value_number (y_part (p)));
29192 if (number_lessequal(a, b)) {
29193 reversed = false;
29194 } else {
29195 reversed = true;
29196 number_swap (a, b);
29197 }
29198 /* Dispense with the cases |a<0| and/or |b>l| */
29199 if (number_negative(a)) {
29200 if (mp_left_type (cur_exp_knot ()) == mp_endpoint) {
29201 set_number_to_zero(a);
29202 if (number_negative(b))
29203 set_number_to_zero(b);
29204 } else {
29205 do {
29206 number_add (a, l);
29207 number_add (b, l);
29208 } while (number_negative(a)); /* a cycle always has length |l>0| */
29209 }
29210 }
29211 if (number_greater (b, l)) {
29212 if (mp_left_type (cur_exp_knot ()) == mp_endpoint) {
29213 number_clone (b, l);
29214 if (number_greater (a, l))
29215 number_clone(a, l);
29216 } else {
29217 while (number_greaterequal (a, l)) {
29218 number_substract (a, l);
29219 number_substract (b, l);
29220 }
29221 }
29222 }
29223
29224 q = cur_exp_knot ();
29225 while (number_greaterequal(a, unity_t)) {
29226 q = mp_next_knot (q);
29227 number_substract(a, unity_t);
29228 number_substract(b, unity_t);
29229 }
29230 if (number_equal(b, a)) {
29231 /* Construct a path from |pp| to |qq| of length zero */
29232 if (number_positive (a)) {
29233 mp_number arg1;
29234 new_number (arg1);
29235 number_clone (arg1, a);
29236 convert_scaled_to_fraction (arg1);
29237 mp_split_cubic (mp, q, arg1);
29238 free_number (arg1);
29239 q = mp_next_knot (q);
29240 }
29241 pp = mp_copy_knot (mp, q);
29242 qq = pp;
29243
29244 } else {
29245 /* Construct a path from |pp| to |qq| of length $\lceil b\rceil$ */
29246 pp = mp_copy_knot (mp, q);
29247 qq = pp;
29248 do {
29249 q = mp_next_knot (q);
29250 rr = qq;
29251 qq = mp_copy_knot (mp, q);
29252 mp_next_knot (rr) = qq;
29253 number_substract (b, unity_t);
29254 } while (number_positive (b));
29255 if (number_positive (a)) {
29256 mp_number arg1;
29257 new_number (arg1);
29258 ss = pp;
29259 number_clone (arg1, a);
29260 convert_scaled_to_fraction (arg1);
29261 mp_split_cubic (mp, ss, arg1);
29262 free_number (arg1);
29263 pp = mp_next_knot (ss);
29264 mp_toss_knot (mp, ss);
29265 if (rr == ss) {
29266 mp_number arg1, arg2;
29267 new_number (arg1);
29268 new_number (arg2);
29269 set_number_from_substraction (arg1, unity_t, a);
29270 number_clone (arg2, b);
29271 make_scaled (b, arg2, arg1);
29272 free_number (arg1);
29273 free_number (arg2);
29274 rr = pp;
29275 }
29276 }
29277 if (number_negative (b)) {
29278 mp_number arg1;
29279 new_number (arg1);
29280 set_number_from_addition (arg1, b, unity_t);
29281 convert_scaled_to_fraction (arg1);
29282 mp_split_cubic (mp, rr, arg1);
29283 free_number (arg1);
29284 mp_toss_knot (mp, qq);
29285 qq = mp_next_knot (rr);
29286 }
29287
29288 }
29289 mp_left_type (pp) = mp_endpoint;
29290 mp_right_type (qq) = mp_endpoint;
29291 mp_next_knot (qq) = pp;
29292 mp_toss_knot_list (mp, cur_exp_knot ());
29293 if (reversed) {
29294 set_cur_exp_knot (mp_next_knot (mp_htap_ypoc (mp, pp)));
29295 mp_toss_knot_list (mp, pp);
29296 } else {
29297 set_cur_exp_knot (pp);
29298 }
29299 free_number (l);
29300 free_number (a);
29301 free_number (b);
29302 }
29303
29304
29305 @ @<Declare binary action...@>=
29306 static void mp_set_up_offset (MP mp, mp_node p) {
29307 mp_find_offset (mp, value_number (x_part (p)), value_number (y_part (p)),
29308 cur_exp_knot ());
29309 mp_pair_value (mp, mp->cur_x, mp->cur_y);
29310 }
29311 static void mp_set_up_direction_time (MP mp, mp_node p) {
29312 mp_value new_expr;
29313 memset(&new_expr,0,sizeof(mp_value));
29314 new_number (new_expr.data.n);
29315 mp_find_direction_time (mp, &new_expr.data.n, value_number (x_part (p)),
29316 value_number (y_part (p)),
29317 cur_exp_knot ());
29318 mp_flush_cur_exp (mp, new_expr);
29319 }
29320 static void mp_set_up_envelope (MP mp, mp_node p) {
29321 unsigned char ljoin, lcap;
29322 mp_number miterlim;
29323 mp_knot q = mp_copy_path (mp, cur_exp_knot ()); /* the original path */
29324 new_number(miterlim);
29325 /* TODO: accept elliptical pens for straight paths */
29326 if (pen_is_elliptical (value_knot (p))) {
29327 mp_bad_envelope_pen (mp);
29328 set_cur_exp_knot (q);
29329 mp->cur_exp.type = mp_path_type;
29330 return;
29331 }
29332 if (number_greater (internal_value (mp_linejoin), unity_t))
29333 ljoin = 2;
29334 else if (number_positive (internal_value (mp_linejoin)))
29335 ljoin = 1;
29336 else
29337 ljoin = 0;
29338 if (number_greater (internal_value (mp_linecap), unity_t))
29339 lcap = 2;
29340 else if (number_positive (internal_value (mp_linecap)))
29341 lcap = 1;
29342 else
29343 lcap = 0;
29344 if (number_less (internal_value (mp_miterlimit), unity_t))
29345 set_number_to_unity(miterlim);
29346 else
29347 number_clone(miterlim, internal_value (mp_miterlimit));
29348 set_cur_exp_knot (mp_make_envelope
29349 (mp, q, value_knot (p), ljoin, lcap, miterlim));
29350 mp->cur_exp.type = mp_path_type;
29351 }
29352 static void mp_set_up_boundingpath (MP mp, mp_node p) {
29353 unsigned char ljoin, lcap;
29354 mp_number miterlim;
29355 mp_knot q = mp_copy_path (mp, cur_exp_knot ()); /* the original path */
29356 mp_knot pen;
29357 mp_knot qq;
29358
29359 new_number(miterlim);
29360 pen = (value_knot (p));
29361 /* accept elliptical pens for s paths */
29362 /* using |mp_make_path| to convert an elliptical pen to a polygonal one. */
29363 /* The approximation of 8 knots should be good enough. */
29364 if (pen_is_elliptical (value_knot (p))) {
29365 mp_knot kp,kq;
29366 pen = copy_pen (value_knot (p));
29367 mp_make_path(mp, pen);
29368 kq=pen;
29369 do {
29370 kp = kq;
29371 kq = mp_next_knot (kq);
29372 mp_prev_knot (kq) = kp;
29373 } while (kq != pen);
29374 mp_close_path_cycle (mp, kp, pen);
29375 }
29376 if (number_greater (internal_value (mp_linejoin), unity_t))
29377 ljoin = 2;
29378 else if (number_positive (internal_value (mp_linejoin)))
29379 ljoin = 1;
29380 else
29381 ljoin = 0;
29382 if (number_greater (internal_value (mp_linecap), unity_t))
29383 lcap = 2;
29384 else if (number_positive (internal_value (mp_linecap)))
29385 lcap = 1;
29386 else
29387 lcap = 0;
29388 if (number_less (internal_value (mp_miterlimit), unity_t))
29389 set_number_to_unity(miterlim);
29390 else
29391 number_clone(miterlim, internal_value (mp_miterlimit));
29392 qq = mp_make_envelope(mp, q, pen, ljoin, lcap, miterlim);
29393 set_cur_exp_knot (qq);
29394 mp->cur_exp.type = mp_path_type;
29395 if (!mp_get_cur_bbox (mp)) {
29396 mp_bad_binary (mp, p, mp_boundingpath_of);
29397 set_cur_exp_knot (q);
29398 mp->cur_exp.type = mp_path_type;
29399 return;
29400 }
29401 else {
29402 mp_knot ll,lr,ur,ul;
29403 ll = mp_new_knot (mp);
29404 lr = mp_new_knot (mp);
29405 ur = mp_new_knot (mp);
29406 ul = mp_new_knot (mp);
29407 if (ll==NULL || lr==NULL || ur==NULL || ul==NULL){
29408 mp_bad_binary (mp, p, mp_boundingpath_of);
29409 set_cur_exp_knot (q);
29410 mp->cur_exp.type = mp_path_type;
29411 return;
29412 }
29413 mp_left_type (ll) = mp_endpoint;
29414 mp_right_type (ll) = mp_endpoint;
29415 mp_originator (ll) = mp_program_code;
29416 number_clone(ll->x_coord,mp_minx);
29417 number_clone(ll->y_coord,mp_miny);
29418
29419 mp_originator (lr) = mp_program_code;
29420 number_clone(lr->x_coord,mp_maxx);
29421 number_clone(lr->y_coord,mp_miny);
29422
29423 mp_originator (ur) = mp_program_code;
29424 number_clone(ur->x_coord,mp_maxx);
29425 number_clone(ur->y_coord,mp_maxy);
29426
29427 mp_originator (ul) = mp_program_code;
29428 number_clone(ul->x_coord,mp_minx);
29429 number_clone(ul->y_coord,mp_maxy);
29430
29431 mp_next_knot (ll) = lr;
29432 mp_next_knot (lr) = ur;
29433 mp_next_knot (ur) = ul;
29434
29435 mp_close_path_cycle (mp, ul, ll);
29436 mp_make_path(mp,ll);
29437 mp->cur_exp.type = mp_path_type;
29438 set_cur_exp_knot(ll);
29439 mp_free_path(mp,qq);
29440
29441 }
29442 }
29443
29444
29445
29446
29447 @ This is pretty straightforward. The one silly thing is that
29448 the output of |mp_ps_do_font_charstring| has to be un-exported.
29449
29450 @s mp_ps_font int
29451
29452 @<Declare binary action...@>=
29453 static void mp_set_up_glyph_infont (MP mp, mp_node p) {
29454 mp_edge_object *h = NULL;
29455 mp_ps_font *f = NULL;
29456 char *n = mp_str (mp, cur_exp_str ());
29457 f = mp_ps_font_parse (mp, (int) mp_find_font (mp, n));
29458 if (f != NULL) {
29459 if (mp_type (p) == mp_known) {
29460 mpinteger64 v = round_unscaled (value_number (p));
29461 if (v < 0 || v > 255) {
29462 char msg[256];
29463 mp_snprintf (msg, 256, "glyph index too high (%" PRId64 ")", v);
29464 mp_error (mp, msg, NULL, true);
29465 } else {
29466 h = mp_ps_font_charstring (mp, f, v);
29467 }
29468 } else {
29469 n = mp_str (mp, value_str (p));
29470 h = mp_ps_do_font_charstring (mp, f, n);
29471 }
29472 mp_ps_font_free (mp, f);
29473 }
29474 if (h != NULL) {
29475 set_cur_exp_node ((mp_node)mp_gr_import (mp, h));
29476 } else {
29477 set_cur_exp_node ((mp_node)mp_get_edge_header_node (mp));
29478 mp_init_edges (mp, (mp_edge_header_node)cur_exp_node ());
29479 }
29480 mp->cur_exp.type = mp_picture_type;
29481 }
29482
29483
29484 @ @<Declare binary action...@>=
29485 static void mp_find_point (MP mp, mp_number v_orig, quarterword c) {
29486 mp_knot p; /* the path */
29487 mp_number n; /* its length */
29488 mp_number v;
29489 new_number (v);
29490 new_number (n);
29491 number_clone (v, v_orig);
29492 p = cur_exp_knot ();
29493 if (mp_left_type (p) == mp_endpoint) {
29494 set_number_to_unity (n);
29495 number_negate (n);
29496 } else {
29497 set_number_to_zero (n);
29498 }
29499 do {
29500 p = mp_next_knot (p);
29501 number_add (n, unity_t);
29502 } while (p != cur_exp_knot ());
29503 if (number_zero (n)) {
29504 set_number_to_zero(v);
29505 } else if (number_negative(v)) {
29506 if (mp_left_type (p) == mp_endpoint) {
29507 set_number_to_zero(v);
29508 } else {
29509 /* |v = n - 1 - ((-v - 1) % n)
29510 == - ((-v - 1) % n) - 1 + n| */
29511 number_negate (v);
29512 number_add_scaled (v, -1);
29513 number_modulo (v, n);
29514 number_negate (v);
29515 number_add_scaled (v, -1);
29516 number_add (v, n);
29517 }
29518 } else if (number_greater(v, n)) {
29519 if (mp_left_type (p) == mp_endpoint)
29520 number_clone (v, n);
29521 else
29522 number_modulo (v, n);
29523 }
29524 p = cur_exp_knot ();
29525 while (number_greaterequal(v, unity_t)) {
29526 p = mp_next_knot (p);
29527 number_substract (v, unity_t);
29528 }
29529 if (number_nonzero(v)) {
29530 /* Insert a fractional node by splitting the cubic */
29531 convert_scaled_to_fraction (v);
29532 mp_split_cubic (mp, p, v);
29533 p = mp_next_knot (p);
29534 }
29535 /* Set the current expression to the desired path coordinates */
29536 switch (c) {
29537 case mp_point_of:
29538 mp_pair_value (mp, p->x_coord, p->y_coord);
29539 break;
29540 case mp_precontrol_of:
29541 if (mp_left_type (p) == mp_endpoint)
29542 mp_pair_value (mp, p->x_coord, p->y_coord);
29543 else
29544 mp_pair_value (mp, p->left_x, p->left_y);
29545 break;
29546 case mp_postcontrol_of:
29547 if (mp_right_type (p) == mp_endpoint)
29548 mp_pair_value (mp, p->x_coord, p->y_coord);
29549 else
29550 mp_pair_value (mp, p->right_x, p->right_y);
29551 break;
29552 } /* there are no other cases */
29553 free_number (v);
29554 free_number (n);
29555 }
29556
29557 @ Function |new_text_node| owns the reference count for its second argument
29558 (the text string) but not its first (the font name).
29559
29560 @<Declare binary action...@>=
29561 static void mp_do_infont (MP mp, mp_node p) {
29562 mp_edge_header_node q;
29563 mp_value new_expr;
29564 memset(&new_expr,0,sizeof(mp_value));
29565 new_number(new_expr.data.n);
29566 q = mp_get_edge_header_node (mp);
29567 mp_init_edges (mp, q);
29568 add_str_ref (cur_exp_str());
29569 mp_link (obj_tail (q)) =
29570 mp_new_text_node (mp, mp_str (mp, cur_exp_str ()), value_str (p));
29571 obj_tail (q) = mp_link (obj_tail (q));
29572 mp_free_value_node (mp, p);
29573 new_expr.data.node = (mp_node)q;
29574 mp_flush_cur_exp (mp, new_expr);
29575 mp->cur_exp.type = mp_picture_type;
29576 }
29577
29578
29579 @* Statements and commands.
29580 The chief executive of \MP\ is the |do_statement| routine, which
29581 contains the master switch that causes all the various pieces of \MP\
29582 to do their things, in the right order.
29583
29584 In a sense, this is the grand climax of the program: It applies all the
29585 tools that we have worked so hard to construct. In another sense, this is
29586 the messiest part of the program: It necessarily refers to other pieces
29587 of code all over the place, so that a person can't fully understand what is
29588 going on without paging back and forth to be reminded of conventions that
29589 are defined elsewhere. We are now at the hub of the web.
29590
29591 The structure of |do_statement| itself is quite simple. The first token
29592 of the statement is fetched using |get_x_next|. If it can be the first
29593 token of an expression, we look for an equation, an assignment, or a
29594 title. Otherwise we use a \&{case} construction to branch at high speed to
29595 the appropriate routine for various and sundry other types of commands,
29596 each of which has an ``action procedure'' that does the necessary work.
29597
29598 The program uses the fact that
29599 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
29600 to interpret a statement that starts with, e.g., `\&{string}',
29601 as a type declaration rather than a boolean expression.
29602
29603 @c
29604 static void worry_about_bad_statement (MP mp);
29605 static void flush_unparsable_junk_after_statement (MP mp);
29606 void mp_do_statement (MP mp) { /* governs \MP's activities */
29607 mp->cur_exp.type = mp_vacuous;
29608 mp_get_x_next (mp);
29609 if (cur_cmd() > mp_max_primary_command) {
29610 worry_about_bad_statement (mp);
29611 } else if (cur_cmd() > mp_max_statement_command) {
29612 /* Do an equation, assignment, title, or
29613 `$\langle\,$expression$\,\rangle\,$\&{endgroup}'; */
29614 /* The most important statements begin with expressions */
29615 mp_value new_expr;
29616 mp->var_flag = mp_assignment;
29617 mp_scan_expression (mp);
29618 if (cur_cmd() < mp_end_group) {
29619 if (cur_cmd() == mp_equals)
29620 mp_do_equation (mp);
29621 else if (cur_cmd() == mp_assignment)
29622 mp_do_assignment (mp);
29623 else if (mp->cur_exp.type == mp_string_type) {
29624 /* Do a title */
29625 if (number_positive (internal_value (mp_tracing_titles))) {
29626 mp_print_nl (mp, "");
29627 mp_print_str (mp, cur_exp_str ());
29628 update_terminal();
29629 }
29630 } else if (mp->cur_exp.type != mp_vacuous) {
29631 const char *hlp[] = {
29632 "I couldn't find an `=' or `:=' after the",
29633 "expression that is shown above this error message,",
29634 "so I guess I'll just ignore it and carry on.",
29635 NULL };
29636 mp_disp_err(mp, NULL);
29637 mp_back_error (mp, "Isolated expression", hlp, true);
29638 mp_get_x_next (mp);
29639 }
29640 memset(&new_expr,0,sizeof(mp_value));
29641 new_number(new_expr.data.n);
29642 set_number_to_zero (new_expr.data.n);
29643 mp_flush_cur_exp (mp, new_expr);
29644 mp->cur_exp.type = mp_vacuous;
29645 }
29646 } else {
29647 /* Do a statement that doesn't begin with an expression */
29648 /* If |do_statement| ends with |cur_cmd=end_group|, we should have
29649 |cur_type=mp_vacuous| unless the statement was simply an expression;
29650 in the latter case, |cur_type| and |cur_exp| should represent that
29651 expression. */
29652 if (number_positive (internal_value (mp_tracing_commands)))
29653 show_cur_cmd_mod;
29654 switch (cur_cmd()) {
29655 case mp_type_name:
29656 mp_do_type_declaration (mp);
29657 break;
29658 case mp_macro_def:
29659 if (cur_mod() > var_def)
29660 mp_make_op_def (mp);
29661 else if (cur_mod() > end_def)
29662 mp_scan_def (mp);
29663 break;
29664 case mp_random_seed:
29665 mp_do_random_seed (mp);
29666 break;
29667 case mp_mode_command:
29668 mp_print_ln (mp);
29669 mp->interaction = cur_mod();
29670 initialize_print_selector();
29671 if (mp->log_opened)
29672 mp->selector = mp->selector + 2;
29673 mp_get_x_next (mp);
29674 break;
29675 case mp_protection_command:
29676 mp_do_protection (mp);
29677 break;
29678 case mp_delimiters:
29679 mp_def_delims (mp);
29680 break;
29681 case mp_save_command:
29682 do {
29683 mp_get_symbol (mp);
29684 mp_save_variable (mp, cur_sym());
29685 mp_get_x_next (mp);
29686 } while (cur_cmd() == mp_comma);
29687 break;
29688 case mp_interim_command:
29689 mp_do_interim (mp);
29690 break;
29691 case mp_let_command:
29692 mp_do_let (mp);
29693 break;
29694 case mp_new_internal:
29695 mp_do_new_internal (mp);
29696 break;
29697 case mp_show_command:
29698 mp_do_show_whatever (mp);
29699 break;
29700 case mp_add_to_command:
29701 mp_do_add_to (mp);
29702 break;
29703 case mp_bounds_command:
29704 mp_do_bounds (mp);
29705 break;
29706 case mp_ship_out_command:
29707 mp_do_ship_out (mp);
29708 break;
29709 case mp_every_job_command:
29710 mp_get_symbol (mp);
29711 mp->start_sym = cur_sym();
29712 mp_get_x_next (mp);
29713 break;
29714 case mp_message_command:
29715 mp_do_message (mp);
29716 break;
29717 case mp_write_command:
29718 mp_do_write (mp);
29719 break;
29720 case mp_tfm_command:
29721 mp_do_tfm_command (mp);
29722 break;
29723 case mp_special_command:
29724 if (cur_mod() == 0)
29725 mp_do_special (mp);
29726 else if (cur_mod() == 1)
29727 mp_do_mapfile (mp);
29728 else
29729 mp_do_mapline (mp);
29730 break;
29731 default:
29732 break; /* make the compiler happy */
29733 }
29734 mp->cur_exp.type = mp_vacuous;
29735 }
29736 if (cur_cmd() < mp_semicolon)
29737 flush_unparsable_junk_after_statement(mp);
29738 mp->error_count = 0;
29739 }
29740
29741
29742 @ @<Declarations@>=
29743 @<Declare action procedures for use by |do_statement|@>
29744
29745
29746 @ The only command codes |>max_primary_command| that can be present
29747 at the beginning of a statement are |semicolon| and higher; these
29748 occur when the statement is null.
29749
29750 @c
29751 static void worry_about_bad_statement (MP mp) {
29752 if (cur_cmd() < mp_semicolon) {
29753 char msg[256];
29754 mp_string sname;
29755 int old_setting = mp->selector;
29756 const char *hlp[] = {
29757 "I was looking for the beginning of a new statement.",
29758 "If you just proceed without changing anything, I'll ignore",
29759 "everything up to the next `;'. Please insert a semicolon",
29760 "now in front of anything that you don't want me to delete.",
29761 "(See Chapter 27 of The METAFONTbook for an example.)",
29762 NULL };
29763 mp->selector = new_string;
29764 mp_print_cmd_mod (mp, cur_cmd(), cur_mod());
29765 sname = mp_make_string(mp);
29766 mp->selector = old_setting;
29767 mp_snprintf (msg, 256, "A statement can't begin with `%s'", mp_str(mp, sname));
29768 delete_str_ref(sname);
29769 mp_back_error (mp, msg, hlp, true);
29770 mp_get_x_next (mp);
29771 }
29772 }
29773
29774
29775 @ The help message printed here says that everything is flushed up to
29776 a semicolon, but actually the commands |end_group| and |stop| will
29777 also terminate a statement.
29778
29779 @c
29780 static void flush_unparsable_junk_after_statement (MP mp)
29781 {
29782 const char *hlp[] = {
29783 "I've just read as much of that statement as I could fathom,",
29784 "so a semicolon should have been next. It's very puzzling...",
29785 "but I'll try to get myself back together, by ignoring",
29786 "everything up to the next `;'. Please insert a semicolon",
29787 "now in front of anything that you don't want me to delete.",
29788 "(See Chapter 27 of The METAFONTbook for an example.)",
29789 NULL };
29790 mp_back_error (mp, "Extra tokens will be flushed", hlp, true);
29791 mp->scanner_status = flushing;
29792 do {
29793 get_t_next (mp);
29794 if (cur_cmd() == mp_string_token) {
29795 delete_str_ref (cur_mod_str());
29796 }
29797 } while (!mp_end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
29798 mp->scanner_status = normal;
29799 }
29800
29801
29802
29803 @ Equations and assignments are performed by the pair of mutually recursive
29804 @^recursion@>
29805 routines |do_equation| and |do_assignment|. These routines are called when
29806 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
29807 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
29808 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
29809 will be equal to the right-hand side (which will normally be equal
29810 to the left-hand side).
29811
29812 @<Declarations@>=
29813 @<Declare the procedure called |make_eq|@>
29814 static void mp_do_equation (MP mp);
29815
29816 @ @c
29817 static void trace_equation (MP mp, mp_node lhs) {
29818 mp_begin_diagnostic (mp);
29819 mp_print_nl (mp, "{(");
29820 mp_print_exp (mp, lhs, 0);
29821 mp_print (mp, ")=(");
29822 mp_print_exp (mp, NULL, 0);
29823 mp_print (mp, ")}");
29824 mp_end_diagnostic (mp, false);
29825 }
29826 void mp_do_equation (MP mp) {
29827 mp_node lhs; /* capsule for the left-hand side */
29828 lhs = mp_stash_cur_exp (mp);
29829 mp_get_x_next (mp);
29830 mp->var_flag = mp_assignment;
29831 mp_scan_expression (mp);
29832 if (cur_cmd() == mp_equals)
29833 mp_do_equation (mp);
29834 else if (cur_cmd() == mp_assignment)
29835 mp_do_assignment (mp);
29836 if (number_greater (internal_value (mp_tracing_commands), two_t)) {
29837 trace_equation(mp, lhs);
29838 }
29839 if (mp->cur_exp.type == mp_unknown_path) {
29840 if (mp_type (lhs) == mp_pair_type) {
29841 mp_node p; /* temporary register */
29842 p = mp_stash_cur_exp (mp);
29843 mp_unstash_cur_exp (mp, lhs);
29844 lhs = p;
29845 } /* in this case |make_eq| will change the pair to a path */
29846 }
29847 mp_make_eq (mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
29848 }
29849
29850
29851 @ And |do_assignment| is similar to |do_equation|:
29852
29853 @<Declarations@>=
29854 static void mp_do_assignment (MP mp);
29855
29856 @ @c
29857 static void bad_lhs (MP mp) {
29858 const char *hlp[] = {
29859 "I didn't find a variable name at the left of the `:=',",
29860 "so I'm going to pretend that you said `=' instead.",
29861 NULL };
29862 mp_disp_err(mp, NULL);
29863 mp_error (mp, "Improper `:=' will be changed to `='", hlp, true);
29864 mp_do_equation (mp);
29865 }
29866 static void bad_internal_assignment (MP mp, mp_node lhs) {
29867 char msg[256];
29868 const char *hlp[] = {
29869 "I can\'t set this internal quantity to anything but a known",
29870 "numeric value, so I'll have to ignore this assignment.",
29871 NULL };
29872 mp_disp_err(mp, NULL);
29873 if (internal_type (mp_sym_info (lhs)) == mp_known) {
29874 mp_snprintf (msg, 256, "Internal quantity `%s' must receive a known numeric value",
29875 internal_name (mp_sym_info (lhs)));
29876 } else {
29877 mp_snprintf (msg, 256, "Internal quantity `%s' must receive a known string",
29878 internal_name (mp_sym_info (lhs)));
29879 hlp[1] = "string, so I'll have to ignore this assignment.";
29880 }
29881 mp_back_error (mp, msg, hlp, true);
29882 mp_get_x_next (mp);
29883 }
29884 static void forbidden_internal_assignment (MP mp, mp_node lhs) {
29885 char msg[256];
29886 const char *hlp[] = {
29887 "I can\'t set this internal quantity to anything just yet",
29888 "(it is read-only), so I'll have to ignore this assignment.",
29889 NULL };
29890 mp_snprintf (msg, 256, "Internal quantity `%s' is read-only",
29891 internal_name (mp_sym_info (lhs)));
29892 mp_back_error (mp, msg, hlp, true);
29893 mp_get_x_next (mp);
29894 }
29895 static void bad_internal_assignment_precision (MP mp, mp_node lhs, mp_number min, mp_number max) {
29896 char msg[256];
29897 char s[256];
29898 const char *hlp[] = {
29899 "Precision values are limited by the current numbersystem.",
29900 NULL,
29901 NULL } ;
29902 mp_snprintf (msg, 256, "Bad '%s' has been ignored", internal_name (mp_sym_info (lhs)));
29903 mp_snprintf (s, 256, "Currently I am using '%s'; the allowed precision range is [%s,%s].",
29904 mp_str (mp, internal_string (mp_number_system)), number_tostring(min), number_tostring(max));
29905 hlp[1] = s;
29906 mp_back_error (mp, msg, hlp, true);
29907 mp_get_x_next (mp);
29908 }
29909 static void bad_expression_assignment (MP mp, mp_node lhs) {
29910 const char *hlp[] = {
29911 "It seems you did a nasty thing---probably by accident,",
29912 "but nevertheless you nearly hornswoggled me...",
29913 "While I was evaluating the right-hand side of this",
29914 "command, something happened, and the left-hand side",
29915 "is no longer a variable! So I won't change anything.",
29916 NULL };
29917 char *msg = mp_obliterated (mp, lhs);
29918 mp_back_error (mp, msg, hlp, true);
29919 free(msg);
29920 mp_get_x_next (mp);
29921 }
29922 static void trace_assignment (MP mp, mp_node lhs) {
29923 mp_begin_diagnostic (mp);
29924 mp_print_nl (mp, "{");
29925 if (mp_name_type (lhs) == mp_internal_sym)
29926 mp_print (mp, internal_name (mp_sym_info (lhs)));
29927 else
29928 mp_show_token_list (mp, lhs, NULL, 1000, 0);
29929 mp_print (mp, ":=");
29930 mp_print_exp (mp, NULL, 0);
29931 mp_print_char (mp, xord ('}'));
29932 mp_end_diagnostic (mp, false);
29933 }
29934 void mp_do_assignment (MP mp) {
29935 if (mp->cur_exp.type != mp_token_list) {
29936 bad_lhs(mp);
29937 } else {
29938 mp_node lhs; /* token list for the left-hand side */
29939 lhs = cur_exp_node ();
29940 mp->cur_exp.type = mp_vacuous;
29941 mp_get_x_next (mp);
29942 mp->var_flag = mp_assignment;
29943 mp_scan_expression (mp);
29944 if (cur_cmd() == mp_equals)
29945 mp_do_equation (mp);
29946 else if (cur_cmd() == mp_assignment)
29947 mp_do_assignment (mp);
29948 if (number_greater (internal_value (mp_tracing_commands), two_t)) {
29949 trace_assignment (mp, lhs);
29950 }
29951 if (mp_name_type (lhs) == mp_internal_sym) {
29952 /* Assign the current expression to an internal variable */
29953 if ((mp->cur_exp.type == mp_known || mp->cur_exp.type == mp_string_type)
29954 && (internal_type (mp_sym_info (lhs)) == mp->cur_exp.type)) {
29955 if(mp_sym_info (lhs) == mp_number_system) {
29956 forbidden_internal_assignment (mp, lhs);
29957 } else if (mp_sym_info (lhs) == mp_number_precision) {
29958 if (!(mp->cur_exp.type == mp_known &&
29959 (!number_less(cur_exp_value_number(), precision_min)) &&
29960 (!number_greater(cur_exp_value_number(), precision_max))
29961 )) {
29962 bad_internal_assignment_precision(mp, lhs, precision_min, precision_max);
29963 } else {
29964 set_internal_from_cur_exp(mp_sym_info (lhs));
29965 set_precision();
29966 }
29967 } else {
29968 set_internal_from_cur_exp(mp_sym_info (lhs));
29969 }
29970 } else {
29971 bad_internal_assignment (mp, lhs);
29972 }
29973 } else {
29974 /* Assign the current expression to the variable |lhs| */
29975 mp_node p; /* where the left-hand value is stored */
29976 mp_node q; /* temporary capsule for the right-hand value */
29977 p = mp_find_variable (mp, lhs);
29978 if (p != NULL) {
29979 q = mp_stash_cur_exp (mp);
29980 mp->cur_exp.type = mp_und_type (mp, p);
29981 mp_recycle_value (mp, p);
29982 mp_type (p) = mp->cur_exp.type;
29983 set_value_number (p, zero_t);
29984 mp_make_exp_copy (mp, p);
29985 p = mp_stash_cur_exp (mp);
29986 mp_unstash_cur_exp (mp, q);
29987 mp_make_eq (mp, p);
29988 } else {
29989 bad_expression_assignment(mp, lhs);
29990 }
29991 }
29992 mp_flush_node_list (mp, lhs);
29993 }
29994 }
29995
29996
29997 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
29998 a pointer to a capsule that is to be equated to the current expression.
29999
30000 @<Declare the procedure called |make_eq|@>=
30001 static void mp_make_eq (MP mp, mp_node lhs);
30002
30003 @ @c
30004 static void announce_bad_equation (MP mp, mp_node lhs) {
30005 char msg[256];
30006 const char *hlp[] = {
30007 "I'm sorry, but I don't know how to make such things equal.",
30008 "(See the two expressions just above the error message.)",
30009 NULL };
30010 mp_snprintf(msg, 256, "Equation cannot be performed (%s=%s)",
30011 (mp_type (lhs) <= mp_pair_type ? mp_type_string (mp_type (lhs)) : "numeric"),
30012 (mp->cur_exp.type <= mp_pair_type ? mp_type_string (mp->cur_exp.type) : "numeric"));
30013 mp_disp_err (mp, lhs);
30014 mp_disp_err(mp, NULL);
30015 mp_back_error (mp, msg, hlp, true);
30016 mp_get_x_next (mp);
30017 }
30018 static void exclaim_inconsistent_equation (MP mp) {
30019 const char *hlp[] = {
30020 "The equation I just read contradicts what was said before.",
30021 "But don't worry; continue and I'll just ignore it.",
30022 NULL };
30023 mp_back_error (mp,"Inconsistent equation", hlp, true);
30024 mp_get_x_next (mp);
30025 }
30026 static void exclaim_redundant_or_inconsistent_equation (MP mp) {
30027 const char *hlp[] = {
30028 "An equation between already-known quantities can't help.",
30029 "But don't worry; continue and I'll just ignore it.",
30030 NULL };
30031 mp_back_error (mp, "Redundant or inconsistent equation", hlp, true);
30032 mp_get_x_next (mp);
30033 }
30034 static void report_redundant_or_inconsistent_equation (MP mp, mp_node lhs, mp_number v) {
30035 if (mp->cur_exp.type <= mp_string_type) {
30036 if (mp->cur_exp.type == mp_string_type) {
30037 if (mp_str_vs_str (mp, value_str (lhs), cur_exp_str ()) != 0) {
30038 exclaim_inconsistent_equation(mp);
30039 } else {
30040 exclaim_redundant_equation(mp);
30041 }
30042 } else if (!number_equal (v, cur_exp_value_number ())) {
30043 exclaim_inconsistent_equation(mp);
30044 } else {
30045 exclaim_redundant_equation(mp);
30046 }
30047 } else {
30048 exclaim_redundant_or_inconsistent_equation (mp);
30049 }
30050 }
30051
30052 void mp_make_eq (MP mp, mp_node lhs) {
30053 mp_value new_expr;
30054 mp_variable_type t; /* type of the left-hand side */
30055 mp_number v; /* value of the left-hand side */
30056 memset(&new_expr,0,sizeof(mp_value));
30057 new_number (v);
30058 RESTART:
30059 t = mp_type (lhs);
30060 if (t <= mp_pair_type)
30061 number_clone (v, value_number (lhs));
30062 /* For each type |t|, make an equation or complain if |cur_type|
30063 is incompatible with~|t| */
30064 switch (t) {
30065 case mp_boolean_type:
30066 case mp_string_type:
30067 case mp_pen_type:
30068 case mp_path_type:
30069 case mp_picture_type:
30070 if (mp->cur_exp.type == t + unknown_tag) {
30071 new_number(new_expr.data.n);
30072 if (t==mp_boolean_type) {
30073 number_clone (new_expr.data.n, v);
30074 } else if (t==mp_string_type) {
30075 new_expr.data.str = value_str(lhs);
30076 } else if (t==mp_picture_type) {
30077 new_expr.data.node = value_node(lhs);
30078 } else { /* pen or path */
30079 new_expr.data.p = value_knot(lhs);
30080 }
30081 mp_nonlinear_eq (mp, new_expr, cur_exp_node (), false);
30082 mp_unstash_cur_exp (mp, cur_exp_node ());
30083 } else if (mp->cur_exp.type == t) {
30084 report_redundant_or_inconsistent_equation(mp, lhs, v);
30085 } else {
30086 announce_bad_equation(mp, lhs);
30087 }
30088 break;
30089 case unknown_types:
30090 if (mp->cur_exp.type == t - unknown_tag) {
30091 mp_nonlinear_eq (mp, mp->cur_exp, lhs, true);
30092 } else if (mp->cur_exp.type == t) {
30093 mp_ring_merge (mp, lhs, cur_exp_node ());
30094 } else if (mp->cur_exp.type == mp_pair_type) {
30095 if (t == mp_unknown_path) {
30096 mp_pair_to_path (mp);
30097 goto RESTART;
30098 }
30099 } else {
30100 announce_bad_equation(mp, lhs);
30101 }
30102 break;
30103 case mp_transform_type:
30104 case mp_color_type:
30105 case mp_cmykcolor_type:
30106 case mp_pair_type:
30107 if (mp->cur_exp.type == t) {
30108 /* Do multiple equations */
30109 mp_node q = value_node (cur_exp_node ());
30110 mp_node p = value_node (lhs);
30111 switch (t) {
30112 case mp_transform_type:
30113 mp_try_eq (mp, yy_part (p), yy_part (q));
30114 mp_try_eq (mp, yx_part (p), yx_part (q));
30115 mp_try_eq (mp, xy_part (p), xy_part (q));
30116 mp_try_eq (mp, xx_part (p), xx_part (q));
30117 mp_try_eq (mp, ty_part (p), ty_part (q));
30118 mp_try_eq (mp, tx_part (p), tx_part (q));
30119 break;
30120 case mp_color_type:
30121 mp_try_eq (mp, blue_part (p), blue_part (q));
30122 mp_try_eq (mp, green_part (p), green_part (q));
30123 mp_try_eq (mp, red_part (p), red_part (q));
30124 break;
30125 case mp_cmykcolor_type:
30126 mp_try_eq (mp, black_part (p), black_part (q));
30127 mp_try_eq (mp, yellow_part (p), yellow_part (q));
30128 mp_try_eq (mp, magenta_part (p), magenta_part (q));
30129 mp_try_eq (mp, cyan_part (p), cyan_part (q));
30130 break;
30131 case mp_pair_type:
30132 mp_try_eq (mp, y_part (p), y_part (q));
30133 mp_try_eq (mp, x_part (p), x_part (q));
30134 break;
30135 default: /* there are no other valid cases, but please the compiler */
30136 break;
30137 }
30138 } else {
30139 announce_bad_equation(mp, lhs);
30140 }
30141 break;
30142 case mp_known:
30143 case mp_dependent:
30144 case mp_proto_dependent:
30145 case mp_independent:
30146 if (mp->cur_exp.type >= mp_known) {
30147 mp_try_eq (mp, lhs, NULL);
30148 } else {
30149 announce_bad_equation(mp, lhs);
30150 }
30151 break;
30152 case mp_vacuous:
30153 announce_bad_equation(mp, lhs);
30154 break;
30155 default: /* there are no other valid cases, but please the compiler */
30156 announce_bad_equation(mp, lhs);
30157 break;
30158 }
30159 check_arith();
30160 mp_recycle_value (mp, lhs);
30161 free_number (v);
30162 mp_free_value_node (mp, lhs);
30163 }
30164
30165 @ The first argument to |try_eq| is the location of a value node
30166 in a capsule that will soon be recycled. The second argument is
30167 either a location within a pair or transform node pointed to by
30168 |cur_exp|, or it is |NULL| (which means that |cur_exp| itself
30169 serves as the second argument). The idea is to leave |cur_exp| unchanged,
30170 but to equate the two operands.
30171
30172 @<Declarations@>=
30173 static void mp_try_eq (MP mp, mp_node l, mp_node r);
30174
30175 @ @d equation_threshold_k ((math_data *)mp->math)->equation_threshold_t
30176
30177 @c
30178 static void deal_with_redundant_or_inconsistent_equation(MP mp, mp_value_node p, mp_node r) {
30179 mp_number absp;
30180 new_number (absp);
30181 number_clone (absp, value_number (p));
30182 number_abs (absp);
30183 if (number_greater (absp, equation_threshold_k)) { /* off by .001 or more */
30184 char msg[256];
30185 const char *hlp[] = {
30186 "The equation I just read contradicts what was said before.",
30187 "But don't worry; continue and I'll just ignore it.",
30188 NULL };
30189 mp_snprintf (msg, 256, "Inconsistent equation (off by %s)", number_tostring (value_number (p)));
30190 mp_back_error (mp, msg, hlp, true);
30191 mp_get_x_next (mp);
30192 } else if (r == NULL) {
30193 exclaim_redundant_equation(mp);
30194 }
30195 free_number (absp);
30196 mp_free_dep_node (mp, p);
30197 }
30198
30199 void mp_try_eq (MP mp, mp_node l, mp_node r) {
30200 mp_value_node p; /* dependency list for right operand minus left operand */
30201 mp_variable_type t; /* the type of list |p| */
30202 mp_value_node q; /* the constant term of |p| is here */
30203 mp_value_node pp; /* dependency list for right operand */
30204 mp_variable_type tt; /* the type of list |pp| */
30205 boolean copied; /* have we copied a list that ought to be recycled? */
30206 /* Remove the left operand from its container, negate it, and
30207 put it into dependency list~|p| with constant term~|q| */
30208 t = mp_type (l);
30209 if (t == mp_known) {
30210 mp_number arg1;
30211 new_number (arg1);
30212 number_clone (arg1, value_number(l));
30213 number_negate (arg1);
30214 t = mp_dependent;
30215 p = mp_const_dependency (mp, arg1);
30216 q = p;
30217 free_number (arg1);
30218 } else if (t == mp_independent) {
30219 t = mp_dependent;
30220 p = mp_single_dependency (mp, l);
30221 number_negate(dep_value (p));
30222 q = mp->dep_final;
30223 } else {
30224 mp_value_node ll = (mp_value_node) l;
30225 p = (mp_value_node) dep_list (ll);
30226 q = p;
30227 while (1) {
30228 number_negate(dep_value (q));
30229 if (dep_info (q) == NULL)
30230 break;
30231 q = (mp_value_node) mp_link (q);
30232 }
30233 mp_link (prev_dep (ll)) = mp_link (q);
30234 set_prev_dep ((mp_value_node) mp_link (q), prev_dep (ll));
30235 mp_type (ll) = mp_known;
30236 }
30237
30238 /* Add the right operand to list |p| */
30239 if (r == NULL) {
30240 if (mp->cur_exp.type == mp_known) {
30241 number_add (value_number (q), cur_exp_value_number ());
30242 goto DONE1;
30243 } else {
30244 tt = mp->cur_exp.type;
30245 if (tt == mp_independent)
30246 pp = mp_single_dependency (mp, cur_exp_node ());
30247 else
30248 pp = (mp_value_node) dep_list ((mp_value_node) cur_exp_node ());
30249 }
30250 } else {
30251 if (mp_type (r) == mp_known) {
30252 number_add (dep_value (q), value_number (r));
30253 goto DONE1;
30254 } else {
30255 tt = mp_type (r);
30256 if (tt == mp_independent)
30257 pp = mp_single_dependency (mp, r);
30258 else
30259 pp = (mp_value_node) dep_list ((mp_value_node) r);
30260 }
30261 }
30262 if (tt != mp_independent) {
30263 copied = false;
30264 } else {
30265 copied = true;
30266 tt = mp_dependent;
30267 }
30268 /* Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t| */
30269 mp->watch_coefs = false;
30270 if (t == tt) {
30271 p = mp_p_plus_q (mp, p, pp, (quarterword) t);
30272 } else if (t == mp_proto_dependent) {
30273 p = mp_p_plus_fq (mp, p, unity_t, pp, mp_proto_dependent, mp_dependent);
30274 } else {
30275 mp_number x;
30276 new_number (x);
30277 q = p;
30278 while (dep_info (q) != NULL) {
30279 number_clone (x, dep_value (q));
30280 fraction_to_round_scaled (x);
30281 set_dep_value (q, x);
30282 q = (mp_value_node) mp_link (q);
30283 }
30284 free_number (x);
30285 t = mp_proto_dependent;
30286 p = mp_p_plus_q (mp, p, pp, (quarterword) t);
30287 }
30288 mp->watch_coefs = true;
30289
30290 if (copied)
30291 mp_flush_node_list (mp, (mp_node) pp);
30292 DONE1:
30293
30294 if (dep_info (p) == NULL) {
30295 deal_with_redundant_or_inconsistent_equation(mp, p, r);
30296 } else {
30297 mp_linear_eq (mp, p, (quarterword) t);
30298 if (r == NULL && mp->cur_exp.type != mp_known) {
30299 if (mp_type (cur_exp_node ()) == mp_known) {
30300 mp_node pp = cur_exp_node ();
30301 set_cur_exp_value_number (value_number (pp));
30302 mp->cur_exp.type = mp_known;
30303 mp_free_value_node (mp, pp);
30304 }
30305 }
30306 }
30307 }
30308
30309 @ Our next goal is to process type declarations. For this purpose it's
30310 convenient to have a procedure that scans a $\langle\,$declared
30311 variable$\,\rangle$ and returns the corresponding token list. After the
30312 following procedure has acted, the token after the declared variable
30313 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
30314 and~|cur_sym|.
30315
30316 @<Declarations@>=
30317 static mp_node mp_scan_declared_variable (MP mp);
30318
30319 @ @c
30320 mp_node mp_scan_declared_variable (MP mp) {
30321 mp_sym x; /* hash address of the variable's root */
30322 mp_node h, t; /* head and tail of the token list to be returned */
30323 mp_get_symbol (mp);
30324 x = cur_sym();
30325 if (cur_cmd() != mp_tag_token)
30326 mp_clear_symbol (mp, x, false);
30327 h = mp_get_symbolic_node (mp);
30328 set_mp_sym_sym (h, x);
30329 t = h;
30330 while (1) {
30331 mp_get_x_next (mp);
30332 if (cur_sym() == NULL)
30333 break;
30334 if (cur_cmd() != mp_tag_token) {
30335 if (cur_cmd() != mp_internal_quantity) {
30336 if (cur_cmd() == mp_left_bracket) {
30337 /* Descend past a collective subscript */
30338 /* If the subscript isn't collective, we don't accept it as part of the
30339 declared variable. */
30340 mp_sym ll = cur_sym(); /* hash address of left bracket */
30341 mp_get_x_next (mp);
30342 if (cur_cmd() == mp_right_bracket) {
30343 set_cur_sym(collective_subscript);
30344 } else {
30345 mp_back_input (mp);
30346 set_cur_sym(ll);
30347 set_cur_cmd((mp_variable_type)mp_left_bracket);
30348 break;
30349 }
30350 } else {
30351 break;
30352 }
30353 }
30354 }
30355 mp_link (t) = mp_get_symbolic_node (mp);
30356 t = mp_link (t);
30357 set_mp_sym_sym (t, cur_sym());
30358 mp_name_type (t) = cur_sym_mod();
30359 }
30360 if ((eq_type (x) % mp_outer_tag) != mp_tag_token)
30361 mp_clear_symbol (mp, x, false);
30362 if (equiv_node (x) == NULL)
30363 mp_new_root (mp, x);
30364 return h;
30365 }
30366
30367
30368 @ Type declarations are introduced by the following primitive operations.
30369
30370 @<Put each...@>=
30371 mp_primitive (mp, "numeric", mp_type_name, mp_numeric_type);
30372 @:numeric_}{\&{numeric} primitive@>
30373 mp_primitive (mp, "string", mp_type_name, mp_string_type);
30374 @:string_}{\&{string} primitive@>
30375 mp_primitive (mp, "boolean", mp_type_name, mp_boolean_type);
30376 @:boolean_}{\&{boolean} primitive@>
30377 mp_primitive (mp, "path", mp_type_name, mp_path_type);
30378 @:path_}{\&{path} primitive@>
30379 mp_primitive (mp, "pen", mp_type_name, mp_pen_type);
30380 @:pen_}{\&{pen} primitive@>
30381 mp_primitive (mp, "picture", mp_type_name, mp_picture_type);
30382 @:picture_}{\&{picture} primitive@>
30383 mp_primitive (mp, "transform", mp_type_name, mp_transform_type);
30384 @:transform_}{\&{transform} primitive@>
30385 mp_primitive (mp, "color", mp_type_name, mp_color_type);
30386 @:color_}{\&{color} primitive@>
30387 mp_primitive (mp, "rgbcolor", mp_type_name, mp_color_type);
30388 @:color_}{\&{rgbcolor} primitive@>
30389 mp_primitive (mp, "cmykcolor", mp_type_name, mp_cmykcolor_type);
30390 @:color_}{\&{cmykcolor} primitive@>
30391 mp_primitive (mp, "pair", mp_type_name, mp_pair_type);
30392 @:pair_}{\&{pair} primitive@>
30393
30394
30395 @ @<Cases of |print_cmd...@>=
30396 case mp_type_name:
30397 mp_print_type (mp, (quarterword) m);
30398 break;
30399
30400 @ Now we are ready to handle type declarations, assuming that a
30401 |type_name| has just been scanned.
30402
30403 @<Declare action procedures for use by |do_statement|@>=
30404 static void mp_do_type_declaration (MP mp);
30405
30406 @ @c
30407 static void flush_spurious_symbols_after_declared_variable(MP mp);
30408 void mp_do_type_declaration (MP mp) {
30409 integer t; /* the type being declared */
30410 mp_node p; /* token list for a declared variable */
30411 mp_node q; /* value node for the variable */
30412 if (cur_mod() >= mp_transform_type)
30413 t = (quarterword) cur_mod();
30414 else
30415 t = (quarterword) (cur_mod() + unknown_tag);
30416 do {
30417 p = mp_scan_declared_variable (mp);
30418 mp_flush_variable (mp, equiv_node (mp_sym_sym (p)), mp_link (p), false);
30419 q = mp_find_variable (mp, p);
30420 if (q != NULL) {
30421 mp_type (q) = t;
30422 set_value_number (q, zero_t); /* TODO: this was |NULL| */
30423 } else {
30424 const char *hlp[] = {
30425 "You can't use, e.g., `numeric foo[]' after `vardef foo'.",
30426 "Proceed, and I'll ignore the illegal redeclaration.",
30427 NULL };
30428 mp_back_error (mp, "Declared variable conflicts with previous vardef", hlp, true);
30429 mp_get_x_next (mp);
30430 }
30431 mp_flush_node_list (mp, p);
30432 if (cur_cmd() < mp_comma) {
30433 flush_spurious_symbols_after_declared_variable(mp);
30434 }
30435 } while (!mp_end_of_statement);
30436 }
30437
30438
30439 @ @c
30440 static void flush_spurious_symbols_after_declared_variable (MP mp)
30441 {
30442 const char *hlp[] = {
30443 "Variables in declarations must consist entirely of",
30444 "names and collective subscripts, e.g., `x[]a'.",
30445 "Are you trying to use a reserved word in a variable name?",
30446 "I'm going to discard the junk I found here,",
30447 "up to the next comma or the end of the declaration.",
30448 NULL };
30449 if (cur_cmd() == mp_numeric_token)
30450 hlp[2] = "Explicit subscripts like `x15a' aren't permitted.";
30451 mp_back_error (mp, "Illegal suffix of declared variable will be flushed", hlp, true);
30452 mp_get_x_next (mp);
30453 mp->scanner_status = flushing;
30454 do {
30455 get_t_next (mp);
30456 @<Decrease the string reference count...@>;
30457 } while (cur_cmd() < mp_comma); /* break on either |end_of_statement| or |comma| */
30458 mp->scanner_status = normal;
30459 }
30460
30461
30462 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
30463 until coming to the end of the user's program.
30464 Each execution of |do_statement| concludes with
30465 |cur_cmd=semicolon|, |end_group|, or |stop|.
30466
30467 @c
30468 static void mp_main_control (MP mp) {
30469 do {
30470 mp_do_statement (mp);
30471 if (cur_cmd() == mp_end_group) {
30472 mp_value new_expr;
30473 const char *hlp[] = {
30474 "I'm not currently working on a `begingroup',",
30475 "so I had better not try to end anything.",
30476 NULL };
30477 memset(&new_expr,0,sizeof(mp_value));
30478 new_number(new_expr.data.n);
30479 mp_error (mp, "Extra `endgroup'", hlp, true);
30480 mp_flush_cur_exp (mp, new_expr);
30481 }
30482 } while (cur_cmd() != mp_stop);
30483 }
30484 int mp_run (MP mp) {
30485 if (mp->history < mp_fatal_error_stop) {
30486 xfree (mp->jump_buf);
30487 mp->jump_buf = malloc (sizeof (jmp_buf));
30488 if (mp->jump_buf == NULL || setjmp (*(mp->jump_buf)) != 0)
30489 return mp->history;
30490 mp_main_control (mp); /* come to life */
30491 mp_final_cleanup (mp); /* prepare for death */
30492 mp_close_files_and_terminate (mp);
30493 }
30494 return mp->history;
30495 }
30496
30497
30498 @ This function allows setting of internals from an external
30499 source (like the command line or a controlling application).
30500
30501 It accepts two |char *|'s, even for numeric assignments when
30502 it calls |atoi| to get an integer from the start of the string.
30503
30504 @c
30505 void mp_set_internal (MP mp, char *n, char *v, int isstring) {
30506 size_t l = strlen (n);
30507 char err[256];
30508 const char *errid = NULL;
30509 if (l > 0) {
30510 mp_sym p = mp_id_lookup (mp, n, l, false);
30511 if (p == NULL) {
30512 errid = "variable does not exist";
30513 } else {
30514 if (eq_type (p) == mp_internal_quantity) {
30515 if ((internal_type (equiv (p)) == mp_string_type) && (isstring)) {
30516 set_internal_string (equiv (p), mp_rts (mp, v));
30517 } else if ((internal_type (equiv (p)) == mp_known) && (!isstring)) {
30518 int test = atoi (v);
30519 if (test > 16383 && mp->math_mode==mp_math_scaled_mode) {
30520 errid = "value is too large";
30521 } else if (test < -16383 && mp->math_mode==mp_math_scaled_mode) {
30522 errid = "value is too small";
30523 } else {
30524 set_internal_from_number (equiv (p), unity_t);
30525 number_multiply_int (internal_value(equiv (p)), test);
30526 }
30527 } else {
30528 errid = "value has the wrong type";
30529 }
30530 } else {
30531 errid = "variable is not an internal";
30532 }
30533 }
30534 }
30535 if (errid != NULL) {
30536 if (isstring) {
30537 mp_snprintf (err, 256, "%s=\"%s\": %s, assignment ignored.", n, v, errid);
30538 } else {
30539 mp_snprintf (err, 256, "%s=%d: %s, assignment ignored.", n, atoi (v),
30540 errid);
30541 }
30542 mp_warn (mp, err);
30543 }
30544 }
30545
30546
30547 @ @<Exported function headers@>=
30548 void mp_set_internal (MP mp, char *n, char *v, int isstring);
30549
30550 @ For |mp_execute|, we need to define a structure to store the
30551 redirected input and output. This structure holds the five relevant
30552 streams: the three informational output streams, the PostScript
30553 generation stream, and the input stream. These streams have many
30554 things in common, so it makes sense to give them their own structure
30555 definition.
30556
30557 \item{fptr} is a virtual file pointer
30558 \item{data} is the data this stream holds
30559 \item{cur} is a cursor pointing into |data|
30560 \item{size} is the allocated length of the data stream
30561 \item{used} is the actual length of the data stream
30562
30563 There are small differences between input and output: |term_in| never
30564 uses |used|, whereas the other four never use |cur|.
30565
30566 The file |luatexdir/tex/texfileio.h| defines |term_in| as |stdin| and
30567 |term_out| as |stdout|. Moreover |stdio.h| for MinGW defines |stdin| as
30568 |(&_iob[0])| and |stdout| as |(&_iob[1])|. We must avoid all that.
30569
30570 @<Exported types@>=
30571 #undef term_in
30572 #undef term_out
30573
30574 typedef struct {
30575 void *fptr;
30576 char *data;
30577 char *cur;
30578 size_t size;
30579 size_t used;
30580 } mp_stream;
30581 typedef struct {
30582 mp_stream term_out;
30583 mp_stream error_out;
30584 mp_stream log_out;
30585 mp_stream ship_out;
30586 mp_stream term_in;
30587 struct mp_edge_object *edges;
30588 } mp_run_data;
30589
30590 @ We need a function to clear an output stream, this is called at the
30591 beginning of |mp_execute|. We also need one for destroying an output
30592 stream, this is called just before a stream is (re)opened.
30593
30594 @c
30595 static void mp_reset_stream (mp_stream * str) {
30596 xfree (str->data);
30597 str->cur = NULL;
30598 str->size = 0;
30599 str->used = 0;
30600 }
30601 static void mp_free_stream (mp_stream * str) {
30602 xfree (str->fptr);
30603 mp_reset_stream (str);
30604 }
30605
30606
30607 @ @<Declarations@>=
30608 static void mp_reset_stream (mp_stream * str);
30609 static void mp_free_stream (mp_stream * str);
30610
30611 @ The global instance contains a pointer instead of the actual structure
30612 even though it is essentially static, because that makes it is easier to move
30613 the object around.
30614
30615 @<Global ...@>=
30616 mp_run_data run_data;
30617
30618 @ Another type is needed: the indirection will overload some of the
30619 file pointer objects in the instance (but not all). For clarity, an
30620 indirect object is used that wraps a |FILE *|.
30621
30622 @<Types ... @>=
30623 typedef struct File {
30624 FILE *f;
30625 } File;
30626
30627 @ Here are all of the functions that need to be overloaded for |mp_execute|.
30628
30629 @<Declarations@>=
30630 static void *mplib_open_file (MP mp, const char *fname, const char *fmode,
30631 int ftype);
30632 static int mplib_get_char (void *f, mp_run_data * mplib_data);
30633 static void mplib_unget_char (void *f, mp_run_data * mplib_data, int c);
30634 static char *mplib_read_ascii_file (MP mp, void *ff, size_t * size);
30635 static void mplib_write_ascii_file (MP mp, void *ff, const char *s);
30636 static void mplib_read_binary_file (MP mp, void *ff, void **data,
30637 size_t * size);
30638 static void mplib_write_binary_file (MP mp, void *ff, void *s, size_t size);
30639 static void mplib_close_file (MP mp, void *ff);
30640 static int mplib_eof_file (MP mp, void *ff);
30641 static void mplib_flush_file (MP mp, void *ff);
30642 static void mplib_shipout_backend (MP mp, void *h);
30643
30644 @ The |xmalloc(1,1)| calls make sure the stored indirection values are unique.
30645
30646 @d reset_stream(a) do {
30647 mp_reset_stream(&(a));
30648 if (!ff->f) {
30649 ff->f = xmalloc(1,1);
30650 (a).fptr = ff->f;
30651 } } while (0)@;
30652
30653 @c
30654 static void *mplib_open_file (MP mp, const char *fname, const char *fmode,
30655 int ftype) {
30656 File *ff = xmalloc (1, sizeof (File));
30657 mp_run_data *run = mp_rundata (mp);
30658 ff->f = NULL;
30659 if (ftype == mp_filetype_terminal) {
30660 if (fmode[0] == 'r') {
30661 if (!ff->f) {
30662 ff->f = xmalloc (1, 1);
30663 run->term_in.fptr = ff->f;
30664 }
30665 } else {
30666 reset_stream (run->term_out);
30667 }
30668 } else if (ftype == mp_filetype_error) {
30669 reset_stream (run->error_out);
30670 } else if (ftype == mp_filetype_log) {
30671 reset_stream (run->log_out);
30672 } else if (ftype == mp_filetype_postscript) {
30673 mp_free_stream (&(run->ship_out));
30674 ff->f = xmalloc (1, 1);
30675 run->ship_out.fptr = ff->f;
30676 } else if (ftype == mp_filetype_bitmap) {
30677 mp_free_stream (&(run->ship_out));
30678 ff->f = xmalloc (1, 1);
30679 run->ship_out.fptr = ff->f;
30680 } else {
30681 char realmode[3];
30682 char *f = (mp->find_file) (mp, fname, fmode, ftype);
30683 if (f == NULL)
30684 return NULL;
30685 realmode[0] = *fmode;
30686 realmode[1] = 'b';
30687 realmode[2] = 0;
30688 ff->f = fopen (f, realmode);
30689 free (f);
30690 if ((fmode[0] == 'r') && (ff->f == NULL)) {
30691 free (ff);
30692 return NULL;
30693 }
30694 }
30695 return ff;
30696 }
30697 static int mplib_get_char (void *f, mp_run_data * run) {
30698 int c;
30699 if (f == run->term_in.fptr && run->term_in.data != NULL) {
30700 if (run->term_in.size == 0) {
30701 if (run->term_in.cur != NULL) {
30702 run->term_in.cur = NULL;
30703 } else {
30704 xfree (run->term_in.data);
30705 }
30706 c = EOF;
30707 } else {
30708 run->term_in.size--;
30709 c = *(run->term_in.cur)++;
30710 }
30711 } else {
30712 c = fgetc (f);
30713 }
30714 return c;
30715 }
30716 static void mplib_unget_char (void *f, mp_run_data * run, int c) {
30717 if (f == run->term_in.fptr && run->term_in.cur != NULL) {
30718 run->term_in.size++;
30719 run->term_in.cur--;
30720 } else {
30721 ungetc (c, f);
30722 }
30723 }
30724 static char *mplib_read_ascii_file (MP mp, void *ff, size_t * size) {
30725 char *s = NULL;
30726 if (ff != NULL) {
30727 int c;
30728 size_t len = 0, lim = 128;
30729 mp_run_data *run = mp_rundata (mp);
30730 FILE *f = ((File *) ff)->f;
30731 if (f == NULL)
30732 return NULL;
30733 *size = 0;
30734 c = mplib_get_char (f, run);
30735 if (c == EOF)
30736 return NULL;
30737 s = malloc (lim);
30738 if (s == NULL)
30739 return NULL;
30740 while (c != EOF && c != '\n' && c != '\r') {
30741 if (len >= (lim - 1)) {
30742 s = xrealloc (s, (lim + (lim >> 2)), 1);
30743 if (s == NULL)
30744 return NULL;
30745 lim += (lim >> 2);
30746 }
30747 s[len++] = (char) c;
30748 c = mplib_get_char (f, run);
30749 }
30750 if (c == '\r') {
30751 c = mplib_get_char (f, run);
30752 if (c != EOF && c != '\n')
30753 mplib_unget_char (f, run, c);
30754 }
30755 s[len] = 0;
30756 *size = len;
30757 }
30758 return s;
30759 }
30760 static void mp_append_string (MP mp, mp_stream * a, const char *b) {
30761 size_t l = strlen (b) + 1; /* don't forget the trailing |'\0'| */
30762 if ((a->used + l) >= a->size) {
30763 a->size += 256 + (a->size) / 5 + l;
30764 a->data = xrealloc (a->data, a->size, 1);
30765 }
30766 memcpy (a->data + a->used, b, l);
30767 a->used += (l-1);
30768 }
30769 static void mp_append_data (MP mp, mp_stream * a, void *b, size_t l) {
30770 if ((a->used + l) >= a->size) {
30771 a->size += 256 + (a->size) / 5 + l;
30772 a->data = xrealloc (a->data, a->size, 1);
30773 }
30774 memcpy (a->data + a->used, b, l);
30775 a->used += l;
30776 }
30777 static void mplib_write_ascii_file (MP mp, void *ff, const char *s) {
30778 if (ff != NULL) {
30779 void *f = ((File *) ff)->f;
30780 mp_run_data *run = mp_rundata (mp);
30781 if (f != NULL) {
30782 if (f == run->term_out.fptr) {
30783 mp_append_string (mp, &(run->term_out), s);
30784 } else if (f == run->error_out.fptr) {
30785 mp_append_string (mp, &(run->error_out), s);
30786 } else if (f == run->log_out.fptr) {
30787 mp_append_string (mp, &(run->log_out), s);
30788 } else if (f == run->ship_out.fptr) {
30789 mp_append_string (mp, &(run->ship_out), s);
30790 } else {
30791 fprintf ((FILE *) f, "%s", s);
30792 }
30793 }
30794 }
30795 }
30796 static void mplib_read_binary_file (MP mp, void *ff, void **data, size_t * size) {
30797 (void) mp;
30798 if (ff != NULL) {
30799 size_t len = 0;
30800 FILE *f = ((File *) ff)->f;
30801 if (f != NULL)
30802 len = fread (*data, 1, *size, f);
30803 *size = len;
30804 }
30805 }
30806 static void mplib_write_binary_file (MP mp, void *ff, void *s, size_t size) {
30807 (void) mp;
30808 if (ff != NULL) {
30809 void *f = ((File *) ff)->f;
30810 mp_run_data *run = mp_rundata (mp);
30811 if (f != NULL) {
30812 if (f == run->ship_out.fptr) {
30813 mp_append_data (mp, &(run->ship_out), s, size);
30814 } else {
30815 (void) fwrite (s, size, 1, f);
30816 }
30817 }
30818 }
30819 }
30820 static void mplib_close_file (MP mp, void *ff) {
30821 if (ff != NULL) {
30822 mp_run_data *run = mp_rundata (mp);
30823 void *f = ((File *) ff)->f;
30824 if (f != NULL) {
30825 if (f != run->term_out.fptr
30826 && f != run->error_out.fptr
30827 && f != run->log_out.fptr
30828 && f != run->ship_out.fptr && f != run->term_in.fptr) {
30829 fclose (f);
30830 }
30831 }
30832 free (ff);
30833 }
30834 }
30835 static int mplib_eof_file (MP mp, void *ff) {
30836 if (ff != NULL) {
30837 mp_run_data *run = mp_rundata (mp);
30838 FILE *f = ((File *) ff)->f;
30839 if (f == NULL)
30840 return 1;
30841 if (f == run->term_in.fptr && run->term_in.data != NULL) {
30842 return (run->term_in.size == 0);
30843 }
30844 return feof (f);
30845 }
30846 return 1;
30847 }
30848 static void mplib_flush_file (MP mp, void *ff) {
30849 (void) mp;
30850 (void) ff;
30851 return;
30852 }
30853 static void mplib_shipout_backend (MP mp, void *voidh) {
30854 mp_edge_header_node h = (mp_edge_header_node) voidh;
30855 mp_edge_object *hh = mp_gr_export (mp, h);
30856 if (hh) {
30857 mp_run_data *run = mp_rundata (mp);
30858 if (run->edges == NULL) {
30859 run->edges = hh;
30860 } else {
30861 mp_edge_object *p = run->edges;
30862 while (p->next != NULL) {
30863 p = p->next;
30864 }
30865 p->next = hh;
30866 }
30867 }
30868 }
30869
30870
30871 @ This is where we fill them all in.
30872 @<Prepare function pointers for non-interactive use@>=
30873 {
30874 mp->open_file = mplib_open_file;
30875 mp->close_file = mplib_close_file;
30876 mp->eof_file = mplib_eof_file;
30877 mp->flush_file = mplib_flush_file;
30878 mp->write_ascii_file = mplib_write_ascii_file;
30879 mp->read_ascii_file = mplib_read_ascii_file;
30880 mp->write_binary_file = mplib_write_binary_file;
30881 mp->read_binary_file = mplib_read_binary_file;
30882 mp->shipout_backend = mplib_shipout_backend;
30883 }
30884
30885
30886 @ Perhaps this is the most important API function in the library.
30887
30888 @<Exported function ...@>=
30889 extern mp_run_data *mp_rundata (MP mp);
30890
30891 @ @c
30892 mp_run_data *mp_rundata (MP mp) {
30893 return &(mp->run_data);
30894 }
30895
30896
30897 @ @<Dealloc ...@>=
30898 mp_free_stream (&(mp->run_data.term_in));
30899 mp_free_stream (&(mp->run_data.term_out));
30900 mp_free_stream (&(mp->run_data.log_out));
30901 mp_free_stream (&(mp->run_data.error_out));
30902 mp_free_stream (&(mp->run_data.ship_out));
30903
30904 @ @<Finish non-interactive use@>=
30905 {
30906 xfree (mp->term_out);
30907 xfree (mp->term_in);
30908 xfree (mp->err_out);
30909 }
30910
30911 @ @<Start non-interactive work@>=
30912 @<Initialize the output routines@>
30913 mp->input_ptr = 0;
30914 mp->max_in_stack = file_bottom;
30915 mp->in_open = file_bottom;
30916 mp->open_parens = 0;
30917 mp->max_buf_stack = 0;
30918 mp->param_ptr = 0;
30919 mp->max_param_stack = 0;
30920 start = loc = 0;
30921 iindex = file_bottom;
30922 nloc = nstart = NULL;
30923 mp->first = 0;
30924 line = 0;
30925 name = is_term;
30926 mp->mpx_name[file_bottom] = absent;
30927 mp->force_eof = false;
30928 t_open_in();
30929 mp->scanner_status = normal;
30930 if (!mp->ini_version) {
30931 if (!mp_load_preload_file (mp)) {
30932 mp->history = mp_fatal_error_stop;
30933 return mp->history;
30934 }
30935 }
30936 mp_fix_date_and_time (mp);
30937 if (mp->random_seed == 0)
30938 mp->random_seed =
30939 (int)((number_to_scaled (internal_value (mp_time)) / number_to_scaled (unity_t)) + number_to_scaled (internal_value (mp_day)));
30940 init_randoms (mp->random_seed);
30941 initialize_print_selector();
30942 mp_open_log_file (mp);
30943 mp_set_job_id (mp);
30944 mp_init_map_file (mp, mp->troff_mode);
30945 mp->history = mp_spotless; /* ready to go! */
30946 if (mp->troff_mode) {
30947 number_clone (internal_value(mp_gtroffmode), unity_t);
30948 number_clone (internal_value(mp_prologues), unity_t);
30949 }
30950 @<Fix up |mp->internal[mp_job_name]|@>
30951 if (mp->start_sym != NULL) { /* insert the `\&{everyjob}' symbol */
30952 set_cur_sym(mp->start_sym);
30953 mp_back_input (mp);
30954 }
30955
30956 @ @c
30957 int mp_execute (MP mp, char *s, size_t l) {
30958 mp_reset_stream (&(mp->run_data.term_out));
30959 mp_reset_stream (&(mp->run_data.log_out));
30960 mp_reset_stream (&(mp->run_data.error_out));
30961 mp_reset_stream (&(mp->run_data.ship_out));
30962 if (mp->finished) {
30963 return mp->history;
30964 } else if (!mp->noninteractive) {
30965 mp->history = mp_fatal_error_stop;
30966 return mp->history;
30967 }
30968 if (mp->history < mp_fatal_error_stop) {
30969 xfree (mp->jump_buf);
30970 mp->jump_buf = malloc (sizeof (jmp_buf));
30971 if (mp->jump_buf == NULL || setjmp (*(mp->jump_buf)) != 0) {
30972 return mp->history;
30973 }
30974 if (s == NULL) { /* this signals EOF */
30975 mp_final_cleanup (mp); /* prepare for death */
30976 mp_close_files_and_terminate (mp);
30977 return mp->history;
30978 }
30979 mp->tally = 0;
30980 mp->term_offset = 0;
30981 mp->file_offset = 0;
30982 /* Perhaps some sort of warning here when |data| is not
30983 * yet exhausted would be nice ... this happens after errors
30984 */
30985 if (mp->run_data.term_in.data)
30986 xfree (mp->run_data.term_in.data);
30987 mp->run_data.term_in.data = xstrdup (s);
30988 mp->run_data.term_in.cur = mp->run_data.term_in.data;
30989 mp->run_data.term_in.size = l;
30990 if (mp->run_state == 0) {
30991 mp->selector = term_only;
30992 @<Start non-interactive work@>;
30993 }
30994 mp->run_state = 1;
30995 (void) mp_input_ln (mp, mp->term_in);
30996 mp_firm_up_the_line (mp);
30997 mp->buffer[limit] = xord ('%');
30998 mp->first = (size_t) (limit + 1);
30999 loc = start;
31000 do {
31001 mp_do_statement (mp);
31002 } while (cur_cmd() != mp_stop);
31003 mp_final_cleanup (mp);
31004 mp_close_files_and_terminate (mp);
31005 }
31006 return mp->history;
31007 }
31008
31009
31010 @ This function cleans up
31011 @c
31012 int mp_finish (MP mp) {
31013 int history = 0;
31014 if (mp->finished || mp->history >= mp_fatal_error_stop) {
31015 history = mp->history;
31016 mp_free (mp);
31017 return history;
31018 }
31019 xfree (mp->jump_buf);
31020 mp->jump_buf = malloc (sizeof (jmp_buf));
31021 if (mp->jump_buf == NULL || setjmp (*(mp->jump_buf)) != 0) {
31022 history = mp->history;
31023 } else {
31024 history = mp->history;
31025 mp_final_cleanup (mp); /* prepare for death */
31026 }
31027 mp_close_files_and_terminate (mp);
31028 mp_free (mp);
31029 return history;
31030 }
31031
31032
31033 @ People may want to know the library version
31034 @c
31035 char *mp_metapost_version (void) {
31036 return mp_strdup (metapost_version);
31037 }
31038 void mp_show_library_versions (void) {
31039 fprintf(stdout, "Compiled with cairo %s; using %s\n", COMPILED_CAIRO_VERSION_STRING, cairo_version_string());
31040 fprintf(stdout, "Compiled with pixman %s; using %s\n",COMPILED_PIXMAN_VERSION_STRING, pixman_version_string());
31041 fprintf(stdout, "Compiled with libpng %s; using %s\n", PNG_LIBPNG_VER_STRING, png_libpng_ver);
31042 fprintf(stdout, "Compiled with zlib %s; using %s\n", ZLIB_VERSION, zlibVersion());
31043 fprintf(stdout, "Compiled with mpfr %s; using %s\n", COMPILED_MPFR_VERSION_STRING, mpfr_get_version());
31044 fprintf(stdout, "Compiled with mpfi %s; using %s\n", COMPILED_MPFI_VERSION_STRING, mpfi_get_version());
31045 fprintf(stdout, "Compiled with gmp %d.%d.%d; using %s\n\n", COMPILED__GNU_MP_VERSION, COMPILED__GNU_MP_VERSION_MINOR, COMPILED__GNU_MP_VERSION_PATCHLEVEL, COMPILED_gmp_version);
31046 }
31047
31048 @ @<Exported function headers@>=
31049 int mp_run (MP mp);
31050 int mp_execute (MP mp, char *s, size_t l);
31051 int mp_finish (MP mp);
31052 char *mp_metapost_version (void);void mp_show_library_versions (void);
31053
31054 @ @<Put each...@>=
31055 mp_primitive (mp, "end", mp_stop, 0);
31056 @:end_}{\&{end} primitive@>
31057 mp_primitive (mp, "dump", mp_stop, 1);
31058 mp->frozen_dump = mp_frozen_primitive (mp, "dump", mp_stop, 1);
31059 @:dump_}{\&{dump} primitive@>
31060
31061
31062 @ @<Cases of |print_cmd...@>=
31063 case mp_stop:
31064 if (cur_mod() == 0)
31065 mp_print (mp, "end");
31066 else
31067 mp_print (mp, "dump");
31068 break;
31069
31070 @* Commands.
31071 Let's turn now to statements that are classified as ``commands'' because
31072 of their imperative nature. We'll begin with simple ones, so that it
31073 will be clear how to hook command processing into the |do_statement| routine;
31074 then we'll tackle the tougher commands.
31075
31076 Here's one of the simplest:
31077
31078 @<Declare action procedures for use by |do_statement|@>=
31079 static void mp_do_random_seed (MP mp);
31080
31081 @ @c
31082 void mp_do_random_seed (MP mp) {
31083 mp_value new_expr;
31084 memset(&new_expr,0,sizeof(mp_value));
31085 new_number(new_expr.data.n);
31086 mp_get_x_next (mp);
31087 if (cur_cmd() != mp_assignment) {
31088 const char *hlp[] = { "Always say `randomseed:=<numeric expression>'.", NULL };
31089 mp_back_error (mp, "Missing `:=' has been inserted", hlp, true);
31090 @.Missing `:='@>
31091 }
31092 mp_get_x_next (mp);
31093 mp_scan_expression (mp);
31094 if (mp->cur_exp.type != mp_known) {
31095 const char *hlp[] = {
31096 "Your expression was too random for me to handle,",
31097 "so I won't change the random seed just now.",
31098 NULL };
31099 mp_disp_err(mp, NULL);
31100 mp_back_error (mp, "Unknown value will be ignored", hlp, true);
31101 @.Unknown value...ignored@>
31102 mp_get_x_next (mp);
31103 mp_flush_cur_exp (mp, new_expr);
31104 } else
31105 @<Initialize the random seed to |cur_exp|@>@;
31106 }
31107
31108
31109 @ @<Initialize the random seed to |cur_exp|@>=
31110 {
31111 init_randoms ((int)number_to_scaled(cur_exp_value_number ()));
31112 if (mp->selector >= log_only && mp->selector < write_file) {
31113 mp->old_setting = mp->selector;
31114 mp->selector = log_only;
31115 mp_print_nl (mp, "{randomseed:=");
31116 print_number (cur_exp_value_number ());
31117 mp_print_char (mp, xord ('}'));
31118 mp_print_nl (mp, "");
31119 mp->selector = mp->old_setting;
31120 }
31121 }
31122
31123
31124 @ @<Put each...@>=
31125 mp_primitive (mp, "batchmode", mp_mode_command, mp_batch_mode);
31126 @:mp_batch_mode_}{\&{batchmode} primitive@>
31127 mp_primitive (mp, "nonstopmode", mp_mode_command, mp_nonstop_mode);
31128 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
31129 mp_primitive (mp, "scrollmode", mp_mode_command, mp_scroll_mode);
31130 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
31131 mp_primitive (mp, "errorstopmode", mp_mode_command, mp_error_stop_mode);
31132 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
31133
31134
31135 @ @<Cases of |print_cmd_mod|...@>=
31136 case mp_mode_command:
31137 switch (m) {
31138 case mp_batch_mode:
31139 mp_print (mp, "batchmode");
31140 break;
31141 case mp_nonstop_mode:
31142 mp_print (mp, "nonstopmode");
31143 break;
31144 case mp_scroll_mode:
31145 mp_print (mp, "scrollmode");
31146 break;
31147 default:
31148 mp_print (mp, "errorstopmode");
31149 break;
31150 }
31151 break;
31152
31153 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
31154
31155 @<Put each...@>=
31156 mp_primitive (mp, "inner", mp_protection_command, 0);
31157 @:inner_}{\&{inner} primitive@>
31158 mp_primitive (mp, "outer", mp_protection_command, 1);
31159 @:outer_}{\&{outer} primitive@>
31160
31161
31162 @ @<Cases of |print_cmd...@>=
31163 case mp_protection_command:
31164 if (m == 0)
31165 mp_print (mp, "inner");
31166 else
31167 mp_print (mp, "outer");
31168 break;
31169
31170 @ And here's another simple one (somewhat different in flavor):
31171
31172 @<Declare action procedures for use by |do_statement|@>=
31173 static void mp_do_protection (MP mp);
31174
31175 @ @c
31176 void mp_do_protection (MP mp) {
31177 mpinteger64 m; /* 0 to unprotect, 1 to protect */
31178 halfword t; /* the |eq_type| before we change it */
31179 m = cur_mod();
31180 do {
31181 mp_get_symbol (mp);
31182 t = eq_type (cur_sym());
31183 if (m == 0) {
31184 if (t >= mp_outer_tag)
31185 set_eq_type (cur_sym(), (t - mp_outer_tag));
31186 } else if (t < mp_outer_tag) {
31187 set_eq_type (cur_sym(), (t + mp_outer_tag));
31188 }
31189 mp_get_x_next (mp);
31190 } while (cur_cmd() == mp_comma);
31191 }
31192
31193
31194 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
31195 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
31196 declaration assigns the command code |left_delimiter| to `\.{(}' and
31197 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
31198 hash address of its mate.
31199
31200 @<Declare action procedures for use by |do_statement|@>=
31201 static void mp_def_delims (MP mp);
31202
31203 @ @c
31204 void mp_def_delims (MP mp) {
31205 mp_sym l_delim, r_delim; /* the new delimiter pair */
31206 mp_get_clear_symbol (mp);
31207 l_delim = cur_sym();
31208 mp_get_clear_symbol (mp);
31209 r_delim = cur_sym();
31210 set_eq_type (l_delim, mp_left_delimiter);
31211 set_equiv_sym (l_delim, r_delim);
31212 set_eq_type (r_delim, mp_right_delimiter);
31213 set_equiv_sym (r_delim, l_delim);
31214 mp_get_x_next (mp);
31215 }
31216
31217
31218 @ Here is a procedure that is called when \MP\ has reached a point
31219 where some right delimiter is mandatory.
31220
31221 @<Declarations@>=
31222 static void mp_check_delimiter (MP mp, mp_sym l_delim, mp_sym r_delim);
31223
31224 @ @c
31225 void mp_check_delimiter (MP mp, mp_sym l_delim, mp_sym r_delim) {
31226 if (cur_cmd() == mp_right_delimiter)
31227 if (equiv_sym (cur_sym()) == l_delim)
31228 return;
31229 if (cur_sym() != r_delim) {
31230 char msg[256];
31231 const char *hlp[] = {
31232 "I found no right delimiter to match a left one. So I've",
31233 "put one in, behind the scenes; this may fix the problem.",
31234 NULL };
31235 mp_snprintf(msg, 256, "Missing `%s' has been inserted", mp_str (mp, text (r_delim)));
31236 @.Missing `)'@>
31237 mp_back_error (mp, msg, hlp, true);
31238 } else {
31239 char msg[256];
31240 const char *hlp[] = {
31241 "Strange: This token has lost its former meaning!",
31242 "I'll read it as a right delimiter this time;",
31243 "but watch out, I'll probably miss it later.",
31244 NULL };
31245 mp_snprintf(msg, 256, "The token `%s' is no longer a right delimiter", mp_str(mp, text (r_delim)));
31246 @.The token...delimiter@>
31247 mp_error (mp, msg, hlp, true);
31248 }
31249 }
31250
31251
31252 @ The next two commands save or change the values associated with tokens.
31253
31254 @<Declare action procedures for use by |do_statement|@>=
31255 static void mp_do_statement (MP mp);
31256 static void mp_do_interim (MP mp);
31257
31258 @ @c
31259 void mp_do_interim (MP mp) {
31260 mp_get_x_next (mp);
31261 if (cur_cmd() != mp_internal_quantity) {
31262 char msg[256];
31263 const char *hlp[] = {
31264 "Something like `tracingonline' should follow `interim'.",
31265 NULL };
31266 mp_snprintf(msg, 256, "The token `%s' isn't an internal quantity",
31267 (cur_sym() == NULL ? "(%CAPSULE)" : mp_str(mp, text (cur_sym()))));
31268 @.The token...quantity@>
31269 mp_back_error (mp, msg, hlp, true);
31270 } else {
31271 mp_save_internal (mp, cur_mod());
31272 mp_back_input (mp);
31273 }
31274 mp_do_statement (mp);
31275 }
31276
31277
31278 @ The following procedure is careful not to undefine the left-hand symbol
31279 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
31280
31281 @<Declare action procedures for use by |do_statement|@>=
31282 static void mp_do_let (MP mp);
31283
31284 @ @c
31285 void mp_do_let (MP mp) {
31286 mp_sym l; /* hash location of the left-hand symbol */
31287 mp_get_symbol (mp);
31288 l = cur_sym();
31289 mp_get_x_next (mp);
31290 if (cur_cmd() != mp_equals && cur_cmd() != mp_assignment) {
31291 const char *hlp[] = {
31292 "You should have said `let symbol = something'.",
31293 "But don't worry; I'll pretend that an equals sign",
31294 "was present. The next token I read will be `something'.",
31295 NULL };
31296 mp_back_error (mp, "Missing `=' has been inserted", hlp, true);
31297 @.Missing `='@>
31298 }
31299 mp_get_symbol (mp);
31300 switch (cur_cmd()) {
31301 case mp_defined_macro:
31302 case mp_secondary_primary_macro:
31303 case mp_tertiary_secondary_macro:
31304 case mp_expression_tertiary_macro:
31305 add_mac_ref (cur_mod_node());
31306 break;
31307 default:
31308 break;
31309 }
31310 mp_clear_symbol (mp, l, false);
31311 set_eq_type (l, cur_cmd());
31312 if (cur_cmd() == mp_tag_token)
31313 set_equiv (l, 0); /* TODO: this was |NULL| */
31314 else if (cur_cmd() == mp_defined_macro ||
31315 cur_cmd() == mp_secondary_primary_macro ||
31316 cur_cmd() == mp_tertiary_secondary_macro ||
31317 cur_cmd() == mp_expression_tertiary_macro)
31318 set_equiv_node (l, cur_mod_node());
31319 else if (cur_cmd() == mp_left_delimiter ||
31320 cur_cmd() == mp_right_delimiter)
31321 set_equiv_sym (l, equiv_sym (cur_sym()));
31322 else
31323 set_equiv (l, cur_mod());
31324 mp_get_x_next (mp);
31325 }
31326
31327
31328 @ @<Declarations@>=
31329 static void mp_do_new_internal (MP mp);
31330
31331 @ @<Internal library ...@>=
31332 void mp_grow_internals (MP mp, int l);
31333
31334 @ @c
31335 void mp_grow_internals (MP mp, int l) {
31336 mp_internal *internal;
31337 int k;
31338 if (l > max_halfword) {
31339 mp_confusion (mp, "out of memory space"); /* can't be reached */
31340 }
31341 internal = xmalloc ((l + 1), sizeof (mp_internal));
31342 for (k = 0; k <= l; k++) {
31343 if (k <= mp->max_internal) {
31344 memcpy (internal + k, mp->internal + k, sizeof (mp_internal));
31345 } else {
31346 memset (internal + k, 0, sizeof (mp_internal));
31347 new_number(((mp_internal *)(internal + k))->v.data.n);
31348 }
31349 }
31350 xfree (mp->internal);
31351 mp->internal = internal;
31352 mp->max_internal = l;
31353 }
31354 void mp_do_new_internal (MP mp) {
31355 int the_type = mp_known;
31356 mp_get_x_next (mp);
31357 if (cur_cmd() == mp_type_name && cur_mod() == mp_string_type) {
31358 the_type = mp_string_type;
31359 } else {
31360 if (!(cur_cmd() == mp_type_name && cur_mod() == mp_numeric_type)) {
31361 mp_back_input (mp);
31362 }
31363 }
31364 do {
31365 if (mp->int_ptr == mp->max_internal) {
31366 mp_grow_internals (mp, (mp->max_internal + (mp->max_internal / 4)));
31367 }
31368 mp_get_clear_symbol (mp);
31369 incr (mp->int_ptr);
31370 set_eq_type (cur_sym(), mp_internal_quantity);
31371 set_equiv (cur_sym(), mp->int_ptr);
31372 if (internal_name (mp->int_ptr) != NULL)
31373 xfree (internal_name (mp->int_ptr));
31374 set_internal_name (mp->int_ptr,
31375 mp_xstrdup (mp, mp_str (mp, text (cur_sym()))));
31376 if (the_type == mp_string_type) {
31377 set_internal_string (mp->int_ptr, mp_rts(mp,""));
31378 } else {
31379 set_number_to_zero (internal_value (mp->int_ptr));
31380 }
31381 set_internal_type (mp->int_ptr, the_type);
31382 mp_get_x_next (mp);
31383 } while (cur_cmd() == mp_comma);
31384 }
31385
31386
31387 @ @<Dealloc variables@>=
31388 for (k = 0; k <= mp->max_internal; k++) {
31389 free_number(mp->internal[k].v.data.n);
31390 xfree (internal_name (k));
31391 }
31392 xfree (mp->internal);
31393
31394
31395 @ The various `\&{show}' commands are distinguished by modifier fields
31396 in the usual way.
31397
31398 @d show_token_code 0 /* show the meaning of a single token */
31399 @d show_stats_code 1 /* show current memory and string usage */
31400 @d show_code 2 /* show a list of expressions */
31401 @d show_var_code 3 /* show a variable and its descendants */
31402 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
31403
31404 @<Put each...@>=
31405 mp_primitive (mp, "showtoken", mp_show_command, show_token_code);
31406 @:show_token_}{\&{showtoken} primitive@>
31407 mp_primitive (mp, "showstats", mp_show_command, show_stats_code);
31408 @:show_stats_}{\&{showstats} primitive@>
31409 mp_primitive (mp, "show", mp_show_command, show_code);
31410 @:show_}{\&{show} primitive@>
31411 mp_primitive (mp, "showvariable", mp_show_command, show_var_code);
31412 @:show_var_}{\&{showvariable} primitive@>
31413 mp_primitive (mp, "showdependencies", mp_show_command, show_dependencies_code);
31414 @:show_dependencies_}{\&{showdependencies} primitive@>
31415
31416
31417 @ @<Cases of |print_cmd...@>=
31418 case mp_show_command:
31419 switch (m) {
31420 case show_token_code:
31421 mp_print (mp, "showtoken");
31422 break;
31423 case show_stats_code:
31424 mp_print (mp, "showstats");
31425 break;
31426 case show_code:
31427 mp_print (mp, "show");
31428 break;
31429 case show_var_code:
31430 mp_print (mp, "showvariable");
31431 break;
31432 default:
31433 mp_print (mp, "showdependencies");
31434 break;
31435 }
31436 break;
31437
31438 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
31439 if it's |show_code|, complicated structures are abbreviated, otherwise
31440 they aren't.
31441
31442 @<Declare action procedures for use by |do_statement|@>=
31443 static void mp_do_show (MP mp);
31444
31445 @ @c
31446 void mp_do_show (MP mp) {
31447 mp_value new_expr;
31448 do {
31449 memset(&new_expr,0,sizeof(mp_value));
31450 new_number(new_expr.data.n);
31451 mp_get_x_next (mp);
31452 mp_scan_expression (mp);
31453 mp_print_nl (mp, ">> ");
31454 @.>>@>
31455 mp_print_exp (mp, NULL, 2);
31456 mp_flush_cur_exp (mp, new_expr);
31457 } while (cur_cmd() == mp_comma);
31458 }
31459
31460
31461 @ @<Declare action procedures for use by |do_statement|@>=
31462 static void mp_disp_token (MP mp);
31463
31464 @ @c
31465 void mp_disp_token (MP mp) {
31466 mp_print_nl (mp, "> ");
31467 @.>\relax@>
31468 if (cur_sym() == NULL)
31469 @<Show a numeric or string or capsule token@>@;
31470 else {
31471 mp_print_text (cur_sym());
31472 mp_print_char (mp, xord ('='));
31473 if (eq_type (cur_sym()) >= mp_outer_tag)
31474 mp_print (mp, "(outer) ");
31475 mp_print_cmd_mod (mp, cur_cmd(), cur_mod());
31476 if (cur_cmd() == mp_defined_macro) {
31477 mp_print_ln (mp);
31478 mp_show_macro (mp, cur_mod_node(), NULL, 100000);
31479 } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
31480 @^recursion@>
31481 }
31482 }
31483
31484
31485 @ @<Show a numeric or string or capsule token@>=
31486 {
31487 if (cur_cmd() == mp_numeric_token) {
31488 print_number (cur_mod_number());
31489 } else if (cur_cmd() == mp_capsule_token) {
31490 mp_print_capsule (mp, cur_mod_node());
31491 } else {
31492 mp_print_char (mp, xord ('"'));
31493 mp_print_str (mp, cur_mod_str());
31494 mp_print_char (mp, xord ('"'));
31495 delete_str_ref (cur_mod_str());
31496 }
31497 }
31498
31499
31500 @ The following cases of |print_cmd_mod| might arise in connection
31501 with |disp_token|, although they don't necessarily correspond to
31502 primitive tokens.
31503
31504 @<Cases of |print_cmd_...@>=
31505 case mp_left_delimiter:
31506 case mp_right_delimiter:
31507 if (c == mp_left_delimiter)
31508 mp_print (mp, "left");
31509 else
31510 mp_print (mp, "right");
31511 #if 0
31512 mp_print (mp, " delimiter that matches ");
31513 mp_print_text (m);
31514 #else
31515 mp_print (mp, " delimiter");
31516 #endif
31517 break;
31518 case mp_tag_token:
31519 if (m == 0) /* TODO: this was |NULL| */
31520 mp_print (mp, "tag");
31521 else
31522 mp_print (mp, "variable");
31523 break;
31524 case mp_defined_macro:
31525 mp_print (mp, "macro:");
31526 break;
31527 case mp_secondary_primary_macro:
31528 case mp_tertiary_secondary_macro:
31529 case mp_expression_tertiary_macro:
31530 mp_print_cmd_mod(mp, mp_macro_def,c);
31531 mp_print(mp, "'d macro:");
31532 mp_print_ln(mp);
31533 mp_show_token_list(mp, mp_link(mp_link(cur_mod_node())),0,1000,0);
31534 break;
31535 case mp_repeat_loop:
31536 mp_print (mp, "[repeat the loop]");
31537 break;
31538 case mp_internal_quantity:
31539 mp_print (mp, internal_name (m));
31540 break;
31541
31542
31543 @ @<Declare action procedures for use by |do_statement|@>=
31544 static void mp_do_show_token (MP mp);
31545
31546 @ @c
31547 void mp_do_show_token (MP mp) {
31548 do {
31549 get_t_next (mp);
31550 mp_disp_token (mp);
31551 mp_get_x_next (mp);
31552 } while (cur_cmd() == mp_comma);
31553 }
31554
31555
31556 @ @<Declare action procedures for use by |do_statement|@>=
31557 static void mp_do_show_stats (MP mp);
31558
31559 @ @c
31560 void mp_do_show_stats (MP mp) {
31561 mp_print_nl (mp, "Memory usage ");
31562 @.Memory usage...@>
31563 mp_print_int (mp, (integer) mp->var_used);
31564 mp_print_ln (mp);
31565 mp_print_nl (mp, "String usage ");
31566 mp_print_int (mp, (int) mp->strs_in_use);
31567 mp_print_char (mp, xord ('&'));
31568 mp_print_int (mp, (int) mp->pool_in_use);
31569 mp_print_ln (mp);
31570 mp_get_x_next (mp);
31571 }
31572
31573
31574 @ Here's a recursive procedure that gives an abbreviated account
31575 of a variable, for use by |do_show_var|.
31576
31577 @<Declare action procedures for use by |do_statement|@>=
31578 static void mp_disp_var (MP mp, mp_node p);
31579
31580 @ @c
31581 void mp_disp_var (MP mp, mp_node p) {
31582 mp_node q; /* traverses attributes and subscripts */
31583 int n; /* amount of macro text to show */
31584 if (mp_type (p) == mp_structured)
31585 @<Descend the structure@>@;
31586 else if (mp_type (p) >= mp_unsuffixed_macro)
31587 @<Display a variable macro@>@;
31588 else if (mp_type (p) != mp_undefined) {
31589 mp_print_nl (mp, "");
31590 mp_print_variable_name (mp, p);
31591 mp_print_char (mp, xord ('='));
31592 mp_print_exp (mp, p, 0);
31593 }
31594 }
31595
31596
31597 @ @<Descend the structure@>=
31598 {
31599 q = attr_head (p);
31600 do {
31601 mp_disp_var (mp, q);
31602 q = mp_link (q);
31603 } while (q != mp->end_attr);
31604 q = subscr_head (p);
31605 while (mp_name_type (q) == mp_subscr) {
31606 mp_disp_var (mp, q);
31607 q = mp_link (q);
31608 }
31609 }
31610
31611
31612 @ @<Display a variable macro@>=
31613 {
31614 mp_print_nl (mp, "");
31615 mp_print_variable_name (mp, p);
31616 if (mp_type (p) > mp_unsuffixed_macro)
31617 mp_print (mp, "@@#"); /* |suffixed_macro| */
31618 mp_print (mp, "=macro:");
31619 if ((int) mp->file_offset >= mp->max_print_line - 20)
31620 n = 5;
31621 else
31622 n = mp->max_print_line - (int) mp->file_offset - 15;
31623 mp_show_macro (mp, value_node (p), NULL, n);
31624 }
31625
31626
31627 @ @<Declare action procedures for use by |do_statement|@>=
31628 static void mp_do_show_var (MP mp);
31629
31630 @ @c
31631 void mp_do_show_var (MP mp) {
31632 do {
31633 get_t_next (mp);
31634 if (cur_sym() != NULL)
31635 if (cur_sym_mod() == 0)
31636 if (cur_cmd() == mp_tag_token)
31637 if (cur_mod() != 0 || cur_mod_node()!=NULL) {
31638 mp_disp_var (mp, cur_mod_node());
31639 goto DONE;
31640 }
31641 mp_disp_token (mp);
31642 DONE:
31643 mp_get_x_next (mp);
31644 } while (cur_cmd() == mp_comma);
31645 }
31646
31647
31648 @ @<Declare action procedures for use by |do_statement|@>=
31649 static void mp_do_show_dependencies (MP mp);
31650
31651 @ @c
31652 void mp_do_show_dependencies (MP mp) {
31653 mp_value_node p; /* link that runs through all dependencies */
31654 p = (mp_value_node) mp_link (mp->dep_head);
31655 while (p != mp->dep_head) {
31656 if (mp_interesting (mp, (mp_node) p)) {
31657 mp_print_nl (mp, "");
31658 mp_print_variable_name (mp, (mp_node) p);
31659 if (mp_type (p) == mp_dependent)
31660 mp_print_char (mp, xord ('='));
31661 else
31662 mp_print (mp, " = "); /* extra spaces imply proto-dependency */
31663 mp_print_dependency (mp, (mp_value_node) dep_list (p), mp_type (p));
31664 }
31665 p = (mp_value_node) dep_list (p);
31666 while (dep_info (p) != NULL)
31667 p = (mp_value_node) mp_link (p);
31668 p = (mp_value_node) mp_link (p);
31669 }
31670 mp_get_x_next (mp);
31671 }
31672
31673
31674 @ Finally we are ready for the procedure that governs all of the
31675 show commands.
31676
31677 @<Declare action procedures for use by |do_statement|@>=
31678 static void mp_do_show_whatever (MP mp);
31679
31680 @ @c
31681 void mp_do_show_whatever (MP mp) {
31682 if (mp->interaction == mp_error_stop_mode)
31683 wake_up_terminal();
31684 switch (cur_mod()) {
31685 case show_token_code:
31686 mp_do_show_token (mp);
31687 break;
31688 case show_stats_code:
31689 mp_do_show_stats (mp);
31690 break;
31691 case show_code:
31692 mp_do_show (mp);
31693 break;
31694 case show_var_code:
31695 mp_do_show_var (mp);
31696 break;
31697 case show_dependencies_code:
31698 mp_do_show_dependencies (mp);
31699 break;
31700 } /* there are no other cases */
31701 if (number_positive (internal_value (mp_showstopping))) {
31702 const char *hlp[] = {
31703 "This isn't an error message; I'm just showing something.",
31704 NULL };
31705 if (mp->interaction < mp_error_stop_mode) {
31706 hlp[0] = NULL;
31707 decr (mp->error_count);
31708 }
31709 if (cur_cmd() == mp_semicolon) {
31710 mp_error (mp, "OK", hlp, true);
31711 } else {
31712 mp_back_error (mp, "OK", hlp, true);
31713 mp_get_x_next (mp);
31714 }
31715 @.OK@>
31716 }
31717 }
31718
31719
31720 @ The `\&{addto}' command needs the following additional primitives:
31721
31722 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
31723 @d contour_code 1 /* command modifier for `\&{contour}' */
31724 @d also_code 2 /* command modifier for `\&{also}' */
31725
31726 @ Pre- and postscripts need two new identifiers:
31727
31728 @d with_mp_pre_script 11
31729 @d with_mp_post_script 13
31730
31731 @<Put each...@>=
31732 mp_primitive (mp, "doublepath", mp_thing_to_add, double_path_code);
31733 @:double_path_}{\&{doublepath} primitive@>
31734 mp_primitive (mp, "contour", mp_thing_to_add, contour_code);
31735 @:contour_}{\&{contour} primitive@>
31736 mp_primitive (mp, "also", mp_thing_to_add, also_code);
31737 @:also_}{\&{also} primitive@>
31738 mp_primitive (mp, "withpen", mp_with_option, mp_pen_type);
31739 @:with_pen_}{\&{withpen} primitive@>
31740 mp_primitive (mp, "dashed", mp_with_option, mp_picture_type);
31741 @:dashed_}{\&{dashed} primitive@>
31742 mp_primitive (mp, "withprescript", mp_with_option, with_mp_pre_script);
31743 @:with_mp_pre_script_}{\&{withprescript} primitive@>
31744 mp_primitive (mp, "withpostscript", mp_with_option, with_mp_post_script);
31745 @:with_mp_post_script_}{\&{withpostscript} primitive@>
31746 mp_primitive (mp, "withoutcolor", mp_with_option, mp_no_model);
31747 @:with_color_}{\&{withoutcolor} primitive@>
31748 mp_primitive (mp, "withgreyscale", mp_with_option, mp_grey_model);
31749 @:with_color_}{\&{withgreyscale} primitive@>
31750 mp_primitive (mp, "withcolor", mp_with_option, mp_uninitialized_model);
31751 @:with_color_}{\&{withcolor} primitive@>
31752 /* \&{withrgbcolor} is an alias for \&{withcolor} */
31753 mp_primitive (mp, "withrgbcolor", mp_with_option, mp_rgb_model);
31754 @:with_color_}{\&{withrgbcolor} primitive@>
31755 mp_primitive (mp, "withcmykcolor", mp_with_option, mp_cmyk_model);
31756 @:with_color_}{\&{withcmykcolor} primitive@>
31757
31758
31759 @ @<Cases of |print_cmd...@>=
31760 case mp_thing_to_add:
31761 if (m == contour_code)
31762 mp_print (mp, "contour");
31763 else if (m == double_path_code)
31764 mp_print (mp, "doublepath");
31765 else
31766 mp_print (mp, "also");
31767 break;
31768 case mp_with_option:
31769 if (m == mp_pen_type)
31770 mp_print (mp, "withpen");
31771 else if (m == with_mp_pre_script)
31772 mp_print (mp, "withprescript");
31773 else if (m == with_mp_post_script)
31774 mp_print (mp, "withpostscript");
31775 else if (m == mp_no_model)
31776 mp_print (mp, "withoutcolor");
31777 else if (m == mp_rgb_model)
31778 mp_print (mp, "withrgbcolor");
31779 else if (m == mp_uninitialized_model)
31780 mp_print (mp, "withcolor");
31781 else if (m == mp_cmyk_model)
31782 mp_print (mp, "withcmykcolor");
31783 else if (m == mp_grey_model)
31784 mp_print (mp, "withgreyscale");
31785 else
31786 mp_print (mp, "dashed");
31787 break;
31788
31789 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
31790 updates the list of graphical objects starting at |p|. Each $\langle$with
31791 clause$\rangle$ updates all graphical objects whose |type| is compatible.
31792 Other objects are ignored.
31793
31794 @<Declare action procedures for use by |do_statement|@>=
31795 static void mp_scan_with_list (MP mp, mp_node p);
31796
31797 @ Forcing the color to be between |0| and |unity| here guarantees that no
31798 picture will ever contain a color outside the legal range for \ps\ graphics.
31799
31800 @d make_cp_a_colored_object() do {
31801 cp = p;
31802 while (cp != NULL) {
31803 if (has_color (cp))
31804 break;
31805 cp = mp_link (cp);
31806 }
31807 } while (0)@;
31808
31809 @d clear_color(A) do {
31810 set_number_to_zero(((mp_stroked_node)(A))->cyan);
31811 set_number_to_zero(((mp_stroked_node)(A))->magenta);
31812 set_number_to_zero(((mp_stroked_node)(A))->yellow);
31813 set_number_to_zero(((mp_stroked_node)(A))->black);
31814 mp_color_model ((A)) = mp_uninitialized_model;
31815 } while (0)@;
31816
31817 @d set_color_val(A,B) do {
31818 number_clone(A, (B));
31819 if (number_negative(A))
31820 set_number_to_zero(A);
31821 if (number_greater(A,unity_t))
31822 set_number_to_unity(A);
31823 } while (0)@;
31824
31825 @c
31826 static int is_invalid_with_list (MP mp, mp_variable_type t) {
31827 return ((t == with_mp_pre_script) && (mp->cur_exp.type != mp_string_type)) || @|
31828 ((t == with_mp_post_script) && (mp->cur_exp.type != mp_string_type)) || @|
31829 ((t == (mp_variable_type) mp_uninitialized_model) && @|
31830 ((mp->cur_exp.type != mp_cmykcolor_type) @|
31831 && (mp->cur_exp.type != mp_color_type) @|
31832 && (mp->cur_exp.type != mp_known) @|
31833 && (mp->cur_exp.type != mp_boolean_type))) || @|
31834 ((t == (mp_variable_type) mp_cmyk_model) @|
31835 && (mp->cur_exp.type != mp_cmykcolor_type)) || @|
31836 ((t == (mp_variable_type) mp_rgb_model) @|
31837 && (mp->cur_exp.type != mp_color_type)) || @|
31838 ((t == (mp_variable_type) mp_grey_model) @|
31839 && (mp->cur_exp.type != mp_known)) || @|
31840 ((t == (mp_variable_type) mp_pen_type) @|
31841 && (mp->cur_exp.type != t)) || @|
31842 ((t == (mp_variable_type) mp_picture_type) @|
31843 && (mp->cur_exp.type != t));
31844 }
31845 static void complain_invalid_with_list (MP mp, mp_variable_type t) {
31846 /* Complain about improper type */
31847 mp_value new_expr;
31848 const char *hlp[] = {
31849 "Next time say `withpen <known pen expression>';",
31850 "I'll ignore the bad `with' clause and look for another.",
31851 NULL };
31852 memset(&new_expr,0,sizeof(mp_value));
31853 new_number(new_expr.data.n);
31854 mp_disp_err(mp, NULL);
31855 if (t == with_mp_pre_script)
31856 hlp[0] = "Next time say `withprescript <known string expression>';";
31857 else if (t == with_mp_post_script)
31858 hlp[0] = "Next time say `withpostscript <known string expression>';";
31859 else if (t == mp_picture_type)
31860 hlp[0] = "Next time say `dashed <known picture expression>';";
31861 else if (t == (mp_variable_type) mp_uninitialized_model)
31862 hlp[0] = "Next time say `withcolor <known color expression>';";
31863 else if (t == (mp_variable_type) mp_rgb_model)
31864 hlp[0] = "Next time say `withrgbcolor <known color expression>';";
31865 else if (t == (mp_variable_type) mp_cmyk_model)
31866 hlp[0] = "Next time say `withcmykcolor <known cmykcolor expression>';";
31867 else if (t == (mp_variable_type) mp_grey_model)
31868 hlp[0] = "Next time say `withgreyscale <known numeric expression>';";
31869 mp_back_error (mp, "Improper type", hlp, true);
31870 mp_get_x_next (mp);
31871 mp_flush_cur_exp (mp, new_expr);
31872 }
31873
31874 void mp_scan_with_list (MP mp, mp_node p) {
31875 mp_variable_type t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
31876 mp_node q; /* for list manipulation */
31877 mp_node cp, pp, dp, ap, bp;
31878 /* objects being updated; |void| initially; |NULL| to suppress update */
31879 cp = MP_VOID;
31880 pp = MP_VOID;
31881 dp = MP_VOID;
31882 ap = MP_VOID;
31883 bp = MP_VOID;
31884 while (cur_cmd() == mp_with_option) {
31885 /* TODO: this is not very nice: the color models have their own enumeration */
31886 t = (mp_variable_type) cur_mod();
31887 mp_get_x_next (mp);
31888 if (t != (mp_variable_type) mp_no_model)
31889 mp_scan_expression (mp);
31890 if (is_invalid_with_list(mp, t)) {
31891 complain_invalid_with_list (mp, t);
31892 continue;
31893 }
31894 if (t == (mp_variable_type) mp_uninitialized_model) {
31895 mp_value new_expr;
31896 memset(&new_expr,0,sizeof(mp_value));
31897 new_number(new_expr.data.n);
31898 if (cp == MP_VOID)
31899 make_cp_a_colored_object();
31900 if (cp != NULL) {
31901 /* Transfer a color from the current expression to object~|cp| */
31902 if (mp->cur_exp.type == mp_color_type) {
31903 /* Transfer a rgbcolor from the current expression to object~|cp| */
31904 mp_stroked_node cp0 = (mp_stroked_node)cp;
31905 q = value_node (cur_exp_node ());
31906 clear_color(cp0);
31907 mp_color_model (cp) = mp_rgb_model;
31908 set_color_val (cp0->red, value_number (red_part (q)));
31909 set_color_val (cp0->green, value_number (green_part (q)));
31910 set_color_val (cp0->blue, value_number (blue_part (q)));
31911 } else if (mp->cur_exp.type == mp_cmykcolor_type) {
31912 /* Transfer a cmykcolor from the current expression to object~|cp| */
31913 mp_stroked_node cp0 = (mp_stroked_node)cp;
31914 q = value_node (cur_exp_node ());
31915 set_color_val (cp0->cyan, value_number (cyan_part (q)));
31916 set_color_val (cp0->magenta, value_number (magenta_part (q)));
31917 set_color_val (cp0->yellow, value_number (yellow_part (q)));
31918 set_color_val (cp0->black, value_number (black_part (q)));
31919 mp_color_model (cp) = mp_cmyk_model;
31920 } else if (mp->cur_exp.type == mp_known) {
31921 /* Transfer a greyscale from the current expression to object~|cp| */
31922 mp_number qq;
31923 mp_stroked_node cp0 = (mp_stroked_node)cp;
31924 new_number (qq);
31925 number_clone (qq, cur_exp_value_number ());
31926 clear_color (cp);
31927 mp_color_model (cp) = mp_grey_model;
31928 set_color_val (cp0->grey, qq);
31929 free_number (qq);
31930 } else if (cur_exp_value_boolean () == mp_false_code) {
31931 /* Transfer a noncolor from the current expression to object~|cp| */
31932 clear_color (cp);
31933 mp_color_model (cp) = mp_no_model;
31934 } else if (cur_exp_value_boolean () == mp_true_code) {
31935 /* Transfer no color from the current expression to object~|cp| */
31936 clear_color (cp);
31937 mp_color_model (cp) = mp_uninitialized_model;
31938 }
31939 }
31940 mp_flush_cur_exp (mp, new_expr);
31941 } else if (t == (mp_variable_type) mp_rgb_model) {
31942 mp_value new_expr;
31943 memset(&new_expr,0,sizeof(mp_value));
31944 new_number(new_expr.data.n);
31945 if (cp == MP_VOID)
31946 make_cp_a_colored_object();
31947 if (cp != NULL) {
31948 /* Transfer a rgbcolor from the current expression to object~|cp| */
31949 mp_stroked_node cp0 = (mp_stroked_node)cp;
31950 q = value_node (cur_exp_node ());
31951 clear_color(cp0);
31952 mp_color_model (cp) = mp_rgb_model;
31953 set_color_val (cp0->red, value_number (red_part (q)));
31954 set_color_val (cp0->green, value_number (green_part (q)));
31955 set_color_val (cp0->blue, value_number (blue_part (q)));
31956 }
31957 mp_flush_cur_exp (mp, new_expr);
31958 } else if (t == (mp_variable_type) mp_cmyk_model) {
31959 mp_value new_expr;
31960 memset(&new_expr,0,sizeof(mp_value));
31961 new_number(new_expr.data.n);
31962 if (cp == MP_VOID)
31963 make_cp_a_colored_object();
31964 if (cp != NULL) {
31965 /* Transfer a cmykcolor from the current expression to object~|cp| */
31966 mp_stroked_node cp0 = (mp_stroked_node)cp;
31967 q = value_node (cur_exp_node ());
31968 set_color_val (cp0->cyan, value_number (cyan_part (q)));
31969 set_color_val (cp0->magenta, value_number (magenta_part (q)));
31970 set_color_val (cp0->yellow, value_number (yellow_part (q)));
31971 set_color_val (cp0->black, value_number (black_part (q)));
31972 mp_color_model (cp) = mp_cmyk_model;
31973 }
31974 mp_flush_cur_exp (mp, new_expr);
31975 } else if (t == (mp_variable_type) mp_grey_model) {
31976 mp_value new_expr;
31977 memset(&new_expr,0,sizeof(mp_value));
31978 new_number(new_expr.data.n);
31979 if (cp == MP_VOID)
31980 make_cp_a_colored_object();
31981 if (cp != NULL) {
31982 /* Transfer a greyscale from the current expression to object~|cp| */
31983 mp_number qq;
31984 mp_stroked_node cp0 = (mp_stroked_node)cp;
31985 new_number (qq);
31986 number_clone (qq, cur_exp_value_number ());
31987 clear_color (cp);
31988 mp_color_model (cp) = mp_grey_model;
31989 set_color_val (cp0->grey, qq);
31990 free_number (qq);
31991 }
31992 mp_flush_cur_exp (mp, new_expr);
31993 } else if (t == (mp_variable_type) mp_no_model) {
31994 if (cp == MP_VOID)
31995 make_cp_a_colored_object();
31996 if (cp != NULL) {
31997 /* Transfer a noncolor from the current expression to object~|cp| */
31998 clear_color (cp);
31999 mp_color_model (cp) = mp_no_model;
32000 }
32001 } else if (t == mp_pen_type) {
32002 if (pp == MP_VOID) {
32003 /* Make |pp| an object in list~|p| that needs a pen */
32004 pp = p;
32005 while (pp != NULL) {
32006 if (has_pen (pp))
32007 break;
32008 pp = mp_link (pp);
32009 }
32010 }
32011
32012 if (pp != NULL) {
32013 switch (mp_type (pp)) {
32014 case mp_fill_node_type:
32015 if (mp_pen_p ((mp_fill_node) pp) != NULL)
32016 mp_toss_knot_list (mp, mp_pen_p ((mp_fill_node) pp));
32017 mp_pen_p ((mp_fill_node) pp) = cur_exp_knot ();
32018 break;
32019 case mp_stroked_node_type:
32020 if (mp_pen_p ((mp_stroked_node) pp) != NULL)
32021 mp_toss_knot_list (mp, mp_pen_p ((mp_stroked_node) pp));
32022 mp_pen_p ((mp_stroked_node) pp) = cur_exp_knot ();
32023 break;
32024 default:
32025 assert (0);
32026 break;
32027 }
32028 mp->cur_exp.type = mp_vacuous;
32029 }
32030 } else if (t == with_mp_pre_script) {
32031 if (cur_exp_str ()->len) {
32032 if (ap == MP_VOID)
32033 ap = p;
32034 while ((ap != NULL) && (!has_color (ap)))
32035 ap = mp_link (ap);
32036 if (ap != NULL) {
32037 if (mp_pre_script (ap) != NULL) { /* build a new,combined string */
32038 unsigned old_setting; /* saved |selector| setting */
32039 mp_string s; /* for string cleanup after combining */
32040 s = mp_pre_script (ap);
32041 old_setting = mp->selector;
32042 mp->selector = new_string;
32043 str_room (mp_pre_script (ap)->len + cur_exp_str ()->len + 2);
32044 mp_print_str (mp, cur_exp_str ());
32045 append_char (13); /* a forced \ps\ newline */
32046 mp_print_str (mp, mp_pre_script (ap));
32047 mp_pre_script (ap) = mp_make_string (mp);
32048 delete_str_ref (s);
32049 mp->selector = old_setting;
32050 } else {
32051 mp_pre_script (ap) = cur_exp_str ();
32052 }
32053 add_str_ref (mp_pre_script (ap));
32054 mp->cur_exp.type = mp_vacuous;
32055 }
32056 }
32057 } else if (t == with_mp_post_script) {
32058 if (cur_exp_str ()->len) {
32059 if (bp == MP_VOID)
32060 bp = p;
32061 while ((bp != NULL) && (!has_color (bp)))
32062 bp = mp_link (bp);
32063 if (bp != NULL) {
32064 if (mp_post_script (bp) != NULL) {
32065 unsigned old_setting; /* saved |selector| setting */
32066 mp_string s; /* for string cleanup after combining */
32067 s = mp_post_script (bp);
32068 old_setting = mp->selector;
32069 mp->selector = new_string;
32070 str_room (mp_post_script (bp)->len + cur_exp_str ()->len + 2);
32071 mp_print_str (mp, mp_post_script (bp));
32072 append_char (13); /* a forced \ps\ newline */
32073 mp_print_str (mp, cur_exp_str ());
32074 mp_post_script (bp) = mp_make_string (mp);
32075 delete_str_ref (s);
32076 mp->selector = old_setting;
32077 } else {
32078 mp_post_script (bp) = cur_exp_str ();
32079 }
32080 add_str_ref (mp_post_script (bp));
32081 mp->cur_exp.type = mp_vacuous;
32082 }
32083 }
32084 } else {
32085 if (dp == MP_VOID) {
32086 /* Make |dp| a stroked node in list~|p| */
32087 dp = p;
32088 while (dp != NULL) {
32089 if (mp_type (dp) == mp_stroked_node_type)
32090 break;
32091 dp = mp_link (dp);
32092 }
32093 }
32094 if (dp != NULL) {
32095 if (mp_dash_p (dp) != NULL)
32096 delete_edge_ref (mp_dash_p (dp));
32097 mp_dash_p (dp) = (mp_node)mp_make_dashes (mp, (mp_edge_header_node)cur_exp_node ());
32098 set_number_to_unity(((mp_stroked_node)dp)->dash_scale);
32099 mp->cur_exp.type = mp_vacuous;
32100 }
32101 }
32102 }
32103 /* Copy the information from objects |cp|, |pp|, and |dp| into the rest
32104 of the list */
32105 if (cp > MP_VOID) {
32106 /* Copy |cp|'s color into the colored objects linked to~|cp| */
32107 q = mp_link (cp);
32108 while (q != NULL) {
32109 if (has_color (q)) {
32110 mp_stroked_node q0 = (mp_stroked_node)q;
32111 mp_stroked_node cp0 = (mp_stroked_node)cp;
32112 number_clone(q0->red, cp0->red);
32113 number_clone(q0->green, cp0->green);
32114 number_clone(q0->blue, cp0->blue);
32115 number_clone(q0->black, cp0->black);
32116 mp_color_model (q) = mp_color_model (cp);
32117 }
32118 q = mp_link (q);
32119 }
32120 }
32121 if (pp > MP_VOID) {
32122 /* Copy |mp_pen_p(pp)| into stroked and filled nodes linked to |pp| */
32123 q = mp_link (pp);
32124 while (q != NULL) {
32125 if (has_pen (q)) {
32126 switch (mp_type (q)) {
32127 case mp_fill_node_type:
32128 if (mp_pen_p ((mp_fill_node) q) != NULL)
32129 mp_toss_knot_list (mp, mp_pen_p ((mp_fill_node) q));
32130 mp_pen_p ((mp_fill_node) q) = copy_pen (mp_pen_p ((mp_fill_node) pp));
32131 break;
32132 case mp_stroked_node_type:
32133 if (mp_pen_p ((mp_stroked_node) q) != NULL)
32134 mp_toss_knot_list (mp, mp_pen_p ((mp_stroked_node) q));
32135 mp_pen_p ((mp_stroked_node) q) =
32136 copy_pen (mp_pen_p ((mp_stroked_node) pp));
32137 break;
32138 default:
32139 assert (0);
32140 break;
32141 }
32142 }
32143 q = mp_link (q);
32144 }
32145 }
32146 if (dp > MP_VOID) {
32147 /* Make stroked nodes linked to |dp| refer to |mp_dash_p(dp)| */
32148 q = mp_link (dp);
32149 while (q != NULL) {
32150 if (mp_type (q) == mp_stroked_node_type) {
32151 if (mp_dash_p (q) != NULL)
32152 delete_edge_ref (mp_dash_p (q));
32153 mp_dash_p (q) = mp_dash_p (dp);
32154 set_number_to_unity(((mp_stroked_node)q)->dash_scale);
32155 if (mp_dash_p (q) != NULL)
32156 add_edge_ref (mp_dash_p (q));
32157 }
32158 q = mp_link (q);
32159 }
32160 }
32161 }
32162
32163
32164 @ One of the things we need to do when we've parsed an \&{addto} or
32165 similar command is find the header of a supposed \&{picture} variable, given
32166 a token list for that variable. Since the edge structure is about to be
32167 updated, we use |private_edges| to make sure that this is possible.
32168
32169 @<Declare action procedures for use by |do_statement|@>=
32170 static mp_edge_header_node mp_find_edges_var (MP mp, mp_node t);
32171
32172 @ @c
32173 mp_edge_header_node mp_find_edges_var (MP mp, mp_node t) {
32174 mp_node p;
32175 mp_edge_header_node cur_edges; /* the return value */
32176 p = mp_find_variable (mp, t);
32177 cur_edges = NULL;
32178 if (p == NULL) {
32179 const char *hlp[] = {
32180 "It seems you did a nasty thing---probably by accident,",
32181 "but nevertheless you nearly hornswoggled me...",
32182 "While I was evaluating the right-hand side of this",
32183 "command, something happened, and the left-hand side",
32184 "is no longer a variable! So I won't change anything.",
32185 NULL };
32186 char *msg = mp_obliterated (mp, t);
32187 mp_back_error (mp, msg, hlp, true);
32188 free(msg);
32189 mp_get_x_next (mp);
32190 } else if (mp_type (p) != mp_picture_type) {
32191 char msg[256];
32192 mp_string sname;
32193 int old_setting = mp->selector;
32194 const char *hlp[] = {
32195 "I was looking for a \"known\" picture variable.",
32196 "So I'll not change anything just now.",
32197 NULL };
32198 mp->selector = new_string;
32199 mp_show_token_list (mp, t, NULL, 1000, 0);
32200 sname = mp_make_string(mp);
32201 mp->selector = old_setting;
32202 mp_snprintf (msg, 256, "Variable %s is the wrong type(%s)",
32203 mp_str(mp, sname), mp_type_string(mp_type (p)));
32204 @.Variable x is the wrong type@>
32205 delete_str_ref(sname);
32206 mp_back_error (mp, msg, hlp, true);
32207 mp_get_x_next (mp);
32208 } else {
32209 set_value_node (p, (mp_node)mp_private_edges (mp, (mp_edge_header_node)value_node (p)));
32210 cur_edges = (mp_edge_header_node)value_node (p);
32211 }
32212 mp_flush_node_list (mp, t);
32213 return cur_edges;
32214 }
32215
32216
32217 @ @<Put each...@>=
32218 mp_primitive (mp, "clip", mp_bounds_command, mp_start_clip_node_type);
32219 @:clip_}{\&{clip} primitive@>
32220 mp_primitive (mp, "setbounds", mp_bounds_command, mp_start_bounds_node_type);
32221 @:set_bounds_}{\&{setbounds} primitive@>
32222
32223
32224 @ @<Cases of |print_cmd...@>=
32225 case mp_bounds_command:
32226 if (m == mp_start_clip_node_type)
32227 mp_print (mp, "clip");
32228 else
32229 mp_print (mp, "setbounds");
32230 break;
32231
32232 @ The following function parses the beginning of an \&{addto} or \&{clip}
32233 command: it expects a variable name followed by a token with |cur_cmd=sep|
32234 and then an expression. The function returns the token list for the variable
32235 and stores the command modifier for the separator token in the global variable
32236 |last_add_type|. We must be careful because this variable might get overwritten
32237 any time we call |get_x_next|.
32238
32239 @<Glob...@>=
32240 quarterword last_add_type;
32241 /* command modifier that identifies the last \&{addto} command */
32242
32243 @ @<Declare action procedures for use by |do_statement|@>=
32244 static mp_node mp_start_draw_cmd (MP mp, quarterword sep);
32245
32246 @ @c
32247 mp_node mp_start_draw_cmd (MP mp, quarterword sep) {
32248 mp_node lhv; /* variable to add to left */
32249 quarterword add_type = 0; /* value to be returned in |last_add_type| */
32250 lhv = NULL;
32251 mp_get_x_next (mp);
32252 mp->var_flag = sep;
32253 mp_scan_primary (mp);
32254 if (mp->cur_exp.type != mp_token_list) {
32255 /* Abandon edges command because there's no variable */
32256 mp_value new_expr;
32257 const char *hlp[] = {
32258 "At this point I needed to see the name of a picture variable.",
32259 "(Or perhaps you have indeed presented me with one; I might",
32260 "have missed it, if it wasn't followed by the proper token.)",
32261 "So I'll not change anything just now.",
32262 NULL };
32263 memset(&new_expr,0,sizeof(mp_value));
32264 new_number(new_expr.data.n);
32265 mp_disp_err(mp, NULL);
32266 set_number_to_zero (new_expr.data.n);
32267 mp_back_error (mp, "Not a suitable variable", hlp, true);
32268 mp_get_x_next (mp);
32269 mp_flush_cur_exp (mp, new_expr);
32270 } else {
32271 lhv = cur_exp_node ();
32272 add_type = (quarterword) cur_mod();
32273 mp->cur_exp.type = mp_vacuous;
32274 mp_get_x_next (mp);
32275 mp_scan_expression (mp);
32276 }
32277 mp->last_add_type = add_type;
32278 return lhv;
32279 }
32280
32281 @ Here is an example of how to use |mp_start_draw_cmd|.
32282
32283 @<Declare action procedures for use by |do_statement|@>=
32284 static void mp_do_bounds (MP mp);
32285
32286 @ @c
32287 void mp_do_bounds (MP mp) {
32288 mp_node lhv; /* variable on left, the corresponding edge structure */
32289 mp_edge_header_node lhe;
32290 mp_node p; /* for list manipulation */
32291 mpinteger64 m; /* initial value of |cur_mod| */
32292 m = cur_mod();
32293 lhv = mp_start_draw_cmd (mp, mp_to_token);
32294 if (lhv != NULL) {
32295 mp_value new_expr;
32296 memset(&new_expr,0,sizeof(mp_value));
32297 lhe = mp_find_edges_var (mp, lhv);
32298 if (lhe == NULL) {
32299 new_number(new_expr.data.n);
32300 set_number_to_zero (new_expr.data.n);
32301 mp_flush_cur_exp (mp, new_expr);
32302 } else if (mp->cur_exp.type != mp_path_type) {
32303 const char *hlp[] ={
32304 "This expression should have specified a known path.",
32305 "So I'll not change anything just now.",
32306 NULL };
32307 mp_disp_err(mp, NULL);
32308 new_number(new_expr.data.n);
32309 set_number_to_zero (new_expr.data.n);
32310 mp_back_error (mp, "Improper `clip'", hlp, true);
32311 mp_get_x_next (mp);
32312 mp_flush_cur_exp (mp, new_expr);
32313 } else if (mp_left_type (cur_exp_knot ()) == mp_endpoint) {
32314 /* Complain about a non-cycle */
32315 const char *hlp[] = {
32316 "That contour should have ended with `..cycle' or `&cycle'.",
32317 "So I'll not change anything just now.",
32318 NULL };
32319 mp_back_error (mp, "Not a cycle" , hlp, true);
32320 mp_get_x_next (mp);
32321 } else {
32322 /* Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe| */
32323 p = mp_new_bounds_node (mp, cur_exp_knot (), (quarterword) m);
32324 mp_link (p) = mp_link (edge_list (lhe));
32325 mp_link (edge_list (lhe)) = p;
32326 if (obj_tail (lhe) == edge_list (lhe))
32327 obj_tail (lhe) = p;
32328 if (m == mp_start_clip_node_type) {
32329 p = mp_new_bounds_node (mp, NULL, mp_stop_clip_node_type);
32330 } else if (m == mp_start_bounds_node_type) {
32331 p = mp_new_bounds_node (mp, NULL, mp_stop_bounds_node_type);
32332 }
32333 mp_link (obj_tail (lhe)) = p;
32334 obj_tail (lhe) = p;
32335 mp_init_bbox (mp, lhe);
32336 }
32337 }
32338 }
32339
32340
32341 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
32342 cases to deal with.
32343
32344 @<Declare action procedures for use by |do_statement|@>=
32345 static void mp_do_add_to (MP mp);
32346
32347 @ @c
32348 void mp_do_add_to (MP mp) {
32349 mp_node lhv;
32350 mp_edge_header_node lhe; /* variable on left, the corresponding edge structure */
32351 mp_node p; /* the graphical object or list for |scan_with_list| to update */
32352 mp_edge_header_node e; /* an edge structure to be merged */
32353 quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
32354 lhv = mp_start_draw_cmd (mp, mp_thing_to_add);
32355 add_type = mp->last_add_type;
32356 if (lhv != NULL) {
32357 if (add_type == also_code) {
32358 /* Make sure the current expression is a suitable picture and set |e| and |p|
32359 appropriately */
32360 /* Setting |p:=NULL| causes the $\langle$with list$\rangle$ to be ignored;
32361 setting |e:=NULL| prevents anything from being added to |lhe|. */
32362 p = NULL;
32363 e = NULL;
32364 if (mp->cur_exp.type != mp_picture_type) {
32365 mp_value new_expr;
32366 const char *hlp[]= {
32367 "This expression should have specified a known picture.",
32368 "So I'll not change anything just now.",
32369 NULL };
32370 memset(&new_expr,0,sizeof(mp_value));
32371 new_number(new_expr.data.n);
32372 mp_disp_err(mp, NULL);
32373 set_number_to_zero (new_expr.data.n);
32374 mp_back_error (mp, "Improper `addto'", hlp, true);
32375 mp_get_x_next (mp);
32376 mp_flush_cur_exp (mp, new_expr);
32377 } else {
32378 e = mp_private_edges (mp, (mp_edge_header_node)cur_exp_node ());
32379 mp->cur_exp.type = mp_vacuous;
32380 p = mp_link (edge_list (e));
32381 }
32382
32383 } else {
32384 /* Create a graphical object |p| based on |add_type| and the current
32385 expression */
32386 /* In this case |add_type<>also_code| so setting |p:=NULL| suppresses future
32387 attempts to add to the edge structure. */
32388 e = NULL;
32389 p = NULL;
32390 if (mp->cur_exp.type == mp_pair_type)
32391 mp_pair_to_path (mp);
32392 if (mp->cur_exp.type != mp_path_type) {
32393 mp_value new_expr;
32394 const char *hlp[] = {
32395 "This expression should have specified a known path.",
32396 "So I'll not change anything just now.",
32397 NULL };
32398 memset(&new_expr,0,sizeof(mp_value));
32399 new_number(new_expr.data.n);
32400 mp_disp_err(mp, NULL);
32401 set_number_to_zero (new_expr.data.n);
32402 mp_back_error (mp, "Improper `addto'", hlp, true);
32403 mp_get_x_next (mp);
32404 mp_flush_cur_exp (mp, new_expr);
32405 } else if (add_type == contour_code) {
32406 if (mp_left_type (cur_exp_knot ()) == mp_endpoint) {
32407 /* Complain about a non-cycle */
32408 const char *hlp[] = {
32409 "That contour should have ended with `..cycle' or `&cycle'.",
32410 "So I'll not change anything just now.",
32411 NULL };
32412 mp_back_error (mp, "Not a cycle" , hlp, true);
32413 mp_get_x_next (mp);
32414
32415 } else {
32416 p = mp_new_fill_node (mp, cur_exp_knot ());
32417 mp->cur_exp.type = mp_vacuous;
32418 }
32419 } else {
32420 p = mp_new_stroked_node (mp, cur_exp_knot ());
32421 mp->cur_exp.type = mp_vacuous;
32422 }
32423
32424 }
32425 mp_scan_with_list (mp, p);
32426 /* Use |p|, |e|, and |add_type| to augment |lhv| as requested */
32427 lhe = mp_find_edges_var (mp, lhv);
32428 if (lhe == NULL) {
32429 if ((e == NULL) && (p != NULL))
32430 e = mp_toss_gr_object (mp, p);
32431 if (e != NULL)
32432 delete_edge_ref (e);
32433 } else if (add_type == also_code) {
32434 if (e != NULL) {
32435 /* Merge |e| into |lhe| and delete |e| */
32436 if (mp_link (edge_list (e)) != NULL) {
32437 mp_link (obj_tail (lhe)) = mp_link (edge_list (e));
32438 obj_tail (lhe) = obj_tail (e);
32439 obj_tail (e) = edge_list (e);
32440 mp_link (edge_list (e)) = NULL;
32441 mp_flush_dash_list (mp, lhe);
32442 }
32443 mp_toss_edges (mp, e);
32444 }
32445 } else if (p != NULL) {
32446 mp_link (obj_tail (lhe)) = p;
32447 obj_tail (lhe) = p;
32448 if (add_type == double_path_code) {
32449 if (mp_pen_p ((mp_stroked_node) p) == NULL) {
32450 mp_pen_p ((mp_stroked_node) p) = mp_get_pen_circle (mp, zero_t);
32451 }
32452 }
32453 }
32454 }
32455 }
32456
32457 @ @<Declare action procedures for use by |do_statement|@>=
32458 @<Declare the \ps\ output procedures@>
32459 static void mp_do_ship_out (MP mp);
32460
32461 @ @c
32462 void mp_do_ship_out (MP mp) {
32463 mpinteger64 c; /* the character code */
32464 mp_value new_expr;
32465 memset(&new_expr,0,sizeof(mp_value));
32466 new_number(new_expr.data.n);
32467 mp_get_x_next (mp);
32468 mp_scan_expression (mp);
32469 if (mp->cur_exp.type != mp_picture_type) {
32470 @<Complain that it's not a known picture@>;
32471 } else {
32472 c = round_unscaled (internal_value (mp_char_code)) % 256;
32473 if (c < 0)
32474 c = c + 256;
32475 @<Store the width information for character code~|c|@>;
32476 mp_ship_out (mp, cur_exp_node ());
32477 set_number_to_zero (new_expr.data.n);
32478 mp_flush_cur_exp (mp, new_expr);
32479 }
32480 }
32481
32482
32483 @ @<Complain that it's not a known picture@>=
32484 {
32485 const char *hlp[] = { "I can only output known pictures.", NULL };
32486 mp_disp_err(mp, NULL);
32487 set_number_to_zero (new_expr.data.n);
32488 mp_back_error (mp, "Not a known picture", hlp, true);
32489 mp_get_x_next (mp);
32490 mp_flush_cur_exp (mp, new_expr);
32491 }
32492
32493
32494 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
32495 |start_sym|.
32496
32497 @<Glob...@>=
32498 mp_sym start_sym; /* a symbolic token to insert at beginning of job */
32499
32500 @ @<Set init...@>=
32501 mp->start_sym = NULL;
32502
32503 @ Finally, we have only the ``message'' commands remaining.
32504
32505 @d message_code 0
32506 @d err_message_code 1
32507 @d err_help_code 2
32508 @d filename_template_code 3
32509 @d print_with_leading_zeroes(A,B) do {
32510 size_t g = mp->cur_length;
32511 size_t f = (size_t)(B);
32512 mp_print_int(mp, (A));
32513 g = mp->cur_length - g;
32514 if ( f>g ) {
32515 mp->cur_length = mp->cur_length - g;
32516 while ( f>g ) {
32517 mp_print_char(mp, xord('0'));
32518 decr(f);
32519 }
32520 mp_print_int(mp, (A));
32521 }
32522 f = 0;
32523 } while (0)@;
32524
32525 @<Put each...@>=
32526 mp_primitive (mp, "message", mp_message_command, message_code);
32527 @:message_}{\&{message} primitive@>
32528 mp_primitive (mp, "errmessage", mp_message_command, err_message_code);
32529 @:err_message_}{\&{errmessage} primitive@>
32530 mp_primitive (mp, "errhelp", mp_message_command, err_help_code);
32531 @:err_help_}{\&{errhelp} primitive@>
32532 mp_primitive (mp, "filenametemplate", mp_message_command, filename_template_code);
32533 @:filename_template_}{\&{filenametemplate} primitive@>
32534
32535
32536 @ @<Cases of |print_cmd...@>=
32537 case mp_message_command:
32538 if (m < err_message_code)
32539 mp_print (mp, "message");
32540 else if (m == err_message_code)
32541 mp_print (mp, "errmessage");
32542 else if (m == filename_template_code)
32543 mp_print (mp, "filenametemplate");
32544 else
32545 mp_print (mp, "errhelp");
32546 break;
32547
32548 @ @<Declare action procedures for use by |do_statement|@>=
32549 @<Declare a procedure called |no_string_err|@>
32550 static void mp_do_message (MP mp);
32551
32552 @ @c
32553 void mp_do_message (MP mp) {
32554 mpinteger64 m; /* the type of message */
32555 mp_value new_expr;
32556 m = cur_mod();
32557 memset(&new_expr,0,sizeof(mp_value));
32558 new_number(new_expr.data.n);
32559 mp_get_x_next (mp);
32560 mp_scan_expression (mp);
32561 if (mp->cur_exp.type != mp_string_type)
32562 mp_no_string_err (mp, "A message should be a known string expression.");
32563 else {
32564 switch (m) {
32565 case message_code:
32566 mp_print_nl (mp, "");
32567 mp_print_str (mp, cur_exp_str ());
32568 break;
32569 case err_message_code:
32570 @<Print string |cur_exp| as an error message@>;
32571 break;
32572 case err_help_code:
32573 @<Save string |cur_exp| as the |err_help|@>;
32574 break;
32575 case filename_template_code:
32576 @<Save the filename template@>;
32577 break;
32578 } /* there are no other cases */
32579 }
32580 set_number_to_zero (new_expr.data.n);
32581 mp_flush_cur_exp (mp, new_expr);
32582 }
32583
32584
32585 @ @<Save the filename template@>=
32586 {
32587 delete_str_ref (internal_string (mp_output_template));
32588 if (cur_exp_str ()->len == 0) {
32589 set_internal_string (mp_output_template, mp_rts (mp, "%j.%c"));
32590 } else {
32591 set_internal_string (mp_output_template, cur_exp_str ());
32592 add_str_ref (internal_string (mp_output_template));
32593 }
32594 }
32595
32596
32597 @ @<Declare a procedure called |no_string_err|@>=
32598 static void mp_no_string_err (MP mp, const char *s) {
32599 const char *hlp[] = {s, NULL};
32600 mp_disp_err(mp, NULL);
32601 mp_back_error (mp, "Not a string", hlp, true);
32602 @.Not a string@>
32603 mp_get_x_next (mp);
32604 }
32605
32606
32607 @ The global variable |err_help| is zero when the user has most recently
32608 given an empty help string, or if none has ever been given.
32609
32610 @<Save string |cur_exp| as the |err_help|@>=
32611 {
32612 if (mp->err_help != NULL)
32613 delete_str_ref (mp->err_help);
32614 if (cur_exp_str ()->len == 0)
32615 mp->err_help = NULL;
32616 else {
32617 mp->err_help = cur_exp_str ();
32618 add_str_ref (mp->err_help);
32619 }
32620 }
32621
32622
32623 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
32624 \&{errhelp}, we don't want to give a long help message each time. So we
32625 give a verbose explanation only once.
32626
32627 @<Glob...@>=
32628 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
32629
32630 @ @<Set init...@>=
32631 mp->long_help_seen = false;
32632
32633 @ @<Print string |cur_exp| as an error message@>=
32634 {
32635 char msg[256];
32636 mp_snprintf(msg, 256, "%s", mp_str(mp, cur_exp_str ()));
32637 if (mp->err_help != NULL) {
32638 mp->use_err_help = true;
32639 mp_back_error (mp, msg, NULL, true);
32640 } else if (mp->long_help_seen) {
32641 const char *hlp[] = { "(That was another `errmessage'.)", NULL };
32642 mp_back_error (mp, msg, hlp, true);
32643 } else {
32644 const char *hlp[] = {
32645 "This error message was generated by an `errmessage'",
32646 "command, so I can\'t give any explicit help.",
32647 "Pretend that you're Miss Marple: Examine all clues,",
32648 "and deduce the truth by inspired guesses.",
32649 NULL };
32650 @^Marple, Jane@>
32651 if (mp->interaction < mp_error_stop_mode)
32652 mp->long_help_seen = true;
32653 mp_back_error (mp, msg, hlp, true);
32654 }
32655 mp_get_x_next (mp);
32656 mp->use_err_help = false;
32657 }
32658
32659
32660 @ @<Declare action procedures for use by |do_statement|@>=
32661 static void mp_do_write (MP mp);
32662
32663 @ @c
32664 void mp_do_write (MP mp) {
32665 mp_string t; /* the line of text to be written */
32666 write_index n, n0; /* for searching |wr_fname| and |wr_file| arrays */
32667 unsigned old_setting; /* for saving |selector| during output */
32668 mp_value new_expr;
32669 memset(&new_expr,0,sizeof(mp_value));
32670 new_number(new_expr.data.n);
32671 mp_get_x_next (mp);
32672 mp_scan_expression (mp);
32673 if (mp->cur_exp.type != mp_string_type) {
32674 mp_no_string_err (mp,
32675 "The text to be written should be a known string expression");
32676 } else if (cur_cmd() != mp_to_token) {
32677 const char *hlp[] = { "A write command should end with `to <filename>'", NULL };
32678 mp_back_error (mp, "Missing `to' clause", hlp, true);
32679 mp_get_x_next (mp);
32680 } else {
32681 t = cur_exp_str ();
32682 mp->cur_exp.type = mp_vacuous;
32683 mp_get_x_next (mp);
32684 mp_scan_expression (mp);
32685 if (mp->cur_exp.type != mp_string_type)
32686 mp_no_string_err (mp,
32687 "I can\'t write to that file name. It isn't a known string");
32688 else {
32689 @<Write |t| to the file named by |cur_exp|@>;
32690 }
32691 /* |delete_str_ref(t);| *//* TODO: is this right? */
32692 }
32693 set_number_to_zero (new_expr.data.n);
32694 mp_flush_cur_exp (mp, new_expr);
32695 }
32696
32697
32698 @ @<Write |t| to the file named by |cur_exp|@>=
32699 {
32700 @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
32701 |cur_exp| must be inserted@>;
32702 if (mp_str_vs_str (mp, t, mp->eof_line) == 0)
32703 @<Record the end of file on |wr_file[n]|@>@;
32704 else {
32705 old_setting = mp->selector;
32706 mp->selector = n + write_file;
32707 mp_print_str (mp, t);
32708 mp_print_ln (mp);
32709 mp->selector = old_setting;
32710 }
32711 }
32712
32713
32714 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
32715 {
32716 char *fn = mp_str (mp, cur_exp_str ());
32717 n = mp->write_files;
32718 n0 = mp->write_files;
32719 while (mp_xstrcmp (fn, mp->wr_fname[n]) != 0) {
32720 if (n == 0) { /* bottom reached */
32721 if (n0 == mp->write_files) {
32722 if (mp->write_files < mp->max_write_files) {
32723 incr (mp->write_files);
32724 } else {
32725 void **wr_file;
32726 char **wr_fname;
32727 write_index l, k;
32728 l = mp->max_write_files + (mp->max_write_files / 4);
32729 wr_file = xmalloc ((l + 1), sizeof (void *));
32730 wr_fname = xmalloc ((l + 1), sizeof (char *));
32731 for (k = 0; k <= l; k++) {
32732 if (k <= mp->max_write_files) {
32733 wr_file[k] = mp->wr_file[k];
32734 wr_fname[k] = mp->wr_fname[k];
32735 } else {
32736 wr_file[k] = 0;
32737 wr_fname[k] = NULL;
32738 }
32739 }
32740 xfree (mp->wr_file);
32741 xfree (mp->wr_fname);
32742 mp->max_write_files = l;
32743 mp->wr_file = wr_file;
32744 mp->wr_fname = wr_fname;
32745 }
32746 }
32747 n = n0;
32748 mp_open_write_file (mp, fn, n);
32749 } else {
32750 decr (n);
32751 if (mp->wr_fname[n] == NULL)
32752 n0 = n;
32753 }
32754 }
32755 }
32756
32757
32758 @ @<Record the end of file on |wr_file[n]|@>=
32759 {
32760 (mp->close_file) (mp, mp->wr_file[n]);
32761 xfree (mp->wr_fname[n]);
32762 if (n == mp->write_files - 1)
32763 mp->write_files = n;
32764 }
32765
32766
32767 @* Writing font metric data.
32768 \TeX\ gets its knowledge about fonts from font metric files, also called
32769 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
32770 but other programs know about them too. One of \MP's duties is to
32771 write \.{TFM} files so that the user's fonts can readily be
32772 applied to typesetting.
32773 @:TFM files}{\.{TFM} files@>
32774 @^font metric files@>
32775
32776 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
32777 Since the number of bytes is always a multiple of~4, we could
32778 also regard the file as a sequence of 32-bit words, but \MP\ uses the
32779 byte interpretation. The format of \.{TFM} files was designed by
32780 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
32781 @^Ramshaw, Lyle Harold@>
32782 of information in a compact but useful form.
32783
32784 @<Glob...@>=
32785 void *tfm_file; /* the font metric output goes here */
32786 char *metric_file_name; /* full name of the font metric file */
32787
32788 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
32789 integers that give the lengths of the various subsequent portions
32790 of the file. These twelve integers are, in order:
32791 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
32792 |lf|&length of the entire file, in words;\cr
32793 |lh|&length of the header data, in words;\cr
32794 |bc|&smallest character code in the font;\cr
32795 |ec|&largest character code in the font;\cr
32796 |nw|&number of words in the width table;\cr
32797 |nh|&number of words in the height table;\cr
32798 |nd|&number of words in the depth table;\cr
32799 |ni|&number of words in the italic correction table;\cr
32800 |nl|&number of words in the lig/kern table;\cr
32801 |nk|&number of words in the kern table;\cr
32802 |ne|&number of words in the extensible character table;\cr
32803 |np|&number of font parameter words.\cr}}$$
32804 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
32805 |ne<=256|, and
32806 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
32807 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
32808 and as few as 0 characters (if |bc=ec+1|).
32809
32810 Incidentally, when two or more 8-bit bytes are combined to form an integer of
32811 16 or more bits, the most significant bytes appear first in the file.
32812 This is called BigEndian order.
32813 @^BigEndian order@>
32814
32815 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
32816 arrays.
32817
32818 The most important data type used here is a |fix_word|, which is
32819 a 32-bit representation of a binary fraction. A |fix_word| is a signed
32820 quantity, with the two's complement of the entire word used to represent
32821 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
32822 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
32823 the smallest is $-2048$. We will see below, however, that all but two of
32824 the |fix_word| values must lie between $-16$ and $+16$.
32825
32826 @ The first data array is a block of header information, which contains
32827 general facts about the font. The header must contain at least two words,
32828 |header[0]| and |header[1]|, whose meaning is explained below. Additional
32829 header information of use to other software routines might also be
32830 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
32831 For example, 16 more words of header information are in use at the Xerox
32832 Palo Alto Research Center; the first ten specify the character coding
32833 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
32834 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
32835 last gives the ``face byte.''
32836
32837 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
32838 the \.{GF} output file. This helps ensure consistency between files,
32839 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
32840 should match the check sums on actual fonts that are used. The actual
32841 relation between this check sum and the rest of the \.{TFM} file is not
32842 important; the check sum is simply an identification number with the
32843 property that incompatible fonts almost always have distinct check sums.
32844 @^check sum@>
32845
32846 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
32847 font, in units of \TeX\ points. This number must be at least 1.0; it is
32848 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
32849 font, i.e., a font that was designed to look best at a 10-point size,
32850 whatever that really means. When a \TeX\ user asks for a font `\.{at}
32851 $\delta$ \.{pt}', the effect is to override the design size and replace it
32852 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
32853 the font image by a factor of $\delta$ divided by the design size. {\sl
32854 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
32855 numbers in design-size units.} Thus, for example, the value of |param[6]|,
32856 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
32857 since many fonts have a design size equal to one em. The other dimensions
32858 must be less than 16 design-size units in absolute value; thus,
32859 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
32860 \.{TFM} file whose first byte might be something besides 0 or 255.
32861 @^design size@>
32862
32863 @ Next comes the |char_info| array, which contains one |char_info_word|
32864 per character. Each word in this part of the file contains six fields
32865 packed into four bytes as follows.
32866
32867 \yskip\hang first byte: |width_index| (8 bits)\par
32868 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
32869 (4~bits)\par
32870 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
32871 (2~bits)\par
32872 \hang fourth byte: |remainder| (8 bits)\par
32873 \yskip\noindent
32874 The actual width of a character is \\{width}|[width_index]|, in design-size
32875 units; this is a device for compressing information, since many characters
32876 have the same width. Since it is quite common for many characters
32877 to have the same height, depth, or italic correction, the \.{TFM} format
32878 imposes a limit of 16 different heights, 16 different depths, and
32879 64 different italic corrections.
32880
32881 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
32882 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
32883 value of zero. The |width_index| should never be zero unless the
32884 character does not exist in the font, since a character is valid if and
32885 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
32886
32887 @ The |tag| field in a |char_info_word| has four values that explain how to
32888 interpret the |remainder| field.
32889
32890 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
32891 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
32892 program starting at location |remainder| in the |lig_kern| array.\par
32893 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
32894 characters of ascending sizes, and not the largest in the chain. The
32895 |remainder| field gives the character code of the next larger character.\par
32896 \hang|tag=3| (|ext_tag|) means that this character code represents an
32897 extensible character, i.e., a character that is built up of smaller pieces
32898 so that it can be made arbitrarily large. The pieces are specified in
32899 |exten[remainder]|.\par
32900 \yskip\noindent
32901 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
32902 unless they are used in special circumstances in math formulas. For example,
32903 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
32904 operation looks for both |list_tag| and |ext_tag|.
32905
32906 @d no_tag 0 /* vanilla character */
32907 @d lig_tag 1 /* character has a ligature/kerning program */
32908 @d list_tag 2 /* character has a successor in a charlist */
32909 @d ext_tag 3 /* character is extensible */
32910
32911 @ The |lig_kern| array contains instructions in a simple programming language
32912 that explains what to do for special letter pairs. Each word in this array is a
32913 |lig_kern_command| of four bytes.
32914
32915 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
32916 step if the byte is 128 or more, otherwise the next step is obtained by
32917 skipping this number of intervening steps.\par
32918 \hang second byte: |next_char|, ``if |next_char| follows the current character,
32919 then perform the operation and stop, otherwise continue.''\par
32920 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
32921 a kern step otherwise.\par
32922 \hang fourth byte: |remainder|.\par
32923 \yskip\noindent
32924 In a kern step, an
32925 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
32926 between the current character and |next_char|. This amount is
32927 often negative, so that the characters are brought closer together
32928 by kerning; but it might be positive.
32929
32930 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
32931 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
32932 |remainder| is inserted between the current character and |next_char|;
32933 then the current character is deleted if $b=0$, and |next_char| is
32934 deleted if $c=0$; then we pass over $a$~characters to reach the next
32935 current character (which may have a ligature/kerning program of its own).
32936
32937 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
32938 the |next_char| byte is the so-called right boundary character of this font;
32939 the value of |next_char| need not lie between |bc| and~|ec|.
32940 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
32941 there is a special ligature/kerning program for a left boundary character,
32942 beginning at location |256*op_byte+remainder|.
32943 The interpretation is that \TeX\ puts implicit boundary characters
32944 before and after each consecutive string of characters from the same font.
32945 These implicit characters do not appear in the output, but they can affect
32946 ligatures and kerning.
32947
32948 If the very first instruction of a character's |lig_kern| program has
32949 |skip_byte>128|, the program actually begins in location
32950 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
32951 arrays, because the first instruction must otherwise
32952 appear in a location |<=255|.
32953
32954 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
32955 the condition
32956 $$\hbox{|256*op_byte+remainder<nl|.}$$
32957 If such an instruction is encountered during
32958 normal program execution, it denotes an unconditional halt; no ligature
32959 command is performed.
32960
32961 @d stop_flag (128)
32962 /* value indicating `\.{STOP}' in a lig/kern program */
32963 @d kern_flag (128) /* op code for a kern step */
32964 @d skip_byte(A) mp->lig_kern[(A)].b0
32965 @d next_char(A) mp->lig_kern[(A)].b1
32966 @d op_byte(A) mp->lig_kern[(A)].b2
32967 @d rem_byte(A) mp->lig_kern[(A)].b3
32968
32969 @ Extensible characters are specified by an |extensible_recipe|, which
32970 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
32971 order). These bytes are the character codes of individual pieces used to
32972 build up a large symbol. If |top|, |mid|, or |bot| are zero, they are not
32973 present in the built-up result. For example, an extensible vertical line is
32974 like an extensible bracket, except that the top and bottom pieces are missing.
32975
32976 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
32977 if the piece isn't present. Then the extensible characters have the form
32978 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
32979 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
32980 The width of the extensible character is the width of $R$; and the
32981 height-plus-depth is the sum of the individual height-plus-depths of the
32982 components used, since the pieces are butted together in a vertical list.
32983
32984 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
32985 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
32986 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
32987 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
32988
32989 @ The final portion of a \.{TFM} file is the |param| array, which is another
32990 sequence of |fix_word| values.
32991
32992 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
32993 to help position accents. For example, |slant=.25| means that when you go
32994 up one unit, you also go .25 units to the right. The |slant| is a pure
32995 number; it is the only |fix_word| other than the design size itself that is
32996 not scaled by the design size.
32997 @^design size@>
32998
32999 \hang|param[2]=space| is the normal spacing between words in text.
33000 Note that character 040 in the font need not have anything to do with
33001 blank spaces.
33002
33003 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
33004
33005 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
33006
33007 \hang|param[5]=x_height| is the size of one ex in the font; it is also
33008 the height of letters for which accents don't have to be raised or lowered.
33009
33010 \hang|param[6]=quad| is the size of one em in the font.
33011
33012 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
33013 ends of sentences.
33014
33015 \yskip\noindent
33016 If fewer than seven parameters are present, \TeX\ sets the missing parameters
33017 to zero.
33018
33019 @d slant_code 1
33020 @d space_code 2
33021 @d space_stretch_code 3
33022 @d space_shrink_code 4
33023 @d x_height_code 5
33024 @d quad_code 6
33025 @d extra_space_code 7
33026
33027 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
33028 information, and it does this all at once at the end of a job.
33029 In order to prepare for such frenetic activity, it squirrels away the
33030 necessary facts in various arrays as information becomes available.
33031
33032 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
33033 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
33034 |tfm_ital_corr|. Other information about a character (e.g., about
33035 its ligatures or successors) is accessible via the |char_tag| and
33036 |char_remainder| arrays. Other information about the font as a whole
33037 is kept in additional arrays called |header_byte|, |lig_kern|,
33038 |kern|, |exten|, and |param|.
33039
33040 @d max_tfm_int 32510
33041 @d undefined_label max_tfm_int /* an undefined local label */
33042
33043 @<Glob...@>=
33044 #define TFM_ITEMS 257
33045 eight_bits bc;
33046 eight_bits ec; /* smallest and largest character codes shipped out */
33047 mp_node tfm_width[TFM_ITEMS]; /* \&{charwd} values */
33048 mp_node tfm_height[TFM_ITEMS]; /* \&{charht} values */
33049 mp_node tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
33050 mp_node tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
33051 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
33052 int char_tag[TFM_ITEMS]; /* |remainder| category */
33053 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
33054 char *header_byte; /* bytes of the \.{TFM} header */
33055 int header_last; /* last initialized \.{TFM} header byte */
33056 int header_size; /* size of the \.{TFM} header */
33057 four_quarters *lig_kern; /* the ligature/kern table */
33058 short nl; /* the number of ligature/kern steps so far */
33059 mp_number *kern; /* distinct kerning amounts */
33060 short nk; /* the number of distinct kerns so far */
33061 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
33062 short ne; /* the number of extensible characters so far */
33063 mp_number *param; /* \&{fontinfo} parameters */
33064 short np; /* the largest \&{fontinfo} parameter specified so far */
33065 short nw;
33066 short nh;
33067 short nd;
33068 short ni; /* sizes of \.{TFM} subtables */
33069 short skip_table[TFM_ITEMS]; /* local label status */
33070 boolean lk_started; /* has there been a lig/kern step in this command yet? */
33071 mpinteger64 bchar; /* right boundary character */
33072 short bch_label; /* left boundary starting location */
33073 short ll;
33074 short lll; /* registers used for lig/kern processing */
33075 short label_loc[257]; /* lig/kern starting addresses */
33076 eight_bits label_char[257]; /* characters for |label_loc| */
33077 short label_ptr; /* highest position occupied in |label_loc| */
33078
33079 @ @<Allocate or initialize ...@>=
33080 mp->header_last = 7;
33081 mp->header_size = 128; /* just for init */
33082 mp->header_byte = xmalloc (mp->header_size, sizeof (char));
33083
33084 @ @<Dealloc variables@>=
33085 xfree (mp->header_byte);
33086 xfree (mp->lig_kern);
33087 if (mp->kern) {
33088 int i;
33089 for (i=0;i<(max_tfm_int + 1);i++) {
33090 free_number(mp->kern[i]);
33091 }
33092 xfree (mp->kern);
33093 }
33094 if (mp->param) {
33095 int i;
33096 for (i=0;i<(max_tfm_int + 1);i++) {
33097 free_number(mp->param[i]);
33098 }
33099 xfree (mp->param);
33100 }
33101
33102 @ @<Set init...@>=
33103 for (k = 0; k <= 255; k++) {
33104 mp->tfm_width[k] = 0;
33105 mp->tfm_height[k] = 0;
33106 mp->tfm_depth[k] = 0;
33107 mp->tfm_ital_corr[k] = 0;
33108 mp->char_exists[k] = false;
33109 mp->char_tag[k] = no_tag;
33110 mp->char_remainder[k] = 0;
33111 mp->skip_table[k] = undefined_label;
33112 }
33113 memset (mp->header_byte, 0, (size_t) mp->header_size);
33114 mp->bc = 255;
33115 mp->ec = 0;
33116 mp->nl = 0;
33117 mp->nk = 0;
33118 mp->ne = 0;
33119 mp->np = 0;
33120 set_internal_from_number (mp_boundary_char, unity_t);
33121 number_negate (internal_value (mp_boundary_char));
33122 mp->bch_label = undefined_label;
33123 mp->label_loc[0] = -1;
33124 mp->label_ptr = 0;
33125
33126 @ @<Declarations@>=
33127 static mp_node mp_tfm_check (MP mp, quarterword m);
33128
33129 @ @c
33130 static mp_node mp_tfm_check (MP mp, quarterword m) {
33131 mp_number absm;
33132 mp_node p = mp_get_value_node (mp);
33133 new_number (absm);
33134 number_clone (absm, internal_value (m));
33135 number_abs (absm);
33136 if (number_greaterequal (absm, fraction_half_t)) {
33137 char msg[256];
33138 const char *hlp[] = {
33139 "Font metric dimensions must be less than 2048pt.",
33140 NULL } ;
33141 mp_snprintf (msg, 256, "Enormous %s has been reduced", internal_name (m));
33142 @.Enormous charwd...@>
33143 @.Enormous chardp...@>
33144 @.Enormous charht...@>
33145 @.Enormous charic...@>
33146 @.Enormous designsize...@>
33147 mp_back_error (mp, msg, hlp, true);
33148 mp_get_x_next (mp);
33149 if (number_positive (internal_value (m))) {
33150 set_value_number (p, fraction_half_t);
33151 number_add_scaled (value_number (p), -1);
33152 } else {
33153 set_value_number (p, fraction_half_t);
33154 number_negate (value_number (p));
33155 number_add_scaled (value_number (p), 1);
33156 }
33157 } else {
33158 set_value_number (p, internal_value (m));
33159 }
33160 free_number (absm);
33161 return p;
33162 }
33163
33164 @ @<Store the width information for character code~|c|@>=
33165 if (c < mp->bc)
33166 mp->bc = (eight_bits) c;
33167 if (c > mp->ec)
33168 mp->ec = (eight_bits) c;
33169 mp->char_exists[c] = true;
33170 mp_free_value_node (mp, mp->tfm_width[c]);
33171 mp->tfm_width[c] = mp_tfm_check (mp, mp_char_wd);
33172 mp_free_value_node (mp, mp->tfm_height[c]);
33173 mp->tfm_height[c] = mp_tfm_check (mp, mp_char_ht);
33174 mp_free_value_node (mp, mp->tfm_depth[c]);
33175 mp->tfm_depth[c] = mp_tfm_check (mp, mp_char_dp);
33176 mp_free_value_node (mp, mp->tfm_ital_corr[c]);
33177 mp->tfm_ital_corr[c] = mp_tfm_check (mp, mp_char_ic)@;
33178
33179
33180 @ Now let's consider \MP's special \.{TFM}-oriented commands.
33181
33182
33183 @
33184 @d char_list_code 0
33185 @d lig_table_code 1
33186 @d extensible_code 2
33187 @d header_byte_code 3
33188 @d font_dimen_code 4
33189
33190 @<Put each...@>=
33191 mp_primitive (mp, "charlist", mp_tfm_command, char_list_code);
33192 @:char_list_}{\&{charlist} primitive@>
33193 mp_primitive (mp, "ligtable", mp_tfm_command, lig_table_code);
33194 @:lig_table_}{\&{ligtable} primitive@>
33195 mp_primitive (mp, "extensible", mp_tfm_command, extensible_code);
33196 @:extensible_}{\&{extensible} primitive@>
33197 mp_primitive (mp, "headerbyte", mp_tfm_command, header_byte_code);
33198 @:header_byte_}{\&{headerbyte} primitive@>
33199 mp_primitive (mp, "fontdimen", mp_tfm_command, font_dimen_code);
33200 @:font_dimen_}{\&{fontdimen} primitive@>
33201
33202
33203 @ @<Cases of |print_cmd...@>=
33204 case mp_tfm_command:
33205 switch (m) {
33206 case char_list_code:
33207 mp_print (mp, "charlist");
33208 break;
33209 case lig_table_code:
33210 mp_print (mp, "ligtable");
33211 break;
33212 case extensible_code:
33213 mp_print (mp, "extensible");
33214 break;
33215 case header_byte_code:
33216 mp_print (mp, "headerbyte");
33217 break;
33218 default:
33219 mp_print (mp, "fontdimen");
33220 break;
33221 }
33222 break;
33223
33224 @ @<Declare action procedures for use by |do_statement|@>=
33225 static eight_bits mp_get_code (MP mp);
33226
33227 @ @c
33228 eight_bits mp_get_code (MP mp) { /* scans a character code value */
33229 mpinteger64 c; /* the code value found */
33230 mp_value new_expr;
33231 const char *hlp[] = {
33232 "I was looking for a number between 0 and 255, or for a",
33233 "string of length 1. Didn't find it; will use 0 instead.",
33234 NULL };
33235 memset(&new_expr,0,sizeof(mp_value));
33236 new_number(new_expr.data.n);
33237 mp_get_x_next (mp);
33238 mp_scan_expression (mp);
33239 if (mp->cur_exp.type == mp_known) {
33240 c = round_unscaled (cur_exp_value_number ());
33241 if (c >= 0)
33242 if (c < 256)
33243 return (eight_bits) c;
33244 } else if (mp->cur_exp.type == mp_string_type) {
33245 if (cur_exp_str ()->len == 1) {
33246 c = (integer) (*(cur_exp_str ()->str));
33247 return (eight_bits) c;
33248 }
33249 }
33250 mp_disp_err(mp, NULL);
33251 set_number_to_zero (new_expr.data.n);
33252 mp_back_error (mp, "Invalid code has been replaced by 0", hlp, true);
33253 @.Invalid code...@>
33254 mp_get_x_next (mp);
33255 mp_flush_cur_exp (mp, new_expr);
33256 c = 0;
33257 return (eight_bits) c;
33258 }
33259
33260
33261 @ @<Declare action procedures for use by |do_statement|@>=
33262 static void mp_set_tag (MP mp, halfword c, quarterword t, halfword r);
33263
33264 @ @c
33265 void mp_set_tag (MP mp, halfword c, quarterword t, halfword r) {
33266 if (mp->char_tag[c] == no_tag) {
33267 mp->char_tag[c] = t;
33268 mp->char_remainder[c] = r;
33269 if (t == lig_tag) {
33270 mp->label_ptr++;
33271 mp->label_loc[mp->label_ptr] = (short) r;
33272 mp->label_char[mp->label_ptr] = (eight_bits) c;
33273 }
33274 } else
33275 @<Complain about a character tag conflict@>@;
33276 }
33277
33278
33279 @ @<Complain about a character tag conflict@>=
33280 {
33281 const char *xtra = NULL;
33282 char msg[256];
33283 const char *hlp[] = {
33284 "It's not legal to label a character more than once.",
33285 "So I'll not change anything just now.",
33286 NULL };
33287 switch (mp->char_tag[c]) {
33288 case lig_tag: xtra = "in a ligtable"; break;
33289 case list_tag: xtra = "in a charlist"; break;
33290 case ext_tag: xtra = "extensible"; break;
33291 default: xtra = ""; break;
33292 }
33293 if ((c > ' ') && (c < 127)) {
33294 mp_snprintf(msg, 256, "Character %c is already %s", xord(c), xtra);
33295 } else if (c == 256) {
33296 mp_snprintf(msg, 256, "Character || is already %s", xtra);
33297 } else {
33298 mp_snprintf(msg, 256, "Character code %d is already %s", c, xtra);
33299 }
33300 @.Character c is already...@>
33301 mp_back_error (mp, msg, hlp, true);
33302 mp_get_x_next (mp);
33303 }
33304
33305
33306 @ @<Declare action procedures for use by |do_statement|@>=
33307 static void mp_do_tfm_command (MP mp);
33308
33309 @ @c
33310 void mp_do_tfm_command (MP mp) {
33311 mpinteger64 c, cc; /* character codes */
33312 int k; /* index into the |kern| array */
33313 int j; /* index into |header_byte| or |param| */
33314 mp_value new_expr;
33315 memset(&new_expr,0,sizeof(mp_value));
33316 new_number(new_expr.data.n);
33317 switch (cur_mod()) {
33318 case char_list_code:
33319 c = mp_get_code (mp);
33320 /* we will store a list of character successors */
33321 while (cur_cmd() == mp_colon) {
33322 cc = mp_get_code (mp);
33323 mp_set_tag (mp, c, list_tag, cc);
33324 c = cc;
33325 }
33326 break;
33327 case lig_table_code:
33328 if (mp->lig_kern == NULL)
33329 mp->lig_kern = xmalloc ((max_tfm_int + 1), sizeof (four_quarters));
33330 if (mp->kern == NULL) {
33331 int i;
33332 mp->kern = xmalloc ((max_tfm_int + 1), sizeof (mp_number));
33333 for (i=0;i<(max_tfm_int + 1);i++)
33334 new_number (mp->kern[i]);
33335 }
33336 @<Store a list of ligature/kern steps@>;
33337 break;
33338 case extensible_code:
33339 @<Define an extensible recipe@>;
33340 break;
33341 case header_byte_code:
33342 case font_dimen_code:
33343 c = cur_mod();
33344 mp_get_x_next (mp);
33345 mp_scan_expression (mp);
33346 if ((mp->cur_exp.type != mp_known) || number_less(cur_exp_value_number (), half_unit_t)) {
33347 const char *hlp[] = {
33348 "I was looking for a known, positive number.",
33349 "For safety's sake I'll ignore the present command.",
33350 NULL };
33351 mp_disp_err(mp, NULL);
33352 mp_back_error (mp, "Improper location", hlp, true);
33353 @.Improper location@>
33354 mp_get_x_next (mp);
33355 } else {
33356 j = round_unscaled (cur_exp_value_number ());
33357 if (cur_cmd() != mp_colon) {
33358 const char *hlp[] = {
33359 "A colon should follow a headerbyte or fontinfo location.",
33360 NULL };
33361 mp_back_error (mp, "Missing `:' has been inserted", hlp, true);
33362 @.Missing `:'@>
33363 }
33364 if (c == header_byte_code)
33365 @<Store a list of header bytes@>@;
33366 else {
33367 if (mp->param == NULL) {
33368 int i;
33369 mp->param = xmalloc ((max_tfm_int + 1), sizeof (mp_number));
33370 for (i=0;i<(max_tfm_int + 1);i++)
33371 new_number (mp->param[i]);
33372 }
33373 @<Store a list of font dimensions@>;
33374 }
33375 }
33376 break;
33377 } /* there are no other cases */
33378 }
33379
33380
33381 @ @<Store a list of ligature/kern steps@>=
33382 {
33383 mp->lk_started = false;
33384 CONTINUE:
33385 mp_get_x_next (mp);
33386 if ((cur_cmd() == mp_skip_to) && mp->lk_started)
33387 @<Process a |skip_to| command and |goto done|@>;
33388 if (cur_cmd() == mp_bchar_label) {
33389 c = 256;
33390 set_cur_cmd((mp_variable_type)mp_colon);
33391 } else {
33392 mp_back_input (mp);
33393 c = mp_get_code (mp);
33394 }
33395 if ((cur_cmd() == mp_colon) || (cur_cmd() == mp_double_colon))
33396 @<Record a label in a lig/kern subprogram and |goto continue|@>@;
33397 if (cur_cmd() == mp_lig_kern_token)
33398 @<Compile a ligature/kern command@>@;
33399 else {
33400 const char *hlp[] = { "I was looking for `=:' or `kern' here.", NULL };
33401 mp_back_error (mp, "Illegal ligtable step", hlp, true);
33402 @.Illegal ligtable step@>
33403 next_char (mp->nl) = qi (0);
33404 op_byte (mp->nl) = qi (0);
33405 rem_byte (mp->nl) = qi (0);
33406 skip_byte (mp->nl) = stop_flag + 1; /* this specifies an unconditional stop */
33407 }
33408 if (mp->nl == max_tfm_int)
33409 mp_fatal_error (mp, "ligtable too large");
33410 mp->nl++;
33411 if (cur_cmd() == mp_comma)
33412 goto CONTINUE;
33413 if (skip_byte (mp->nl - 1) < stop_flag)
33414 skip_byte (mp->nl - 1) = stop_flag;
33415 }
33416 DONE:
33417
33418 @ @<Put each...@>=
33419 mp_primitive (mp, "=:", mp_lig_kern_token, 0);
33420 @:=:_}{\.{=:} primitive@>
33421 mp_primitive (mp, "=:|", mp_lig_kern_token, 1);
33422 @:=:/_}{\.{=:\char'174} primitive@>
33423 mp_primitive (mp, "=:|>", mp_lig_kern_token, 5);
33424 @:=:/>_}{\.{=:\char'174>} primitive@>
33425 mp_primitive (mp, "|=:", mp_lig_kern_token, 2);
33426 @:=:/_}{\.{\char'174=:} primitive@>
33427 mp_primitive (mp, "|=:>", mp_lig_kern_token, 6);
33428 @:=:/>_}{\.{\char'174=:>} primitive@>
33429 mp_primitive (mp, "|=:|", mp_lig_kern_token, 3);
33430 @:=:/_}{\.{\char'174=:\char'174} primitive@>
33431 mp_primitive (mp, "|=:|>", mp_lig_kern_token, 7);
33432 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
33433 mp_primitive (mp, "|=:|>>", mp_lig_kern_token, 11);
33434 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
33435 mp_primitive (mp, "kern", mp_lig_kern_token, mp_kern_flag);
33436 @:kern_}{\&{kern} primitive@>
33437
33438
33439 @ @<Cases of |print_cmd...@>=
33440 case mp_lig_kern_token:
33441 switch (m) {
33442 case 0:
33443 mp_print (mp, "=:");
33444 break;
33445 case 1:
33446 mp_print (mp, "=:|");
33447 break;
33448 case 2:
33449 mp_print (mp, "|=:");
33450 break;
33451 case 3:
33452 mp_print (mp, "|=:|");
33453 break;
33454 case 5:
33455 mp_print (mp, "=:|>");
33456 break;
33457 case 6:
33458 mp_print (mp, "|=:>");
33459 break;
33460 case 7:
33461 mp_print (mp, "|=:|>");
33462 break;
33463 case 11:
33464 mp_print (mp, "|=:|>>");
33465 break;
33466 default:
33467 mp_print (mp, "kern");
33468 break;
33469 }
33470 break;
33471
33472 @ Local labels are implemented by maintaining the |skip_table| array,
33473 where |skip_table[c]| is either |undefined_label| or the address of the
33474 most recent lig/kern instruction that skips to local label~|c|. In the
33475 latter case, the |skip_byte| in that instruction will (temporarily)
33476 be zero if there were no prior skips to this label, or it will be the
33477 distance to the prior skip.
33478
33479 We may need to cancel skips that span more than 127 lig/kern steps.
33480
33481 @d cancel_skips(A) mp->ll=(A);
33482 do {
33483 mp->lll=qo(skip_byte(mp->ll));
33484 skip_byte(mp->ll)=stop_flag; mp->ll=(short)(mp->ll-mp->lll);
33485 } while (mp->lll!=0)@;
33486
33487 @d skip_error(A) {
33488 const char *hlp[] = { "At most 127 lig/kern steps can separate skipto1 from 1::.", NULL};
33489 mp_error(mp, "Too far to skip", hlp, true);
33490 @.Too far to skip@>
33491 cancel_skips((A));
33492 }
33493
33494 @<Process a |skip_to| command and |goto done|@>=
33495 {
33496 c = mp_get_code (mp);
33497 if (mp->nl - mp->skip_table[c] > 128) {
33498 skip_error (mp->skip_table[c]);
33499 mp->skip_table[c] = (short) undefined_label;
33500 }
33501 if (mp->skip_table[c] == undefined_label)
33502 skip_byte (mp->nl - 1) = qi (0);
33503 else
33504 skip_byte (mp->nl - 1) = qi (mp->nl - mp->skip_table[c] - 1);
33505 mp->skip_table[c] = (short) (mp->nl - 1);
33506 goto DONE;
33507 }
33508
33509
33510 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
33511 {
33512 if (cur_cmd() == mp_colon) {
33513 if (c == 256)
33514 mp->bch_label = mp->nl;
33515 else
33516 mp_set_tag (mp, c, lig_tag, mp->nl);
33517 } else if (mp->skip_table[c] < undefined_label) {
33518 mp->ll = mp->skip_table[c];
33519 mp->skip_table[c] = undefined_label;
33520 do {
33521 mp->lll = qo (skip_byte (mp->ll));
33522 if (mp->nl - mp->ll > 128) {
33523 skip_error (mp->ll);
33524 goto CONTINUE;
33525 }
33526 skip_byte (mp->ll) = qi (mp->nl - mp->ll - 1);
33527 mp->ll = (short) (mp->ll - mp->lll);
33528 } while (mp->lll != 0);
33529 }
33530 goto CONTINUE;
33531 }
33532
33533
33534 @ @<Compile a ligature/kern...@>=
33535 {
33536 next_char (mp->nl) = qi (c);
33537 skip_byte (mp->nl) = qi (0);
33538 if (cur_mod() < 128) { /* ligature op */
33539 op_byte (mp->nl) = qi (cur_mod());
33540 rem_byte (mp->nl) = qi (mp_get_code (mp));
33541 } else {
33542 mp_get_x_next (mp);
33543 mp_scan_expression (mp);
33544 if (mp->cur_exp.type != mp_known) {
33545 const char *hlp[] = {
33546 "The amount of kern should be a known numeric value.",
33547 "I'm zeroing this one. Proceed, with fingers crossed.",
33548 NULL };
33549 mp_disp_err(mp, NULL);
33550 set_number_to_zero (new_expr.data.n);
33551 mp_back_error (mp, "Improper kern", hlp, true);
33552 @.Improper kern@>
33553 mp_get_x_next (mp);
33554 mp_flush_cur_exp (mp, new_expr);
33555 }
33556 number_clone (mp->kern[mp->nk], cur_exp_value_number ());
33557 k = 0;
33558 while (!number_equal (mp->kern[k], cur_exp_value_number ()))
33559 incr (k);
33560 if (k == mp->nk) {
33561 if (mp->nk == max_tfm_int)
33562 mp_fatal_error (mp, "too many TFM kerns");
33563 mp->nk++;
33564 }
33565 op_byte (mp->nl) = qi (kern_flag + (k / 256));
33566 rem_byte (mp->nl) = qi ((k % 256));
33567 }
33568 mp->lk_started = true;
33569 }
33570
33571
33572 @ @d missing_extensible_punctuation(A)
33573 {
33574 char msg[256];
33575 const char *hlp[] = { "I'm processing `extensible c: t,m,b,r'.", NULL };
33576 mp_snprintf(msg, 256, "Missing %s has been inserted", (A));
33577 mp_back_error(mp, msg, hlp, true);
33578 @.Missing `\char`\#'@>
33579 }
33580
33581 @<Define an extensible recipe@>=
33582 {
33583 if (mp->ne == 256)
33584 mp_fatal_error (mp, "too many extensible recipes");
33585 c = mp_get_code (mp);
33586 mp_set_tag (mp, c, ext_tag, mp->ne);
33587 if (cur_cmd() != mp_colon)
33588 missing_extensible_punctuation (":");
33589 ext_top (mp->ne) = qi (mp_get_code (mp));
33590 if (cur_cmd() != mp_comma)
33591 missing_extensible_punctuation (",");
33592 ext_mid (mp->ne) = qi (mp_get_code (mp));
33593 if (cur_cmd() != mp_comma)
33594 missing_extensible_punctuation (",");
33595 ext_bot (mp->ne) = qi (mp_get_code (mp));
33596 if (cur_cmd() != mp_comma)
33597 missing_extensible_punctuation (",");
33598 ext_rep (mp->ne) = qi (mp_get_code (mp));
33599 mp->ne++;
33600 }
33601
33602
33603 @ The header could contain ASCII zeroes, so can't use |strdup|.
33604 The index |j| can be beyond the index |header_last|, hence we
33605 have to sure to update the end of stream marker to reflect the
33606 actual position.
33607
33608 @<Store a list of header bytes@>=
33609 {
33610 j--;
33611 if (mp->header_last<j){
33612 mp->header_last=j;
33613 }
33614 do {
33615 if (j >= mp->header_size) {
33616 size_t l = (size_t) (mp->header_size + (mp->header_size / 4));
33617 char *t = xmalloc (l, 1);
33618 memset (t, 0, l);
33619 (void) memcpy (t, mp->header_byte, (size_t) mp->header_size);
33620 xfree (mp->header_byte);
33621 mp->header_byte = t;
33622 mp->header_size = (int) l;
33623 }
33624 mp->header_byte[j] = (char) mp_get_code (mp);
33625 if (mp->header_last<j){
33626 incr (mp->header_last);
33627 }
33628 incr (j);
33629 } while (cur_cmd() == mp_comma);
33630 }
33631
33632 @ @<Store a list of font dimensions@>=
33633 do {
33634 if (j > max_tfm_int)
33635 mp_fatal_error (mp, "too many fontdimens");
33636 while (j > mp->np) {
33637 mp->np++;
33638 set_number_to_zero(mp->param[mp->np]);
33639 }
33640 mp_get_x_next (mp);
33641 mp_scan_expression (mp);
33642 if (mp->cur_exp.type != mp_known) {
33643 const char *hlp[] = { "I'm zeroing this one. Proceed, with fingers crossed.", NULL };
33644 mp_disp_err(mp, NULL);
33645 set_number_to_zero (new_expr.data.n);
33646 mp_back_error (mp, "Improper font parameter", hlp, true);
33647 @.Improper font parameter@>
33648 mp_get_x_next (mp);
33649 mp_flush_cur_exp (mp, new_expr);
33650 }
33651 number_clone (mp->param[j], cur_exp_value_number ());
33652 incr (j);
33653 } while (cur_cmd() == mp_comma)@;
33654
33655 @ OK: We've stored all the data that is needed for the \.{TFM} file.
33656 All that remains is to output it in the correct format.
33657
33658 An interesting problem needs to be solved in this connection, because
33659 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
33660 and 64~italic corrections. If the data has more distinct values than
33661 this, we want to meet the necessary restrictions by perturbing the
33662 given values as little as possible.
33663
33664 \MP\ solves this problem in two steps. First the values of a given
33665 kind (widths, heights, depths, or italic corrections) are sorted;
33666 then the list of sorted values is perturbed, if necessary.
33667
33668 The sorting operation is facilitated by having a special node of
33669 essentially infinite |value| at the end of the current list.
33670
33671 @<Initialize table entries@>=
33672 mp->inf_val = mp_get_value_node (mp);
33673 set_value_number (mp->inf_val, fraction_four_t);
33674
33675 @ @<Free table entries@>=
33676 mp_free_value_node (mp, mp->inf_val);
33677
33678 @ Straight linear insertion is good enough for sorting, since the lists
33679 are usually not terribly long. As we work on the data, the current list
33680 will start at |mp_link(temp_head)| and end at |inf_val|; the nodes in this
33681 list will be in increasing order of their |value| fields.
33682
33683 Given such a list, the |sort_in| function takes a value and returns a pointer
33684 to where that value can be found in the list. The value is inserted in
33685 the proper place, if necessary.
33686
33687 At the time we need to do these operations, most of \MP's work has been
33688 completed, so we will have plenty of memory to play with. The value nodes
33689 that are allocated for sorting will never be returned to free storage.
33690
33691 @d clear_the_list mp_link(mp->temp_head)=mp->inf_val
33692
33693 @c
33694 static mp_node mp_sort_in (MP mp, mp_number v) {
33695 mp_node p, q, r; /* list manipulation registers */
33696 p = mp->temp_head;
33697 while (1) {
33698 q = mp_link (p);
33699 if (number_lessequal(v, value_number (q)))
33700 break;
33701 p = q;
33702 }
33703 if (number_less (v, value_number (q))) {
33704 r = mp_get_value_node (mp);
33705 set_value_number (r, v);
33706 mp_link (r) = q;
33707 mp_link (p) = r;
33708 }
33709 return mp_link (p);
33710 }
33711
33712
33713 @ Now we come to the interesting part, where we reduce the list if necessary
33714 until it has the required size. The |min_cover| routine is basic to this
33715 process; it computes the minimum number~|m| such that the values of the
33716 current sorted list can be covered by |m|~intervals of width~|d|. It
33717 also sets the global value |perturbation| to the smallest value $d'>d$
33718 such that the covering found by this algorithm would be different.
33719
33720 In particular, |min_cover(0)| returns the number of distinct values in the
33721 current list and sets |perturbation| to the minimum distance between
33722 adjacent values.
33723
33724 @c
33725 static integer mp_min_cover (MP mp, mp_number d) {
33726 mp_node p; /* runs through the current list */
33727 mp_number l; /* the least element covered by the current interval */
33728 mp_number test;
33729 integer m; /* lower bound on the size of the minimum cover */
33730 m = 0;
33731 new_number (l);
33732 new_number (test);
33733 p = mp_link (mp->temp_head);
33734 set_number_to_inf(mp->perturbation);
33735 while (p != mp->inf_val) {
33736 incr (m);
33737 number_clone (l, value_number (p));
33738 do {
33739 p = mp_link (p);
33740 set_number_from_addition(test, l, d);
33741 } while (number_lessequal(value_number (p), test));
33742
33743 set_number_from_substraction(test, value_number (p), l);
33744 if (number_less (test, mp->perturbation)) {
33745 number_clone (mp->perturbation, test);
33746 }
33747 }
33748 free_number (test);
33749 free_number (l);
33750 return m;
33751 }
33752
33753
33754 @ @<Glob...@>=
33755 mp_number perturbation; /* quantity related to \.{TFM} rounding */
33756 integer excess; /* the list is this much too long */
33757
33758 @ @<Initialize table...@>=
33759 new_number (mp->perturbation);
33760
33761 @ @<Dealloc...@>=
33762 free_number (mp->perturbation);
33763
33764 @ The smallest |d| such that a given list can be covered with |m| intervals
33765 is determined by the |threshold| routine, which is sort of an inverse
33766 to |min_cover|. The idea is to increase the interval size rapidly until
33767 finding the range, then to go sequentially until the exact borderline has
33768 been discovered.
33769
33770 @c
33771 static void mp_threshold (MP mp, mp_number *ret, integer m) {
33772 mp_number d, arg1; /* lower bound on the smallest interval size */
33773 new_number (d);
33774 new_number (arg1);
33775 mp->excess = mp_min_cover (mp, zero_t) - m;
33776 if (mp->excess <= 0) {
33777 number_clone (*ret, zero_t);
33778 } else {
33779 do {
33780 number_clone (d, mp->perturbation);
33781 set_number_from_addition(arg1, d, d);
33782 } while (mp_min_cover (mp, arg1) > m);
33783 while (mp_min_cover (mp, d) > m) {
33784 number_clone (d, mp->perturbation);
33785 }
33786 number_clone (*ret, d);
33787 }
33788 free_number (d);
33789 free_number (arg1);
33790 }
33791
33792
33793 @ The |skimp| procedure reduces the current list to at most |m| entries,
33794 by changing values if necessary. It also sets |indep_value(p):=k| if |value(p)|
33795 is the |k|th distinct value on the resulting list, and it sets
33796 |perturbation| to the maximum amount by which a |value| field has
33797 been changed. The size of the resulting list is returned as the
33798 value of |skimp|.
33799
33800 @c
33801 static integer mp_skimp (MP mp, integer m) {
33802 mp_number d; /* the size of intervals being coalesced */
33803 mp_node p, q, r; /* list manipulation registers */
33804 mp_number l; /* the least value in the current interval */
33805 mp_number v; /* a compromise value */
33806 mp_number l_d;
33807 new_number (d);
33808 mp_threshold (mp, &d, m);
33809 new_number (l);
33810 new_number (l_d);
33811 new_number (v);
33812 set_number_to_zero (mp->perturbation);
33813 q = mp->temp_head;
33814 m = 0;
33815 p = mp_link (mp->temp_head);
33816 while (p != mp->inf_val) {
33817 incr (m);
33818 number_clone (l, value_number (p));
33819 set_indep_value (p,m);
33820 set_number_from_addition (l_d, l, d);
33821 if (number_lessequal (value_number (mp_link (p)), l_d))
33822 @<Replace an interval of values by its midpoint@>@;
33823 q = p;
33824 p = mp_link (p);
33825 }
33826 free_number (l_d);
33827 free_number (d);
33828 free_number (l);
33829 free_number (v);
33830 return m;
33831 }
33832
33833
33834 @ @<Replace an interval...@>=
33835 {
33836 mp_number test;
33837 new_number (test);
33838 do {
33839 p = mp_link (p);
33840 set_indep_value (p, m);
33841 decr (mp->excess);
33842 if (mp->excess == 0) {
33843 number_clone (l_d, l);
33844 set_number_to_zero (d);
33845 }
33846 } while (number_lessequal(value_number (mp_link (p)), l_d));
33847 set_number_from_substraction (test, value_number (p), l);
33848 number_halfp(test);
33849 set_number_from_addition (v, l, test);
33850 set_number_from_substraction (test, value_number (p), v);
33851 if (number_greater (test, mp->perturbation))
33852 number_clone (mp->perturbation, test);
33853 r = q;
33854 do {
33855 r = mp_link (r);
33856 set_value_number (r, v);
33857 } while (r != p);
33858 mp_link (q) = p; /* remove duplicate values from the current list */
33859 free_number (test);
33860 }
33861
33862
33863 @ A warning message is issued whenever something is perturbed by
33864 more than 1/16\thinspace pt.
33865
33866 @c
33867 static void mp_tfm_warning (MP mp, quarterword m) {
33868 mp_print_nl (mp, "(some ");
33869 mp_print (mp, internal_name (m));
33870 @.some charwds...@>
33871 @.some chardps...@>
33872 @.some charhts...@>
33873 @.some charics...@>
33874 mp_print (mp, " values had to be adjusted by as much as ");
33875 print_number (mp->perturbation);
33876 mp_print (mp, "pt)");
33877 }
33878
33879
33880 @ Here's an example of how we use these routines.
33881 The width data needs to be perturbed only if there are 256 distinct
33882 widths, but \MP\ must check for this case even though it is
33883 highly unusual.
33884
33885 An integer variable |k| will be defined when we use this code.
33886 The |dimen_head| array will contain pointers to the sorted
33887 lists of dimensions.
33888
33889 @d tfm_warn_threshold_k ((math_data *)mp->math)->tfm_warn_threshold_t
33890
33891 @<Massage the \.{TFM} widths@>=
33892 clear_the_list;
33893 for (k = mp->bc; k <= mp->ec; k++) {
33894 if (mp->char_exists[k])
33895 mp->tfm_width[k] = mp_sort_in (mp, value_number (mp->tfm_width[k]));
33896 }
33897 mp->nw = (short) (mp_skimp (mp, 255) + 1);
33898 mp->dimen_head[1] = mp_link (mp->temp_head);
33899 if (number_greaterequal (mp->perturbation, tfm_warn_threshold_k))
33900 mp_tfm_warning (mp, mp_char_wd)
33901
33902
33903 @ @<Glob...@>=
33904 mp_node dimen_head[5]; /* lists of \.{TFM} dimensions */
33905
33906 @ Heights, depths, and italic corrections are different from widths
33907 not only because their list length is more severely restricted, but
33908 also because zero values do not need to be put into the lists.
33909
33910 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
33911 clear_the_list;
33912 for (k = mp->bc; k <= mp->ec; k++) {
33913 if (mp->char_exists[k]) {
33914 if (number_zero(value_number (mp->tfm_height[k])))
33915 mp->tfm_height[k] = mp->zero_val;
33916 else
33917 mp->tfm_height[k] = mp_sort_in (mp, value_number (mp->tfm_height[k]));
33918 }
33919 }
33920 mp->nh = (short) (mp_skimp (mp, 15) + 1);
33921 mp->dimen_head[2] = mp_link (mp->temp_head);
33922 if (number_greaterequal (mp->perturbation, tfm_warn_threshold_k))
33923 mp_tfm_warning (mp, mp_char_ht);
33924 clear_the_list;
33925 for (k = mp->bc; k <= mp->ec; k++) {
33926 if (mp->char_exists[k]) {
33927 if (number_zero(value_number (mp->tfm_depth[k])))
33928 mp->tfm_depth[k] = mp->zero_val;
33929 else
33930 mp->tfm_depth[k] = mp_sort_in (mp, value_number (mp->tfm_depth[k]));
33931 }
33932 }
33933 mp->nd = (short) (mp_skimp (mp, 15) + 1);
33934 mp->dimen_head[3] = mp_link (mp->temp_head);
33935 if (number_greaterequal (mp->perturbation, tfm_warn_threshold_k))
33936 mp_tfm_warning (mp, mp_char_dp);
33937 clear_the_list;
33938 for (k = mp->bc; k <= mp->ec; k++) {
33939 if (mp->char_exists[k]) {
33940 if (number_zero(value_number (mp->tfm_ital_corr[k])))
33941 mp->tfm_ital_corr[k] = mp->zero_val;
33942 else
33943 mp->tfm_ital_corr[k] = mp_sort_in (mp, value_number (mp->tfm_ital_corr[k]));
33944 }
33945 }
33946 mp->ni = (short) (mp_skimp (mp, 63) + 1);
33947 mp->dimen_head[4] = mp_link (mp->temp_head);
33948 if (number_greaterequal (mp->perturbation, tfm_warn_threshold_k))
33949 mp_tfm_warning (mp, mp_char_ic)
33950
33951
33952 @ @<Initialize table entries@>=
33953 mp->zero_val = mp_get_value_node (mp);
33954 set_value_number (mp->zero_val, zero_t);
33955
33956 @ @<Free table entries@>=
33957 mp_free_value_node (mp, mp->zero_val);
33958
33959 @ Bytes 5--8 of the header are set to the design size, unless the user has
33960 some crazy reason for specifying them differently.
33961 @^design size@>
33962
33963 Error messages are not allowed at the time this procedure is called,
33964 so a warning is printed instead.
33965
33966 The value of |max_tfm_dimen| is calculated so that
33967 $$\hbox{|make_scaled(16*max_tfm_dimen,internal_value(mp_design_size))|}
33968 < \\{three\_bytes}.$$
33969
33970 @d three_bytes 0100000000 /* $2^{24}$ */
33971
33972 @c
33973 static void mp_fix_design_size (MP mp) {
33974 mp_number d; /* the design size */
33975 new_number (d);
33976 number_clone (d, internal_value (mp_design_size));
33977 if (number_less(d, unity_t) || number_greaterequal(d, fraction_half_t)) {
33978 if (!number_zero (d))
33979 mp_print_nl (mp, "(illegal design size has been changed to 128pt)");
33980 @.illegal design size...@>
33981 set_number_from_scaled (d, 040000000);
33982 number_clone (internal_value (mp_design_size), d);
33983 }
33984 if (mp->header_byte[4] == 0 && mp->header_byte[5] == 0 &&
33985 mp->header_byte[6] == 0 && mp->header_byte[7] == 0) {
33986 mpinteger64 dd = number_to_scaled (d);
33987 mp->header_byte[4] = (char) (dd / 04000000);
33988 mp->header_byte[5] = (char) ((dd / 4096) % 256);
33989 mp->header_byte[6] = (char) ((dd / 16) % 256);
33990 mp->header_byte[7] = (char) ((dd % 16) * 16);
33991 }
33992 /* |mp->max_tfm_dimen = 16 * internal_value (mp_design_size) - 1 - internal_value (mp_design_size) / 010000000| */
33993 {
33994 mp_number secondpart;
33995 new_number (secondpart);
33996 number_clone (secondpart, internal_value (mp_design_size));
33997 number_clone (mp->max_tfm_dimen, secondpart);
33998 number_divide_int (secondpart, 010000000);
33999 number_multiply_int (mp->max_tfm_dimen, 16);
34000 number_add_scaled (mp->max_tfm_dimen, -1);
34001 number_substract (mp->max_tfm_dimen, secondpart);
34002 free_number (secondpart);
34003 }
34004 if (number_greaterequal (mp->max_tfm_dimen, fraction_half_t)) {
34005 number_clone (mp->max_tfm_dimen, fraction_half_t);
34006 number_add_scaled (mp->max_tfm_dimen, -1);
34007 }
34008 free_number (d);
34009 }
34010
34011
34012 @ The |dimen_out| procedure computes a |fix_word| relative to the
34013 design size. If the data was out of range, it is corrected and the
34014 global variable |tfm_changed| is increased by~one.
34015
34016 @c
34017 static integer mp_dimen_out (MP mp, mp_number x_orig) {
34018 integer ret;
34019 mp_number abs_x;
34020 mp_number x;
34021 new_number (abs_x);
34022 new_number (x);
34023 number_clone (x, x_orig);
34024 number_clone (abs_x, x_orig);
34025 number_abs (abs_x);
34026 if (number_greater (abs_x, mp->max_tfm_dimen)) {
34027 incr (mp->tfm_changed);
34028 if (number_positive(x))
34029 number_clone (x, mp->max_tfm_dimen);
34030 else {
34031 number_clone (x, mp->max_tfm_dimen);
34032 number_negate (x);
34033 }
34034 }
34035 {
34036 mp_number arg1;
34037 new_number (arg1);
34038 number_clone (arg1, x);
34039 number_multiply_int (arg1, 16);
34040 make_scaled (x, arg1, internal_value (mp_design_size));
34041 free_number (arg1);
34042 }
34043 free_number (abs_x);
34044 ret = number_to_scaled (x);
34045 free_number (x);
34046 return ret;
34047 }
34048
34049
34050 @ @<Glob...@>=
34051 mp_number max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
34052 integer tfm_changed; /* the number of data entries that were out of bounds */
34053
34054 @ @<Initialize table...@>=
34055 new_number (mp->max_tfm_dimen);
34056
34057 @ @<Dealloc...@>=
34058 free_number (mp->max_tfm_dimen);
34059
34060
34061 @ If the user has not specified any of the first four header bytes,
34062 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
34063 from the |tfm_width| data relative to the design size.
34064 @^check sum@>
34065
34066 @c
34067 static void mp_fix_check_sum (MP mp) {
34068 eight_bits k; /* runs through character codes */
34069 eight_bits B1, B2, B3, B4; /* bytes of the check sum */
34070 integer x; /* hash value used in check sum computation */
34071 if (mp->header_byte[0] == 0 && mp->header_byte[1] == 0 &&
34072 mp->header_byte[2] == 0 && mp->header_byte[3] == 0) {
34073 @<Compute a check sum in |(b1,b2,b3,b4)|@>;
34074 mp->header_byte[0] = (char) B1;
34075 mp->header_byte[1] = (char) B2;
34076 mp->header_byte[2] = (char) B3;
34077 mp->header_byte[3] = (char) B4;
34078 return;
34079 }
34080 }
34081
34082
34083 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
34084 B1 = mp->bc;
34085 B2 = mp->ec;
34086 B3 = mp->bc;
34087 B4 = mp->ec;
34088 mp->tfm_changed = 0;
34089 for (k = mp->bc; k <= mp->ec; k++) {
34090 if (mp->char_exists[k]) {
34091 x = mp_dimen_out (mp, value_number (mp->tfm_width[k])) + (k + 4) * 020000000; /* this is positive */
34092 B1 = (eight_bits) ((B1 + B1 + x) % 255);
34093 B2 = (eight_bits) ((B2 + B2 + x) % 253);
34094 B3 = (eight_bits) ((B3 + B3 + x) % 251);
34095 B4 = (eight_bits) ((B4 + B4 + x) % 247);
34096 }
34097 if (k == mp->ec)
34098 break;
34099 }
34100
34101
34102 @ Finally we're ready to actually write the \.{TFM} information.
34103 Here are some utility routines for this purpose.
34104
34105 @d tfm_out(A) do { /* output one byte to |tfm_file| */
34106 unsigned char s=(unsigned char)(A);
34107 (mp->write_binary_file)(mp,mp->tfm_file,(void *)&s,1);
34108 } while (0)@;
34109
34110 @c
34111 static void mp_tfm_two (MP mp, integer x) { /* output two bytes to |tfm_file| */
34112 tfm_out (x / 256);
34113 tfm_out (x % 256);
34114 }
34115 static void mp_tfm_four (MP mp, integer x) { /* output four bytes to |tfm_file| */
34116 if (x >= 0)
34117 tfm_out (x / three_bytes);
34118 else {
34119 x = x + 010000000000; /* use two's complement for negative values */
34120 x = x + 010000000000;
34121 tfm_out ((x / three_bytes) + 128);
34122 }
34123 x = x % three_bytes;
34124 tfm_out (x / number_to_scaled (unity_t));
34125 x = x % number_to_scaled (unity_t);
34126 tfm_out (x / 0400);
34127 tfm_out (x % 0400);
34128 }
34129 static void mp_tfm_qqqq (MP mp, four_quarters x) { /* output four quarterwords to |tfm_file| */
34130 tfm_out (qo (x.b0));
34131 tfm_out (qo (x.b1));
34132 tfm_out (qo (x.b2));
34133 tfm_out (qo (x.b3));
34134 }
34135
34136
34137 @ @<Finish the \.{TFM} file@>=
34138 if (mp->job_name == NULL)
34139 mp_open_log_file (mp);
34140 mp_pack_job_name (mp, ".tfm");
34141 while (!mp_open_out (mp, &mp->tfm_file, mp_filetype_metrics))
34142 mp_prompt_file_name (mp, "file name for font metrics", ".tfm");
34143 mp->metric_file_name = xstrdup (mp->name_of_file);
34144 @<Output the subfile sizes and header bytes@>
34145 @<Output the character information bytes, then
34146 output the dimensions themselves@>;
34147 @<Output the ligature/kern program@>
34148 @<Output the extensible character recipes and the font metric parameters@>
34149 if (number_positive (internal_value (mp_tracing_stats)))
34150 @<Log the subfile sizes of the \.{TFM} file@>;
34151 mp_print_nl (mp, "Font metrics written on ");
34152 mp_print (mp, mp->metric_file_name);
34153 mp_print_char (mp, xord ('.'));
34154 @.Font metrics written...@>
34155 (mp->close_file) (mp, mp->tfm_file)@;
34156
34157
34158 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
34159 this code.
34160
34161 @<Output the subfile sizes and header bytes@>=
34162 k = mp->header_last;
34163 LH = (k + 4) / 4; /* this is the number of header words */
34164 if (mp->bc > mp->ec)
34165 mp->bc = 1; /* if there are no characters, |ec=0| and |bc=1| */
34166 @<Compute the ligature/kern program offset and implant the
34167 left boundary label@>;
34168 mp_tfm_two (mp,
34169 6 + LH + (mp->ec - mp->bc + 1) + mp->nw + mp->nh + mp->nd + mp->ni +
34170 mp->nl + lk_offset + mp->nk + mp->ne + mp->np);
34171 /* this is the total number of file words that will be output */
34172 mp_tfm_two (mp, LH);
34173 mp_tfm_two (mp, mp->bc);
34174 mp_tfm_two (mp, mp->ec);
34175 mp_tfm_two (mp, mp->nw);
34176 mp_tfm_two (mp, mp->nh);
34177 mp_tfm_two (mp, mp->nd);
34178 mp_tfm_two (mp, mp->ni);
34179 mp_tfm_two (mp, mp->nl + lk_offset);
34180 mp_tfm_two (mp, mp->nk);
34181 mp_tfm_two (mp, mp->ne);
34182 mp_tfm_two (mp, mp->np);
34183 for (k = 0; k < 4 * LH; k++) {
34184 tfm_out (mp->header_byte[k]);
34185 }
34186
34187
34188 @ @<Output the character information bytes...@>=
34189 for (k = mp->bc; k <= mp->ec; k++) {
34190 if (!mp->char_exists[k]) {
34191 mp_tfm_four (mp, 0);
34192 } else {
34193 tfm_out (indep_value (mp->tfm_width[k])); /* the width index */
34194 tfm_out ((indep_value (mp->tfm_height[k])) * 16 + indep_value (mp->tfm_depth[k]));
34195 tfm_out ((indep_value (mp->tfm_ital_corr[k])) * 4 + mp->char_tag[k]);
34196 tfm_out (mp->char_remainder[k]);
34197 }
34198 }
34199 mp->tfm_changed = 0;
34200 for (k = 1; k <= 4; k++) {
34201 mp_tfm_four (mp, 0);
34202 p = mp->dimen_head[k];
34203 while (p != mp->inf_val) {
34204 mp_tfm_four (mp, mp_dimen_out (mp, value_number (p)));
34205 p = mp_link (p);
34206 }
34207 }
34208
34209
34210 @ We need to output special instructions at the beginning of the
34211 |lig_kern| array in order to specify the right boundary character
34212 and/or to handle starting addresses that exceed 255. The |label_loc|
34213 and |label_char| arrays have been set up to record all the
34214 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
34215 \le|label_loc|[|label_ptr]|$.
34216
34217 @<Compute the ligature/kern program offset...@>=
34218 mp->bchar = round_unscaled (internal_value (mp_boundary_char));
34219 if ((mp->bchar < 0) || (mp->bchar > 255)) {
34220 mp->bchar = -1;
34221 mp->lk_started = false;
34222 lk_offset = 0;
34223 } else {
34224 mp->lk_started = true;
34225 lk_offset = 1;
34226 }
34227 @<Find the minimum |lk_offset| and adjust all remainders@>
34228 if (mp->bch_label < undefined_label) {
34229 skip_byte (mp->nl) = qi (255);
34230 next_char (mp->nl) = qi (0);
34231 op_byte (mp->nl) = qi (((mp->bch_label + lk_offset) / 256));
34232 rem_byte (mp->nl) = qi (((mp->bch_label + lk_offset) % 256));
34233 mp->nl++; /* possibly |nl=lig_table_size+1| */
34234 }
34235
34236 @ @<Find the minimum |lk_offset|...@>=
34237 k = mp->label_ptr; /* pointer to the largest unallocated label */
34238 if (mp->label_loc[k] + lk_offset > 255) {
34239 lk_offset = 0;
34240 mp->lk_started = false; /* location 0 can do double duty */
34241 do {
34242 mp->char_remainder[mp->label_char[k]] = lk_offset;
34243 while (mp->label_loc[k - 1] == mp->label_loc[k]) {
34244 decr (k);
34245 mp->char_remainder[mp->label_char[k]] = lk_offset;
34246 }
34247 incr (lk_offset);
34248 decr (k);
34249 } while (!(lk_offset + mp->label_loc[k] < 256));
34250 /* N.B.: |lk_offset=256| satisfies this when |k=0| */
34251 }
34252 if (lk_offset > 0) {
34253 while (k > 0) {
34254 mp->char_remainder[mp->label_char[k]]
34255 = mp->char_remainder[mp->label_char[k]] + lk_offset;
34256 decr (k);
34257 }
34258 }
34259
34260 @ @<Output the ligature/kern program@>=
34261 for (k = 0; k <= 255; k++) {
34262 if (mp->skip_table[k] < undefined_label) {
34263 mp_print_nl (mp, "(local label ");
34264 mp_print_int (mp, k);
34265 mp_print (mp, ":: was missing)");
34266 @.local label l:: was missing@>
34267 cancel_skips (mp->skip_table[k]);
34268 }
34269 }
34270 if (mp->lk_started) { /* |lk_offset=1| for the special |bchar| */
34271 tfm_out (255);
34272 tfm_out (mp->bchar);
34273 mp_tfm_two (mp, 0);
34274 } else {
34275 for (k = 1; k <= lk_offset; k++) { /* output the redirection specs */
34276 mp->ll = mp->label_loc[mp->label_ptr];
34277 if (mp->bchar < 0) {
34278 tfm_out (254);
34279 tfm_out (0);
34280 } else {
34281 tfm_out (255);
34282 tfm_out (mp->bchar);
34283 }
34284 mp_tfm_two (mp, mp->ll + lk_offset);
34285 do {
34286 mp->label_ptr--;
34287 } while (!(mp->label_loc[mp->label_ptr] < mp->ll));
34288 }
34289 }
34290 for (k = 0; k < mp->nl; k++)
34291 mp_tfm_qqqq (mp, mp->lig_kern[k]);
34292 {
34293 mp_number arg;
34294 new_number (arg);
34295 for (k = 0; k < mp->nk; k++) {
34296 number_clone (arg, mp->kern[k]);
34297 mp_tfm_four (mp, mp_dimen_out (mp, arg));
34298 }
34299 free_number (arg);
34300 }
34301
34302 @ @<Output the extensible character recipes...@>=
34303 for (k = 0; k < mp->ne; k++)
34304 mp_tfm_qqqq (mp, mp->exten[k]);
34305 {
34306 mp_number arg;
34307 new_number (arg);
34308 for (k = 1; k <= mp->np; k++) {
34309 if (k == 1) {
34310 number_clone (arg, mp->param[1]);
34311 number_abs (arg);
34312 if (number_less(arg, fraction_half_t)) {
34313 mp_tfm_four (mp, number_to_scaled (mp->param[1]) * 16);
34314 } else {
34315 incr (mp->tfm_changed);
34316 if (number_positive(mp->param[1]))
34317 mp_tfm_four (mp, max_integer);
34318 else
34319 mp_tfm_four (mp, -max_integer);
34320 }
34321 } else {
34322 number_clone (arg, mp->param[k]);
34323 mp_tfm_four (mp, mp_dimen_out (mp, arg));
34324 }
34325 }
34326 free_number (arg);
34327 }
34328 if (mp->tfm_changed > 0) {
34329 if (mp->tfm_changed == 1) {
34330 mp_print_nl (mp, "(a font metric dimension");
34331 @.a font metric dimension...@>
34332 } else {
34333 mp_print_nl (mp, "(");
34334 mp_print_int (mp, mp->tfm_changed);
34335 @.font metric dimensions...@>
34336 mp_print (mp, " font metric dimensions");
34337 }
34338 mp_print (mp, " had to be decreased)");
34339 }
34340
34341 @ @<Log the subfile sizes of the \.{TFM} file@>=
34342 {
34343 char s[200];
34344 wlog_ln (" ");
34345 if (mp->bch_label < undefined_label)
34346 mp->nl--;
34347 mp_snprintf (s, 128,
34348 "(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
34349 mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne, mp->np);
34350 wlog_ln (s);
34351 }
34352
34353
34354 @* Reading font metric data.
34355
34356 \MP\ isn't a typesetting program but it does need to find the bounding box
34357 of a sequence of typeset characters. Thus it needs to read \.{TFM} files as
34358 well as write them.
34359
34360 @<Glob...@>=
34361 void *tfm_infile;
34362
34363 @ All the width, height, and depth information is stored in an array called
34364 |font_info|. This array is allocated sequentially and each font is stored
34365 as a series of |char_info| words followed by the width, height, and depth
34366 tables. Since |font_name| entries are permanent, their |str_ref| values are
34367 set to |MAX_STR_REF|.
34368
34369 @<Types...@>=
34370 typedef unsigned int font_number; /* |0..font_max| */
34371
34372 @ The |font_info| array is indexed via a group directory arrays.
34373 For example, the |char_info| data for character~|c| in font~|f| will be
34374 in |font_info[char_base[f]+c].qqqq|.
34375
34376 @<Glob...@>=
34377 font_number font_max; /* maximum font number for included text fonts */
34378 size_t font_mem_size; /* number of words for \.{TFM} information for text fonts */
34379 font_data *font_info; /* height, width, and depth data */
34380 char **font_enc_name; /* encoding names, if any */
34381 boolean *font_ps_name_fixed; /* are the postscript names fixed already? */
34382 size_t next_fmem; /* next unused entry in |font_info| */
34383 font_number last_fnum; /* last font number used so far */
34384 integer *font_dsize; /* 16 times the ``design'' size in \ps\ points */
34385 char **font_name; /* name as specified in the \&{infont} command */
34386 char **font_ps_name; /* PostScript name for use when |internal[mp_prologues]>0| */
34387 font_number last_ps_fnum; /* last valid |font_ps_name| index */
34388 eight_bits *font_bc;
34389 eight_bits *font_ec; /* first and last character code */
34390 int *char_base; /* base address for |char_info| */
34391 int *width_base; /* index for zeroth character width */
34392 int *height_base; /* index for zeroth character height */
34393 int *depth_base; /* index for zeroth character depth */
34394 mp_node *font_sizes;
34395
34396 @ @<Allocate or initialize ...@>=
34397 mp->font_mem_size = 10000;
34398 mp->font_info = xmalloc ((mp->font_mem_size + 1), sizeof (font_data));
34399 memset (mp->font_info, 0, sizeof (font_data) * (mp->font_mem_size + 1));
34400 mp->last_fnum = null_font;
34401
34402 @ @<Dealloc variables@>=
34403 for (k = 1; k <= (int) mp->last_fnum; k++) {
34404 xfree (mp->font_enc_name[k]);
34405 xfree (mp->font_name[k]);
34406 xfree (mp->font_ps_name[k]);
34407 }
34408 for (k = 0; k <= 255; k++) {
34409 /* These are disabled for now following a bug-report about double free
34410 errors. TO BE FIXED, bug tracker id 831 */
34411 /*|
34412 mp_free_value_node (mp, mp->tfm_width[k]);
34413 mp_free_value_node (mp, mp->tfm_height[k]);
34414 mp_free_value_node (mp, mp->tfm_depth[k]);
34415 mp_free_value_node (mp, mp->tfm_ital_corr[k]);
34416 |*/
34417 }
34418
34419 xfree (mp->font_info);
34420 xfree (mp->font_enc_name);
34421 xfree (mp->font_ps_name_fixed);
34422 xfree (mp->font_dsize);
34423 xfree (mp->font_name);
34424 xfree (mp->font_ps_name);
34425 xfree (mp->font_bc);
34426 xfree (mp->font_ec);
34427 xfree (mp->char_base);
34428 xfree (mp->width_base);
34429 xfree (mp->height_base);
34430 xfree (mp->depth_base);
34431 xfree (mp->font_sizes);
34432
34433 @ @c
34434 void mp_reallocate_fonts (MP mp, font_number l) {
34435 font_number f;
34436 XREALLOC (mp->font_enc_name, l, char *);
34437 XREALLOC (mp->font_ps_name_fixed, l, boolean);
34438 XREALLOC (mp->font_dsize, l, integer);
34439 XREALLOC (mp->font_name, l, char *);
34440 XREALLOC (mp->font_ps_name, l, char *);
34441 XREALLOC (mp->font_bc, l, eight_bits);
34442 XREALLOC (mp->font_ec, l, eight_bits);
34443 XREALLOC (mp->char_base, l, int);
34444 XREALLOC (mp->width_base, l, int);
34445 XREALLOC (mp->height_base, l, int);
34446 XREALLOC (mp->depth_base, l, int);
34447 XREALLOC (mp->font_sizes, l, mp_node);
34448 for (f = (mp->last_fnum + 1); f <= l; f++) {
34449 mp->font_enc_name[f] = NULL;
34450 mp->font_ps_name_fixed[f] = false;
34451 mp->font_name[f] = NULL;
34452 mp->font_ps_name[f] = NULL;
34453 mp->font_sizes[f] = NULL;
34454 }
34455 mp->font_max = l;
34456 }
34457
34458
34459 @ @<Internal library declarations@>=
34460 void mp_reallocate_fonts (MP mp, font_number l);
34461
34462
34463 @ A |null_font| containing no characters is useful for error recovery. Its
34464 |font_name| entry starts out empty but is reset each time an erroneous font is
34465 found. This helps to cut down on the number of duplicate error messages without
34466 wasting a lot of space.
34467
34468 @d null_font 0 /* the |font_number| for an empty font */
34469
34470 @<Set initial...@>=
34471 mp->font_dsize[null_font] = 0;
34472 mp->font_bc[null_font] = 1;
34473 mp->font_ec[null_font] = 0;
34474 mp->char_base[null_font] = 0;
34475 mp->width_base[null_font] = 0;
34476 mp->height_base[null_font] = 0;
34477 mp->depth_base[null_font] = 0;
34478 mp->next_fmem = 0;
34479 mp->last_fnum = null_font;
34480 mp->last_ps_fnum = null_font;
34481 {
34482 static char nullfont_name[] = "nullfont";
34483 static char nullfont_psname[] = "";
34484 mp->font_name[null_font] = nullfont_name;
34485 mp->font_ps_name[null_font] = nullfont_psname;
34486 }
34487 mp->font_ps_name_fixed[null_font] = false;
34488 mp->font_enc_name[null_font] = NULL;
34489 mp->font_sizes[null_font] = NULL;
34490
34491 @ Each |char_info| word is of type |four_quarters|. The |b0| field contains
34492 the |width index|; the |b1| field contains the height
34493 index; the |b2| fields contains the depth index, and the |b3| field used only
34494 for temporary storage. (It is used to keep track of which characters occur in
34495 an edge structure that is being shipped out.)
34496 The corresponding words in the width, height, and depth tables are stored as
34497 |scaled| values in units of \ps\ points.
34498
34499 With the macros below, the |char_info| word for character~|c| in font~|f| is
34500 |char_mp_info(f,c)| and the width~is
34501 $$\hbox{|char_width(f,char_mp_info(f,c)).sc|.}$$
34502
34503 @d char_mp_info(A,B) mp->font_info[mp->char_base[(A)]+(B)].qqqq
34504 @d char_width(A,B) mp->font_info[mp->width_base[(A)]+(B).b0].sc
34505 @d char_height(A,B) mp->font_info[mp->height_base[(A)]+(B).b1].sc
34506 @d char_depth(A,B) mp->font_info[mp->depth_base[(A)]+(B).b2].sc
34507 @d ichar_exists(A) ((A).b0>0)
34508
34509 @ When we have a font name and we don't know whether it has been loaded yet,
34510 we scan the |font_name| array before calling |read_font_info|.
34511
34512 @<Declarations@>=
34513 static font_number mp_find_font (MP mp, char *f);
34514
34515 @ @c
34516 font_number mp_find_font (MP mp, char *f) {
34517 font_number n;
34518 for (n = 0; n <= mp->last_fnum; n++) {
34519 if (mp_xstrcmp (f, mp->font_name[n]) == 0) {
34520 return n;
34521 }
34522 }
34523 n = mp_read_font_info (mp, f);
34524 return n;
34525 }
34526
34527
34528 @ This is an interface function for getting the width of character,
34529 as a double in ps units
34530
34531 @c
34532 double mp_get_char_dimension (MP mp, char *fname, int c, int t) {
34533 unsigned n;
34534 four_quarters cc;
34535 font_number f = 0;
34536 double w = -1.0;
34537 for (n = 0; n <= mp->last_fnum; n++) {
34538 if (mp_xstrcmp (fname, mp->font_name[n]) == 0) {
34539 f = n;
34540 break;
34541 }
34542 }
34543 if (f == 0)
34544 return 0.0;
34545 cc = char_mp_info (f, c);
34546 if (!ichar_exists (cc))
34547 return 0.0;
34548 if (t == 'w')
34549 w = (double) char_width (f, cc);
34550 else if (t == 'h')
34551 w = (double) char_height (f, cc);
34552 else if (t == 'd')
34553 w = (double) char_depth (f, cc);
34554 return w / 655.35 * (72.27 / 72);
34555 }
34556
34557
34558 @ @<Exported function ...@>=
34559 double mp_get_char_dimension (MP mp, char *fname, int n, int t);
34560
34561
34562 @ If we discover that the font doesn't have a requested character, we omit it
34563 from the bounding box computation and expect the \ps\ interpreter to drop it.
34564 This routine issues a warning message if the user has asked for it.
34565
34566 @<Declarations@>=
34567 static void mp_lost_warning (MP mp, font_number f, int k);
34568
34569 @ @c
34570 void mp_lost_warning (MP mp, font_number f, int k) {
34571 if (number_positive (internal_value (mp_tracing_lost_chars))) {
34572 mp_begin_diagnostic (mp);
34573 if (mp->selector == log_only)
34574 incr (mp->selector);
34575 mp_print_nl (mp, "Missing character: There is no ");
34576 @.Missing character@>
34577 mp_print_int (mp, k);
34578 mp_print (mp, " in font ");
34579 mp_print (mp, mp->font_name[f]);
34580 mp_print_char (mp, xord ('!'));
34581 mp_end_diagnostic (mp, false);
34582 }
34583 }
34584
34585
34586 @ The whole purpose of saving the height, width, and depth information is to be
34587 able to find the bounding box of an item of text in an edge structure. The
34588 |set_text_box| procedure takes a text node and adds this information.
34589
34590 @<Declarations@>=
34591 static void mp_set_text_box (MP mp, mp_text_node p);
34592
34593 @ @c
34594 void mp_set_text_box (MP mp, mp_text_node p) {
34595 font_number f; /* |mp_font_n(p)| */
34596 ASCII_code bc, ec; /* range of valid characters for font |f| */
34597 size_t k, kk; /* current character and character to stop at */
34598 four_quarters cc; /* the |char_info| for the current character */
34599 mp_number h, d; /* dimensions of the current character */
34600 mp_number minus_inf_t; /* check the -inf of height and depth */
34601 new_number(h);
34602 new_number(d);
34603 new_number(minus_inf_t);
34604 number_clone(minus_inf_t, inf_t);
34605 number_negate(minus_inf_t);
34606 set_number_to_zero(p->width);
34607 set_number_to_neg_inf(p->height);
34608 set_number_to_neg_inf(p->depth);
34609 f = (font_number) mp_font_n (p);
34610 bc = mp->font_bc[f];
34611 ec = mp->font_ec[f];
34612 kk = mp_text_p (p)->len;
34613 k = 0;
34614 while (k < kk)
34615 @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>@;
34616 @<Set the height and depth to zero if the bounding box is empty@>;
34617 free_number (h);
34618 free_number (d);
34619 free_number (minus_inf_t);
34620 }
34621
34622
34623 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
34624 {
34625 if ((*(mp_text_p (p)->str + k) < bc) || (*(mp_text_p (p)->str + k) > ec)) {
34626 mp_lost_warning (mp, f, *(mp_text_p (p)->str + k));
34627 } else {
34628 cc = char_mp_info (f, *(mp_text_p (p)->str + k));
34629 if (!ichar_exists (cc)) {
34630 mp_lost_warning (mp, f, *(mp_text_p (p)->str + k));
34631 } else {
34632 set_number_from_scaled(p->width, number_to_scaled(p->width) + char_width (f, cc));
34633 set_number_from_scaled(h, char_height (f, cc));
34634 set_number_from_scaled(d, char_depth (f, cc));
34635 if (number_greater(h, p->height))
34636 number_clone(p->height, h);
34637 if (number_greater(d, p->depth))
34638 number_clone(p->depth, d);
34639 }
34640 }
34641 incr (k);
34642 }
34643
34644
34645 @ Let's hope modern compilers do comparisons correctly when the difference would
34646 overflow.
34647
34648 @<Set the height and depth to zero if the bounding box is empty@>=
34649 if (number_equal(p->height,p->depth) && number_equal(p->height,minus_inf_t)) {
34650 set_number_to_zero(p->height);
34651 set_number_to_zero(p->depth);
34652 } else if (number_to_scaled(p->height) < -number_to_scaled(p->depth)) {
34653 set_number_to_zero(p->height);
34654 set_number_to_zero(p->depth);
34655 }
34656
34657 @ The new primitives fontmapfile and fontmapline.
34658
34659 @<Declare action procedures for use by |do_statement|@>=
34660 static void mp_do_mapfile (MP mp);
34661 static void mp_do_mapline (MP mp);
34662
34663 @ @c
34664 static void mp_do_mapfile (MP mp) {
34665 mp_get_x_next (mp);
34666 mp_scan_expression (mp);
34667 if (mp->cur_exp.type != mp_string_type)
34668 @<Complain about improper map operation@>@;
34669 else {
34670 mp_map_file (mp, cur_exp_str ());
34671 }
34672 }
34673 static void mp_do_mapline (MP mp) {
34674 mp_get_x_next (mp);
34675 mp_scan_expression (mp);
34676 if (mp->cur_exp.type != mp_string_type)
34677 @<Complain about improper map operation@>@;
34678 else {
34679 mp_map_line (mp, cur_exp_str ());
34680 }
34681 }
34682
34683
34684 @ @<Complain about improper map operation@>=
34685 {
34686 const char *hlp[] = { "Only known strings can be map files or map lines.", NULL };
34687 mp_disp_err(mp, NULL);
34688 mp_back_error (mp, "Unsuitable expression", hlp, true);
34689 mp_get_x_next (mp);
34690 }
34691
34692
34693 @ To print |scaled| value to PDF output we need some subroutines to ensure
34694 accuracy.
34695
34696 @d max_integer 0x7FFFFFFF /* $2^{31}-1$ */
34697
34698 @<Glob...@>=
34699 integer ten_pow[10]; /* $10^0..10^9$ */
34700 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
34701
34702 @ @<Set init...@>=
34703 mp->ten_pow[0] = 1;
34704 for (i = 1; i <= 9; i++) {
34705 mp->ten_pow[i] = 10 * mp->ten_pow[i - 1];
34706 }
34707
34708
34709 @* Shipping pictures out.
34710 The |ship_out| procedure, to be described below, is given a pointer to
34711 an edge structure. Its mission is to output a file containing the \ps\
34712 description of an edge structure.
34713
34714 @ Each time an edge structure is shipped out we write a new \ps\ output
34715 file named according to the current \&{charcode}.
34716 @:char_code_}{\&{charcode} primitive@>
34717
34718 This is the only backend function that remains in the main |mpost.w| file.
34719 There are just too many variable accesses needed for status reporting
34720 etcetera to make it worthwhile to move the code to |psout.w|.
34721
34722 @<Internal library declarations@>=
34723 void mp_open_output_file (MP mp);
34724 char *mp_get_output_file_name (MP mp);
34725 char *mp_set_output_file_name (MP mp, integer c);
34726
34727 @ @c
34728 static void mp_append_to_template (MP mp, integer ff, integer c, boolean rounding) {
34729 if (internal_type (c) == mp_string_type) {
34730 char *ss = mp_str (mp, internal_string (c));
34731 mp_print (mp, ss);
34732 } else if (internal_type (c) == mp_known) {
34733 if (rounding) {
34734 mpinteger64 cc = round_unscaled (internal_value (c));
34735 print_with_leading_zeroes (cc, ff);
34736 } else {
34737 print_number (internal_value (c));
34738 }
34739 }
34740 }
34741 char *mp_set_output_file_name (MP mp, integer c) {
34742 char *ss = NULL; /* filename extension proposal */
34743 char *nn = NULL; /* temp string for str() */
34744 unsigned old_setting; /* previous |selector| setting */
34745 size_t i; /* indexes into |filename_template| */
34746 integer f; /* field width */
34747 str_room (1024);
34748 if (mp->job_name == NULL)
34749 mp_open_log_file (mp);
34750 if (internal_string (mp_output_template) == NULL) {
34751 char *s; /* a file extension derived from |c| */
34752 if (c < 0)
34753 s = xstrdup (".ps");
34754 else
34755 @<Use |c| to compute the file extension |s|@>@;
34756 mp_pack_job_name (mp, s);
34757 free (s);
34758 ss = xstrdup (mp->name_of_file);
34759 } else { /* initializations */
34760 mp_string s, n, ftemplate; /* a file extension derived from |c| */
34761 mp_number saved_char_code;
34762 new_number (saved_char_code);
34763 number_clone (saved_char_code, internal_value (mp_char_code));
34764 set_internal_from_number (mp_char_code, unity_t);
34765 number_multiply_int (internal_value (mp_char_code), c);
34766 if (internal_string (mp_job_name) == NULL) {
34767 if (mp->job_name == NULL) {
34768 mp->job_name = xstrdup ("mpout");
34769 }
34770 @<Fix up |mp->internal[mp_job_name]|@>;
34771 }
34772 old_setting = mp->selector;
34773 mp->selector = new_string;
34774 i = 0;
34775 n = mp_rts(mp,""); /* initialize */
34776 ftemplate = internal_string (mp_output_template);
34777 while (i < ftemplate->len) {
34778 f = 0;
34779 if (*(ftemplate->str + i) == '%') {
34780 CONTINUE:
34781 incr (i);
34782 if (i < ftemplate->len) {
34783 switch (*(ftemplate->str + i)) {
34784 case 'j':
34785 mp_append_to_template (mp, f, mp_job_name, true);
34786 break;
34787 case 'c':
34788 if (number_negative (internal_value (mp_char_code))) {
34789 mp_print (mp, "ps");
34790 } else {
34791 mp_append_to_template (mp, f, mp_char_code, true);
34792 }
34793 break;
34794 case 'o':
34795 mp_append_to_template (mp, f, mp_output_format, true);
34796 break;
34797 case 'd':
34798 mp_append_to_template (mp, f, mp_day, true);
34799 break;
34800 case 'm':
34801 mp_append_to_template (mp, f, mp_month, true);
34802 break;
34803 case 'y':
34804 mp_append_to_template (mp, f, mp_year, true);
34805 break;
34806 case 'H':
34807 mp_append_to_template (mp, f, mp_hour, true);
34808 break;
34809 case 'M':
34810 mp_append_to_template (mp, f, mp_minute, true);
34811 break;
34812 case '{':
34813 {
34814 /* look up a name */
34815 size_t l = 0;
34816 size_t frst = i + 1;
34817 while (i < ftemplate->len) {
34818 i++;
34819 if (*(ftemplate->str + i) == '}')
34820 break;
34821 l++;
34822 }
34823 if (l > 0) {
34824 mp_sym p =
34825 mp_id_lookup (mp, (char *) (ftemplate->str + frst), l, false);
34826 char *id = xmalloc ((l + 1), 1);
34827 (void) memcpy (id, (char *) (ftemplate->str + frst), (size_t) l);
34828 *(id + l) = '\0';
34829 if (p == NULL) {
34830 char err[256];
34831 mp_snprintf (err, 256,
34832 "requested identifier (%s) in outputtemplate not found.",
34833 id);
34834 mp_warn (mp, err);
34835 } else {
34836 if (eq_type (p) == mp_internal_quantity) {
34837 if (equiv (p) == mp_output_template) {
34838 char err[256];
34839 mp_snprintf (err, 256,
34840 "The appearance of outputtemplate inside outputtemplate is ignored.");
34841 mp_warn (mp, err);
34842 } else {
34843 mp_append_to_template (mp, f, equiv (p), false);
34844 }
34845 } else {
34846 char err[256];
34847 mp_snprintf (err, 256,
34848 "requested identifier (%s) in outputtemplate is not an internal.",
34849 id);
34850 mp_warn (mp, err);
34851 }
34852 }
34853 free (id);
34854 }
34855 }
34856 break;
34857 case '0':
34858 case '1':
34859 case '2':
34860 case '3':
34861 case '4':
34862 case '5':
34863 case '6':
34864 case '7':
34865 case '8':
34866 case '9':
34867 if ((f < 10))
34868 f = (f * 10) + ftemplate->str[i] - '0';
34869 goto CONTINUE;
34870 break;
34871 case '%':
34872 mp_print_char (mp, '%');
34873 break;
34874 default:
34875 {
34876 char err[256];
34877 mp_snprintf (err, 256,
34878 "requested format (%c) in outputtemplate is unknown.",
34879 *(ftemplate->str + i));
34880 mp_warn (mp, err);
34881 }
34882 mp_print_char (mp, *(ftemplate->str + i));
34883 }
34884 }
34885 } else {
34886 if (*(ftemplate->str + i) == '.')
34887 if (n->len == 0)
34888 n = mp_make_string (mp);
34889 mp_print_char (mp, *(ftemplate->str + i));
34890 }
34891 incr (i);
34892 }
34893 s = mp_make_string (mp);
34894 number_clone (internal_value (mp_char_code), saved_char_code);
34895 free_number (saved_char_code);
34896 mp->selector = old_setting;
34897 if (n->len == 0) {
34898 n = s;
34899 s = mp_rts(mp,"");
34900 }
34901 ss = mp_str (mp, s);
34902 nn = mp_str (mp, n);
34903 mp_pack_file_name (mp, nn, "", ss);
34904 delete_str_ref (n);
34905 delete_str_ref (s);
34906 }
34907 return ss;
34908 }
34909 char *mp_get_output_file_name (MP mp) {
34910 char *f;
34911 char *saved_name; /* saved |name_of_file| */
34912 saved_name = xstrdup (mp->name_of_file);
34913 (void) mp_set_output_file_name (mp, round_unscaled (internal_value(mp_char_code)));
34914 f = xstrdup (mp->name_of_file);
34915 mp_pack_file_name (mp, saved_name, NULL, NULL);
34916 free (saved_name);
34917 return f;
34918 }
34919 void mp_open_output_file (MP mp) {
34920 char *ss; /* filename extension proposal */
34921 mpinteger64 c; /* \&{charcode} rounded to the nearest integer */
34922 c = round_unscaled (internal_value (mp_char_code));
34923 ss = mp_set_output_file_name (mp, c);
34924 while (!mp_open_out (mp, (void *) &mp->output_file, mp_filetype_postscript))
34925 mp_prompt_file_name (mp, "file name for output", ss);
34926 mp_store_true_output_filename (mp, c);
34927 }
34928
34929
34930 @ The file extension created here could be up to five characters long in
34931 extreme cases so it may have to be shortened on some systems.
34932 @^system dependencies@>
34933
34934 @<Use |c| to compute the file extension |s|@>=
34935 {
34936 s = xmalloc (14, 1);
34937 mp_snprintf (s, 13, ".%i", (int) c);
34938 s[13]='\0';
34939 }
34940
34941
34942 @ The user won't want to see all the output file names so we only save the
34943 first and last ones and a count of how many there were. For this purpose
34944 files are ordered primarily by \&{charcode} and secondarily by order of
34945 creation.
34946 @:char_code_}{\&{charcode} primitive@>
34947
34948 @<Internal library ...@>=
34949 void mp_store_true_output_filename (MP mp, int c);
34950
34951 @ @c
34952 void mp_store_true_output_filename (MP mp, int c)
34953 {
34954 if ((c < mp->first_output_code) && (mp->first_output_code >= 0)) {
34955 mp->first_output_code = c;
34956 xfree (mp->first_file_name);
34957 mp->first_file_name = xstrdup (mp->name_of_file);
34958 }
34959 if (c >= mp->last_output_code) {
34960 mp->last_output_code = c;
34961 xfree (mp->last_file_name);
34962 mp->last_file_name = xstrdup (mp->name_of_file);
34963 }
34964 set_internal_string (mp_output_filename, mp_rts (mp, mp->name_of_file));
34965 }
34966
34967 @ @<Glob...@>=
34968 char *first_file_name;
34969 char *last_file_name; /* full file names */
34970 integer first_output_code;
34971 integer last_output_code; /* rounded \&{charcode} values */
34972 @:char_code_}{\&{charcode} primitive@>
34973 integer total_shipped; /* total number of |ship_out| operations completed */
34974
34975 @ @<Set init...@>=
34976 mp->first_file_name = xstrdup ("");
34977 mp->last_file_name = xstrdup ("");
34978 mp->first_output_code = 32768;
34979 mp->last_output_code = -32768;
34980 mp->total_shipped = 0;
34981
34982 @ @<Dealloc variables@>=
34983 xfree (mp->first_file_name);
34984 xfree (mp->last_file_name);
34985
34986 @ @<Begin the progress report for the output of picture~|c|@>=
34987 if ((int) mp->term_offset > mp->max_print_line - 6)
34988 mp_print_ln (mp);
34989 else if ((mp->term_offset > 0) || (mp->file_offset > 0))
34990 mp_print_char (mp, xord (' '));
34991 mp_print_char (mp, xord ('['));
34992 if (c >= 0)
34993 mp_print_int (mp, c)@;
34994
34995
34996 @ @<End progress report@>=
34997 mp_print_char (mp, xord (']'));
34998 update_terminal();
34999 incr (mp->total_shipped)@;
35000
35001
35002 @ @<Explain what output files were written@>=
35003 if (mp->total_shipped > 0) {
35004 mp_print_nl (mp, "");
35005 mp_print_int (mp, mp->total_shipped);
35006 if (mp->noninteractive) {
35007 mp_print (mp, " figure");
35008 if (mp->total_shipped > 1)
35009 mp_print_char (mp, xord ('s'));
35010 mp_print (mp, " created.");
35011 } else {
35012 mp_print (mp, " output file");
35013 if (mp->total_shipped > 1)
35014 mp_print_char (mp, xord ('s'));
35015 mp_print (mp, " written: ");
35016 mp_print (mp, mp->first_file_name);
35017 if (mp->total_shipped > 1) {
35018 if (31 + strlen (mp->first_file_name) +
35019 strlen (mp->last_file_name) > (unsigned) mp->max_print_line)
35020 mp_print_ln (mp);
35021 mp_print (mp, " .. ");
35022 mp_print (mp, mp->last_file_name);
35023 }
35024 mp_print_nl (mp, "");
35025 }
35026 }
35027
35028 @ @<Internal library declarations@>=
35029 boolean mp_has_font_size (MP mp, font_number f);
35030
35031 @ @c
35032 boolean mp_has_font_size (MP mp, font_number f) {
35033 return (mp->font_sizes[f] != NULL);
35034 }
35035
35036
35037 @ The \&{special} command saves up lines of text to be printed during the next
35038 |ship_out| operation. The saved items are stored as a list of capsule tokens.
35039
35040 @<Glob...@>=
35041 mp_node last_pending; /* the last token in a list of pending specials */
35042
35043
35044 @ @<Declare action procedures for use by |do_statement|@>=
35045 static void mp_do_special (MP mp);
35046
35047 @ @c
35048 void mp_do_special (MP mp) {
35049 mp_get_x_next (mp);
35050 mp_scan_expression (mp);
35051 if (mp->cur_exp.type != mp_string_type)
35052 @<Complain about improper special operation@>@;
35053 else {
35054 mp_link (mp->last_pending) = mp_stash_cur_exp (mp);
35055 mp->last_pending = mp_link (mp->last_pending);
35056 mp_link (mp->last_pending) = NULL;
35057 }
35058 }
35059
35060
35061 @ @<Complain about improper special operation@>=
35062 {
35063 const char *hlp[] = { "Only known strings are allowed for output as specials.", NULL };
35064 mp_disp_err(mp, NULL);
35065 mp_back_error (mp, "Unsuitable expression", hlp, true);
35066 mp_get_x_next (mp);
35067 }
35068
35069
35070 @ On the export side, we need an extra object type for special strings.
35071
35072 @<Graphical object codes@>=
35073 mp_special_code = 8,@[@]@;
35074
35075 @ @s mp_special_object int @<Export pending specials@>=
35076 p = mp_link (mp->spec_head);
35077 while (p != NULL) {
35078 mp_special_object *tp;
35079 tp = (mp_special_object *) mp_new_graphic_object (mp, mp_special_code);
35080 gr_pre_script (tp) = mp_xstrdup(mp,mp_str (mp, value_str (p)));
35081 if (hh->body == NULL)
35082 hh->body = (mp_graphic_object *) tp;
35083 else
35084 gr_link (hp) = (mp_graphic_object *) tp;
35085 hp = (mp_graphic_object *) tp;
35086 p = mp_link (p);
35087 }
35088 mp_flush_token_list (mp, mp_link (mp->spec_head));
35089 mp_link (mp->spec_head) = NULL;
35090 mp->last_pending = mp->spec_head@;
35091
35092 @ We are now ready for the main output procedure. Note that the |selector|
35093 setting is saved in a global variable so that |begin_diagnostic| can access it.
35094
35095 @<Declare the \ps\ output procedures@>=
35096 static void mp_ship_out (MP mp, mp_node h);
35097
35098 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
35099
35100 @s mp_edge_object int
35101 @s mp_graphic_object int
35102 @s mp_text_object int
35103 @s mp_fill_object int
35104 @s mp_stroked_object int
35105 @s mp_clip_object int
35106 @s mp_bounds_object int
35107
35108 @d export_color(q,p)
35109 if ( mp_color_model(p)==mp_uninitialized_model ) {
35110 gr_color_model(q) = (unsigned char)@|(number_to_scaled (internal_value(mp_default_color_model))/65536);
35111 gr_cyan_val(q) = 0;
35112 gr_magenta_val(q) = 0;
35113 gr_yellow_val(q) = 0;
35114 gr_black_val(q) = ((gr_color_model(q)==mp_cmyk_model ? @| number_to_scaled (unity_t) : 0) / 65536.0);
35115 } else {
35116 gr_color_model(q) = (unsigned char)mp_color_model(p);
35117 gr_cyan_val(q) = number_to_double(p->cyan);
35118 gr_magenta_val(q) = number_to_double(p->magenta);
35119 gr_yellow_val(q) = number_to_double(p->yellow);
35120 gr_black_val(q) = number_to_double(p->black);
35121 }
35122
35123 @d export_scripts(q,p)
35124 if (mp_pre_script(p)!=NULL) gr_pre_script(q) = mp_xstrdup(mp, mp_str(mp,mp_pre_script(p)));
35125 if (mp_post_script(p)!=NULL) gr_post_script(q) = mp_xstrdup(mp, mp_str(mp,mp_post_script(p)));
35126
35127 @c
35128 struct mp_edge_object *mp_gr_export (MP mp, mp_edge_header_node h) {
35129 mp_node p; /* the current graphical object */
35130 integer t; /* a temporary value */
35131 integer c; /* a rounded charcode */
35132 mp_number d_width; /* the current pen width */
35133 mp_edge_object *hh; /* the first graphical object */
35134 mp_graphic_object *hq; /* something |hp| points to */
35135 mp_text_object *tt;
35136 mp_fill_object *tf;
35137 mp_stroked_object *ts;
35138 mp_clip_object *tc;
35139 mp_bounds_object *tb;
35140 mp_graphic_object *hp = NULL; /* the current graphical object */
35141 mp_set_bbox (mp, h, true);
35142 hh = xmalloc (1, sizeof (mp_edge_object));
35143 hh->body = NULL;
35144 hh->next = NULL;
35145 hh->parent = mp;
35146 hh->minx = number_to_double(h->minx);
35147 hh->minx = (fabs(hh->minx)<0.00001 ? 0 : hh->minx);
35148 hh->miny = number_to_double(h->miny);
35149 hh->miny = (fabs(hh->miny)<0.00001 ? 0 : hh->miny);
35150 hh->maxx = number_to_double(h->maxx);
35151 hh->maxx = (fabs(hh->maxx)<0.00001 ? 0 : hh->maxx);
35152 hh->maxy = number_to_double(h->maxy);
35153 hh->maxy = (fabs(hh->maxy)<0.00001 ? 0 : hh->maxy);
35154 hh->filename = mp_get_output_file_name (mp);
35155 c = round_unscaled (internal_value (mp_char_code));
35156 hh->charcode = c;
35157 hh->width = number_to_double (internal_value (mp_char_wd));
35158 hh->height = number_to_double (internal_value (mp_char_ht));
35159 hh->depth = number_to_double (internal_value (mp_char_dp));
35160 hh->ital_corr = number_to_double (internal_value (mp_char_ic));
35161 @<Export pending specials@>;
35162 p = mp_link (edge_list (h));
35163 while (p != NULL) {
35164 hq = mp_new_graphic_object (mp, (int) ((mp_type (p) - mp_fill_node_type) + 1));
35165 switch (mp_type (p)) {
35166 case mp_fill_node_type:
35167 {
35168 mp_fill_node p0 = (mp_fill_node)p;
35169 tf = (mp_fill_object *) hq;
35170 gr_pen_p (tf) = mp_export_knot_list (mp, mp_pen_p (p0));
35171 new_number (d_width);
35172 mp_get_pen_scale (mp, &d_width, mp_pen_p (p0)); /* whats the point ? */
35173 free_number (d_width);
35174 if ((mp_pen_p (p0) == NULL) || pen_is_elliptical (mp_pen_p (p0))) {
35175 gr_path_p (tf) = mp_export_knot_list (mp, mp_path_p (p0));
35176 } else {
35177 mp_knot pc, pp;
35178 pc = mp_copy_path (mp, mp_path_p (p0));
35179 pp = mp_make_envelope (mp, pc, mp_pen_p (p0), p0->ljoin, 0, p0->miterlim);
35180 gr_path_p (tf) = mp_export_knot_list (mp, pp);
35181 mp_toss_knot_list (mp, pp);
35182 pc = mp_htap_ypoc (mp, mp_path_p (p0));
35183 pp = mp_make_envelope (mp, pc, mp_pen_p ((mp_fill_node) p), p0->ljoin, 0, p0->miterlim);
35184 gr_htap_p (tf) = mp_export_knot_list (mp, pp);
35185 mp_toss_knot_list (mp, pp);
35186 }
35187 export_color (tf, p0);
35188 export_scripts (tf, p);
35189 gr_ljoin_val (tf) = p0->ljoin;
35190 gr_miterlim_val (tf) = number_to_double(p0->miterlim);
35191 }
35192 break;
35193 case mp_stroked_node_type:
35194 {
35195 mp_stroked_node p0 = (mp_stroked_node)p;
35196 ts = (mp_stroked_object *) hq;
35197 gr_pen_p (ts) = mp_export_knot_list (mp, mp_pen_p (p0));
35198 new_number (d_width);
35199 mp_get_pen_scale (mp, &d_width, mp_pen_p (p0));
35200 if (pen_is_elliptical (mp_pen_p (p0))) {
35201 gr_path_p (ts) = mp_export_knot_list (mp, mp_path_p (p0));
35202 } else {
35203 mp_knot pc;
35204 pc = mp_copy_path (mp, mp_path_p (p0));
35205 t = p0->lcap;
35206 if (mp_left_type (pc) != mp_endpoint) {
35207 mp_left_type (mp_insert_knot (mp, pc, pc->x_coord, pc->y_coord)) = mp_endpoint;
35208 mp_right_type (pc) = mp_endpoint;
35209 pc = mp_next_knot (pc);
35210 t = 1;
35211 }
35212 pc =
35213 mp_make_envelope (mp, pc, mp_pen_p (p0),
35214 p0->ljoin, (quarterword) t,
35215 p0->miterlim);
35216 gr_path_p (ts) = mp_export_knot_list (mp, pc);
35217 mp_toss_knot_list (mp, pc);
35218 }
35219 export_color (ts, p0);
35220 export_scripts (ts, p);
35221 gr_ljoin_val (ts) = p0->ljoin;
35222 gr_miterlim_val (ts) = number_to_double(p0->miterlim);
35223 gr_lcap_val (ts) = p0->lcap;
35224 gr_dash_p (ts) = mp_export_dashes (mp, p0, d_width);
35225 free_number (d_width);
35226 }
35227 break;
35228 case mp_text_node_type:
35229 {
35230 mp_text_node p0 = (mp_text_node)p;
35231 tt = (mp_text_object *) hq;
35232 gr_text_p (tt) = mp_xstrldup (mp, mp_str (mp, mp_text_p (p)),mp_text_p (p)->len);
35233 gr_text_l (tt) = (size_t) mp_text_p (p)->len;
35234 gr_font_n (tt) = (unsigned int) mp_font_n (p);
35235 gr_font_name (tt) = mp_xstrdup (mp, mp->font_name[mp_font_n (p)]);
35236 gr_font_dsize (tt) = mp->font_dsize[mp_font_n (p)] / 65536.0;
35237 export_color (tt, p0);
35238 export_scripts (tt, p);
35239 gr_width_val (tt) = number_to_double(p0->width);
35240 gr_height_val (tt) = number_to_double(p0->height);
35241 gr_depth_val (tt) = number_to_double(p0->depth);
35242 gr_tx_val (tt) = number_to_double(p0->tx);
35243 gr_ty_val (tt) = number_to_double(p0->ty);
35244 gr_txx_val (tt) = number_to_double(p0->txx);
35245 gr_txy_val (tt) = number_to_double(p0->txy);
35246 gr_tyx_val (tt) = number_to_double(p0->tyx);
35247 gr_tyy_val (tt) = number_to_double(p0->tyy);
35248 }
35249 break;
35250 case mp_start_clip_node_type:
35251 tc = (mp_clip_object *) hq;
35252 gr_path_p (tc) =
35253 mp_export_knot_list (mp, mp_path_p ((mp_start_clip_node) p));
35254 break;
35255 case mp_start_bounds_node_type:
35256 tb = (mp_bounds_object *) hq;
35257 gr_path_p (tb) =
35258 mp_export_knot_list (mp, mp_path_p ((mp_start_bounds_node) p));
35259 break;
35260 case mp_stop_clip_node_type:
35261 case mp_stop_bounds_node_type:
35262 /* nothing to do here */
35263 break;
35264 default: /* there are no other valid cases, but please the compiler */
35265 break;
35266 }
35267 if (hh->body == NULL)
35268 hh->body = hq;
35269 else
35270 gr_link (hp) = hq;
35271 hp = hq;
35272 p = mp_link (p);
35273 }
35274 return hh;
35275 }
35276
35277
35278 @ This function is only used for the |glyph| operator, so
35279 it takes quite a few shortcuts for cases that cannot appear
35280 in the output of |mp_ps_font_charstring|.
35281
35282 @c
35283 mp_edge_header_node mp_gr_import (MP mp, struct mp_edge_object *hh) {
35284 mp_edge_header_node h; /* the edge object */
35285 mp_node ph, pn, pt; /* for adding items */
35286 mp_graphic_object *p; /* the current graphical object */
35287 h = mp_get_edge_header_node (mp);
35288 mp_init_edges (mp, h);
35289 ph = edge_list (h);
35290 pt = ph;
35291 p = hh->body;
35292 set_number_from_double(h->minx, hh->minx);
35293 set_number_from_double(h->miny, hh->miny);
35294 set_number_from_double(h->maxx, hh->maxx);
35295 set_number_from_double(h->maxy, hh->maxy);
35296 while (p != NULL) {
35297 switch (gr_type (p)) {
35298 case mp_fill_code:
35299 if (gr_pen_p ((mp_fill_object *) p) == NULL) {
35300 mp_number turns;
35301 new_number (turns);
35302 pn = mp_new_fill_node (mp, NULL);
35303 mp_path_p ((mp_fill_node) pn) =
35304 mp_import_knot_list (mp, gr_path_p ((mp_fill_object *) p));
35305 mp_color_model (pn) = mp_grey_model;
35306 mp_turn_cycles (mp, &turns, mp_path_p ((mp_fill_node) pn));
35307 if (number_negative(turns)) {
35308 set_number_to_unity(((mp_fill_node) pn)->grey);
35309 mp_link (pt) = pn;
35310 pt = mp_link (pt);
35311 } else {
35312 set_number_to_zero(((mp_fill_node) pn)->grey);
35313 mp_link (pn) = mp_link (ph);
35314 mp_link (ph) = pn;
35315 if (ph == pt)
35316 pt = pn;
35317 }
35318 free_number (turns);
35319 }
35320 break;
35321 case mp_stroked_code:
35322 case mp_text_code:
35323 case mp_start_clip_code:
35324 case mp_stop_clip_code:
35325 case mp_start_bounds_code:
35326 case mp_stop_bounds_code:
35327 case mp_special_code:
35328 break;
35329 } /* all cases are enumerated */
35330 p = p->next;
35331 }
35332 mp_gr_toss_objects (hh);
35333 return h;
35334 }
35335
35336
35337 @ @<Declarations@>=
35338 struct mp_edge_object *mp_gr_export (MP mp, mp_edge_header_node h);
35339 mp_edge_header_node mp_gr_import (MP mp, struct mp_edge_object *h);
35340
35341 @ This function is now nearly trivial.
35342
35343 @c
35344 void mp_ship_out (MP mp, mp_node h) { /* output edge structure |h| */
35345 int c; /* \&{charcode} rounded to the nearest integer */
35346 c = round_unscaled (internal_value (mp_char_code));
35347 @<Begin the progress report for the output of picture~|c|@>;
35348 (mp->shipout_backend) (mp, h);
35349 @<End progress report@>;
35350 if (number_positive (internal_value (mp_tracing_output)))
35351 mp_print_edges (mp, h, " (just shipped out)", true);
35352 }
35353
35354
35355 @ @<Declarations@>=
35356 static void mp_shipout_backend (MP mp, void *h);
35357
35358 @ @c
35359 void mp_shipout_backend (MP mp, void *voidh) {
35360 char *s;
35361 mp_edge_object *hh; /* the first graphical object */
35362 mp_edge_header_node h = (mp_edge_header_node) voidh;
35363 hh = mp_gr_export (mp, h);
35364 s = NULL;
35365 if (internal_string (mp_output_format) != NULL)
35366 s = mp_str (mp, internal_string (mp_output_format));
35367 if (s && strcmp (s, "svg") == 0) {
35368 (void) mp_svg_gr_ship_out (hh,
35369 (number_to_scaled (internal_value (mp_prologues)) / 65536), false);
35370 } else if (s && strcmp (s, "png") == 0) {
35371 (void) mp_png_gr_ship_out (hh, (const char *)((internal_string (mp_output_format_options))->str), false);
35372 } else {
35373 (void) mp_gr_ship_out (hh,
35374 (number_to_scaled (internal_value (mp_prologues)) / 65536),
35375 (number_to_scaled (internal_value (mp_procset)) / 65536), false);
35376 }
35377 mp_gr_toss_objects (hh);
35378 }
35379
35380
35381 @ @<Exported types@>=
35382 typedef void @[@] (*mp_backend_writer) (MP, void *);
35383
35384 @ @<Option variables@>=
35385 mp_backend_writer shipout_backend;
35386
35387 @ Now that we've finished |ship_out|, let's look at the other commands
35388 by which a user can send things to the \.{GF} file.
35389
35390 @ @<Glob...@>=
35391 psout_data ps;
35392 svgout_data svg;
35393 pngout_data png;
35394
35395 @ @<Allocate or initialize ...@>=
35396 mp_ps_backend_initialize (mp);
35397 mp_svg_backend_initialize (mp);
35398 mp_png_backend_initialize (mp);
35399
35400 @ @<Dealloc...@>=
35401 mp_ps_backend_free (mp);
35402 mp_svg_backend_free (mp);
35403 mp_png_backend_free (mp);
35404
35405
35406 @* Dumping and undumping the tables.
35407
35408 When \.{MP} is started, it is possible to preload a macro file
35409 containing definitions that will be usable in the main input
35410 file. This action even takes place automatically, based on the
35411 name of the executable (\.{mpost} will attempt to preload the
35412 macros in the file \.{mpost.mp}). If such a preload is not
35413 desired, the option variable |ini_version| has to be set |true|.
35414
35415 The variable |mem_file| holds the open file pointer.
35416
35417 @<Glob...@>=
35418 void *mem_file; /* file for input or preloaded macros */
35419
35420 @ @<Declarations@>=
35421 extern boolean mp_load_preload_file (MP mp);
35422
35423 @ Preloading a file is a lot like |mp_run| itself, except that
35424 \MP\ should not exit and that a bit of trickery is needed with
35425 the input buffer to make sure that the preloading does not
35426 interfere with the actual job.
35427
35428 @c
35429 boolean mp_load_preload_file (MP mp) {
35430 size_t k;
35431 in_state_record old_state;
35432 integer old_in_open = mp->in_open;
35433 void *old_cur_file = cur_file;
35434 char *fname = xstrdup (mp->name_of_file);
35435 size_t l = strlen (fname);
35436 old_state = mp->cur_input;
35437 str_room (l);
35438 for (k = 0; k < l; k++) {
35439 append_char (*(fname + k));
35440 }
35441 name = mp_make_string (mp);
35442 if (!mp->log_opened) {
35443 mp_open_log_file (mp);
35444 } /* |open_log_file| doesn't |show_context|, so |limit|
35445 and |loc| needn't be set to meaningful values yet */
35446 if (((int) mp->term_offset + (int) strlen (fname)) > (mp->max_print_line - 2))
35447 mp_print_ln (mp);
35448 else if ((mp->term_offset > 0) || (mp->file_offset > 0))
35449 mp_print_char (mp, xord (' '));
35450 mp_print_char (mp, xord ('('));
35451 incr (mp->open_parens);
35452 mp_print (mp, fname);
35453 update_terminal();
35454 {
35455 line = 1;
35456 start = loc = limit + (mp->noninteractive ? 0 : 1);
35457 cur_file = mp->mem_file;
35458 (void) mp_input_ln (mp, cur_file);
35459 mp_firm_up_the_line (mp);
35460 mp->buffer[limit] = xord ('%');
35461 mp->first = (size_t) (limit + 1);
35462 loc = start;
35463 }
35464 mp->reading_preload = true;
35465 do {
35466 mp_do_statement (mp);
35467 } while (!(cur_cmd() == mp_stop)); /* ``dump'' or EOF */
35468 mp->reading_preload = false;
35469 mp_primitive (mp, "dump", mp_relax, 0); /* reset |dump| */
35470 while (mp->input_ptr > 0) {
35471 if (token_state)
35472 mp_end_token_list (mp);
35473 else
35474 mp_end_file_reading (mp);
35475 }
35476 while (mp->loop_ptr != NULL)
35477 mp_stop_iteration (mp);
35478 while (mp->open_parens > 0) {
35479 mp_print (mp, " )");
35480 decr (mp->open_parens);
35481 }
35482 while (mp->cond_ptr != NULL) {
35483 mp_print_nl (mp, "(dump occurred when ");
35484 @.dump occurred...@>
35485 mp_print_cmd_mod (mp, mp_fi_or_else, mp->cur_if);
35486 /* `\.{if}' or `\.{elseif}' or `\.{else}' */
35487 if (mp->if_line != 0) {
35488 mp_print (mp, " on line ");
35489 mp_print_int (mp, mp->if_line);
35490 }
35491 mp_print (mp, " was incomplete)");
35492 mp->if_line = if_line_field (mp->cond_ptr);
35493 mp->cur_if = mp_name_type (mp->cond_ptr);
35494 mp->cond_ptr = mp_link (mp->cond_ptr);
35495 }
35496
35497 /* |(mp->close_file) (mp, mp->mem_file);| */
35498 cur_file = old_cur_file;
35499 mp->cur_input = old_state;
35500 mp->in_open = old_in_open;
35501 return true;
35502 }
35503
35504
35505 @* The main program.
35506 This is it: the part of \MP\ that executes all those procedures we have
35507 written.
35508
35509 Well---almost. We haven't put the parsing subroutines into the
35510 program yet; and we'd better leave space for a few more routines that may
35511 have been forgotten.
35512
35513 @c
35514 @<Declare the basic parsing subroutines@>
35515 @<Declare miscellaneous procedures that were declared |forward|@>
35516
35517
35518 @ Here we do whatever is needed to complete \MP's job gracefully on the
35519 local operating system. The code here might come into play after a fatal
35520 error; it must therefore consist entirely of ``safe'' operations that
35521 cannot produce error messages. For example, it would be a mistake to call
35522 |str_room| or |make_string| at this time, because a call on |overflow|
35523 might lead to an infinite loop.
35524 @^system dependencies@>
35525
35526 @ @c
35527 void mp_close_files_and_terminate (MP mp) {
35528 integer k; /* all-purpose index */
35529 integer LH; /* the length of the \.{TFM} header, in words */
35530 int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
35531 mp_node p; /* runs through a list of \.{TFM} dimensions */
35532 if (mp->finished)
35533 return;
35534 @<Close all open files in the |rd_file| and |wr_file| arrays@>;
35535 if (number_positive (internal_value (mp_tracing_stats)))
35536 @<Output statistics about this job@>;
35537 wake_up_terminal();
35538 @<Do all the finishing work on the \.{TFM} file@>;
35539 @<Explain what output files were written@>;
35540 if (mp->log_opened && !mp->noninteractive) {
35541 wlog_cr;
35542 (mp->close_file) (mp, mp->log_file);
35543 mp->selector = mp->selector - 2;
35544 if (mp->selector == term_only) {
35545 mp_print_nl (mp, "Transcript written on ");
35546 @.Transcript written...@>
35547 mp_print (mp, mp->log_name);
35548 mp_print_char (mp, xord ('.'));
35549 }
35550 }
35551 mp_print_ln (mp);
35552 mp->finished = true;
35553 }
35554
35555
35556 @ @<Declarations@>=
35557 static void mp_close_files_and_terminate (MP mp);
35558
35559 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
35560 if (mp->rd_fname != NULL) {
35561 for (k = 0; k < (int) mp->read_files; k++) {
35562 if (mp->rd_fname[k] != NULL) {
35563 (mp->close_file) (mp, mp->rd_file[k]);
35564 xfree (mp->rd_fname[k]);
35565 }
35566 }
35567 }
35568 if (mp->wr_fname != NULL) {
35569 for (k = 0; k < (int) mp->write_files; k++) {
35570 if (mp->wr_fname[k] != NULL) {
35571 (mp->close_file) (mp, mp->wr_file[k]);
35572 xfree (mp->wr_fname[k]);
35573 }
35574 }
35575 }
35576
35577 @ @<Dealloc ...@>=
35578 for (k = 0; k < (int) mp->max_read_files; k++) {
35579 if (mp->rd_fname[k] != NULL) {
35580 (mp->close_file) (mp, mp->rd_file[k]);
35581 xfree (mp->rd_fname[k]);
35582 }
35583 }
35584 xfree (mp->rd_file);
35585 xfree (mp->rd_fname);
35586 for (k = 0; k < (int) mp->max_write_files; k++) {
35587 if (mp->wr_fname[k] != NULL) {
35588 (mp->close_file) (mp, mp->wr_file[k]);
35589 xfree (mp->wr_fname[k]);
35590 }
35591 }
35592 xfree (mp->wr_file);
35593 xfree (mp->wr_fname);
35594
35595
35596 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
35597
35598 We reclaim all of the variable-size memory at this point, so that
35599 there is no chance of another memory overflow after the memory capacity
35600 has already been exceeded.
35601
35602 @<Do all the finishing work on the \.{TFM} file@>=
35603 if (number_positive (internal_value (mp_fontmaking))) {
35604 @<Massage the \.{TFM} widths@>;
35605 mp_fix_design_size (mp);
35606 mp_fix_check_sum (mp);
35607 @<Massage the \.{TFM} heights, depths, and italic corrections@>;
35608 set_number_to_zero (internal_value (mp_fontmaking)); /* avoid loop in case of fatal error */
35609 @<Finish the \.{TFM} file@>;
35610 }
35611
35612 @ The present section goes directly to the log file instead of using
35613 |print| commands, because there's no need for these strings to take
35614 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
35615
35616 @<Output statistics...@>=
35617 if (mp->log_opened) {
35618 char s[128];
35619 wlog_ln (" ");
35620 wlog_ln ("Here is how much of MetaPost's memory you used:");
35621 @.Here is how much...@>
35622 mp_snprintf (s, 128, " %i string%s using %i character%s",
35623 (int) mp->max_strs_used, (mp->max_strs_used != 1 ? "s" : ""),
35624 (int) mp->max_pl_used, (mp->max_pl_used != 1 ? "s" : ""));
35625 wlog_ln (s);
35626 mp_snprintf (s, 128, " %i bytes of node memory", (int) mp->var_used_max);
35627 wlog_ln (s);
35628 mp_snprintf (s, 128, " %i symbolic tokens", (int) mp->st_count);
35629 wlog_ln (s);
35630 mp_snprintf (s, 128,
35631 " %ii,%in,%ip,%ib,%if stack positions out of %ii,%in,%ip,%ib,%if",
35632 (int) mp->max_in_stack, (int) mp->int_ptr,
35633 (int) mp->max_param_stack, (int) mp->max_buf_stack + 1,
35634 (int) mp->in_open_max - file_bottom, (int) mp->stack_size,
35635 (int) mp->max_internal, (int) mp->param_size, (int) mp->buf_size,
35636 (int) mp->max_in_open - file_bottom);
35637 wlog_ln (s);
35638 }
35639
35640 @ It is nice to have some of the stats available from the API.
35641
35642 @<Exported function ...@>=
35643 int mp_memory_usage (MP mp);
35644 int mp_hash_usage (MP mp);
35645 int mp_param_usage (MP mp);
35646 int mp_open_usage (MP mp);
35647
35648 @ @c
35649 int mp_memory_usage (MP mp) {
35650 return (int) mp->var_used;
35651 }
35652 int mp_hash_usage (MP mp) {
35653 return (int) mp->st_count;
35654 }
35655 int mp_param_usage (MP mp) {
35656 return (int) mp->max_param_stack;
35657 }
35658 int mp_open_usage (MP mp) {
35659 return (int) mp->max_in_stack;
35660 }
35661
35662
35663 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
35664 been scanned.
35665
35666 @c
35667 void mp_final_cleanup (MP mp) {
35668 /* \.{-Wunused}: integer c; */ /* 0 for \&{end}, 1 for \&{dump} */
35669 /* clang: never read: |c = cur_mod();| */
35670 if (mp->job_name == NULL)
35671 mp_open_log_file (mp);
35672 while (mp->input_ptr > 0) {
35673 if (token_state)
35674 mp_end_token_list (mp);
35675 else
35676 mp_end_file_reading (mp);
35677 }
35678 while (mp->loop_ptr != NULL)
35679 mp_stop_iteration (mp);
35680 while (mp->open_parens > 0) {
35681 mp_print (mp, " )");
35682 decr (mp->open_parens);
35683 }
35684 while (mp->cond_ptr != NULL) {
35685 mp_print_nl (mp, "(end occurred when ");
35686 @.end occurred...@>
35687 mp_print_cmd_mod (mp, mp_fi_or_else, mp->cur_if);
35688 /* `\.{if}' or `\.{elseif}' or `\.{else}' */
35689 if (mp->if_line != 0) {
35690 mp_print (mp, " on line ");
35691 mp_print_int (mp, mp->if_line);
35692 }
35693 mp_print (mp, " was incomplete)");
35694 mp->if_line = if_line_field (mp->cond_ptr);
35695 mp->cur_if = mp_name_type (mp->cond_ptr);
35696 mp->cond_ptr = mp_link (mp->cond_ptr);
35697 }
35698 if (mp->history != mp_spotless)
35699 if (((mp->history == mp_warning_issued)
35700 || (mp->interaction < mp_error_stop_mode)))
35701 if (mp->selector == term_and_log) {
35702 mp->selector = term_only;
35703 mp_print_nl (mp,
35704 "(see the transcript file for additional information)");
35705 @.see the transcript file...@>
35706 mp->selector = term_and_log;
35707 }
35708 }
35709
35710
35711 @ @<Declarations@>=
35712 static void mp_final_cleanup (MP mp);
35713 static void mp_init_prim (MP mp);
35714 static void mp_init_tab (MP mp);
35715
35716 @ @c
35717 void mp_init_prim (MP mp) { /* initialize all the primitives */
35718 @<Put each...@>;
35719 }
35720 @#
35721 void mp_init_tab (MP mp) { /* initialize other tables */
35722 @<Initialize table entries@>;
35723 }
35724
35725
35726 @ When we begin the following code, \MP's tables may still contain garbage;
35727 thus we must proceed cautiously to get bootstrapped in.
35728
35729 But when we finish this part of the program, \MP\ is ready to call on the
35730 |main_control| routine to do its work.
35731
35732 @<Get the first line...@>=
35733 {
35734 @<Initialize the input routines@>;
35735 if (!mp->ini_version) {
35736 if (!mp_load_preload_file (mp)) {
35737 mp->history = mp_fatal_error_stop;
35738 return mp;
35739 }
35740 }
35741 @<Initializations following first line@>;
35742 }
35743
35744
35745 @ @<Initializations following first line@>=
35746 mp->buffer[limit] = (ASCII_code) '%';
35747 mp_fix_date_and_time (mp);
35748 if (mp->random_seed == 0)
35749 mp->random_seed = (int)((number_to_scaled (internal_value (mp_time)) / number_to_scaled (unity_t)) + number_to_scaled (internal_value (mp_day)));
35750 init_randoms (mp->random_seed);
35751 initialize_print_selector();
35752 mp_normalize_selector (mp);
35753 if (loc < limit)
35754 if (mp->buffer[loc] != '\\')
35755 mp_start_input (mp); /* \&{input} assumed */
35756
35757 @* Debugging.
35758
35759
35760 @* System-dependent changes.
35761 This section should be replaced, if necessary, by any special
35762 modification of the program
35763 that are necessary to make \MP\ work at a particular installation.
35764 It is usually best to design your change file so that all changes to
35765 previous sections preserve the section numbering; then everybody's version
35766 will be consistent with the published program. More extensive changes,
35767 which introduce new sections, can be inserted here; then only the index
35768 itself will get a new section number.
35769 @^system dependencies@>
35770
35771 @* Index.
35772 Here is where you can find all uses of each identifier in the program,
35773 with underlined entries pointing to where the identifier was defined.
35774 If the identifier is only one letter long, however, you get to see only
35775 the underlined entries. {\sl All references are to section numbers instead of
35776 page numbers.}
35777
35778 This index also lists error messages and other aspects of the program
35779 that you might want to look up some day. For example, the entry
35780 for ``system dependencies'' lists all sections that should receive
35781 special attention from people who are installing \MP\ in a new
35782 operating environment. A list of various things that can't happen appears
35783 under ``this can't happen''.
35784 Approximately 25 sections are listed under ``inner loop''; these account
35785 for more than 60\pct! of \MP's running time, exclusive of input and output.