The Basic Language

Because we want to keep things simple, the only datatype in Kaleidoscope is a 64-bit floating point type (aka ‘double’ in C parlance). As such, all values are implicitly double precision and the language doesn’t require type declarations. This gives the language a very nice and simple syntax. For example, the following simple example computes Fibonacci numbers:

  1. # Compute the x'th fibonacci number.
  2. def fib(x)
  3. if x < 3 then
  4. 1
  5. else
  6. fib(x-1)+fib(x-2);
  7. # This expression will compute the 40th number.
  8. fib(40);

We also allow Kaleidoscope to call into standard library functions (the LLVM JIT makes this completely trivial). This means that we can use the ‘extern’ keyword to define a function before we use it (this is also useful for mutually recursive functions). For example:

  1. extern sin(arg);
  2. extern cos(arg);
  3. extern atan2(arg1 arg2);
  4. atan2(sin(.4), cos(42));

A more interesting example is included in Chapter 6 where we write a little Kaleidoscope application that displays a Mandelbrot Set at various levels of magnification.

Let’s dive into the implementation of this language!