File: parse.c

package info (click to toggle)
mathomatic 12.1c-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 812 kB
  • ctags: 499
  • sloc: ansic: 14,790; makefile: 105
file content (613 lines) | stat: -rw-r--r-- 16,697 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/*
 * Algebraic manipulator help command and parsing routines.
 *
 * Copyright (c) 1996 George Gesslein II.
 */

#include "am.h"
#include "externs.h"

/* The Mathomatic command list follows.  It must be in alphabetical order. */
com_type	com_list[] = {
	"calculate",	calculate,	"[variable number-of-iterations]",		"Temporarily plug values into the RHS and display.  Option to iterate.",
	"clear",	clear,		"[equation-number-range]",			"Delete equations so equation space can be reused.",
	"code",		list_code,	"[\"c\" or \"java\" or \"integer\"] [equation-number-range]",	"Output C or Java code for the specified equations.",
	"compare",	compare,	"equation-number [\"with\" equation-number]",	"Compare two equations to see if they are the same.",
	"copy",		copy_cmd,	"[equation-number-range]",			"Duplicate the specified equations.",
	"derivative",	derivative,	"variable or \"all\" [order]",			"Differentiate the RHS of the current equation, order times.",
	"divide",	divide_cmd,	"[variable]",					"Prompt for 2 polynomials/numbers and divide.  Display result and GCD.",
#if	(UNIX || CYGWIN) && !SECURE
	"edit",		edit,		"[file-name]",					"Edit your equations or an input file.",
#endif
	"eliminate",	eliminate,	"variables or \"all\" [\"using\" equation-number]",	"Substitute the specified variables with solved equations.",
	"extrema",	extrema_cmd,	"variable",					"Find the minimums and maximums of the current equation.",
	"factor",	factor,		"[\"number\" [integers]] or [equation-number-range] [variables]",	"Factor integers or equations.  For polynomial factoring, use \"simplify\".",
	"group",	group_cmd,	"[\"factor\"] [equation-number-range]",		"Display equations in fraction format.  Option to factor integers.",
	"help",		help,		"[topic or command-name]",			"Short, built-in help.",
	"imaginary",	imaginary,	"[equation-number]",				"Copy the imaginary part of an equation (see the \"real\" command).",
	"integrate",	integrate_cmd,	"variable [order]",				"Integrate the RHS of the current equation, order times.",
	"laplace",	laplace_cmd,	"[\"inverse\"] variable",			"Compute the Laplace or inverse Laplace transform of the RHS.",
	"limit",	limit_cmd,	"variable expression",				"Take the limit of the current equation as variable goes to expression.",
	"list",		list_cmd,	"[\"export\"] [equation-number-range]",		"Display equations in single line format.  Option for exportable format.",
	"optimize",	optimize_cmd,	"[equation-number]",				"Split up an equation into smaller multiple equations.",
	"pause",	pause_cmd,	"",						"Wait for user to press the Enter key.",
	"product",	product_cmd,	"variable low high",				"Compute the product of the RHS of the current equation.",
	"quit",		quit,		"",						"Terminate this program.  All equations in memory are lost.",
#if	!SECURE
	"read",		read_in,	"file-name",					"Read in a text file as if it was typed in.",
#endif
	"real",		real,		"[equation-number]",				"Copy the real part of an equation (see the \"imaginary\" command).",
	"replace",	replace,	"[variables [\"with\" expression]]",		"Substitute variables in both sides of an equation with expressions.",
	"roots",	roots,		"",						"Display all the roots of a complex number.",
#if	!SECURE
	"save",		save,		"file-name",					"Save all equations in a text file (restore with the \"read\" command).",
#endif
	"sensitivity",	sensitivity,	"variables",					"Compute the exact sensitivity equation.",
	"set",		set_cmd,	"[\"no\"] [option]",				"Set various session options.",
	"simplify",	simplify,	"[\"symbolic\" or \"quick\" or \"poly\"] [equation-number-range]",	"Completely simplify equations.",
	"sum",		sum_cmd,	"variable low high",				"Compute the summation of the RHS of the current equation.",
	"tally",	tally,		"",						"Prompt for and add numerical entries.  Show running total.",
	"taylor",	taylor,		"variable",					"Compute the Taylor series expansion of the RHS, with respect to variable.",
	"unfactor",	unfactor,	"[\"fully\"] [equation-number-range]",		"Expand equations."
};

int	point_flag;	/* point to error if true */

/*
 * Process a line of input to Mathomatic.
 * It may be a command, an equation, etc.
 * Return true if successful.
 */
int
process(cp)
char	*cp;
{
	char	*cp1, *cp2;
	char	*cp_start;
	int	i, j;
	int	n;
	int	simp_flag;
	int	rv;
	char	buf2[MAX_CMD_LEN];
	int	i1;
	char	*filename;
	FILE	*fp;
	int	append_flag;

	set_sign_array();
	cp_start = cp;
	simp_flag = true;
	set_error_level(cp);
	cp = skip_space(cp);
	if (*cp == '#') {
		cp++;
		if (isascii(*cp) && isdigit(*cp)) {
			i = atoi(cp) - 1;
			if (i < 0 || i >= n_equations) {
				put_up_arrow((int) (cp - cp_start));
				printf(_("Equation number out of range.\n"));
				return false;
			}
			cp = skip_num(cp);
			if (*cp == ':') {
				simp_flag = false;
				cp++;
			}
			cp = skip_space(cp);
			if (*cp) {
				n = i;
				goto e_parse;
			}
			cur_equation = i;
			list_sub(cur_equation);
		}
		return true;
	}
#if	!SECURE
	if (*cp == '!') {
		cp++;
		cp = skip_space(cp);
		if (*cp) {
			return(!shell_out(cp));
		}
		cp1 = getenv("SHELL");
		if (cp1) {
			return(!shell_out(cp1));
		}
		return false;
	}
#endif
/* See if the string pointed to by "cp" is a command. */
/* If so, execute it. */
	cp1 = cp;
	while (*cp1 && isascii(*cp1) && isalpha(*cp1))
		cp1++;
	for (i = 0; i < ARR_CNT(com_list); i++) {
		if (strlen(com_list[i].name) < 4) {
			if ((cp1 - cp) != strlen(com_list[i].name))
				continue;
		} else {
			if ((cp1 - cp) < 4)
				continue;
		}
		if (strncasecmp(cp, com_list[i].name, cp1 - cp) == 0) {
			cp1 = skip_space(cp1);
			input_column += (cp1 - cp_start);
			for (cp2 = cp1, j = 0; *cp2; cp2++, j++) {
				if (j >= (sizeof(buf2) - 1)) {
					printf(_("Error: Command line too long.\n"));
					return false;
				}
				buf2[j] = *cp2;
			}
			buf2[j] = '\0';
			cp2 = buf2;
			fp = NULL;
#if	!SECURE
			append_flag = false;
			filename = NULL;
			for (i1 = strlen(cp2) - 1; i1 >= 0; i1--) {
				if (cp2[i1] == '>') {
					filename = skip_space(&cp2[i1+1]);
					if (i1 && cp2[i1-1] == '>') {
						i1--;
						append_flag = true;
					}
					cp2[i1] = '\0';
					break;
				}
			}
			if (filename) {
				if (append_flag) {
					fp = fopen(filename, "a");
				} else {
					fp = fopen(filename, "w");
				}
				if (fp == NULL) {
					printf(_("Can't open '%s' for writing.\n"), filename);
					return false;
				}
				gfp = fp;
			}
#endif
/* remove trailing spaces from the command line */
		        i1 = strlen(cp2) - 1;
		        while (i1 >= 0 && isascii(cp2[i1]) && isspace(cp2[i1])) {
        		        cp2[i1] = '\0';
                		i1--;
			}
/* execute the command */
			rv = (*com_list[i].func)(cp2);
#if	!SECURE
			if (fp) {	/* if output redirected, close file */
				if (gfp != stdout)
					fclose(gfp);
				else
					fclose(fp);
				gfp = stdout;
			}
#endif
#if	false
			if (!rv) {
				printf(_("Usage: %s %s\n"), com_list[i].name, com_list[i].usage);
			}
#endif
			return rv;
		}
	}
/* "cp" is not a command, so parse the expression or equation. */
	n = next_espace();
e_parse:
	if (!case_sensitive_flag) {
		str_tolower(cp);
	}
	input_column += (cp - cp_start);
	cp_start = cp;
	if ((cp = parse_section(lhs[n], &n_lhs[n], cp)) != NULL) {
		input_column += (cp - cp_start);
		if ((cp = parse_section(rhs[n], &n_rhs[n], cp)) != NULL) {
			if (n_lhs[n] == 0 && n_rhs[n] == 0)
				return true;
			if (n_lhs[n] == 0 || n_rhs[n] == 0) {
				if ((n_lhs[n] == 1 && (lhs[n][0].kind != CONSTANT || lhs[n][0].token.constant == 0.0)
				    && !(lhs[n][0].kind == VARIABLE && lhs[n][0].token.variable < IMAGINARY))
				    || (n_rhs[n] == 1 && (rhs[n][0].kind != CONSTANT || rhs[n][0].token.constant == 0.0)
				    && !(rhs[n][0].kind == VARIABLE && rhs[n][0].token.variable < IMAGINARY))) {
					if (solve(n, cur_equation)) {
						list_sub(cur_equation);
						return true;
					}
					return false;
				}
				if (n_lhs[n]) {
					blt(rhs[n], lhs[n], n_lhs[n] * sizeof(token_type));
					n_rhs[n] = n_lhs[n];
				}
				lhs[n][0].level = 1;
				lhs[n][0].kind = VARIABLE;
				lhs[n][0].token.variable = SPECIAL;
				n_lhs[n] = 1;
				for (i = 0; i < n_rhs[n]; i += 2) {
					if (rhs[n][i].kind == VARIABLE
					    && (rhs[n][i].token.variable & VAR_MASK) > SIGN) {
						printf(_("You may enter a numerical expression, or an algebraic equation,\n"));
						printf(_("or a variable to solve for, or a command (like \"help\" or \"quit\").\n"));
						n_lhs[n] = 0;
						return false;
					}
				}
				i = cur_equation;
				cur_equation = n;
				calculate("");
				cur_equation = i;
				n_lhs[n] = 0;
				return true;
			}
			cur_equation = n;
			if (simp_flag) {
				simp_sub(n);
			} else {
				organize(lhs[n], &n_lhs[n]);
				organize(rhs[n], &n_rhs[n]);
			}
			list_sub(cur_equation);
			return true;
		}
	}
	n_lhs[n] = 0;
	return false;
}

#if	!SECURE
/*
 * Execute a system command.
 * Returns exit value of command (0 if no error).
 */
int
shell_out(cp)
char	*cp;
{
	int	rv;

	reset_attr();
	rv = system(cp);
	default_color();
	return rv;
}
#endif

#include "parse.h"

char	*
parse_var2(vp, cp)
long	*vp;
char	*cp;
{
	char	*cp1;

	cp = skip_space(cp);
	cp = parse_var(vp, cp);
	if (cp == NULL) {
		printf(_("Invalid variable.\n"));
		return NULL;
	}
	if (*cp) {
		cp1 = skip_space(cp);
		if (cp == cp1) {
			printf(_("Please separate variables with spaces.\n"));
			return NULL;
		}
		return cp1;
	}
	return cp;
}

set_error_level(cp)
char	*cp;
{
	char	*cp1;

	point_flag = true;
/* remove trailing newlines */
	cp1 = &cp[strlen(cp)];
	while (cp1 != cp) {
		cp1--;
		if (*cp1 == '\n' || *cp1 == '\r') {
			*cp1 = '\0';
		} else
			break;
	}
/* don't point to error if input contains tabs */
	for (cp1 = cp; *cp1; cp1++) {
		if (isspace(*cp1) && *cp1 != ' ') {
			point_flag = false;
			break;
		}
	}
/* handle comments */
	for (cp1 = cp; *cp1; cp1++) {
		if (*cp1 == ';') {
			*cp1 = '\0';
			break;
		}
	}
}

/*
 * Display an up arrow pointing to the error under the input string.
 */
put_up_arrow(cnt)
int	cnt;	/* position of error, relative to "input_column" */
{
	int	 i;

	if (piping_in_flag)
		return;
	if (!point_flag)
		return;
	for (i = 0; i < (input_column + cnt); i++) {
		printf(" ");
	}
	printf("^ ");
}

/*
 * Return true if the first word in the passed string is "all".
 */
int
is_all(cp)
char	*cp;
{
	return(strcmp_tospace(cp, "all") == 0);
}

/*
 * Process an equation number range.
 * Return true if successful,
 * with the starting equation number in "*ip"
 * and ending equation number in "*jp".
 */
int
get_range(cpp, ip, jp)
char	**cpp;
int	*ip, *jp;
{
	int	i;

	if (is_all(*cpp)) {
		*cpp = skip_param(*cpp);
		*ip = 0;
		*jp = n_equations - 1;
		goto test_range;
	}
	if (isascii(**cpp) && isdigit(**cpp)) {
		*ip = atoi(*cpp) - 1;
	} else {
		*ip = cur_equation;
	}
	if (*ip < 0 || *ip >= n_equations) {
		printf(_("Invalid equation number.\n"));
		return false;
	}
	*cpp = skip_num(*cpp);
	if (**cpp != '-') {
		if (notdefined(*ip)) {
			return false;
		}
		*jp = *ip;
		return true;
	}
	(*cpp)++;
	*cpp = skip_space(*cpp);
	if (isascii(**cpp) && isdigit(**cpp)) {
		*jp = atoi(*cpp) - 1;
	} else {
		*jp = cur_equation;
	}
	if (*jp < 0 || *jp >= n_equations) {
		printf(_("Invalid equation number.\n"));
		return false;
	}
	if (*jp < *ip) {
		i = *ip;
		*ip = *jp;
		*jp = i;
	}
	*cpp = skip_num(*cpp);
test_range:
	for (i = *ip; i <= *jp; i++) {
		if (n_lhs[i] > 0) {
			return true;
		}
	}
	printf(_("No equations defined in specified range.\n"));
	return false;
}

/*
 * This function is provided to make sure there is nothing else
 * on a command line.
 */
int
extra_garbage(cp)
char	*cp;
{
	cp = skip_space(cp);
	if (*cp) {
		printf(_("ERROR: Extra characters on command line.\n"));
		return true;
	}
	return false;
}

/*
 * Skip over digits and any spaces that follow.
 */
char	*
skip_num(cp)
char	*cp;
{
	while (*cp && isascii(*cp) && isdigit(*cp))
		cp++;
	return skip_space(cp);
}

/*
 * Skip over space characters.
 */
char	*
skip_space(cp)
char	*cp;
{
	while (*cp && isascii(*cp) && isspace(*cp))
		cp++;
	return cp;
}

/*
 * Skip over a parameter (command line argument).
 */
char	*
skip_param(cp)
char	*cp;
{
	while (*cp && (!isascii(*cp) || (!isspace(*cp) && *cp != '='))) {
		cp++;
	}
	cp = skip_space(cp);
	if (*cp == '=') {
		cp++;
		cp = skip_space(cp);
	}
	return(cp);
}

/*
 * Compare strings up to the first space.
 * Must be an exact match.
 * Compare is alphabetic case insensitive.
 */
int
strcmp_tospace(cp1, cp2)
char	*cp1, *cp2;
{
	char	*cp1a, *cp2a;

	for (cp1a = cp1; *cp1a && (!isascii(*cp1a) || !isspace(*cp1a)); cp1a++)
		;
	for (cp2a = cp2; *cp2a && (!isascii(*cp2a) || !isspace(*cp2a)); cp2a++)
		;
	return strncasecmp(cp1, cp2, max(cp1a - cp1, cp2a - cp2));
}

#define P(A)	fprintf(gfp, "%s\n", A)

/*
 * The help command.
 */
help(cp)
char	*cp;
{
	int	i, j;
	char	*cp1;
	int	flag;
	int	row;

	cp1 = cp;
	while (*cp1 && !(isascii(*cp1) && isspace(*cp1)))
		cp1++;
	if (cp1 != cp) {
		flag = false;
		for (i = 0; i < ARR_CNT(com_list); i++) {
			if (strncasecmp(cp, com_list[i].name, cp1 - cp) == 0) {
				fprintf(gfp, "%s - %s\n", com_list[i].name, com_list[i].info);
				fprintf(gfp, "Usage: %s %s\n\n", com_list[i].name, com_list[i].usage);
				flag = true;
			}
		}
		if (flag)
			return true;
		if (strncasecmp(cp, "usage", cp1 - cp) == 0) {
			for (i = 0; i < ARR_CNT(com_list); i++) {
				fprintf(gfp, "%s %s\n", com_list[i].name, com_list[i].usage);
			}
			return true;
		}
		if (strncasecmp(cp, "geometry", cp1 - cp) == 0) {
			P("Commonly Used Geometric Formulas");
			P("--------------------------------\n");
			P("Triangle of base 'b' and height 'h':");
			P("    Area = b*h/2\n");
			P("Rectangle of length 'l' and width 'w':");
			P("    Area = l*w               Perimeter = 2*l + 2*w\n");
			P("Trapezoid of height 'h' and parallel sides 'a' and 'b':");
			P("    Area = h*(a+b)/2\n");
			P("Circle of radius 'r':");
			P("    Area = pi*r^2            Perimeter = 2*pi*r\n");
			P("Rectangular solid of length 'l', width 'w', and height 'h':");
			P("    Volume = l*w*h           Surface area = 2*l*w + 2*l*h + 2*w*h\n");
			P("Sphere of radius 'r':");
			P("    Volume = 4/3*pi*r^3      Surface area = 4*pi*r^2\n");
			P("Right circular cylinder of radius 'r' and height 'h':");
			P("    Volume = pi*r^2*h        Surface area = 2*pi*r*(h+r)");
			return true;
		}
		if (strncasecmp(cp, "equations", cp1 - cp) == 0) {
			P("To enter an equation, simply type it in at the prompt.");
			P("Operators have precedence decreasing as indicated:\n");
			P("    - negate");
			P("    ! factorial");
			P("    ^ power");
			P("    * multiply          / divide            % modulus");
			P("    + add               - subtract\n");
			P("Operators in the same precedence level are evaluated left to right.\n");
			P("Variables consist of any combination of letters, numbers,");
			P("and underscores (_).  Variables always start with a letter.");
			P("Predefined constants and variables:\n");
			P("    e# - The universal constant e (2.718281828...).");
			P("    p# or pi - The universal constant pi (3.1415926...).");
			P("    i# - Imaginary Number (square root of -1).");
			P("    sign, sign1, sign2, sign3, ... - may be +1 or -1.");
			P("    integer - may be any integer.\n");
			P("Each equation must have one, and only one, equals sign (=).");
			P("Absolute value notation (|x|) and \"+/-\" are understood.");
			return true;
		}
		if (is_all(cp)) {
			for (i = 0, row = 1;; i++) {
				if (screen_rows && row >= (screen_rows - 3)) {
					row = 1;
					if (!pause_cmd(""))
						return false;
					printf("\n");
				}
				if (i >= ARR_CNT(com_list))
					break;
				fprintf(gfp, "%s - %s\n", com_list[i].name, com_list[i].info);
				fprintf(gfp, "Usage: %s %s\n\n", com_list[i].name, com_list[i].usage);
				row += 3;
			}
			P("End of command list.");
			return true;
		}
	}
	P("This \"help\" command is provided as a quick reference.");
	P("Type \"help all\" for a summary of the all commands.");
	P("Type \"help usage\" for syntax of all commands.");
	P("Type \"help equations\" for help with entering equations.");
	P("Type \"help geometry\" for some commonly used geometric formulas.");
	P("\"help\" followed by a command name will give info on a command.\n");
	P("The following is a list of available commands:\n");
	for (i = 0; i < ARR_CNT(com_list); i++) {
		if (i && (i % 4) == 0)
			fprintf(gfp, "\n");
		fprintf(gfp, "%s", com_list[i].name);
		j = 19 - strlen(com_list[i].name);
		for (; j > 0; j--)
			fprintf(gfp, " ");
	}
	P("\n\nTo select an equation in memory, enter \"#\" followed by the equation number.");
	P("For example, to select equation number 2, enter \"#2\" at the prompt.");
	P("\nTo solve an equation, simply type the variable name at the prompt.");
	return true;
}