LaTeXML icon indicating copy to clipboard operation
LaTeXML copied to clipboard

\pgfmathparse calls every function *twice*

Open xworld21 opened this issue 10 months ago • 1 comments

Tweak any PGF function to have a side effect, for example edit pgfmath.code.tex.ltxml as follows:

    e          => sub { NoteSTDERR('evaluating `e`'); $E; },

Then run the innocuous

\pgfmathparse{e}\pgfmathresult

LaTeXML will print 'evaluating e' twice!

Aside from the performance impact, which is probably negligible, this is making it impossible to replicate PGF's random number generator because rand gets called twice every time.

xworld21 avatar Jan 10 '25 09:01 xworld21

Quick word: this is actually pretty obvious in hindsight. You are slightly abusing the descent parser by evaluating the fuctions within the subrules. It's normal for a rule to be evaluated multiple times as the parser tries each branch, then backtracks when it fails, causing this behaviour. So this is an incompatibility between the current design and the presence of functions with side effects (rnd, rand). One should either create a parsing tree which is evaluated at the end, or for simplicity create an equivalent valid perl string which can be eval'd. Or, carefully write the grammar so that such failures do not happen, which feels incredibly fragile.

I suppose there might be a way to stash the random generator state within the parser so it can be rolled back on failure but it doesn't sound very maintainable, if it can be done at all.

xworld21 avatar Jan 10 '25 12:01 xworld21