octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

constant folding considered harmful


From: John W. Eaton
Subject: constant folding considered harmful
Date: Thu, 12 Dec 2013 23:36:43 -0600
User-agent: Mozilla/5.0 (X11; Linux i686; rv:10.0.11) Gecko/20121123 Icedove/10.0.11

Octave's parser currently performs constant folding (replacing
constant expressions by their computed values) when the internal
parse tree is constructed.  This can improve performance, but the
improvement is probably small in most cases.  It also prevents some
things from working properly.  For example, when Matlab-style
short-circuiting rules are in effect, short-circuit evaluation will
not happen for expressions like

  if (2 | []) ... end

because the constant expression "2 | []" is evaluated before the
parser knows that it is inside an IF statement.  So instead of
returning 2, which is considered TRUE, the expression returns [],
which is considered FALSE.  Perhaps that could be fixed in a way that
would preserve constant folding, but I think it would significantly
complicate the parser (remember that you also have to avoid
short-circuit evaluation for things like

  if (abs (1 | [])) ... end

and other arbitrarily complex expressions inside IF or WHILE
conditions.

This example may seem artificial -- who writes IF or WHILE conditions
that involve constant values, anyway?  But it still seems bad to me
that Octave produces the wrong result here.

A more serious issue is that constant folding gets in the way of
operator overloading for built-in classes (not currently implemented
in Octave, but probably will be before too long).  For example,
suppose you have the following function in your path (not your current
directory):

  function r = f ()
    r = 2 + 2;
  end

and you also have @double/plus.m in your current directory.  Then when
you evaluate the function f, @double/plus.m will be called to evaluate
the expression "2 + 2".  Then, without clearing f, if you cd to
another directory so that @double/plus.m is no longer in your current
direcctory and evaluate the function f again, then the built-in
addition operator for double objects will be called.  I don't see a
good way to make this work with constant folding.  Octave can't use
the @double/plus.m meethod when performing constant folding because
later on that method might not be in the load path.  Or, the function
that performs the operation might have some side effects that are
expected to be performed each time the function is called, not just
once when the function is parsed.

Does anyone object to removing constant folding from the parser?  My
guess is that it will have minimal impact on peformance while making
the parser a bit simpler and allowing it to be correct in more cases,
especially if we implement operator overloading for built-in classes.

jwe


reply via email to

[Prev in Thread] Current Thread [Next in Thread]