2 ms·
So you want a language with a computer algebra system (CAS) that reduces expressions such as "x - x" at compile time. This has been doable in Lisp for a long ti
by chongli 12y ago
So you want a language with a computer algebra system (CAS) that reduces expressions such as "x - x" at compile time. This has been doable in Lisp for a long time using macros. It'd be a bit trickier to do in a C-like language due to the syntax but still reasonable.
- TheLoneWolfling 12y agoNah, nothing quite that bad. Most of it could be done with standard optimization techniques that the compiler's already doing. Though you could use a CAS for this, I suppose. Mind you, if you've got a CAS you may as well start using it for more than just this part of the compiler - and that way lies madness. It's relatively easy. For example: int foo(int a) { int x; if (bar()) x = 0; return a*(x - x) + x; } You start with a first pass by just treating variables that may not being defined as though they are parameters to the function. (I'm doing this all in c-ish syntax, just imagine it's actually in the compiler's IR.) So, the above gets mangled into: int foo(int a, int x) { if (bar()) x = 0; return a*(x - x) + x; } And optimized at this stage as normal into int foo(int a, int x) { if (bar()) x = 0; return x; } And... Here's where a CAS comes in handy. Though for most cases you should be able to do pretty well by just choosing any potentially undefined variables to be the first conditional assignment to it. (Or, more likely, searching among "all" (with a limit) possible first assignments to the variable. This gets complex if you've got many variables that are potentially undefined, but that shouldn't happen often. And again, standard optimization techniques.) Which in this case turns into: int foo(int a) { x = 0; if (bar()) x = 0; return x; } And then into int foo(int a) { return 0; } as expected.