[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 4994 - (download) (as text) (annotate)
Sun Jun 10 01:17:29 2007 UTC (12 years, 8 months ago) by dpvc
File size: 24847 byte(s)
Update to handle the fact that the Value package now includes the
context with all MathObjects.  (This may still need some work.)

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9