Home   Archive   Permalink



Putting the C in 'Ren-C': User Natives

An experimental feature of Ren-C added by Shixin Zeng years ago has been getting some reworking since the new year, and it's really quite nice. It's the ability to code a Rebol function with what looks like an ordinary spec BLOCK!, but whose body is a textual string of C code.
    
As an example, here's a Fibonacci function:
    
     c-fib: make-native [
         "nth Fibonacci Number"
         n [integer!]
     ]{
         int n = rebUnboxInteger(rebArgR("n"));
         if (n < 0) { return rebInteger(-1); }
         if (n <= 1) { return rebInteger(n); }
         int i0 = 0;
         int i1 = 1;
         while (n > 1) {
             int t = i1;
             i1 = i0 + i1;
             i0 = t;
             --n;
         }
         return rebInteger(i1);
     }
    
There's an elegantly designed set of routines for picking apart and building up Rebol values--which deserve a whole discussion in its own right! But here you see a basic extraction of a C `int` from a parameter that's a Rebol value, and a few return statements that produce Rebol values from C integers.
    
This is achieved by way of an extension that integrates the TCC "TinyC" compiler. The extension is optional in the build settings when you compile Ren-C:
    
https://github.com/metaeducation/ren-c/tree/master/extensions/tcc
    
Although TCC isn't an optimizing compiler, the performance is not actually that bad. As users of Red/System have observed, GCC's optimizations get you maybe a factor of 2 or 3 advantage overall on the average code. For many things you won't notice, especially relative to the *much* slower speed of an interpreter. A single addition takes hundreds of CPU cycles instead of just a few!
    
Just as a random example, the user native above is about 60x faster or so than the equivalent Rebol code:
    
https://github.com/metaeducation/ren-c/blob/master/tests/misc/fib.r
    
Anyway, just one of the interesting things we'll be talking about at the conference. I'm already in Philadelphia--planning to take in the 4th-of-July events beforehand...

posted by:   Fork     4-Jun-2019/0:39:49-7:00