home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / fweb153.zip / fweb-1.53 / web / eval.web < prev    next >
Text File  |  1995-09-23  |  30KB  |  1,285 lines

  1. @z --- eval.web ---
  2.  
  3. FWEB version 1.53 (September 23, 1995)
  4.  
  5. Based on version 0.5 of S. Levy's CWEB [copyright (C) 1987 Princeton University]
  6.  
  7. @x-----------------------------------------------------------------------------
  8.  
  9.  
  10. \Title{EVAL.WEB} % Expression evaluation for FTANGLE.
  11.  
  12. @c
  13.  
  14. @* EXPRESSION EVALUATION. The following code is used to evaluate
  15. arithmetic, logical, and bit expressions. This is needed in particular in
  16. order to parse conditional expressions for the macro preprocessor, and can
  17. also be called up with the built-in macro |$EVAL|.
  18.  
  19. Three data types are allowed: |int|, |double|, and |sixteen_bits|
  20. (identifier tokens). These are represented by the enumerated types |Int|,
  21. |Double|, and |Id|. The identifier tokens are only allowed in conjunction
  22. with the |defined| command taken from ANSI~C, which is implemented as a
  23. unary operator with the highest precedence. (Actually, the |int|'s are
  24. really |long|, to accomodate the pc~people. We didn't see the need to have
  25. separate |int| and |long| types.)
  26.  
  27. In addition, a fourth type, |Op|, is used to represent unary or binary
  28. operators. 
  29.  
  30. Although the expression evaluator is patterned after ANSI~C, it isn't
  31. complete, and it doesn't behave exactly identically.  In particular, the
  32. order of evaluation isn't necessarily left-to-right.  Presently, I don't
  33. see the need for anything more elaborate, but time will tell.
  34.  
  35. @m _EVaL_ /* Note that the fully upper-case form conflicts with the
  36.         built-in |_EVAL_|! */
  37. @d _EVAL_h
  38.  
  39. @A
  40. @<Include files@>@;
  41. @<Typedef declarations@>@;
  42. @<Prototypes@>@;
  43. @<Global variables@>@;
  44.  
  45. @I typedefs.hweb
  46.  
  47. @I texts.hweb
  48. @I trunc.hweb
  49.  
  50. @ The function prototypes must appear before the global variables.
  51. @<Proto...@>=
  52.  
  53. #include "e_type.h" // Function prototypes for \.{eval}.
  54. #include "r_type.h" // Prototypes for \.{ratfor}.
  55.  
  56. @ Something from \.{ratfor.web}.
  57.  
  58. @f sixteen_bits int
  59. @f token x
  60.  
  61. @I t_codes.hweb
  62.  
  63. @i val.hweb
  64.  
  65. @ For the error messages, we have a function that returns a pointer to the
  66. name of the type.
  67. @a
  68. outer_char *stype FCN((type))
  69.     TYPE type C1("Type whose name is desired.")@;
  70. {
  71. switch(type)
  72.     {
  73.     case Int: return OC("Int");
  74.     case Double: return OC("Double");
  75.     case Id: return OC("Id");
  76.     case Op: return OC("Op");
  77.     default: return OC("UNKNOWN");
  78.     }
  79. }
  80.  
  81. @ Using the previous ingredients, we represent each token by a |VAL|
  82. structure. First, |evaluate| parses the incoming tokens and fills a |VAL|
  83. structure with the correct data value or operator token; it then links it
  84. into a list, which it later traverses to effect the expression evaluation.
  85. The linkage is necessary because items must be removed as unary operators
  86. are evaluated.
  87.  
  88. @<Typedef...@>=
  89.  
  90. /* A static heap of available |VAL| structures. */
  91. VAL HUGE *val_heap; // Allocated at outer level of |evaluate|.
  92. VAL HUGE *val_ptr; // Next available |VAL| in heap.
  93.  
  94. @ The outermost expression evaluator |eval| used for the preprocessor must
  95. return either~1 for true or~0 for false. The actual evaluation routine
  96. |evaluate| is recursive; the following macro makes the outer call to it. It
  97. also allocates and frees the |VAL| heap used during the evaluation.
  98.  
  99. @a
  100. boolean eval FCN((p0,p1))
  101.     CONST eight_bits HUGE *p0 C0("Beginning of tokens.")@;
  102.     CONST eight_bits HUGE *p1 C1("End of tokens.")@;
  103. {
  104. VAL val;
  105.  
  106. EVALUATE(val,p0,p1);
  107.  
  108. switch(val.type)
  109.     {
  110.     case Int: return (boolean)(val.value.i != 0);
  111.     case Double: return (boolean)(val.value.d != 0.0);
  112.     default: 
  113.         EMACRO_ERR("! Non-numeric type returned from eval \
  114. (undefined macro?); assumed FALSE",YES);
  115.         return 0;    // Error in evaluation.
  116.     }
  117. }
  118.  
  119. @ A related routine returns an integer that is the evaluation of the
  120. expression. 
  121. @a
  122. int neval FCN((p0,p1))
  123.     CONST eight_bits HUGE *p0 C0("Beginning of tokens.")@;
  124.     CONST eight_bits HUGE *p1 C1("End of tokens.")@;
  125. {
  126. VAL val;
  127.  
  128. EVALUATE(val,p0,p1);
  129.  
  130. switch(val.type)
  131.     {
  132.     case Int: return (int)(val.value.i);
  133.     case Double: return (int)(val.value.d);
  134.     default: 
  135.         EMACRO_ERR("! Non-numeric type returned from neval \
  136. (undefined macro?); assumed 0",YES);
  137.         return 0;    // Error in evaluation.
  138.     }
  139. }
  140.  
  141. @ Related to |eval| are an important internal macro |$EVAL|, which
  142. evaluates a string expression.
  143. @<Define internal macros@>=
  144.  
  145. SAVE_MACRO("_EVAL(expr)$$EVAL(expr)"); // Expand the expression.
  146. SAVE_MACRO("$EVAL(expr)$$EVAL(expr)"); // Expand the expression.
  147.  
  148. @ Here is the function that evaluates the value of a string.
  149. @a
  150. SRTN i_eval_ FCN((n,pargs))
  151.     int n C0("")@;
  152.     PARGS pargs C1("")@;
  153. {
  154. VAL val;
  155. eight_bits HUGE *p0;
  156.  
  157. CHK_ARGS("$EVAL",1);
  158.  
  159. p0 = pargs[0] + 1;
  160. EVALUATE(val, p0, pargs[1]);
  161.  
  162. @<Write the expansion directly into the |macrobuf|@>;
  163. }
  164.  
  165. @ Here the result of the evaluation is written directly into the
  166. |macrobuf|. If the result failed to evaluate to a number, the original
  167. expression is just copied over.
  168. @<Write the expansion...@>=
  169. {
  170. MCHECK0(2, "expansion |constant|"); 
  171.     // Takes care of the two bracketing |constant|s. 
  172. *mp++ = constant; // Beginning of the |constant|.
  173.  
  174. switch(val.type)
  175.     {
  176.    case Int: 
  177.     NSPRINTF((outer_char *)mp,"%ld",val.value.i); 
  178.     break;
  179.  
  180.    case Double: 
  181.     NSPRINTF((outer_char *)mp,"%#.*g", DBL_DIG, val.value.d); 
  182. // Format guarantees a decimal point.
  183.     break; 
  184.  
  185.    case Id:
  186.     MCHECK0(pargs[1] - p0,"Id");
  187.     mp--; // Backspace to beginning of |constant|.
  188.     while(p0<pargs[1]) *mp++ = *p0++; // Copy it over.
  189.     return;
  190.  
  191.    default:
  192.     EMACRO_ERR("! Invalid type returned from _eval_",YES);
  193.     return;
  194.     }
  195.  
  196. fin_constant(val.type);
  197. }
  198.  
  199. @ The fundamental recursive routine |evaluate| parses a bounded string of
  200. tokens, possibly ended by a special delimiter. It then evaluates the
  201. resulting expression, fills a |VAL| structure with the value, and returns a
  202. pointer to the next unprocessed token.
  203.  
  204. If an error occurs, a cascade of additional messages would be possible. To
  205. prevent this, we use |setjmp| and |longjmp| to get out fast. Because the
  206. evaluation is recursive, we have to jump all the way out of that (with a
  207. |longjmp|), so we make the top level of |evaluate| simple, and call |eval0|
  208. to do the hard work.
  209.  
  210. @m EVAL_ERR(...) 
  211.     {
  212.     EMACRO_ERR(#.); longjmp(top_of_evaluate,1); /* Non-zero
  213.         value signifies the second return from |setjmp|. */
  214.     }
  215.  
  216. @m EMACRO_ERR(...) if(eval_msgs) MACRO_ERR(#.)@;
  217.  
  218. @f jmp_buf int
  219.  
  220. @<Glob...@>=
  221.  
  222. static jmp_buf top_of_evaluate; // Environment for the |setjmp|--|longjmp|./
  223. boolean eval_msgs ESET(YES); // Sometimes we want to suppress the msgs.
  224.  
  225. @ In the top level, we first call |setjmp|. The first call to |setjmp| is
  226. guaranteed to return~0; from this normal return we call |eval0| to actually
  227. evaluate the expression. If a |longjmp| is executed (see the |EVAL_ERR|
  228. macro, it returns from |setjmp| with a nonzero value; we then fill |val|
  229. with a bad data value and return. The function returns a pointer to the
  230. next token to be examined. 
  231. @a
  232. CONST eight_bits HUGE *evaluate FCN((val,p0,p1))
  233.     VAL HUGE *val C0("Return the evaluated |DATA| structure here.")@;
  234.     CONST eight_bits HUGE *p0 C0("Beginning of the input tokens.")@;
  235.     CONST eight_bits HUGE *p1 C1("End of the input tokens.")@;
  236. {
  237. if(setjmp(top_of_evaluate) == 0) return eval0(val,p0,p1,(eight_bits)'\0');
  238.     // Evaluate the expression.
  239. else
  240.     { /* Get here from |longjmp|. */
  241.     val->type = Id; // Flag for bad expression.
  242.     val->value.id = ignore;
  243.     return p1;
  244.     }
  245. }
  246.  
  247. @ The fundamental expression evaluator must be recursive because of
  248. parenthesized expressions. The basic procedure is simple. (1)~Convert the
  249. input string to a linked list, with some added information such as the
  250. precedence of the operators for efficiency; (2)~scan the list (from left to
  251. right) and evaluate all unary operators, proceeding from highest to lowest
  252. precedence; (3)~scan again to evaluate binary operators. This last scan is
  253. done recursively, proceeding from lowest to highest precedence. At a given
  254. precedence, the list is split to the left and to the right of the given
  255. binary operator; each part is evaluated recursively; then the binary
  256. operator is applied. In order to ensure that the final evaluation is from
  257. left to right at a given precedence, the splitting must be done from right
  258. to left. For example, $2\times 2/4$ must be evaluated as $(2\times 2)/(4)$,
  259. not $2\times(2/4)$.  For ease of coding, the first and last |VAL|s in the
  260. list are dummies, having no values. Only their addresses are used to help
  261. terminate the scans.
  262.  
  263. To help speed things up, the array |found_op| is introduced. When the |VAL|
  264. list is first being formed, |found_op| keeps track of how many operators of
  265. a given precedence were encountered. If there are none at a given
  266. precedence, then the list need not be scanned for it. Also, when an
  267. operator is applied, |found_op| is decremented. At the end, |found_op|
  268. should be identically zero.
  269.  
  270. @a
  271. CONST eight_bits HUGE *eval0 FCN((val,p0,p1,delim))
  272.     VAL HUGE *val C0("Return the evaluated |DATA| structure here.")@;
  273.     CONST eight_bits HUGE *p0 C0("Beginning of the input tokens.")@;
  274.     CONST eight_bits HUGE *p1 C0("End of the input tokens.")@;
  275.     eight_bits delim C1("End the scan when this token is encountered.")@;
  276. {
  277. CONST eight_bits HUGE *p;
  278. eight_bits a;
  279. sixteen_bits id;
  280. VAL v_root,v_end; // Dummies to help terminate the list.
  281. VAL HUGE *v; // Current |VAL|.
  282. VAL HUGE *v0= &v_root, HUGE *v1= &v_end; /* Point to the first and
  283.         last elements in the chain. */ 
  284. VAL HUGE *vlast, HUGE *vnext;    // Temporaries.
  285. int prec;
  286. boolean at_start; // Are we at start of list?
  287. eight_bits last_op; /* The first of two consecutive operator tokens. Also
  288.     used as a |boolean| operator; if it's non-zero, the last token was an
  289.     operator. */
  290. int k,found_op[HIGHEST_PRECEDENCE+1];
  291.  
  292. /* Initialize the speed array. */
  293. for(k=LOWEST_PRECEDENCE; k<=HIGHEST_PRECEDENCE; k++) found_op[k] = 0;
  294.  
  295. /* Check for invalid, null expression. */
  296. if(p0>=p1 || *p0==delim)
  297.     {
  298.     EMACRO_ERR("! Null expression encountered during expression \
  299. evaluation; 0 assumed",YES);
  300.     val->type = Int;
  301.     val->value.i = 0;
  302.     
  303.     if(*p0 == delim) return p0+1;
  304.     else return p1;
  305.     }
  306.  
  307. @<Construct the |VAL| list@>@;
  308. @<Reduce the unary operators@>@;
  309.  
  310. /* Traverse the chain beginning at~|v0| and ending at~|v1|, and reduce
  311. binary operations according to precedence. */
  312. v0 = eval1(v0,v1,(PRECEDENCE)LOWEST_PRECEDENCE,found_op);
  313. val->type = v0->type;
  314. val->value = v0->value;
  315.  
  316. for(k=LOWEST_PRECEDENCE; k<=HIGHEST_PRECEDENCE; k++)
  317.     if(found_op[k]) 
  318.         EVAL_ERR("! Missing operand(s) at precedence \
  319. level %d (null macro?)", YES, k);
  320.  
  321. return p;
  322. }
  323.  
  324. @ Here we scan the input string, converting it into a doubly-linked list.
  325. Note that the |VAL| heap was allocated at the beginning; it's not allocated
  326. during recursive calls to |eval0|.
  327.  
  328. One annoyance is that one must pay attention to the two possible uses of a
  329. minus sign. We assume that if it comes first or after another operator
  330. token, it's the unary minus; otherwise, it's the binary operator. To help
  331. us here, we introduce the flag |at_start|.
  332. @<Construct the |VAL|...@>=
  333. {
  334. at_start = YES; // In case of a leading unary minus.
  335. last_op = ignore;
  336.  
  337. for(p=p0,vlast=v0,v=v0->next= ++val_ptr,v->last=vlast; p<p1; )
  338.     {
  339.     if(TOKEN1(a= *p++)) 
  340.         @<Process single-byte token for |VAL| list@>@;
  341.     else 
  342.         @<Process identifier token for |VAL| list@>@;
  343.  
  344. /* This statement is put here rather than as part of the |for| so we can
  345. skip over it if we're skipping a string. */
  346.     vlast=v; @+ v = v->next = ++val_ptr; @+ v->last=vlast;
  347.     }
  348.  
  349. vlast->next = v1; // Terminate the chain forward.
  350. v1->last = vlast;
  351. }
  352.  
  353. @
  354. @<Process single-byte token...@>=
  355. {
  356. if(a==delim) 
  357.     break; // The token |delim| ends the scan.
  358.  
  359. reswitch:
  360. switch(a)
  361.     {
  362.    case @'(':
  363.     last_op = ignore;
  364.     p = eval0(v,p,p1,@')'); 
  365.         // Recursively evaluate parenthesized expressions. 
  366.     break;
  367.  
  368.    case dot_const:
  369.     {
  370.     extern DOTS dots0[];
  371.     DOTS *d;
  372.     int num = *p++;
  373.  
  374.     if(num > PREDEFINED_DOTS) EVAL_ERR("! May only use predefined dot \
  375. constants such as .AND. here",YES);
  376.  
  377.     d = dots0 + num;
  378.  
  379.     if(d->cat == expr) EVAL_ERR("! .FALSE. and .TRUE. are not handled \
  380. by the expression evaluator.  Please use 0 or 1 instead",YES)@;
  381.     if(d->cat != binop) EVAL_ERR("! Invalid dot constant during \
  382. expression evaluation; was expecting binary operator",YES)@;
  383.     a = d->token; // The translation.
  384.     goto reswitch;
  385.     }
  386.  
  387.    case constant:
  388.     last_op = ignore;
  389.     p = vfill(v,p,p1); // Convert constant to data. 
  390.     break;
  391.  
  392.    case stringg:
  393.     while(*p++ != stringg); /* Skip over embedded string, to
  394. overlook verbatim comments. */
  395.     continue;
  396.  
  397.    case @' ':
  398.    case tab_mark:
  399.     continue; // These sneak in during nuweb mode.
  400.  
  401.    case @'-':
  402.     if(last_op || at_start) a = UNARY_MINUS;
  403.     last_op = ignore; // Falls through to |default|.
  404.  
  405.    default:
  406.     if( (prec=(int)precedence(a)) > 0)
  407.         {
  408.         if(last_op && ((IS_UNARY(last_op) && IS_UNARY(a))
  409. || (IS_BINARY(last_op) && IS_BINARY(a)))) 
  410.             EVAL_ERR("! Adjacent operators \"%s %s\" \
  411. not allowed in expression",YES,op_name(last_op),op_name(a))@;
  412.  
  413.         v->type = Op;
  414.         last_op = v->value.op.token = a;
  415.         found_op[(int)(v->value.op.precedence =    (PRECEDENCE)prec)]++;  
  416.         }
  417.     else EVAL_ERR(_Xx("! Invalid token '%c' (0x%x) in \
  418. expression"),YES,a >= @' ' ? a : '?',a)@;
  419.     break;
  420.     }
  421.  
  422. at_start = NO;
  423. }
  424.  
  425. @
  426. @<Process identifier token...@>=
  427. {
  428. at_start = NO; @+ last_op = ignore;
  429.  
  430. if( (id = IDENTIFIER(a,*p++)) == id_defined)
  431.     {
  432.     v->type = Op;
  433.     last_op = v->value.op.token = DEFINED_TOKEN;
  434.     found_op[(int)(v->value.op.precedence =    precedence(DEFINED_TOKEN))]++; 
  435.     }
  436. else
  437.     {
  438.     v->type = Id; // This had better be the argument of |defined|.
  439.     v->value.id = id;
  440.     }
  441. }
  442.  
  443. @ The previous fragment uses the |vfill| function, which
  444. converts a constant expression to bit form and returns a pointer to the
  445. next token to be processed. Note that we must make special provision for
  446. hex, octal, and binary constants, since when programming in~C these are not
  447. converted automatically.
  448. @a
  449. CONST eight_bits HUGE *vfill FCN((v,p0,p1))
  450.     VAL HUGE *v C0("To be filled.")@;
  451.     CONST eight_bits HUGE *p0 C0("Start of expression.")@;
  452.     CONST eight_bits HUGE *p1 C1("End of expression.")@;
  453. {
  454. CONST eight_bits HUGE *p;
  455. eight_bits a;
  456. ASCII temp[100]; // Should be error checked.
  457. ASCII HUGE *t;
  458. TYPE type = Int;
  459.  
  460. /* Put the stuff between |constant| into a temporary buffer. */
  461. for(p=p0,t=temp; p<p1; )
  462.     {
  463.     if( (a=*p++) == constant) break; // Terminating delimiter found.
  464.     
  465.     if(a==@'.' || a==@'e' || a==@'E' || a==@'d' || a==@'D') type = Double;
  466.  
  467.     *t++ = a;
  468.     }
  469.  
  470. *t = '\0';
  471.  
  472. /* Convert the buffer. */
  473. switch(v->type=type)
  474.     {
  475.    case Int:
  476.     if(temp[0] == @'0')
  477.         if(temp[1] == @'x' || temp[1] == @'X') 
  478.             v->value.i = xtoi(temp,t);
  479.         else if(temp[1] == @'b' || temp[1] == @'B') 
  480.             v->value.i = btoi(temp,t);
  481.         else v->value.i = otoi(temp,t);
  482.     else v->value.i = ATOL(to_outer(temp));
  483.     break;
  484.  
  485.    case Double:
  486.     v->value.d = ATOF(to_outer(temp));
  487.     break;
  488.  
  489.    default: 
  490.     CONFUSION("vfill","Type must be Int or Double here");
  491.     }
  492.  
  493. return p;
  494. }
  495.  
  496. @ Here we scan for and reduce the unary operators. This must be done in
  497. order of decreasing precedence.
  498. @<Reduce the unary...@>=
  499.  
  500. for(prec = (int)HIGHEST_UNARY; prec >= (int)UNARY; prec--)
  501.    if(found_op[prec])
  502.     for(v=v0->next; v != v1; v=vnext)
  503.         {
  504.         vnext = v->next;
  505.  
  506.         if(v->type == Op && v->value.op.precedence == (PRECEDENCE)prec)
  507.             {
  508.             switch(v->value.op.token)
  509.                 {
  510.                 case DEFINED_TOKEN:
  511.                     @<Apply |defined| operator@>; @+ break;
  512.  
  513.                 case @'!':
  514.                     @<Negate@>; @+ break;
  515.  
  516.                 case @'~':
  517.                     @<Complement@>;@+ break;
  518.  
  519.                 case UNARY_MINUS:
  520.                     @<Unary minus@>; @+ break;
  521.                 }
  522.  
  523. /* The value is now where the unary operator was; remove the original value
  524. from the list. */
  525.             v->next = vnext->next;
  526.             v->next->last = v;
  527.             vnext = v->next;
  528.  
  529.             if(!(--found_op[prec])) break;
  530.             }
  531.         }
  532.  
  533. @ The routine |eval1| that actually reduces the expressions is recursive.
  534. We scan for operators with the highest precedence and handle those first.
  535. All unary operators with the same precedence can be evaluated on the same
  536. pass. For binary operators, we split into the expressions to the left and
  537. to the right of the operator, and apply |eval1| recursively to each half.
  538. (The splitting must proceed from right to left in order that the final
  539. order of evaluation is left to right.)  Then we can return the result of
  540. the binary operation.
  541.  
  542. @a
  543. VAL HUGE *eval1 FCN((v0,v1,prec0,found_op))
  544.     CONST VAL HUGE *v0 C0("Start of list.")@;
  545.     CONST VAL HUGE *v1 C0("End of list.")@;
  546.     PRECEDENCE prec0 C0("Start scanning with this value of precedence.")@;
  547.     int found_op[] C1("Array of flags---was an operator found at \
  548. each precedence level?")@;
  549. {
  550. int prec;
  551. VAL HUGE *v, 
  552.     HUGE *val0, HUGE *val1; /* Returned pointers from |eval1| to the
  553. left and right operands of a binary operator. */
  554.  
  555. if(v0->next == v1->last) return v0->next; // Reduced down to constant.
  556.  
  557. for(prec=(int)prec0; prec < (int)UNARY; prec++)
  558.    if(found_op[prec])
  559.     for(v=v1->last; v != v0; v=v->last)
  560.         {
  561.         if(v->type == Op && v->value.op.precedence == (PRECEDENCE)prec)
  562.             {
  563.             val0 = eval1(v0,v,(PRECEDENCE)LOWEST_PRECEDENCE,
  564.                     found_op); // Left-hand expression. 
  565.             val1 = eval1(v,v1,(PRECEDENCE)(prec+1),found_op); 
  566.                     // Right-hand expression.
  567.             promote(val0,val1);
  568.  
  569.             @<Process an operator token@>@;
  570.  
  571.             found_op[prec]--;
  572.             return val0;
  573.             }
  574.         }
  575.  
  576. EVAL_ERR("! Missing binary operator, or undefined macro",YES)@;
  577.  
  578. DUMMY_RETURN(NULL);
  579. }
  580.  
  581. @ In the following, note the use of the pseudo-expression to help out the
  582. formatting.
  583. @<Process an operator...@>=
  584.  
  585. switch(v->value.op.token)
  586.     {
  587.     case star_star:
  588.         @<Exponentiate@>; @+ break;
  589.  
  590.     case @'*': ARITH(*@e);
  591.     case @'/': chk_zero('/',val1); @+ ARITH(@e/@e); 
  592.     case @'%': chk_zero('%',val1); @+ BIT(@e%@e);
  593.  
  594.     case @'+': ARITH(@e+@e);
  595.     case @'-': ARITH(-@e);
  596.  
  597.     case lt_lt: BIT(@e<<@e);
  598.     case gt_gt: BIT(@e>>@e);
  599.  
  600.     case @'<': LOG(@e<@e);
  601.     case lt_eq: LOG(@e<=@e);
  602.     case @'>': LOG(@e>@e);
  603.     case gt_eq: LOG(@e>=@e);
  604.  
  605.     case eq_eq: LOG(@e==@e);
  606.     case not_eq: LOG(@e!=@e);
  607.  
  608.     case @'&': BIT(&@e);
  609.     case @'^': case neqv: BIT(@e^@e);
  610.     case @'|': BIT(@e|@e);
  611.  
  612.     case and_and: BIT(@e&&@e);
  613.     case or_or: BIT(@e||@e);
  614.     }
  615.  
  616.  
  617. @ Check an operand for zero.
  618. @a
  619. SRTN chk_zero FCN((c,pv))
  620.     outer_char c C0("Operator.")@;
  621.     CONST VAL HUGE *pv C1("Right-hand operand.")@;
  622. {
  623. boolean is_zero = NO;
  624.  
  625. switch(pv->type)
  626.     {
  627.     case Int:
  628.         if(pv->value.i == 0) is_zero = YES;
  629.         break;
  630.  
  631.     case Double:
  632.         if(pv->value.d == 0.0) is_zero = YES;
  633.         break;
  634.  
  635.     default:
  636.         EVAL_ERR("! Right operand of '%c' must have type Int or \
  637. Double",YES,c)@;
  638.     }
  639.  
  640. if(is_zero) EVAL_ERR("! RIGHT OPERAND OF '%c' IS ZERO",YES,c)@;
  641. }
  642.  
  643. @ Effect logical negation. The result is always |int|.
  644. @<Negate@>=
  645.  
  646. switch(vnext->type)
  647.     {
  648.     case Int:
  649.         v->value.i = !(vnext->value.i);
  650.         break;
  651.  
  652.     case Double:
  653.         v->value.i = !(vnext->value.d);
  654.         break;
  655.  
  656.     default:
  657.         EVAL_ERR("! Can't negate type %s",YES,stype(vnext->type))@;
  658.     }
  659.  
  660. v->type = Int@;
  661.  
  662.  
  663. @ One's complement.
  664. @<Complement@>=
  665.  
  666. if(vnext->type != Int) 
  667.     {
  668.     EMACRO_ERR("! Can't take one's complement of type %s; \
  669. operand converted to integer",YES,stype(vnext->type));
  670.     v->value.i = (long)(vnext->value.d);
  671.     }
  672.  
  673. v->type = Int;
  674. v->value.i = ~vnext->value.i@;
  675.  
  676. @ The unary minus is straightforward.
  677. @<Unary minus@>=
  678.  
  679. switch(v->type = vnext->type)
  680.     {
  681.     case Int:
  682.         v->value.i = -(vnext->value.i); @+ break;
  683.  
  684.     case Double:
  685.         v->value.d = -(vnext->value.d); @+ break;
  686.  
  687.     default:
  688.         EVAL_ERR("! Missing or invalid operand of unary minus \
  689. has type %s",
  690.             NO, stype(v->type))@;
  691.     }
  692.  
  693. @ ANSI's |defined| command is implemented as a unary operator with the
  694. highest precedence. 
  695.  
  696. @<Apply |defined|...@>=
  697. {
  698. text_pointer m;
  699.  
  700. if(vnext->type != Id)
  701.     EVAL_ERR("! 'defined' must act on identifier, not type %s",
  702.         NO,stype(vnext->type))@;
  703. else v->value.i = ((m=mac_lookup(vnext->value.id)) != NULL && !(m->built_in));
  704.  
  705. v->type = Int;
  706. }
  707.  
  708. @ Computing the binary operation is aided by some macros.
  709.  
  710. @d BINARY(l,token) switch(val0->type)
  711.     {
  712.     case Int:
  713.         val0->value.i = val0->value.i token val1->value.i;
  714.         break;
  715.  
  716.     case Double:
  717.         val0->value.l = val0->value.d token val1->value.d; 
  718.         break;
  719.  
  720.     case Id:
  721.         misplaced_id(val0->value.id,val1->value.id);
  722.  
  723.     default:
  724.         EVAL_ERR("! Shouldn't have type Op here",YES)@;
  725.     }
  726.  
  727. @d ARITH(token) BINARY(d,token)@; break@;
  728.  
  729. @d LOG(token) BINARY(i,token)@; val0->type = Int; break@;
  730.  
  731. @d BIT(token) if(val0->type != Int) EVAL_ERR("! Invalid type %s in bit \
  732. operation. (Macro not defined?)",YES,stype(val0->type))@;
  733.     val0->value.i = val0->value.i token val1->value.i;
  734.     break@;
  735.  
  736. @ An error routine.
  737. @a
  738. SRTN misplaced_id FCN((a0,a1))
  739.     sixteen_bits a0 C0("Left-hand token.")@;
  740.     sixteen_bits a1 C1("Right-hand token.")@;
  741. {
  742. outer_char left_id[MAX_ID_LENGTH],right_id[MAX_ID_LENGTH];
  743.  
  744. STRCPY(left_id,name_of(a0));
  745. STRCPY(right_id,name_of(a1));
  746.  
  747. EVAL_ERR("! Identifier not allowed as binary operand:  \
  748. left = \"%s\" (%d), right = \"%s\" (%d).  (Undefined WEB macro?)",
  749.     NO,left_id,a0,right_id,a1)@;
  750. }
  751.  
  752. @ Since C~doesn't have an explicit exponentation token, we have to
  753. implement explicit code.
  754. @<Unused@>=
  755.  
  756. @#if 0
  757. @#if !ANSI
  758. double pow PROTO((double x,double y));
  759. double atof();
  760. @#endif
  761. @#endif
  762.  
  763. @<Exponentiate@>=
  764.  
  765. switch(val0->type)
  766.     {
  767.     case Int:
  768.         val0->value.i = 
  769.            (long)pow((double)val0->value.i,(double)val1->value.i);
  770.         break;
  771.  
  772.     case Double:
  773.         val0->value.d = pow(val0->value.d,val1->value.d);
  774.         break;
  775.  
  776.     default:
  777.         EVAL_ERR("! Invalid operand of exponentiate has type %s",
  778.             NO,stype(val0->type))@;
  779.     }
  780.  
  781. @* PRECEDENCE. A simple routine returns the precedence of a given token. 
  782.  
  783. @d DEFINED_TOKEN OCTAL(23)
  784. @d UNARY_MINUS OCTAL(24)
  785.  
  786. @d LOWEST_PRECEDENCE 1
  787. @d HIGHEST_PRECEDENCE 13
  788.  
  789. /* In the following, the casting shouldn't be necessary, since according to
  790. ANSI |enum|s behave like integers. But it's necessary to keep the |DSU|
  791. compiler happy. */
  792. @d IS_UNARY(token) ((int)precedence(token) >= (int)UNARY)
  793. @d IS_BINARY(token) ((int)precedence(token) < (int)UNARY)
  794.  
  795. @ This function returns the proper precedence of an operator.
  796. @a
  797. PRECEDENCE precedence FCN((token))
  798.     eight_bits token C1("Operator token whose precedence is desired.")@;
  799. {
  800. switch(token)
  801.     {
  802.     case DEFINED_TOKEN:
  803.         return HIGHEST_UNARY;
  804.  
  805. /* --- The unary operators: Logical negation, one's complement, unary minus. */
  806.     case @'!':
  807.     case @'~':
  808.     case UNARY_MINUS:
  809.         return UNARY;
  810.  
  811. /* --- Exponentiation --- */
  812.     case star_star:
  813.         return EXP;
  814.  
  815. /* --- Multiplication, division, modulus --- */
  816.     case @'*':
  817.     case @'/':
  818.     case @'%':
  819.         return TIMES;
  820.  
  821. /* --- Addition, subtraction --- */
  822.     case @'+':
  823.     case @'-':
  824.         return PLUS_MINUS;
  825.  
  826. /* --- Bit shift --- */
  827.     case lt_lt:
  828.     case gt_gt:
  829.         return BIT_SHIFT;
  830.  
  831. /* --- Less than, greater than --- */
  832.     case @'<': case lt_eq:
  833.     case @'>': case gt_eq:
  834.         return LOG_LT;
  835.  
  836. /* --- Equals, not equals --- */
  837.     case eq_eq:
  838.     case not_eq:
  839.         return LOG_EQ;
  840.  
  841. /* --- Bitwise AND --- */
  842.     case @'&':
  843.         return BIT_AND;
  844.  
  845. /* --- Bitwise EXCLUSIVE OR --- */
  846.     case @'^':
  847.     case neqv:
  848.         return BIT_XOR;
  849.  
  850. /* --- Bitwise OR --- */
  851.     case @'|':
  852.         return BIT_OR;
  853.  
  854. /* --- Logical AND --- */
  855.     case and_and:
  856.         return AND_AND;
  857.  
  858. /* --- Logical OR --- */
  859.     case or_or:
  860.         return OR_OR;
  861.  
  862.     default:
  863.         return BAD_TOKEN;
  864.     }
  865. }
  866.  
  867. @ Return a readable representation of an operator token.
  868. @a
  869.  
  870. #define NAME(token,name) case token: return OC(name)@;
  871.  
  872. outer_char *op_name FCN((token))
  873.     eight_bits token C1("Operator token whose name is desired.")@;
  874. {
  875. switch(token)
  876.     {
  877.     NAME(DEFINED_TOKEN,"defined");
  878.     NAME(@'!',"!");
  879.     NAME(@'~',"~");
  880.     NAME(UNARY_MINUS,"-");
  881.     NAME(star_star,"**");
  882.     NAME(@'*',"*");
  883.     NAME(@'/',"/");
  884.     NAME(@'%',"%");
  885.     NAME(@'+',"+");
  886.     NAME(@'-',"-");
  887.     NAME(lt_lt,"<<");
  888.     NAME(gt_gt,">>");
  889.     NAME(@'<',"<");
  890.     NAME(lt_eq,"<=");
  891.     NAME(@'>',">");
  892.     NAME(gt_eq,">=");
  893.     NAME(eq_eq,"==");
  894.     NAME(not_eq,"!=");
  895.     NAME(@'&',"&");
  896.     NAME(@'^',"^");
  897.     NAME(neqv,"?=");
  898.     NAME(@'|',"|");
  899.     NAME(and_and,"&&");
  900.     NAME(or_or,"||");
  901.  
  902.     default: return OC("(UNKNOWN)");
  903.     }
  904. }
  905.  
  906. #undef NAME
  907.  
  908. @ Promote operands to same type.
  909.  
  910. @d TO_DOUBLE(v)    CONVERT_TO(Double,d,double,v)
  911. @d TO_ID(v) CONVERT_TO(Id, id, sixteen_bits, v)
  912.  
  913. @d CONVERT_TO(t,lhs,cast,v) if(v->type != t) 
  914.     {
  915.     v->value.lhs = (cast)v->value.i;
  916.     v->type = t;
  917.     }
  918.  
  919. @a
  920. SRTN promote FCN((v0,v1))
  921.     VAL HUGE *v0 C0("Left-hand value.")@;
  922.     VAL HUGE *v1 C1("Right-hand value.")@;
  923. {
  924. if((int)v0->type > (int)v1->type) convert_to(v0->type,v0,v1);
  925. else convert_to(v1->type,v0,v1);
  926. }
  927.  
  928. SRTN convert_to FCN((type,v0,v1))
  929.     TYPE type C0("Type to be converted to.")@;
  930.     VAL HUGE *v0 C0("Left-hand value.")@;
  931.     VAL HUGE *v1 C1("Right-hand value.")@;
  932. {
  933. switch(type)
  934.     {
  935.     case Int: break;
  936.  
  937.     case Double:
  938.         TO_DOUBLE(v0);
  939.         TO_DOUBLE(v1);
  940.         break;
  941.  
  942.     case Id:
  943.         TO_ID(v0);
  944.         TO_ID(v1);
  945.         break;
  946.  
  947.     default:
  948.         EVAL_ERR("! Invalid data type %s in promotion",
  949.             NO,stype(type))@;
  950.     }
  951. }
  952.  
  953. @* BUILT-IN FUNCTIONS.
  954. Here is a language facility for the preprocessor.
  955.  
  956. @a
  957. SRTN i_lang_ FCN((n,pargs))
  958.     int n C0("")@;
  959.     PARGS pargs C1("")@;
  960. {
  961. outer_char temp[5],*temp1=temp+1;
  962. sixteen_bits l; // The number of the language identifier.
  963.  
  964. CHK_ARGS("$LANGUAGE",0);
  965.  
  966. /* Initialize to \Fortran--77. */
  967. STRCPY(temp,"$N"); // Some compilers don't allow auto initialization.
  968.  
  969. switch(language)
  970.     {
  971.     case C:
  972.         *temp1 = 'C'; @+ break;
  973.  
  974.     case C_PLUS_PLUS:
  975.         STRCPY(temp1,"CPP"); @+ break;
  976.  
  977.     case RATFOR:
  978.         if(!RAT_OK("(_LANGUAGE)")) 
  979.             CONFUSION("_lang_",
  980.                 "Language shouldn't be Ratfor here");
  981.         *temp1 = 'R'; @+ break;
  982.  
  983.     case RATFOR_90:
  984.         if(!RAT_OK("(_LANGUAGE)")) 
  985.             CONFUSION("_lang_",
  986.                 "Language shouldn't be Ratfor here");
  987.         STRCPY(temp1,"R90"); @+ break;
  988.  
  989.     case TEX:
  990.         *temp1 = 'X'; @+ break;
  991.  
  992.     case LITERAL:
  993.         *temp1 = 'V'; @+ break;
  994.  
  995.     case FORTRAN:
  996.     default:
  997.         *temp1 = 'N'; @+ break;
  998.  
  999.     case FORTRAN_90:
  1000.         STRCPY(temp1,"N90"); @+ break;
  1001.     }
  1002.  
  1003. to_ASCII(temp);
  1004. l = ID_NUM((ASCII HUGE *)temp,(ASCII HUGE *)(temp+STRLEN(temp))); 
  1005.     // Get number of the language identifier.
  1006. MCHECK0(2,"language token");
  1007. *mp++ = LEFT(l,ID0); // Return the language token.
  1008. *mp++ = RIGHT(l);
  1009. }
  1010.  
  1011. @ For |$IFCASE| statements, it is useful to obtain the number of the
  1012. current language.
  1013. @a
  1014. SRTN i_lnum_ FCN((n,pargs))
  1015.     int n C0("")@;
  1016.     PARGS pargs C1("")@;
  1017. {
  1018. num_to_mbuf(n,pargs,"$LANGUAGE_NUM",0,"language number",stnd_num(language));
  1019. }
  1020.  
  1021. @ We need a standardized numbering system for use by the external world.
  1022. This numbering should never change, regardless of what we do internally.
  1023. @a
  1024. unsigned stnd_num FCN((Language))
  1025.     LANGUAGE Language C1("")@;
  1026. {
  1027. proper_language:
  1028.  switch(Language)
  1029.     {
  1030.    case C:        return 0;
  1031.    case C_PLUS_PLUS:    return 1;
  1032.    case FORTRAN:    return 2;
  1033.    case FORTRAN_90:    return 3;
  1034.    case RATFOR:        return 4;
  1035.    case RATFOR_90:    return 5;
  1036.    case TEX:        return 6;
  1037.    case LITERAL:    return 7;
  1038.    default:
  1039.     Language = global_language;
  1040.     goto proper_language;
  1041.     }
  1042. }
  1043.  
  1044. @ For completeness, we have an exponentiation built-in.
  1045. @<Define internal...@>=
  1046.  
  1047. SAVE_MACRO("_POW(x,y)$EVAL((x)^^(y))");
  1048. SAVE_MACRO("$POW(x,y)$EVAL((x)^^(y))");
  1049.  
  1050. @ This is an interface to |predefine_macros| in \FTANGLE. 
  1051. @a
  1052. SRTN e_macros(VOID)
  1053. {
  1054. @<Define internal...@>;
  1055. }
  1056.  
  1057.  
  1058. @ Now we generate some mathematical constants.
  1059. @<Define internal...@>=
  1060.  
  1061. SAVE_MACRO("$PI(...)$$CONST(\"$PI\", \".31415926535897932384626433832795028\
  1062. 8419716939937510\",#.)");
  1063.  
  1064. SAVE_MACRO("$E(...)$$CONST(\"$E\", \".2718281828459045235360287471352662497\
  1065. 75724709369995\",#.)");
  1066.  
  1067. SAVE_MACRO("$EXP(x)$POW($E, x)");
  1068. SAVE_MACRO("$SQRT(x)$POW(x, 0.5)");
  1069.  
  1070. @
  1071. @a
  1072. SRTN i_const_ FCN((n,pargs))
  1073.     int n C0("")@;
  1074.     PARGS pargs C1("")@;
  1075. {
  1076. VAL val;
  1077. int prec, carry;
  1078.  
  1079. if(n == 2)
  1080.     prec = DBL_DIG;
  1081. else
  1082.     {
  1083.     CHK_ARGS("$$CONST", 3);
  1084.     EVALUATE(val, pargs[2]+1, pargs[3]);
  1085.     if(val.type != Int)
  1086.         {
  1087.         EMACRO_ERR("! Precision argument of $PI or $E must be an \
  1088. integer; default precision of %d assumed", YES, DBL_DIG);
  1089.         prec = DBL_DIG;
  1090.         }
  1091.     else
  1092.         {
  1093.         prec = (int)MIN(val.value.i, 49L);
  1094.         prec = MAX(prec, 0);
  1095.         }
  1096.     }
  1097.  
  1098. prec += 2; // Take account of the leading digit and the decimal point.
  1099.  
  1100. MCHECK0(prec+2, "math constant");
  1101.  
  1102. *mp++ = constant;
  1103. STRNCPY(mp, pargs[1]+3, prec+1); 
  1104.     /* The '3' accounts for comma, |constant|, and quote.  We get one
  1105. extra so we can round. */
  1106.  
  1107. n = prec;
  1108. carry = (mp[n--] >= @'5');
  1109.  
  1110. while(carry)
  1111.     {
  1112.     mp[n] += 1;
  1113.  
  1114.     if(mp[n] > @'9')
  1115.         mp[n--] = @'0';
  1116.     else
  1117.         break;
  1118.     }
  1119.  
  1120. mp[0] = mp[1];
  1121. mp[1] = @'.';
  1122.  
  1123. mp += prec;
  1124. *mp++ = constant;
  1125. }
  1126.  
  1127. @
  1128. @
  1129. @<Define internal...@>=
  1130.  
  1131. SAVE_MACRO("$LOG(x)$$LOG(0, x)");
  1132. SAVE_MACRO("$LOG10(x)$$LOG(1, x)");
  1133.  
  1134. @
  1135. @a
  1136. SRTN i_log_ FCN((n,pargs))
  1137.     int n C0("")@;
  1138.     PARGS pargs C1("")@;
  1139. {
  1140. int m;
  1141. VAL val;
  1142. double x,y;
  1143.  
  1144. m = *(pargs[0]+2) - @'0';
  1145. EVALUATE(val, pargs[1]+1, pargs[2]);
  1146.  
  1147. if(val.type == Int)
  1148.     x = (double)val.value.i;
  1149. else if(val.type == Double)
  1150.     x = val.value.d;
  1151. else 
  1152.     {
  1153.     EMACRO_ERR("! Invalid argument to $LOG or $LOG10 (undefined \
  1154. macro?); expansion aborted", YES);
  1155.     return;
  1156.     }
  1157.  
  1158. if(m==0)
  1159.     y = log(x);
  1160. else
  1161.     y = log10(x);
  1162.  
  1163. MCHECK0(DBL_DIG+2, "$$LOG");
  1164. *mp++ = constant;
  1165. sprintf((char *)mp, "%#.*g", DBL_DIG, y);
  1166.  
  1167. fin_constant(Double);
  1168. }
  1169.  
  1170. @ Here we finish the process of putting a constant into the macro buffer.
  1171. Fundamentally we must convert it to |ASCII| and terminate it with
  1172. |constant|.  Also, if the constant is floating point, we kill off trailing
  1173. zeros, except we leave one zero after the decimal point.
  1174.  
  1175. @a
  1176. SRTN fin_constant FCN((type))
  1177.     TYPE type C1("")@;
  1178. {
  1179. int n = STRLEN(mp);
  1180.  
  1181. if(type == Double)
  1182.     while(mp[n-1] == @'0')
  1183.         {
  1184.         if(mp[n-2] == @'.')
  1185.             break;
  1186.  
  1187.         n--;
  1188.         }
  1189.     
  1190. to_ASCII(mp);
  1191. mp += n;
  1192. *mp++ = constant;
  1193. }
  1194.  
  1195. @
  1196. @<Define internal...@>=
  1197.  
  1198. SAVE_MACRO("_MIN(a,...)$$MIN_MAX(0, a, #.)");
  1199. SAVE_MACRO("$MIN(a,...)$$MIN_MAX(0, a, #.)");
  1200.  
  1201. SAVE_MACRO("_MAX(a,...)$$MIN_MAX(1, a, #.)");
  1202. SAVE_MACRO("$MAX(a,...)$$MIN_MAX(1, a, #.)");
  1203.  
  1204. @ The |$MIN| amd |$MAX| functions take at least one, possibly more
  1205. arguments.  The annoyance in the logic is to avoid promoting |int|s to
  1206. |double|s if everything is an |int|.
  1207.  
  1208. @a
  1209. SRTN i_min_max_ FCN((n,pargs))
  1210.     int n C0("")@;
  1211.     PARGS pargs C1("")@;
  1212. {
  1213. int m = *(pargs[0]+2) - @'0';
  1214. long l = 0; // Accumulator for integers.
  1215. double z = 0; // Acuumulator for floating point.
  1216. double v = 0;
  1217. VAL val;
  1218. TYPE type;
  1219. int k;
  1220.  
  1221. EVALUATE(val, pargs[1]+1, pargs[2]); // Obtain the first value.
  1222.  
  1223. type = val.type;
  1224.  
  1225. if(type == Int)
  1226.     l = val.value.i;
  1227. else
  1228.     z = val.value.d;
  1229.  
  1230. for(k=2; k<n; k++)
  1231.     {
  1232.     EVALUATE(val, pargs[k]+1, pargs[k+1]);
  1233.  
  1234.     if(val.type == Double)
  1235.         {
  1236.         if(type == Int)
  1237.             z = (double)l; // From now, accumulate floating point.
  1238.  
  1239.         type = Double;
  1240.         }
  1241.  
  1242.     if(type == Double)
  1243.         if(val.type == Int)
  1244.             v = (double)val.value.i;
  1245.         else
  1246.             v = val.value.d;
  1247.  
  1248.     if(type == Int)
  1249.         if(m == 0)
  1250.             {
  1251.             if(val.value.i < l)
  1252.                 l = val.value.i;
  1253.             }
  1254.         else
  1255.             {
  1256.             if(val.value.i > l)
  1257.                 l = val.value.i;
  1258.             }
  1259.     else
  1260.         if(m == 0)
  1261.             {
  1262.             if(v < z)
  1263.                 z = v;
  1264.             }
  1265.         else
  1266.             {
  1267.             if(v > z)
  1268.                 z = v;
  1269.             }
  1270.     }
  1271.  
  1272. MCHECK0(DBL_DIG+2, "min_max");
  1273. *mp++ = constant;
  1274.  
  1275. if(type == Int)
  1276.     sprintf((char *)mp, "%ld", l);
  1277. else
  1278.     sprintf((char *)mp, "%#.*g", DBL_DIG, z);
  1279.  
  1280. fin_constant(type);
  1281. }
  1282.         
  1283. @* INDEX.
  1284.