[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 2823 - (download) (as text) (annotate)
Thu Sep 23 21:09:14 2004 UTC (15 years, 4 months ago) by dpvc
File size: 24196 byte(s)
Fixed Parser so that you can replace the Formula class as well as the
other object types.

    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 on 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       {$self->Close($type,$self->{ref}); return} else {$self->ImplicitMult()}
  272   }
  273   $self->push({type => 'open', value => $type, ref => $self->{ref}});
  274 }
  275 
  276 ##################################################
  277 #
  278 #  Handle a close parenthesis
  279 #
  280 #  When the top stack object is
  281 #    An open parenthesis (that is empty):
  282 #      Get the data for the type of parentheses
  283 #      If the parentheses can be empty and the parentheses match
  284 #        Save the empty list
  285 #      Otherwise report a message appropriate to the type of parentheses
  286 #
  287 #    An operand:
  288 #      Complete any pending operations, and stop if there was an error
  289 #      If the top is no longer an operand
  290 #        Call Close to report the error and return
  291 #      Get the item before the operand (an OPEN object), and its parenthesis type
  292 #      If the parens match
  293 #        Pop the operand off the stack
  294 #        If the parens can't be removed, or if the operand is a list
  295 #          Make the operand into a list object
  296 #        Replace the paren object with the operand
  297 #        If the parentheses are used for function calls and the
  298 #          previous stack object is a function call, do the function apply
  299 #      Otherwise if the parens can form Intervals, do so
  300 #      Otherwise report an appropriate error message
  301 #
  302 #    A function:
  303 #      Report an error message about missing inputs
  304 #
  305 #    An operator:
  306 #      Report the missing operation
  307 #
  308 sub Close {
  309   my $self = shift; my $type = shift;
  310   my $ref = $self->{ref} = shift;
  311   my $parser = $self->{context}{parser};
  312   my $parens = $self->{context}{parens};
  313 
  314   for ($self->state) {
  315     /open/ and do {
  316       my $top = $self->pop; my $paren = $parens->{$top->{value}};
  317       if ($paren->{emptyOK} && $paren->{close} eq $type) {
  318         $self->pushOperand($parser->{List}->new($self,[],1,$paren))
  319       }
  320       elsif ($type eq 'start') {$self->Error("Missing close parenthesis for '$top->{value}'",$top->{ref})}
  321       elsif ($top->{value} eq 'start') {$self->Error("Extra close parenthesis '$type'",$ref)}
  322       else {$top->{ref}[3]=$ref->[3]; $self->Error("Empty parentheses",$top->{ref})}
  323       last;
  324     };
  325 
  326     /operand/ and do {
  327       $self->Precedence(0); return if ($self->{error});
  328       if ($self->state ne 'operand') {$self->Close($type,$ref); return}
  329       my $paren = $parens->{$self->prev->{value}};
  330       if ($paren->{close} eq $type) {
  331         my $top = $self->pop;
  332         if (!$paren->{removable} || ($top->{value}->type eq "Comma")) {
  333           $top = $top->{value};
  334           $top = {type => 'operand', value =>
  335             $parser->{List}->new($self,[$top->makeList],$top->{isConstant},$paren,
  336                     ($top->type eq 'Comma') ? $top->entryType : $top->typeRef,
  337                     ($type ne 'start') ? ($self->top->{value},$type) : () )};
  338         }
  339         $self->pop; $self->push($top);
  340         $self->CloseFn() if ($paren->{function} && $self->prev->{type} eq 'fn');
  341       } elsif ($paren->{formInterval} eq $type && $self->top->{value}->length == 2) {
  342         my $top = $self->pop->{value}; my $open = $self->pop->{value};
  343         $self->pushOperand(
  344            $parser->{List}->new($self,[$top->makeList],$top->{isConstant},
  345              $paren,$top->entryType,$open,$type));
  346       } else {
  347         my $prev = $self->prev;
  348         if ($type eq "start") {$self->Error("Missing close parenthesis for '$prev->{value}'",$prev->{ref})}
  349         elsif ($prev->{value} eq "start") {$self->Error("Extra close parenthesis '$type'",$ref)}
  350         else {$self->Error("Mismatched parentheses: '$prev->{value}' and '$type'",$ref)}
  351         return;
  352       }
  353       last;
  354     };
  355 
  356     /fn/ and do {
  357       my $top = $self->top;
  358       $self->Error("Function '$top->{name}' is missing its input(s)",$top->{ref});
  359       return;
  360     };
  361 
  362     /operator/ and do {
  363       my $top = $self->top(); my $name = $top->{name}; $name =~ s/^u//;
  364       $self->Error("Missing operand after '$name'",$top->{ref});
  365       return;
  366     };
  367   }
  368 }
  369 
  370 ##################################################
  371 #
  372 #  Handle any pending operations of higher precedence
  373 #
  374 #  While the top stack item is an operand:
  375 #    When the preceding item is:
  376 #      An pending operator:
  377 #        Get the precedence of the operator (use the special right-hand prrecedence
  378 #          of there is one, otherwise use the general precedence)
  379 #        Stop processing if the current operator precedence is higher
  380 #        If the stacked operator is binary or if it is reversed (for function operators)
  381 #          Stop processing if the precedence is equal and we are right associative
  382 #          If the operand for the stacked operator is a function
  383 #            If the operation is ^(-1) (for inverses)
  384 #              Push the inverse function name
  385 #            Otherwise
  386 #              Reverse the order of the stack, so that the function can be applied
  387 #                to the next operand (it will be unreversed later)
  388 #          Otherwise (not a function, so an operand)
  389 #            Get the operands and binary operator off the stack
  390 #            If it is reversed (for functions), get the order right
  391 #            Save the result of the binary operation as an operand on the stack
  392 #        Otherwise (the stack contains a unary operator)
  393 #          Get the operator and operand off the stack
  394 #          Push the result of the unary operator as an operand on the stack
  395 #
  396 #      A pending function call:
  397 #        Keep working if the precedence of the operator is higher than a function call
  398 #        Otherwise apply the function to the operator and continue
  399 #
  400 #      Anything else:
  401 #        Return (no more pending operations)
  402 #
  403 #    If there was an error, stop processing
  404 #
  405 sub Precedence {
  406   my $self = shift; my $precedence = shift;
  407   my $context = $self->{context};
  408   while ($self->state eq 'operand') {
  409     my $prev = $self->prev;
  410     for ($prev->{type}) {
  411 
  412       /operator/ and do {
  413         my $prev_prec = $context->{operators}{$prev->{name}}{rprecedence};
  414         $prev_prec = $prev->{precedence} unless $prev_prec;
  415         return if ($precedence > $prev_prec);
  416         if ($self->top(-2)->{type} eq 'operand' || $prev->{reverse}) {
  417           return if ($precedence == $prev_prec &&
  418               $context->{operators}{$prev->{name}}{associativity} eq 'right');
  419           if ($self->top(-2)->{type} eq 'fn') {
  420             my $top = $self->pop; my $op = $self->pop; my $fun = $self->pop;
  421             if (Parser::Function::checkInverse($self,$fun,$op,$top)) {
  422               $fun->{name} = $context->{functions}{$fun->{name}}{inverse};
  423               $self->push($fun);
  424             } else {$self->push($top,$op,$fun)}
  425           } else {
  426             my $rop = $self->pop; my $op = $self->pop; my $lop = $self->pop;
  427             if ($op->{reverse}) {my $tmp = $rop; $rop = $lop; $lop = $tmp}
  428             $self->pushOperand($context->{parser}{BOP}->new($self,$op->{name},
  429                  $lop->{value},$rop->{value},$op->{ref}),$op->{reverse});
  430           }
  431         } else {
  432           my $rop = $self->pop; my $op = $self->pop;
  433           $self->pushOperand($context->{parser}{UOP}->new
  434              ($self,$op->{name},$rop->{value},$op->{ref}),$op->{reverse});
  435         }
  436         last;
  437       };
  438 
  439       /fn/ and do {
  440         return if ($precedence > $context->{operators}{fn}{precedence});
  441         $self->CloseFn();
  442         last;
  443       };
  444 
  445       return;
  446 
  447     }
  448     return if ($self->{error});
  449   }
  450 }
  451 
  452 ##################################################
  453 #
  454 #  Apply a function to its parameters
  455 #
  456 #  If the operand is a list and the parens are those for function calls
  457 #    Use the list items as the parameters, otherwise use the top item
  458 #  Pop the function object, and push the result of the function call
  459 #
  460 sub CloseFn {
  461   my $self = shift; my $context = $self->{context};
  462   my $top = $self->pop->{value}; my $fn = $self->pop;
  463   my $constant = $top->{isConstant};
  464   if ($context->{parens}{$top->{open}}{function} &&
  465       $context->{parens}{$top->{open}}{close} eq $top->{close} &&
  466       !$context->{functions}{$fn->{name}}{vectorInput})
  467          {$top = $top->coords} else {$top = [$top]}
  468   $self->pushOperand($context->{parser}{Function}->new
  469      ($self,$fn->{name},$top,$constant,$fn->{ref}));
  470 }
  471 
  472 ##################################################
  473 #
  474 #  Handle a numeric token
  475 #
  476 #  Add an implicit multiplication, if needed
  477 #  Create the number object and check it
  478 #  Save the number as an operand
  479 #
  480 sub Num {
  481   my $self = shift;
  482   $self->ImplicitMult() if $self->state eq 'operand';
  483   my $num = $self->{context}{parser}{Number}->new($self,shift,$self->{ref});
  484   my $check = $self->{context}->flag('NumberCheck');
  485   &$check($num) if $check;
  486   $self->pushOperand($num);
  487 }
  488 
  489 ##################################################
  490 #
  491 #  Handle a constant token
  492 #
  493 #  Add an implicit multiplication, if needed
  494 #  Save the number as an operand
  495 #
  496 sub Const {
  497   my $self = shift; my $ref = $self->{ref}; my $name = shift;
  498   my $const = $self->{context}{constants}{$name};
  499   my $parser = $self->{context}{parser};
  500   $self->ImplicitMult() if $self->state eq 'operand';
  501   if (defined($self->{context}{variables}{$name})) {
  502     $self->pushOperand($parser->{Variable}->new($self,$name,$ref));
  503   } elsif ($const->{keepName}) {
  504     $self->pushOperand($parser->{Constant}->new($self,$name,$ref));
  505   } else {
  506     $self->pushOperand($parser->{Value}->new($self,[$const->{value}],$ref));
  507   }
  508 }
  509 
  510 ##################################################
  511 #
  512 #  Handle a variable token
  513 #
  514 #  Add an implicit multiplication, if needed
  515 #  Save the variable as an operand
  516 #
  517 sub Var {
  518   my $self = shift;
  519   $self->ImplicitMult() if $self->state eq 'operand';
  520   $self->pushOperand($self->{context}{parser}{Variable}->new($self,shift,$self->{ref}));
  521 }
  522 
  523 ##################################################
  524 #
  525 #  Handle a function token
  526 #
  527 #  Add an implicit multiplication, if needed
  528 #  Save the function object on the stack
  529 #
  530 sub Fn {
  531   my $self = shift;
  532   $self->ImplicitMult() if $self->state eq 'operand';
  533   $self->push({type => 'fn', name => shift, ref => $self->{ref}});
  534 }
  535 
  536 ##################################################
  537 #
  538 #  Handle a string constant
  539 #
  540 #  Add an implicit multiplication, if needed (will report an error)
  541 #  Save the string object on the stack
  542 #
  543 sub Str {
  544   my $self = shift;
  545   $self->ImplicitMult() if $self->state eq 'operand';
  546   $self->pushOperand($self->{context}{parser}{String}->new($self,shift,$self->{ref}));
  547 }
  548 
  549 ##################################################
  550 ##################################################
  551 #
  552 #  Evaluate the equation using the given values
  553 #
  554 sub eval {
  555   my $self = shift;
  556   $self->setValues(@_);
  557   foreach my $x (keys %{$self->{values}}) {
  558     $self->Error("The value of '$x' can't be a formula")
  559       if Value::isFormula($self->{values}{$x});
  560   }
  561   Value::makeValue($self->{tree}->eval);
  562 }
  563 
  564 ##################################################
  565 #
  566 #  Removes redundent items (like x+-y, 0+x and 1*x, etc)
  567 #  using the provided flags
  568 #
  569 sub reduce {
  570   my $self = shift;
  571   $self = $self->copy($self);
  572   my $reduce = $self->{context}{reduction};
  573   $self->{context}{reduction} = {%{$reduce},@_};
  574   $self->{tree} = $self->{tree}->reduce;
  575   $self->{variables} = $self->{tree}->getVariables;
  576   $self->{context}{reduction} = $reduce if $reduce;
  577   return $self;
  578 }
  579 
  580 ##################################################
  581 #
  582 #  Substitute values for one or more variables
  583 #
  584 sub substitute {
  585   my $self = shift;
  586   $self = $self->copy($self);
  587   $self->setValues(@_);
  588   foreach my $x (keys %{$self->{values}}) {delete $self->{variables}{$x}}
  589   $self->{tree} = $self->{tree}->substitute;
  590   return $self;
  591 }
  592 
  593 ##################################################
  594 #
  595 #  Produces a printable string (substituting the given values).
  596 #
  597 sub string {
  598   my $self = shift;
  599   $self->setValues(@_);
  600   $self->{tree}->string;
  601 }
  602 
  603 ##################################################
  604 #
  605 #  Produces a TeX string (substituting the given values).
  606 #
  607 sub TeX {
  608   my $self = shift;
  609   $self->setValues(@_);
  610   $self->{tree}->TeX;
  611 }
  612 
  613 ##################################################
  614 #
  615 #  Produces a perl eval string (substituting the given values).
  616 #
  617 sub perl {
  618   my $self = shift;
  619   $self->setValues(@_);
  620   my $perl = $self->{tree}->perl;
  621   $perl = 'Real('.$perl.')' if $self->isRealNumber;
  622   return $perl;
  623 }
  624 
  625 ##################################################
  626 #
  627 #  Produce a perl function
  628 #
  629 #  (Parameters specify an optional name and an array reference of
  630 #   optional variables. If the name is not included, an anonymous
  631 #   code reference is returned.  If the variables are not included,
  632 #   then the variables from the formula are used in sorted order.)
  633 #
  634 sub perlFunction {
  635   my $self = shift; my $name = shift; my $vars = shift;
  636   $vars = [sort(keys %{$self->{variables}})] unless $vars;
  637   my $n = scalar(@{$vars}); my $vnames = '';
  638   if ($n > 0) {
  639     my @v = (); foreach my $x (@{$vars}) {push(@v,'$'.$x)}
  640     $vnames = "my (".join(',',@v).") = \@_;";
  641   }
  642   my $fn = eval
  643    "package main;
  644     sub $name {
  645       die \"Wrong number of arguments".($name?" to '$name'":'')."\" if scalar(\@_) != $n;
  646       $vnames
  647       return ".$self->perl.";
  648     }";
  649   $self->Error($@) if $@;
  650   return $fn;
  651 }
  652 
  653 
  654 ##################################################
  655 #
  656 #  Sets the values of variables for evaluation purposes
  657 #
  658 sub setValues {
  659   my $self = shift; my ($value,$type);
  660   my $variables = $self->{context}{variables};
  661   $self->{values} = {@_};
  662   foreach my $x (keys %{$self->{values}}) {
  663     $self->Error("Undeclared variable '$x'") unless defined $variables->{$x};
  664     $value = Value::makeValue($self->{values}{$x});
  665     $value = Value::Formula->new($value) unless Value::isValue($value);
  666     ($value,$type) = Value::getValueType($self,$value);
  667     $self->Error("Variable '$x' should be of type $variables->{$x}{type}{name}")
  668       unless Parser::Item::typeMatch($type,$variables->{$x}{type});
  669     $self->{values}{$x} = $value;
  670   }
  671 }
  672 
  673 
  674 ##################################################
  675 ##################################################
  676 #
  677 #  Produce a vector in ijk form
  678 #
  679 sub ijk {
  680   my $self = shift;
  681   $self->{tree}->ijk;
  682 }
  683 
  684 #########################################################################
  685 #########################################################################
  686 #
  687 #  Load the sub-classes and Value.pm
  688 #
  689 
  690 use Parser::Item;
  691 use Value;
  692 use Parser::Context;
  693 use Parser::Context::Default;
  694 use Parser::Differentiation;
  695 
  696 ###########################################################################
  697 
  698 use vars qw($installed);
  699 $Parser::installed = 1;
  700 
  701 ###########################################################################
  702 ###########################################################################
  703 #
  704 #   To Do:
  705 #
  706 # handle sqrt(-1) and log of negatives (make complexes)
  707 # do division by zero and log of zero checks in compound functions
  708 # make reduce have reduce patterns as parameters
  709 # more reduce patterns
  710 # make operator strings customizable (reduce, and other places they are used)
  711 #
  712 #########################################################################
  713 
  714 1;
  715 

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9