[system] / trunk / pg / lib / Parser.pm Repository:
ViewVC logotype

View of /trunk/pg/lib/Parser.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2985 - (download) (as text) (annotate)
Wed Nov 3 22:39:21 2004 UTC (15 years, 2 months ago) by dpvc
File size: 24377 byte(s)
Fixed a bug in processing absolute values with implicit
multiplication.

    1 package Parser;
    2 my $pkg = "Parser";
    3 use strict;
    4 
    5 BEGIN {
    6   #
    7   #  Map class names to packages (added to Context, and
    8   #  can be overriden to customize the parser)
    9   #
   10   our $class = {Formula => 'Value::Formula'};
   11 
   12   #
   13   #  Collect the default reduction flags for use in the context
   14   #
   15   our $reduce = {};
   16 }
   17 
   18 ##################################################
   19 #
   20 #  Parse a string and create a new Parser object
   21 #  If the string is already a parsed object then copy the parse tree
   22 #  If it is a Value, make an appropriate tree for it.
   23 #
   24 sub new {
   25   my $self = shift;
   26   my $context = Parser::Context->current;
   27   my $class = $context->{parser}{Formula};
   28   my $string = shift;
   29   $string = Value::List->new($string,@_)
   30     if scalar(@_) > 0 || ref($string) eq 'ARRAY';
   31   my $math = bless {
   32     string => undef,
   33     tokens => [], tree => undef,
   34     variables => {}, values => {},
   35     context => $context,
   36   }, $class;
   37   if (ref($string) =~ m/^(Parser|Value::Formula)/) {
   38     my $tree = $string; $tree = $tree->{tree} if exists $tree->{tree};
   39     $math->{tree} = $tree->copy($math);
   40   } elsif (Value::isValue($string)) {
   41     $math->{tree} = $math->{context}{parser}{Value}->new($math,$string);
   42   } else {
   43     $math->{string} = $string;
   44     $math->tokenize;
   45     $math->parse;
   46   }
   47   return $math;
   48 }
   49 
   50 sub copy {my $self = shift; $self->new($self)}
   51 
   52 ##################################################
   53 #
   54 #  Break the string into tokens based on the patterns for the various
   55 #  types of objects.
   56 #
   57 sub tokenize {
   58   my $self = shift; my $space;
   59   my $tokens = $self->{tokens}; my $string = $self->{string};
   60   my $tokenPattern = $self->{context}{pattern}{token};
   61   @{$tokens} = (); $self->{error} = 0; $self->{message} = '';
   62   $string =~ m/^\s*/gc; my $p0 = 0; my $p1;
   63   while (pos($string) < length($string)) {
   64     $p0 = pos($string);
   65     if ($string =~ m/\G$tokenPattern/gc) {
   66       $p1 = pos($string);
   67       push(@{$tokens},['str',$1,$p0,$p1,$space])   if (defined($1));
   68       push(@{$tokens},['fn',$2,$p0,$p1,$space])    if (defined($2));
   69       push(@{$tokens},['const',$3,$p0,$p1,$space]) if (defined($3));
   70       push(@{$tokens},['num',$4,$p0,$p1,$space])   if (defined($4));
   71       push(@{$tokens},['op',$5,$p0,$p1,$space])    if (defined($5));
   72       push(@{$tokens},['open',$6,$p0,$p1,$space])  if (defined($6));
   73       push(@{$tokens},['close',$7,$p0,$p1,$space]) if (defined($7));
   74       push(@{$tokens},['var',$8,$p0,$p1,$space])   if (defined($8));
   75     } else {
   76       push(@{$tokens},['error',substr($string,$p0,1),$p0,$p0+1]);
   77       $self->{error} = 1;
   78       last;
   79     }
   80     $space = ($string =~ m/\G\s+/gc);
   81   }
   82 }
   83 
   84 ##################################################
   85 #
   86 #  Parse the token list to produce the expression tree.  This does syntax checks
   87 #  and reports "compile-time" errors.
   88 #
   89 #  Start with a stack that has a single entry (an OPEN object for the expression)
   90 #  For each token, try to add that token to the tree.
   91 #  After all tokens have been finished, add a CLOSE object for the initial OPEN
   92 #    and save the complete tree
   93 #
   94 sub parse {
   95   my $self = shift;
   96   $self->{tree} = undef; $self->{error} = 0;
   97   $self->{stack} = [{type => 'open', value => 'start'}];
   98   foreach my $ref (@{$self->{tokens}}) {
   99     $self->{ref} = $ref; $self->{space} = $ref->[4];
  100     for ($ref->[0]) {
  101       /open/  and do {$self->Open($ref->[1]); last};
  102       /close/ and do {$self->Close($ref->[1],$ref); last};
  103       /op/    and do {$self->Op($ref->[1],$ref); last};
  104       /num/   and do {$self->Num($ref->[1]); last};
  105       /const/ and do {$self->Const($ref->[1]); last};
  106       /var/   and do {$self->Var($ref->[1]); last};
  107       /fn/    and do {$self->Fn($ref->[1]); last};
  108       /str/   and do {$self->Str($ref->[1]); last};
  109       /error/ and do {$self->Error("Unexpected character '$ref->[1]'",$ref); last};
  110     }
  111     return if ($self->{error});
  112   }
  113   $self->Close('start'); return if ($self->{error});
  114   $self->{tree} = $self->{stack}[0]{value};
  115 }
  116 
  117 
  118 #  Get the top or previous item of the stack
  119 #
  120 sub top {
  121   my $self = shift; my $i = shift || 0;
  122   return $self->{stack}[$i-1];
  123 }
  124 sub prev {(shift)->top(-1)}
  125 
  126 #
  127 #  Push or pop the top of the stack
  128 #
  129 sub pop {pop(@{(shift)->{stack}})}
  130 sub push {push(@{(shift)->{stack}},@_)}
  131 
  132 #
  133 #  Return the type of the top item
  134 #
  135 sub state {(shift)->top->{type}}
  136 
  137 #
  138 #  Report an error at a given possition (if possible)
  139 #
  140 sub Error {
  141   my $self = shift; my $context = $self->{context};
  142   my $message = shift; my $ref = shift; my $string;
  143   if ($ref) {
  144     $message .= "; see position ".($ref->[2]+1)." of formula";
  145     $string = $self->{string};
  146     $ref = [$ref->[2],$ref->[3]];
  147   }
  148   $context->setError($message,$string,$ref);
  149   die $message . Value::getCaller();
  150 }
  151 
  152 #
  153 #  Insert an implicit multiplication
  154 #  (fix up the reference for spaces or juxtaposition)
  155 #
  156 sub ImplicitMult {
  157   my $self = shift;
  158   my $ref = $self->{ref}; my $iref = [@{$ref}];
  159   $iref->[2]--; $iref->[3] = $iref->[2]+1;
  160   $iref->[3]++ unless substr($self->{string},$iref->[2],1) eq ' ';
  161   $self->Error("Can't perform implied multiplication in this context",$iref)
  162     unless $self->{context}{operators}{' '}{class};
  163   $self->Op(' ',$iref);
  164   $self->{ref} = $ref;
  165 }
  166 
  167 #
  168 #  Push an operator onto the expression stack.
  169 #  We save the operator symbol, the precedence, etc.
  170 #
  171 sub pushOperator {
  172   my $self = shift;
  173   my ($op,$precedence,$reverse) = @_;
  174   $self->push({
  175     type => 'operator', ref => $self->{ref},
  176     name => $op, precedence => $precedence, reverse => $reverse
  177   });
  178 }
  179 
  180 #
  181 #  Push an operand onto the expression stack.
  182 #
  183 sub pushOperand {
  184   my $self = shift; my $value = shift;
  185   $self->push({type => 'operand', ref => $self->{ref}, value => $value});
  186 }
  187 
  188 ##################################################
  189 #
  190 #  Handle an operator token
  191 #
  192 #  Get the operator data from the context
  193 #  If the top of the stack is an operand
  194 #    If the operator is a left-associative unary operator
  195 #      Insert an implicit multiplication and save the operator
  196 #    Otherwise
  197 #      Complete any pending operations of higher precedence
  198 #      If the top item is still an operand
  199 #        If we have a (right associative) unary operator
  200 #          Apply it to the top operand
  201 #        Otherwise (binary operator)
  202 #          Convert the space operator to explicit multiplication
  203 #          Save the opertor on the stack
  204 #      Otherwise, (top is not an operand)
  205 #        If the operator is an explicit one or the top is a function
  206 #          Call Op again to report the error, or to apply
  207 #            the operator to the function (this happens when
  208 #            there is a function to a power, for example)
  209 #  Otherwise (top is not an operand)
  210 #    If this is a left-associative unary operator, save it on the stack
  211 #    Otherwise, if it is a left-associative operator that CAN be unary
  212 #      Save the unary version of the operator on the stack
  213 #    Otherwise, if the top item is a function
  214 #      If the operator can be applied to functions, save it on the stack
  215 #      Otherwise, report that the function is missing its inputs
  216 #    Otherwise, report the missing operand for this operator
  217 #
  218 sub Op {
  219   my $self = shift; my $name = shift;
  220   my $ref = $self->{ref} = shift;
  221   my $context = $self->{context}; my $op = $context->{operators}{$name};
  222   $op = $context->{operators}{$op->{space}} if $self->{space} && defined($op->{space});
  223   if ($self->state eq 'operand') {
  224     if ($op->{type} eq 'unary' && $op->{associativity} eq 'left') {
  225       $self->ImplicitMult();
  226       $self->pushOperator($name,$op->{precedence});
  227     } else {
  228       $self->Precedence($op->{precedence});
  229       if ($self->state eq 'operand') {
  230         if ($op->{type} eq 'unary') {
  231           my $top = $self->pop;
  232           $self->pushOperand($context->{parser}{UOP}->new($self,$name,$top->{value},$ref));
  233         } else {
  234           $name = $context->{operators}{' '}{string}
  235             if $name eq ' ' or $name eq $context->{operators}{' '}{space};
  236           $self->pushOperator($name,$op->{precedence});
  237         }
  238       } elsif (($ref && $name ne ' ') || $self->state ne 'fn') {$self->Op($name,$ref)}
  239     }
  240   } else {
  241     $name = 'u'.$name, $op = $context->{operators}{$name}
  242       if ($op->{type} eq 'both' && defined $context->{operators}{'u'.$name});
  243     if ($op->{type} eq 'unary' && $op->{associativity} eq 'left') {
  244       $self->pushOperator($name,$op->{precedence});
  245     } elsif ($self->state eq 'fn') {
  246       if ($op->{leftf}) {
  247         $self->pushOperator($name,$op->{precedence},1);
  248       } else {
  249         my $top = $self->top;
  250         $self->Error("Function '$top->{name}' is missing its input(s)",$top->{ref});
  251       }
  252     } else {$self->Error("Missing operand before '$name'",$ref)}
  253   }
  254 }
  255 
  256 ##################################################
  257 #
  258 #  Handle an open parenthesis
  259 #
  260 #  If the top of the stack is an operand
  261 #    Check if the open paren is really a close paren (for when the open
  262 #      and close symbol are the same)
  263 #    Otherwise insert an implicit multiplication
  264 #  Save the open object on the stack
  265 #
  266 sub Open {
  267   my $self = shift; my $type = shift;
  268   my $paren = $self->{context}{parens}{$type};
  269   if ($self->state eq 'operand') {
  270     if ($type eq $paren->{close}) {
  271       my $stack = $self->{stack}; my $i = scalar(@{$stack})-1;
  272       while ($i >= 0 && $stack->[$i]{type} ne "open") {$i--}
  273       if ($i >= 0 && $stack->[$i]{value} eq $type) {
  274   $self->Close($type,$self->{ref});
  275   return;
  276       }
  277     }
  278     $self->ImplicitMult();
  279   }
  280   $self->push({type => 'open', value => $type, ref => $self->{ref}});
  281 }
  282 
  283 ##################################################
  284 #
  285 #  Handle a close parenthesis
  286 #
  287 #  When the top stack object is
  288 #    An open parenthesis (that is empty):
  289 #      Get the data for the type of parentheses
  290 #      If the parentheses can be empty and the parentheses match
  291 #        Save the empty list
  292 #      Otherwise report a message appropriate to the type of parentheses
  293 #
  294 #    An operand:
  295 #      Complete any pending operations, and stop if there was an error
  296 #      If the top is no longer an operand
  297 #        Call Close to report the error and return
  298 #      Get the item before the operand (an OPEN object), and its parenthesis type
  299 #      If the parens match
  300 #        Pop the operand off the stack
  301 #        If the parens can't be removed, or if the operand is a list
  302 #          Make the operand into a list object
  303 #        Replace the paren object with the operand
  304 #        If the parentheses are used for function calls and the
  305 #          previous stack object is a function call, do the function apply
  306 #      Otherwise if the parens can form Intervals, do so
  307 #      Otherwise report an appropriate error message
  308 #
  309 #    A function:
  310 #      Report an error message about missing inputs
  311 #
  312 #    An operator:
  313 #      Report the missing operation
  314 #
  315 sub Close {
  316   my $self = shift; my $type = shift;
  317   my $ref = $self->{ref} = shift;
  318   my $parser = $self->{context}{parser};
  319   my $parens = $self->{context}{parens};
  320 
  321   for ($self->state) {
  322     /open/ and do {
  323       my $top = $self->pop; my $paren = $parens->{$top->{value}};
  324       if ($paren->{emptyOK} && $paren->{close} eq $type) {
  325         $self->pushOperand($parser->{List}->new($self,[],1,$paren))
  326       }
  327       elsif ($type eq 'start') {$self->Error("Missing close parenthesis for '$top->{value}'",$top->{ref})}
  328       elsif ($top->{value} eq 'start') {$self->Error("Extra close parenthesis '$type'",$ref)}
  329       else {$top->{ref}[3]=$ref->[3]; $self->Error("Empty parentheses",$top->{ref})}
  330       last;
  331     };
  332 
  333     /operand/ and do {
  334       $self->Precedence(0); return if ($self->{error});
  335       if ($self->state ne 'operand') {$self->Close($type,$ref); return}
  336       my $paren = $parens->{$self->prev->{value}};
  337       if ($paren->{close} eq $type) {
  338         my $top = $self->pop;
  339         if (!$paren->{removable} || ($top->{value}->type eq "Comma")) {
  340           $top = $top->{value};
  341           $top = {type => 'operand', value =>
  342             $parser->{List}->new($self,[$top->makeList],$top->{isConstant},$paren,
  343                     ($top->type eq 'Comma') ? $top->entryType : $top->typeRef,
  344                     ($type ne 'start') ? ($self->top->{value},$type) : () )};
  345         }
  346         $self->pop; $self->push($top);
  347         $self->CloseFn() if ($paren->{function} && $self->prev->{type} eq 'fn');
  348       } elsif ($paren->{formInterval} eq $type && $self->top->{value}->length == 2) {
  349         my $top = $self->pop->{value}; my $open = $self->pop->{value};
  350         $self->pushOperand(
  351            $parser->{List}->new($self,[$top->makeList],$top->{isConstant},
  352              $paren,$top->entryType,$open,$type));
  353       } else {
  354         my $prev = $self->prev;
  355         if ($type eq "start") {$self->Error("Missing close parenthesis for '$prev->{value}'",$prev->{ref})}
  356         elsif ($prev->{value} eq "start") {$self->Error("Extra close parenthesis '$type'",$ref)}
  357         else {$self->Error("Mismatched parentheses: '$prev->{value}' and '$type'",$ref)}
  358         return;
  359       }
  360       last;
  361     };
  362 
  363     /fn/ and do {
  364       my $top = $self->top;
  365       $self->Error("Function '$top->{name}' is missing its input(s)",$top->{ref});
  366       return;
  367     };
  368 
  369     /operator/ and do {
  370       my $top = $self->top(); my $name = $top->{name}; $name =~ s/^u//;
  371       $self->Error("Missing operand after '$name'",$top->{ref});
  372       return;
  373     };
  374   }
  375 }
  376 
  377 ##################################################
  378 #
  379 #  Handle any pending operations of higher precedence
  380 #
  381 #  While the top stack item is an operand:
  382 #    When the preceding item is:
  383 #      An pending operator:
  384 #        Get the precedence of the operator (use the special right-hand prrecedence
  385 #          of there is one, otherwise use the general precedence)
  386 #        Stop processing if the current operator precedence is higher
  387 #        If the stacked operator is binary or if it is reversed (for function operators)
  388 #          Stop processing if the precedence is equal and we are right associative
  389 #          If the operand for the stacked operator is a function
  390 #            If the operation is ^(-1) (for inverses)
  391 #              Push the inverse function name
  392 #            Otherwise
  393 #              Reverse the order of the stack, so that the function can be applied
  394 #                to the next operand (it will be unreversed later)
  395 #          Otherwise (not a function, so an operand)
  396 #            Get the operands and binary operator off the stack
  397 #            If it is reversed (for functions), get the order right
  398 #            Save the result of the binary operation as an operand on the stack
  399 #        Otherwise (the stack contains a unary operator)
  400 #          Get the operator and operand off the stack
  401 #          Push the result of the unary operator as an operand on the stack
  402 #
  403 #      A pending function call:
  404 #        Keep working if the precedence of the operator is higher than a function call
  405 #        Otherwise apply the function to the operator and continue
  406 #
  407 #      Anything else:
  408 #        Return (no more pending operations)
  409 #
  410 #    If there was an error, stop processing
  411 #
  412 sub Precedence {
  413   my $self = shift; my $precedence = shift;
  414   my $context = $self->{context};
  415   while ($self->state eq 'operand') {
  416     my $prev = $self->prev;
  417     for ($prev->{type}) {
  418 
  419       /operator/ and do {
  420         my $prev_prec = $context->{operators}{$prev->{name}}{rprecedence};
  421         $prev_prec = $prev->{precedence} unless $prev_prec;
  422         return if ($precedence > $prev_prec);
  423         if ($self->top(-2)->{type} eq 'operand' || $prev->{reverse}) {
  424           return if ($precedence == $prev_prec &&
  425               $context->{operators}{$prev->{name}}{associativity} eq 'right');
  426           if ($self->top(-2)->{type} eq 'fn') {
  427             my $top = $self->pop; my $op = $self->pop; my $fun = $self->pop;
  428             if (Parser::Function::checkInverse($self,$fun,$op,$top)) {
  429               $fun->{name} = $context->{functions}{$fun->{name}}{inverse};
  430               $self->push($fun);
  431             } else {$self->push($top,$op,$fun)}
  432           } else {
  433             my $rop = $self->pop; my $op = $self->pop; my $lop = $self->pop;
  434             if ($op->{reverse}) {my $tmp = $rop; $rop = $lop; $lop = $tmp}
  435             $self->pushOperand($context->{parser}{BOP}->new($self,$op->{name},
  436                  $lop->{value},$rop->{value},$op->{ref}),$op->{reverse});
  437           }
  438         } else {
  439           my $rop = $self->pop; my $op = $self->pop;
  440           $self->pushOperand($context->{parser}{UOP}->new
  441              ($self,$op->{name},$rop->{value},$op->{ref}),$op->{reverse});
  442         }
  443         last;
  444       };
  445 
  446       /fn/ and do {
  447         return if ($precedence > $context->{operators}{fn}{precedence});
  448         $self->CloseFn();
  449         last;
  450       };
  451 
  452       return;
  453 
  454     }
  455     return if ($self->{error});
  456   }
  457 }
  458 
  459 ##################################################
  460 #
  461 #  Apply a function to its parameters
  462 #
  463 #  If the operand is a list and the parens are those for function calls
  464 #    Use the list items as the parameters, otherwise use the top item
  465 #  Pop the function object, and push the result of the function call
  466 #
  467 sub CloseFn {
  468   my $self = shift; my $context = $self->{context};
  469   my $top = $self->pop->{value}; my $fn = $self->pop;
  470   my $constant = $top->{isConstant};
  471   if ($context->{parens}{$top->{open}}{function} &&
  472       $context->{parens}{$top->{open}}{close} eq $top->{close} &&
  473       !$context->{functions}{$fn->{name}}{vectorInput})
  474          {$top = $top->coords} else {$top = [$top]}
  475   $self->pushOperand($context->{parser}{Function}->new
  476      ($self,$fn->{name},$top,$constant,$fn->{ref}));
  477 }
  478 
  479 ##################################################
  480 #
  481 #  Handle a numeric token
  482 #
  483 #  Add an implicit multiplication, if needed
  484 #  Create the number object and check it
  485 #  Save the number as an operand
  486 #
  487 sub Num {
  488   my $self = shift;
  489   $self->ImplicitMult() if $self->state eq 'operand';
  490   my $num = $self->{context}{parser}{Number}->new($self,shift,$self->{ref});
  491   my $check = $self->{context}->flag('NumberCheck');
  492   &$check($num) if $check;
  493   $self->pushOperand($num);
  494 }
  495 
  496 ##################################################
  497 #
  498 #  Handle a constant token
  499 #
  500 #  Add an implicit multiplication, if needed
  501 #  Save the number as an operand
  502 #
  503 sub Const {
  504   my $self = shift; my $ref = $self->{ref}; my $name = shift;
  505   my $const = $self->{context}{constants}{$name};
  506   my $parser = $self->{context}{parser};
  507   $self->ImplicitMult() if $self->state eq 'operand';
  508   if (defined($self->{context}{variables}{$name})) {
  509     $self->pushOperand($parser->{Variable}->new($self,$name,$ref));
  510   } elsif ($const->{keepName}) {
  511     $self->pushOperand($parser->{Constant}->new($self,$name,$ref));
  512   } else {
  513     $self->pushOperand($parser->{Value}->new($self,[$const->{value}],$ref));
  514   }
  515 }
  516 
  517 ##################################################
  518 #
  519 #  Handle a variable token
  520 #
  521 #  Add an implicit multiplication, if needed
  522 #  Save the variable as an operand
  523 #
  524 sub Var {
  525   my $self = shift;
  526   $self->ImplicitMult() if $self->state eq 'operand';
  527   $self->pushOperand($self->{context}{parser}{Variable}->new($self,shift,$self->{ref}));
  528 }
  529 
  530 ##################################################
  531 #
  532 #  Handle a function token
  533 #
  534 #  Add an implicit multiplication, if needed
  535 #  Save the function object on the stack
  536 #
  537 sub Fn {
  538   my $self = shift;
  539   $self->ImplicitMult() if $self->state eq 'operand';
  540   $self->push({type => 'fn', name => shift, ref => $self->{ref}});
  541 }
  542 
  543 ##################################################
  544 #
  545 #  Handle a string constant
  546 #
  547 #  Add an implicit multiplication, if needed (will report an error)
  548 #  Save the string object on the stack
  549 #
  550 sub Str {
  551   my $self = shift;
  552   $self->ImplicitMult() if $self->state eq 'operand';
  553   $self->pushOperand($self->{context}{parser}{String}->new($self,shift,$self->{ref}));
  554 }
  555 
  556 ##################################################
  557 ##################################################
  558 #
  559 #  Evaluate the equation using the given values
  560 #
  561 sub eval {
  562   my $self = shift;
  563   $self->setValues(@_);
  564   foreach my $x (keys %{$self->{values}}) {
  565     $self->Error("The value of '$x' can't be a formula")
  566       if Value::isFormula($self->{values}{$x});
  567   }
  568   Value::makeValue($self->{tree}->eval);
  569 }
  570 
  571 ##################################################
  572 #
  573 #  Removes redundent items (like x+-y, 0+x and 1*x, etc)
  574 #  using the provided flags
  575 #
  576 sub reduce {
  577   my $self = shift;
  578   $self = $self->copy($self);
  579   my $reduce = $self->{context}{reduction};
  580   $self->{context}{reduction} = {%{$reduce},@_};
  581   $self->{tree} = $self->{tree}->reduce;
  582   $self->{variables} = $self->{tree}->getVariables;
  583   $self->{context}{reduction} = $reduce if $reduce;
  584   return $self;
  585 }
  586 
  587 ##################################################
  588 #
  589 #  Substitute values for one or more variables
  590 #
  591 sub substitute {
  592   my $self = shift;
  593   $self = $self->copy($self);
  594   $self->setValues(@_);
  595   foreach my $x (keys %{$self->{values}}) {delete $self->{variables}{$x}}
  596   $self->{tree} = $self->{tree}->substitute;
  597   return $self;
  598 }
  599 
  600 ##################################################
  601 #
  602 #  Produces a printable string (substituting the given values).
  603 #
  604 sub string {
  605   my $self = shift;
  606   $self->setValues(@_);
  607   $self->{tree}->string;
  608 }
  609 
  610 ##################################################
  611 #
  612 #  Produces a TeX string (substituting the given values).
  613 #
  614 sub TeX {
  615   my $self = shift;
  616   $self->setValues(@_);
  617   $self->{tree}->TeX;
  618 }
  619 
  620 ##################################################
  621 #
  622 #  Produces a perl eval string (substituting the given values).
  623 #
  624 sub perl {
  625   my $self = shift;
  626   $self->setValues(@_);
  627   my $perl = $self->{tree}->perl;
  628   $perl = 'Real('.$perl.')' if $self->isRealNumber;
  629   return $perl;
  630 }
  631 
  632 ##################################################
  633 #
  634 #  Produce a perl function
  635 #
  636 #  (Parameters specify an optional name and an array reference of
  637 #   optional variables. If the name is not included, an anonymous
  638 #   code reference is returned.  If the variables are not included,
  639 #   then the variables from the formula are used in sorted order.)
  640 #
  641 sub perlFunction {
  642   my $self = shift; my $name = shift; my $vars = shift;
  643   $vars = [sort(keys %{$self->{variables}})] unless $vars;
  644   my $n = scalar(@{$vars}); my $vnames = '';
  645   if ($n > 0) {
  646     my @v = (); foreach my $x (@{$vars}) {push(@v,'$'.$x)}
  647     $vnames = "my (".join(',',@v).") = \@_;";
  648   }
  649   my $fn = eval
  650    "package main;
  651     sub $name {
  652       die \"Wrong number of arguments".($name?" to '$name'":'')."\" if scalar(\@_) != $n;
  653       $vnames
  654       return ".$self->perl.";
  655     }";
  656   $self->Error($@) if $@;
  657   return $fn;
  658 }
  659 
  660 
  661 ##################################################
  662 #
  663 #  Sets the values of variables for evaluation purposes
  664 #
  665 sub setValues {
  666   my $self = shift; my ($value,$type);
  667   my $variables = $self->{context}{variables};
  668   $self->{values} = {@_};
  669   foreach my $x (keys %{$self->{values}}) {
  670     $self->Error("Undeclared variable '$x'") unless defined $variables->{$x};
  671     $value = Value::makeValue($self->{values}{$x});
  672     $value = Value::Formula->new($value) unless Value::isValue($value);
  673     ($value,$type) = Value::getValueType($self,$value);
  674     $self->Error("Variable '$x' should be of type $variables->{$x}{type}{name}")
  675       unless Parser::Item::typeMatch($type,$variables->{$x}{type});
  676     $self->{values}{$x} = $value;
  677   }
  678 }
  679 
  680 
  681 ##################################################
  682 ##################################################
  683 #
  684 #  Produce a vector in ijk form
  685 #
  686 sub ijk {
  687   my $self = shift;
  688   $self->{tree}->ijk;
  689 }
  690 
  691 #########################################################################
  692 #########################################################################
  693 #
  694 #  Load the sub-classes and Value.pm
  695 #
  696 
  697 use Parser::Item;
  698 use Value;
  699 use Parser::Context;
  700 use Parser::Context::Default;
  701 use Parser::Differentiation;
  702 
  703 ###########################################################################
  704 
  705 use vars qw($installed);
  706 $Parser::installed = 1;
  707 
  708 ###########################################################################
  709 ###########################################################################
  710 #
  711 #   To Do:
  712 #
  713 # handle sqrt(-1) and log of negatives (make complexes)
  714 # do division by zero and log of zero checks in compound functions
  715 # make reduce have reduce patterns as parameters
  716 # more reduce patterns
  717 # make operator strings customizable (reduce, and other places they are used)
  718 #
  719 #########################################################################
  720 
  721 1;
  722 

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9