reddit / emacs

Can I use the synatx rules in calc as a parser generator?

isabellaetore · 2022-09-18 03:53
Lets say I want Calc to understand a TeX formula like $\\int\_a\^b f(x) \\mathrm{d} x$. Clearly, there are many ways to write this, I could have just written "d" instead of "\\mathrm", the integral bounds could be just a single lower index indicating a region, "f(x)" could actually consist of derivatives with the same differential notation as "d x", etc. If I could use Backus-Naur form, I would define a non-terminal like INTEGRAL := "\\\\int" REGION INTEGRAND DIFFERENTIAL DUMMY\_VAR and then individually handle all of these edge cases in each non-terminal. For instance, I could write REGION to accept empty patterns for indefinite integrals, or to accept just a subscript for regions, similarly for DIFFERENTIAL or INTEGRAND. Instead, in Calc, I have to write a messy rewrite rule to just handle the REGION part, and I am not even sure if the INTEGRAND symbol could be implemented since any integrand having terms that look like $\\frac{d f}{d x}$ would prematurely terminate parsing as the denominator would be interpreted as DIFFERENTIAL. It seems to me that Calc is formally incapable of handling these complications, but I may be wrong. Are there ways within calc to implemen the functinality I want? If not, are there libraries that allow me to augment Calc in this way? Failing that, I would be willing to use the Wisent parser generator, but how do I integrate it into Calc?
holgerschurig · 2022-09-23 01:11
> formally incapable You are formally wrong. Lisp isa touring complete language, so certainly you can code up any parsing.Is it easy? You didn't ask. Is it pleasure? Personal preference - I always get hefty 1980 vibes when I have to code something larger in Lisp. But is it doable? Certainly. > within calc You artificially separate calc and Lisp, why? The whole idea of Lisp machines (and Emacs is arguably an implementation of one) is that you can extend/advice anything. You just said "let's ignore all of this". If you limit yourself to what you can enter at the "M-x calc" prompt, then you limit yourself severely. Calc is meant to be expanded via Lisp, see here: https://www.gnu.org/software/emacs/manual/html_node/calc/Lisp-Definitions.html Also calc normally works in stack mode. But it also has a parser for other languages, it can e.g. do infix. Perhaps you start your journey from calc-embedded, see https://www.gnu.org/software/emacs/manual/html_node/calc/Basic-Embedded-Mode.html