I don't actually write much C-style C, but here's some Forth-style C (or at least what I call Forth-style C):tepples wrote:Could you show an example of C-style C and the corresponding Forth-style C?
Code: Select all
int f = 0;
for(size_t i = 0; i < instructions; i++)
{
int op = in[i].op;
int var = in[i].var;
if(op == FUNCTION)
{
f = var;
}
else if(op == JSR)
{
int t = function[var].stack + function[var].locals;
if(t > function[f].stack)
{
function[f].stack = t;
}
}
}
My language forbids forward references in order to prevent accidental recursion (which is impossible with static allocation); to allow those, simply repeat the above routine until function[f].stack = t; stops being executed. (Note that it will never stop executing in the case of recursion.)
I call this code "Forth-style" because it solves a hard problem (building a call graph and allocating stack frames such that their addresses ranges overlap only if they are never active at the same time) with a trivial algorithm (iterating over an assembly listing). It uses zero space (other than space already allocated and used outside the routine), executes in time linear in the size of the program (assuming no forward references, trivially true for my application), and produces an optimal result (RAM usage of any branch of the call graph is exactly equal to the sum of the stack usage of all functions along that branch), in 21 lines of code (including 3 blanks and 8 braces).
The equivalent "C-style" code would build the call graph as an explicit data structure, then apply some form of graph-colouring algorithm to perform the allocation, and would probably total several thousand lines of code. I know that sounds like I'm deliberately bashing on C programmers, but that's only because I picked something I happen know a simple solution to, for maximum contrast.
EDIT
Stack juggling is the #1 most common complaint about Forth (not C) due to its rigidly RPN syntax. I'm refering to "pure" Forth, without named local variables, which were added for ease of use by non-Forth programmers, and result in "C-style Forth" code. (I had a link to a perfect example of what I mean by "C-style Forth", but the page seems to have vanished.)rainwarrior wrote:I thought "stack juggling" was an assembly language concern, not a C concern?