Debian Codegraph @

texmf-dist/tex/generic/pgfplots/lua/pgfplotsoldpgfsupp/luamath/parser.lua

raw
1 --------------------------------------------------------------------------------------------------
2 ------ This file is a copy of some part of PGF/Tikz.
3 ------ It has been copied here to provide :
4 ------ - compatibility with older PGF versions
5 ------ - availability of PGF contributions by Christian Feuersaenger
6 ------ which are necessary or helpful for pgfplots.
7 ------
8 ------ For reasons of simplicity, I have copied the whole file, including own contributions AND
9 ------ PGF parts. The copyrights are as they appear in PGF.
10 ------
11 ------ Note that pgfplots has compatible licenses.
12 ------
13 ------ This copy has been modified in the following ways:
14 ------ - nested \input commands have been updated
15 ------
16 --
17 -- Support for the contents of this file will NOT be done by the PGF/TikZ team.
18 -- Please contact the author and/or maintainer of pgfplots (Christian Feuersaenger) if you need assistance in conjunction
19 -- with the deployment of this patch or partial content of PGF. Note that the author and/or maintainer of pgfplots has no obligation to fix anything:
20 -- This file comes without any warranty as the rest of pgfplots; there is no obligation for help.
21 ----------------------------------------------------------------------------------------------------
22 -- Date of this copy: Mi 6. Jan 11:32:04 CET 2016 ---
23
24
25
26 -- Copyright 2011 by Christophe Jorssen and Mark Wibrow
27 -- Copyright 2014 by Christian Feuersaenger
28 --
29 -- This file may be distributed and/or modified
30 --
31 -- 1. under the LaTeX Project Public License and/or
32 -- 2. under the GNU Public License.
33 --
34 -- See the file doc/generic/pgf/licenses/LICENSE for more details.
35 --
36 -- $Id: parser.lua,v 1.3 2015/11/28 17:20:49 cfeuersaenger Exp $
37 --
38 -- usage:
39 --
40 -- pgfluamathparser = require("pgfplotsoldpgfsupp.luamath.parser")
41 --
42 -- local result = pgfluamathparser.pgfmathparse("1+ 2*4^2")
43 --
44 -- This LUA class has a direct backend in \pgfuselibrary{luamath}, see the documentation of that TeX package.
45
46 local pgfluamathparser = pgfluamathparser or {}
47
48 pgfluamathfunctions = require("pgfplotsoldpgfsupp.luamath.functions")
49
50 -- lpeg is always present in luatex
51 local lpeg = require("lpeg")
52
53 local S, P, R = lpeg.S, lpeg.P, lpeg.R
54 local C, Cc, Ct = lpeg.C, lpeg.Cc, lpeg.Ct
55 local Cf, Cg, Cs = lpeg.Cf, lpeg.Cg, lpeg.Cs
56 local V = lpeg.V
57 local match = lpeg.match
58
59 local space_pattern = S(" \n\r\t")^0
60 local tex_unit =
61 P('pt') + P('mm') + P('cm') + P('in') +
62 -- while valid units, the font-depending ones need special attention... move them to the TeX side. For now.
63 -- P('ex') + P('em') +
64 P('bp') + P('pc') +
65 P('dd') + P('cc') + P('sp');
66
67 local one_digit_pattern = R("09")
68 local positive_integer_pattern = one_digit_pattern^1
69 -- FIXME : it might be a better idea to remove '-' from all number_patterns! Instead, rely on the prefix operator 'neg' to implement negative numbers.
70 -- Is that wise? It is certainly less efficient...
71 local integer_pattern = S("+-")^-1 * positive_integer_pattern
72 -- Valid positive decimals are |xxx.xxx|, |.xxx| and |xxx.|
73 local positive_integer_or_decimal_pattern = positive_integer_pattern * ( P(".") * one_digit_pattern^0)^-1 +
74 (P(".") * one_digit_pattern^1)
75 local integer_or_decimal_pattern = S("+-")^-1 * positive_integer_or_decimal_pattern
76 local fpu_pattern = R"05" * P"Y" * positive_integer_or_decimal_pattern * P"e" * S("+-")^-1 * R("09")^1 * P"]"
77 local unbounded_pattern = P"inf" + P"INF" + P"nan" + P"NaN" + P"Inf"
78 local number_pattern = C(unbounded_pattern + fpu_pattern + integer_or_decimal_pattern * (S"eE" * integer_pattern + C(tex_unit))^-1)
79
80 local underscore_pattern = P("_")
81
82 local letter_pattern = R("az","AZ")
83 local alphanum__pattern = letter_pattern + one_digit_pattern + underscore_pattern
84
85 local identifier_pattern = letter_pattern^1 * alphanum__pattern^0
86
87 local openparen_pattern = P("(") * space_pattern
88 local closeparen_pattern = P(")")
89 local opencurlybrace_pattern = P("{")
90 local closecurlybrace_pattern = P("}")
91 local openbrace_pattern = P("[")
92 local closebrace_pattern = P("]")
93
94 -- hm. what about '\\' or '\%' ?
95 -- accept \pgf@x, \count0, \dimen42, \c@pgf@counta, \wd0, \ht0, \dp 0
96 local controlsequence_pattern = P"\\" * C( (R("az","AZ") + P"@")^1) * space_pattern* C( R"09"^0 )
97
98 -- local string = P('"') * C((1 - P('"'))^0) * P('"')
99
100 local comma_pattern = P(",") * space_pattern
101
102
103 ----------------
104 local TermOp = C(S("+-")) * space_pattern
105 local EqualityOp = C( P"==" + P"!=" ) * space_pattern
106 local RelationalOp = C( P"<=" + P">=" + P"<" + P">" ) * space_pattern
107 local FactorOp = C(S("*/")) * space_pattern
108
109 -- Grammar
110 local Exp, Term, Factor = V"Exp", V"Term", V"Factor"
111 local Prefix = V"Prefix"
112 local Postfix = V"Postfix"
113
114
115
116 local function eval (v1, op, v2)
117 if (op == "+") then return v1 + v2
118 elseif (op == "-") then return v1 - v2
119 elseif (op == "*") then return v1 * v2
120 elseif (op == "/") then return v1 / v2
121 else
122 error("This function must not be invoked for operator "..op)
123 end
124 end
125
126 local pgfStringToFunctionMap = pgfluamathfunctions.stringToFunctionMap
127 local function function_eval(name, ... )
128 local f = pgfStringToFunctionMap[name]
129 if not f then
130 error("Function '" .. name .. "' is undefined (did not find pgfluamathfunctions."..name .." (looked into pgfluamathfunctions.stringToFunctionMap))")
131 end
132 -- FIXME: validate signature
133 return f(...)
134 end
135
136
137 local func =
138 (C(identifier_pattern) * space_pattern * openparen_pattern * Exp * (comma_pattern * Exp)^0 * closeparen_pattern) / function_eval;
139
140 local functionWithoutArg = identifier_pattern / function_eval
141
142 -- this is what can occur as exponent after '^'.
143 -- I have the impression that the priorities could be implemented in a better way than this... but it seems to work.
144 local pow_exponent =
145 -- allows 2^-4, 2^1e4, 2^2
146 -- FIXME : why not 2^1e2 ?
147 Cg(C(integer_or_decimal_pattern)
148 -- 2^pi, 2^multiply(2,2)
149 + Cg(func+functionWithoutArg)
150 -- 2^(2+2)
151 + openparen_pattern * Exp * closeparen_pattern )
152
153 local function prefix_eval(op, x)
154 if op == "-" then
155 return pgfluamathfunctions.neg(x)
156 elseif op == "!" then
157 return pgfluamathfunctions.notPGF(x)
158 else
159 error("This function must not be invoked for operator "..op)
160 end
161 end
162
163
164 local prefix_operator = C( S"-!" )
165 local prefix_operator_pattern = (prefix_operator * space_pattern * Cg(Prefix) ) / prefix_eval
166
167 -- apparently, we need to distinghuish between <expr> ! and <expr> != <expr2>:
168 local postfix_operator = C( S"r!" - P"!=" ) + C(P"^") * space_pattern * pow_exponent
169
170
171 local ternary_eval = pgfluamathfunctions.ifthenelse
172
173 local factorial_eval = pgfluamathfunctions.factorial
174 local deg = pgfluamathfunctions.deg
175 local pow_eval = pgfluamathfunctions.pow
176
177 -- @param prefix the argument before the postfix operator.
178 -- @param op either nil or the postfix operator
179 -- @param arg either nil or the (mandatory) argument for 'op'
180 local function postfix_eval(prefix, op, arg)
181 local result
182 if op == nil then
183 result = prefix
184 elseif op == "r" then
185 if arg then error("parser setup error: expected nil argument") end
186 result = deg(prefix)
187 elseif op == "!" then
188 if arg then error("parser setup error: expected nil argument") end
189 result = factorial_eval(prefix)
190 elseif op == "^" then
191 if not arg then error("parser setup error: ^ with its argument") end
192 result = pow_eval(prefix, arg)
193 else
194 error("Parser setup error: " .. tostring(op) .. " unexpected in this context")
195 end
196 return result
197 end
198
199 local function equality_eval(v1, op, v2)
200 local fct
201 if (op == "==") then fct = pgfluamathfunctions.equal
202 elseif (op == "!=") then fct = pgfluamathfunctions.notequal
203 else
204 error("This function must not be invoked for operator "..op)
205 end
206 return fct(v1,v2)
207 end
208 local function relational_eval(v1, op, v2)
209 local fct
210 if (op == "<") then fct = pgfluamathfunctions.less
211 elseif (op == ">") then fct = pgfluamathfunctions.greater
212 elseif (op == ">=") then fct = pgfluamathfunctions.notless
213 elseif (op == "<=") then fct = pgfluamathfunctions.notgreater
214 else
215 error("This function must not be invoked for operator "..op)
216 end
217 return fct(v1,v2)
218 end
219
220 -- @return either the box property or nil
221 -- @param cs "wd", "ht", or "dp"
222 -- @param intSuffix some integer
223 local function get_tex_box(cs, intSuffix)
224 -- assume get_tex_box is only called when a dimension is required.
225 local result
226 pgfluamathparser.units_declared = true
227 local box =tex.box[tonumber(intSuffix)]
228 if not box then error("There is no box " .. intSuffix) end
229 if cs == "wd" then
230 result = box.width / 65536
231 elseif cs == "ht" then
232 result = box.height / 65536
233 elseif cs == "dp" then
234 result = box.depth / 65536
235 else
236 result = nil
237 end
238 return result
239 end
240
241
242 local function controlsequence_eval(cs, intSuffix)
243 local result
244 if intSuffix and #intSuffix >0 then
245 if cs == "count" then
246 result= pgfluamathparser.get_tex_count(intSuffix)
247 elseif cs == "dimen" then
248 result= pgfluamathparser.get_tex_dimen(intSuffix)
249 else
250 result = get_tex_box(cs,intSuffix)
251 if not result then
252 -- this can happen - we cannot expand \chardef'ed boxes here.
253 -- this will be done by the TeX part
254 error('I do not know/support the TeX register "\\' .. cs .. '"')
255 end
256 end
257 else
258 result = pgfluamathparser.get_tex_register(cs)
259 end
260 return result
261 end
262
263 pgfluamathparser.units_declared = false
264 function pgfluamathparser.get_tex_register(register)
265 -- register is a string which could be a count or a dimen.
266 if pcall(tex.getcount, register) then
267 return tex.count[register]
268 elseif pcall(tex.getdimen, register) then
269 pgfluamathparser.units_declared = true
270 return tex.dimen[register] / 65536 -- return in points.
271 else
272 error('I do not know the TeX register "' .. register .. '"')
273 return nil
274 end
275
276 end
277
278 function pgfluamathparser.get_tex_count(count)
279 -- count is expected to be a number
280 return tex.count[tonumber(count)]
281 end
282
283 function pgfluamathparser.get_tex_dimen(dimen)
284 -- dimen is expected to be a number
285 pgfluamathparser.units_declared = true
286 return tex.dimen[tonumber(dimen)] / 65536
287 end
288
289 function pgfluamathparser.get_tex_sp(dimension)
290 -- dimension should be a string
291 pgfluamathparser.units_declared = true
292 return tex.sp(dimension) / 65536
293 end
294
295
296 local initialRule = V"initial"
297
298 local Summand = V"Summand"
299 local Relational = V"Relational"
300 local Equality = V"Equality"
301 local LogicalOr = V"LogicalOr"
302 local LogicalAnd = V"LogicalAnd"
303
304 local pgftonumber = pgfluamathfunctions.tonumber
305 local tonumber_withunit = pgfluamathparser.get_tex_sp
306 local function number_optional_units_eval(x, unit)
307 if not unit then
308 return pgftonumber(x)
309 else
310 return tonumber_withunit(x)
311 end
312 end
313
314 -- @param scale the number.
315 -- @param controlsequence either nil in which case just the number must be returned or a control sequence
316 -- @see controlsequence_eval
317 local function scaled_controlsequence_eval(scale, controlsequence, intSuffix)
318 if controlsequence==nil then
319 return scale
320 else
321 return scale * controlsequence_eval(controlsequence, intSuffix)
322 end
323 end
324
325 -- Grammar
326 --
327 -- for me:
328 -- - use '/' to evaluate all expressions which contain a _constant_ number of captures.
329 -- - use Cf to evaluate expressions which contain a _dynamic_ number of captures
330 --
331 -- see unittest_luamathparser.tex for tons of examples
332 local G = P{ "initialRule",
333 initialRule = space_pattern* Exp * -1;
334 -- ternary operator (or chained ternary operators):
335 -- FIXME : is this chaining a good idea!?
336 Exp = Cf( LogicalOr * Cg(P"?" * space_pattern * LogicalOr * P":" *space_pattern * LogicalOr )^0, ternary_eval) ;
337 LogicalOr = Cf(LogicalAnd * (P"||" * space_pattern * LogicalAnd)^0, pgfluamathfunctions.orPGF);
338 LogicalAnd = Cf(Equality * (P"&&" * space_pattern * Equality)^0, pgfluamathfunctions.andPGF);
339 Equality = Cf(Relational * Cg(EqualityOp * Relational)^0, equality_eval);
340 Relational = Cf(Summand * Cg(RelationalOp * Summand)^0, relational_eval);
341 Summand = Cf(Term * Cg(TermOp * Term)^0, eval) ;
342 Term = Cf(Prefix * Cg(FactorOp * Prefix)^0, eval);
343 Prefix = prefix_operator_pattern + Postfix;
344 -- this calls 'postfix_eval' with nil arguments if it is no postfix operation.. but that does not hurt (right?)
345 Postfix = Factor * (postfix_operator * space_pattern)^-1 / postfix_eval;
346 Factor =
347 (
348 number_pattern / number_optional_units_eval *
349 -- this construction will evaluate number_pattern with 'number_optional_units_eval' FIRST.
350 -- also accept '0.5 \pgf@x' here:
351 space_pattern *controlsequence_pattern^-1 / scaled_controlsequence_eval
352 + func
353 + functionWithoutArg
354 + openparen_pattern * Exp * closeparen_pattern
355 + controlsequence_pattern / controlsequence_eval
356 ) *space_pattern
357 ;
358 }
359
360 -- does not reset units_declared.
361 local function pgfmathparseinternal(str)
362 local result = match(G,str)
363 if result == nil then
364 error("The string '" .. str .. "' is no valid PGF math expression. Please check for syntax errors.")
365 end
366 return result
367 end
368
369
370 -- This is the math parser function in this module.
371 --
372 -- @param str a string like "1+1" which is accepted by the PGF math language
373 -- @return the result of the expression.
374 --
375 -- Throws an error if the string is no valid expression.
376 function pgfluamathparser.pgfmathparse(str)
377 pgfluamathparser.units_declared = false
378
379 return pgfmathparseinternal(str)
380 end
381
382 local pgfmathparse = pgfluamathparser.pgfmathparse
383 local tostringfixed = pgfluamathfunctions.tostringfixed
384 local tostringfpu = pgfluamathfunctions.toTeXstring
385
386 local tmpFunctionArgumentPrefix = "tmpVar"
387 local stackOfLocalFunctions = {}
388
389 -- This is a backend for PGF's 'declare function'.
390 -- \tikzset{declare function={mu(\x,\i)=\x^\i;}}
391 -- will boil down to
392 -- pgfluamathparser.declareExpressionFunction("mu", 2, "#1^#2")
393 --
394 -- The local function will be pushed on a stack of known local functions and is
395 -- available until popLocalExpressionFunction() is called. TeX will call this using
396 -- \aftergroup.
397 --
398 -- @param name the name of the new function
399 -- @param numArgs the number of arguments
400 -- @param expression an expression containing #1, ... #n where n is numArgs
401 --
402 -- ATTENTION: local functions behave DIFFERENTLY in LUA!
403 -- In LUA, local variables are not expanded whereas TeX expands them.
404 -- The difference is
405 --
406 -- declare function={mu1(\x,\i)=\x^\i;}
407 -- \pgfmathparse{mu1(-5,2)} --> -25
408 -- \pgfluamathparse{mu1(-5,2)} --> 25
409 --
410 -- x = -5
411 -- \pgfmathparse{mu1(x,2)} --> 25
412 -- \pgfluamathparse{mu1(x,2)} --> 25
413 --
414 -- In an early prototype, I simulated TeX's expansion to fix the first case (successfully).
415 -- BUT: that "simulated expansion" broke the second case because LUA will evaluate "x" and hand -5 to the local function.
416 -- I decided to keep it as is. Perhaps we should fix PGF's expansion approach in TeX (which is ugly anyway)
417 function pgfluamathparser.pushLocalExpressionFunction(name, numArgs, expression)
418 -- now we have "tmpVar1^tmpVar2" instead of "#1^#2"
419 local normalizedExpr = expression:gsub("#", tmpFunctionArgumentPrefix)
420 local restores = {}
421 local tmpVars = {}
422 for i=1,numArgs do
423 local tmpVar = tmpFunctionArgumentPrefix .. tostring(i)
424 tmpVars[i] = tmpVar
425 end
426
427 local newFunction = function(...)
428 local args = table.pack(...)
429
430 -- define "tmpVar1" ... "tmpVarN" to return args[i].
431 -- Of course, we need to restore "tmpVar<i>" after we return!
432 for i=1,numArgs do
433 local tmpVar = tmpVars[i]
434 local value = args[i]
435 restores[i] = pgfStringToFunctionMap[tmpVar]
436 pgfStringToFunctionMap[tmpVar] = function () return value end
437 end
438
439 -- parse our expression.
440
441 -- FIXME : this here is an attempt to mess around with "units_declared".
442 -- It would be better to call pgfmathparse and introduce some
443 -- semaphore to check if pgfmathparse is a nested call-- in this case, it should
444 -- not reset units_declared. But there is no "finally" block and pcall is crap (looses stack trace).
445 local success,result = pcall(pgfmathparseinternal, normalizedExpr)
446
447 -- remove 'tmpVar1', ... from the function table:
448 for i=1,numArgs do
449 local tmpVar = tmpVars[i]
450 pgfStringToFunctionMap[tmpVar] = restores[i]
451 end
452
453 if success==false then error(result) end
454 return result
455 end
456 table.insert(stackOfLocalFunctions, name)
457 pgfStringToFunctionMap[name] = newFunction
458 end
459
460 function pgfluamathparser.popLocalExpressionFunction()
461 local name = stackOfLocalFunctions[#stackOfLocalFunctions]
462 pgfStringToFunctionMap[name] = nil
463 -- this removes the last element:
464 table.remove(stackOfLocalFunctions)
465 end
466
467
468 -- A Utility function which simplifies the interaction with the TeX code
469 -- @param expression the input expression (string)
470 -- @param outputFormatChoice 0 if the result should be a fixed point number, 1 if it should be in FPU format
471 -- @param showErrorMessage (boolean) true if any error should be displayed, false if errors should simply result in an invocation of TeX's parser (the default)
472 --
473 -- it defines \pgfmathresult and \ifpgfmathunitsdeclared
474 function pgfluamathparser.texCallParser(expression, outputFormatChoice, showErrorMessage)
475 local success, result
476 if showErrorMessage then
477 result = pgfmathparse(expression)
478 success = true
479 else
480 success, result = pcall(pgfmathparse, expression)
481 end
482
483 if success and result then
484 local result_str
485 if outputFormatChoice == 0 then
486 -- luamath/output format=fixed
487 result_str = tostringfixed(result)
488 else
489 -- luamath/output format=fixed
490 result_str = tostringfpu(result)
491 end
492 tex.sprint("\\def\\pgfmathresult{" .. result_str .. "}")
493 if pgfluamathparser.units_declared then
494 tex.sprint("\\pgfmathunitsdeclaredtrue")
495 else
496 tex.sprint("\\pgfmathunitsdeclaredfalse")
497 end
498 else
499 tex.sprint("\\def\\pgfmathresult{}")
500 tex.sprint("\\pgfmathunitsdeclaredfalse")
501 end
502 end
503
504 return pgfluamathparser