Home | History | Annotate | Download | only in tutorial
      1 =================================================
      2 Kaleidoscope: Tutorial Introduction and the Lexer
      3 =================================================
      4 
      5 .. contents::
      6    :local:
      7 
      8 Tutorial Introduction
      9 =====================
     10 
     11 Welcome to the "Implementing a language with LLVM" tutorial. This
     12 tutorial runs through the implementation of a simple language, showing
     13 how fun and easy it can be. This tutorial will get you up and started as
     14 well as help to build a framework you can extend to other languages. The
     15 code in this tutorial can also be used as a playground to hack on other
     16 LLVM specific things.
     17 
     18 The goal of this tutorial is to progressively unveil our language,
     19 describing how it is built up over time. This will let us cover a fairly
     20 broad range of language design and LLVM-specific usage issues, showing
     21 and explaining the code for it all along the way, without overwhelming
     22 you with tons of details up front.
     23 
     24 It is useful to point out ahead of time that this tutorial is really
     25 about teaching compiler techniques and LLVM specifically, *not* about
     26 teaching modern and sane software engineering principles. In practice,
     27 this means that we'll take a number of shortcuts to simplify the
     28 exposition. For example, the code leaks memory, uses global variables
     29 all over the place, doesn't use nice design patterns like
     30 `visitors <http://en.wikipedia.org/wiki/Visitor_pattern>`_, etc... but
     31 it is very simple. If you dig in and use the code as a basis for future
     32 projects, fixing these deficiencies shouldn't be hard.
     33 
     34 I've tried to put this tutorial together in a way that makes chapters
     35 easy to skip over if you are already familiar with or are uninterested
     36 in the various pieces. The structure of the tutorial is:
     37 
     38 -  `Chapter #1 <#language>`_: Introduction to the Kaleidoscope
     39    language, and the definition of its Lexer - This shows where we are
     40    going and the basic functionality that we want it to do. In order to
     41    make this tutorial maximally understandable and hackable, we choose
     42    to implement everything in C++ instead of using lexer and parser
     43    generators. LLVM obviously works just fine with such tools, feel free
     44    to use one if you prefer.
     45 -  `Chapter #2 <LangImpl2.html>`_: Implementing a Parser and AST -
     46    With the lexer in place, we can talk about parsing techniques and
     47    basic AST construction. This tutorial describes recursive descent
     48    parsing and operator precedence parsing. Nothing in Chapters 1 or 2
     49    is LLVM-specific, the code doesn't even link in LLVM at this point.
     50    :)
     51 -  `Chapter #3 <LangImpl3.html>`_: Code generation to LLVM IR - With
     52    the AST ready, we can show off how easy generation of LLVM IR really
     53    is.
     54 -  `Chapter #4 <LangImpl4.html>`_: Adding JIT and Optimizer Support
     55    - Because a lot of people are interested in using LLVM as a JIT,
     56    we'll dive right into it and show you the 3 lines it takes to add JIT
     57    support. LLVM is also useful in many other ways, but this is one
     58    simple and "sexy" way to show off its power. :)
     59 -  `Chapter #5 <LangImpl5.html>`_: Extending the Language: Control
     60    Flow - With the language up and running, we show how to extend it
     61    with control flow operations (if/then/else and a 'for' loop). This
     62    gives us a chance to talk about simple SSA construction and control
     63    flow.
     64 -  `Chapter #6 <LangImpl6.html>`_: Extending the Language:
     65    User-defined Operators - This is a silly but fun chapter that talks
     66    about extending the language to let the user program define their own
     67    arbitrary unary and binary operators (with assignable precedence!).
     68    This lets us build a significant piece of the "language" as library
     69    routines.
     70 -  `Chapter #7 <LangImpl7.html>`_: Extending the Language: Mutable
     71    Variables - This chapter talks about adding user-defined local
     72    variables along with an assignment operator. The interesting part
     73    about this is how easy and trivial it is to construct SSA form in
     74    LLVM: no, LLVM does *not* require your front-end to construct SSA
     75    form!
     76 -  `Chapter #8 <LangImpl8.html>`_: Conclusion and other useful LLVM
     77    tidbits - This chapter wraps up the series by talking about
     78    potential ways to extend the language, but also includes a bunch of
     79    pointers to info about "special topics" like adding garbage
     80    collection support, exceptions, debugging, support for "spaghetti
     81    stacks", and a bunch of other tips and tricks.
     82 
     83 By the end of the tutorial, we'll have written a bit less than 700 lines
     84 of non-comment, non-blank, lines of code. With this small amount of
     85 code, we'll have built up a very reasonable compiler for a non-trivial
     86 language including a hand-written lexer, parser, AST, as well as code
     87 generation support with a JIT compiler. While other systems may have
     88 interesting "hello world" tutorials, I think the breadth of this
     89 tutorial is a great testament to the strengths of LLVM and why you
     90 should consider it if you're interested in language or compiler design.
     91 
     92 A note about this tutorial: we expect you to extend the language and
     93 play with it on your own. Take the code and go crazy hacking away at it,
     94 compilers don't need to be scary creatures - it can be a lot of fun to
     95 play with languages!
     96 
     97 The Basic Language
     98 ==================
     99 
    100 This tutorial will be illustrated with a toy language that we'll call
    101 "`Kaleidoscope <http://en.wikipedia.org/wiki/Kaleidoscope>`_" (derived
    102 from "meaning beautiful, form, and view"). Kaleidoscope is a procedural
    103 language that allows you to define functions, use conditionals, math,
    104 etc. Over the course of the tutorial, we'll extend Kaleidoscope to
    105 support the if/then/else construct, a for loop, user defined operators,
    106 JIT compilation with a simple command line interface, etc.
    107 
    108 Because we want to keep things simple, the only datatype in Kaleidoscope
    109 is a 64-bit floating point type (aka 'double' in C parlance). As such,
    110 all values are implicitly double precision and the language doesn't
    111 require type declarations. This gives the language a very nice and
    112 simple syntax. For example, the following simple example computes
    113 `Fibonacci numbers: <http://en.wikipedia.org/wiki/Fibonacci_number>`_
    114 
    115 ::
    116 
    117     # Compute the x'th fibonacci number.
    118     def fib(x)
    119       if x < 3 then
    120         1
    121       else
    122         fib(x-1)+fib(x-2)
    123 
    124     # This expression will compute the 40th number.
    125     fib(40)
    126 
    127 We also allow Kaleidoscope to call into standard library functions (the
    128 LLVM JIT makes this completely trivial). This means that you can use the
    129 'extern' keyword to define a function before you use it (this is also
    130 useful for mutually recursive functions). For example:
    131 
    132 ::
    133 
    134     extern sin(arg);
    135     extern cos(arg);
    136     extern atan2(arg1 arg2);
    137 
    138     atan2(sin(.4), cos(42))
    139 
    140 A more interesting example is included in Chapter 6 where we write a
    141 little Kaleidoscope application that `displays a Mandelbrot
    142 Set <LangImpl6.html#example>`_ at various levels of magnification.
    143 
    144 Lets dive into the implementation of this language!
    145 
    146 The Lexer
    147 =========
    148 
    149 When it comes to implementing a language, the first thing needed is the
    150 ability to process a text file and recognize what it says. The
    151 traditional way to do this is to use a
    152 "`lexer <http://en.wikipedia.org/wiki/Lexical_analysis>`_" (aka
    153 'scanner') to break the input up into "tokens". Each token returned by
    154 the lexer includes a token code and potentially some metadata (e.g. the
    155 numeric value of a number). First, we define the possibilities:
    156 
    157 .. code-block:: c++
    158 
    159     // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
    160     // of these for known things.
    161     enum Token {
    162       tok_eof = -1,
    163 
    164       // commands
    165       tok_def = -2, tok_extern = -3,
    166 
    167       // primary
    168       tok_identifier = -4, tok_number = -5,
    169     };
    170 
    171     static std::string IdentifierStr;  // Filled in if tok_identifier
    172     static double NumVal;              // Filled in if tok_number
    173 
    174 Each token returned by our lexer will either be one of the Token enum
    175 values or it will be an 'unknown' character like '+', which is returned
    176 as its ASCII value. If the current token is an identifier, the
    177 ``IdentifierStr`` global variable holds the name of the identifier. If
    178 the current token is a numeric literal (like 1.0), ``NumVal`` holds its
    179 value. Note that we use global variables for simplicity, this is not the
    180 best choice for a real language implementation :).
    181 
    182 The actual implementation of the lexer is a single function named
    183 ``gettok``. The ``gettok`` function is called to return the next token
    184 from standard input. Its definition starts as:
    185 
    186 .. code-block:: c++
    187 
    188     /// gettok - Return the next token from standard input.
    189     static int gettok() {
    190       static int LastChar = ' ';
    191 
    192       // Skip any whitespace.
    193       while (isspace(LastChar))
    194         LastChar = getchar();
    195 
    196 ``gettok`` works by calling the C ``getchar()`` function to read
    197 characters one at a time from standard input. It eats them as it
    198 recognizes them and stores the last character read, but not processed,
    199 in LastChar. The first thing that it has to do is ignore whitespace
    200 between tokens. This is accomplished with the loop above.
    201 
    202 The next thing ``gettok`` needs to do is recognize identifiers and
    203 specific keywords like "def". Kaleidoscope does this with this simple
    204 loop:
    205 
    206 .. code-block:: c++
    207 
    208       if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
    209         IdentifierStr = LastChar;
    210         while (isalnum((LastChar = getchar())))
    211           IdentifierStr += LastChar;
    212 
    213         if (IdentifierStr == "def") return tok_def;
    214         if (IdentifierStr == "extern") return tok_extern;
    215         return tok_identifier;
    216       }
    217 
    218 Note that this code sets the '``IdentifierStr``' global whenever it
    219 lexes an identifier. Also, since language keywords are matched by the
    220 same loop, we handle them here inline. Numeric values are similar:
    221 
    222 .. code-block:: c++
    223 
    224       if (isdigit(LastChar) || LastChar == '.') {   // Number: [0-9.]+
    225         std::string NumStr;
    226         do {
    227           NumStr += LastChar;
    228           LastChar = getchar();
    229         } while (isdigit(LastChar) || LastChar == '.');
    230 
    231         NumVal = strtod(NumStr.c_str(), 0);
    232         return tok_number;
    233       }
    234 
    235 This is all pretty straight-forward code for processing input. When
    236 reading a numeric value from input, we use the C ``strtod`` function to
    237 convert it to a numeric value that we store in ``NumVal``. Note that
    238 this isn't doing sufficient error checking: it will incorrectly read
    239 "1.23.45.67" and handle it as if you typed in "1.23". Feel free to
    240 extend it :). Next we handle comments:
    241 
    242 .. code-block:: c++
    243 
    244       if (LastChar == '#') {
    245         // Comment until end of line.
    246         do LastChar = getchar();
    247         while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
    248 
    249         if (LastChar != EOF)
    250           return gettok();
    251       }
    252 
    253 We handle comments by skipping to the end of the line and then return
    254 the next token. Finally, if the input doesn't match one of the above
    255 cases, it is either an operator character like '+' or the end of the
    256 file. These are handled with this code:
    257 
    258 .. code-block:: c++
    259 
    260       // Check for end of file.  Don't eat the EOF.
    261       if (LastChar == EOF)
    262         return tok_eof;
    263 
    264       // Otherwise, just return the character as its ascii value.
    265       int ThisChar = LastChar;
    266       LastChar = getchar();
    267       return ThisChar;
    268     }
    269 
    270 With this, we have the complete lexer for the basic Kaleidoscope
    271 language (the `full code listing <LangImpl2.html#code>`_ for the Lexer
    272 is available in the `next chapter <LangImpl2.html>`_ of the tutorial).
    273 Next we'll `build a simple parser that uses this to build an Abstract
    274 Syntax Tree <LangImpl2.html>`_. When we have that, we'll include a
    275 driver so that you can use the lexer and parser together.
    276 
    277 `Next: Implementing a Parser and AST <LangImpl2.html>`_
    278 
    279