I’m writing a calculator with an ability to accept new function definitions. Being aware of the need of newbies to try recursive functions such as Fibonacci, I would like my calculator to be able to recognize Tail-recursive functions with Flex + Bison and convert code to an Iterative form. I’m using Flex & Bison to do the job. If you have any hints or ideas, I welcome them warmly. Thanks!
EDIT:
Let’s not worry about C or C++ output from Flex & Bison. Mainly I want an idea or a hint. Thanks.
Suppose you have a function…
then note that the AST will have something like return -> func -> otherargs, with some annotations about types and whatevers. When you walk it and note that there exists return F where F is the current function frame, you can transform that into PUSH ARGS, GOTO F, instead of fully forming the stack frame and so forth. You’ll have to fiddle the return values yourself.
Also note this will be substantially harder if you want to walk-and-execute, instead of having a multipass system. My instinct suggests that walk-and-execute will require a lookahead.
And, no, I don’t think bison will do this for you without chaining parsers. You are analyzing semantics in a context-sensitive fashion.