Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recognizing Tail-recursive functions with Flex+Bison and convert code to an Iterative form

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.

like image 618
Viet Avatar asked Apr 02 '26 19:04

Viet


1 Answers

As I suggested in my comment, this is not an issue at all for the lexer, and possibly only slightly so for the parser. If you have a function something like this:

func f( a ) 
    if ( a == 0 )  
       return a
    return f( a - 1 )

then for a typical C compiler it would be up to the optimiser/code generator to convert that recursive call to a loop. Of course, in an interpretive calculator, you can be much more flexible, but I'd suggest that it's still one of the last processes that should perform the tail call removal, not the first ones.