• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1=================================================
2Kaleidoscope: Tutorial Introduction and the Lexer
3=================================================
4
5.. contents::
6   :local:
7
8Tutorial Introduction
9=====================
10
11Welcome to the "Implementing a language with LLVM" tutorial. This
12tutorial runs through the implementation of a simple language, showing
13how fun and easy it can be. This tutorial will get you up and started as
14well as help to build a framework you can extend to other languages. The
15code in this tutorial can also be used as a playground to hack on other
16LLVM specific things.
17
18The goal of this tutorial is to progressively unveil our language,
19describing how it is built up over time. This will let us cover a fairly
20broad range of language design and LLVM-specific usage issues, showing
21and explaining the code for it all along the way, without overwhelming
22you with tons of details up front.
23
24It is useful to point out ahead of time that this tutorial is really
25about teaching compiler techniques and LLVM specifically, *not* about
26teaching modern and sane software engineering principles. In practice,
27this means that we'll take a number of shortcuts to simplify the
28exposition. For example, the code leaks memory, uses global variables
29all over the place, doesn't use nice design patterns like
30`visitors <http://en.wikipedia.org/wiki/Visitor_pattern>`_, etc... but
31it is very simple. If you dig in and use the code as a basis for future
32projects, fixing these deficiencies shouldn't be hard.
33
34I've tried to put this tutorial together in a way that makes chapters
35easy to skip over if you are already familiar with or are uninterested
36in 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 Objective Caml instead of using lexer and
43   parser generators. LLVM obviously works just fine with such tools,
44   feel free to use one if you prefer.
45-  `Chapter #2 <OCamlLangImpl2.html>`_: Implementing a Parser and
46   AST - With the lexer in place, we can talk about parsing techniques
47   and 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 <OCamlLangImpl3.html>`_: Code generation to LLVM IR -
52   With the AST ready, we can show off how easy generation of LLVM IR
53   really is.
54-  `Chapter #4 <OCamlLangImpl4.html>`_: Adding JIT and Optimizer
55   Support - Because a lot of people are interested in using LLVM as a
56   JIT, we'll dive right into it and show you the 3 lines it takes to
57   add JIT support. LLVM is also useful in many other ways, but this is
58   one simple and "sexy" way to shows off its power. :)
59-  `Chapter #5 <OCamlLangImpl5.html>`_: Extending the Language:
60   Control Flow - With the language up and running, we show how to
61   extend it with control flow operations (if/then/else and a 'for'
62   loop). This gives us a chance to talk about simple SSA construction
63   and control flow.
64-  `Chapter #6 <OCamlLangImpl6.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 <OCamlLangImpl7.html>`_: Extending the Language:
71   Mutable Variables - This chapter talks about adding user-defined
72   local variables along with an assignment operator. The interesting
73   part about this is how easy and trivial it is to construct SSA form
74   in LLVM: no, LLVM does *not* require your front-end to construct SSA
75   form!
76-  `Chapter #8 <OCamlLangImpl8.html>`_: Conclusion and other useful
77   LLVM 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
83By the end of the tutorial, we'll have written a bit less than 700 lines
84of non-comment, non-blank, lines of code. With this small amount of
85code, we'll have built up a very reasonable compiler for a non-trivial
86language including a hand-written lexer, parser, AST, as well as code
87generation support with a JIT compiler. While other systems may have
88interesting "hello world" tutorials, I think the breadth of this
89tutorial is a great testament to the strengths of LLVM and why you
90should consider it if you're interested in language or compiler design.
91
92A note about this tutorial: we expect you to extend the language and
93play with it on your own. Take the code and go crazy hacking away at it,
94compilers don't need to be scary creatures - it can be a lot of fun to
95play with languages!
96
97The Basic Language
98==================
99
100This tutorial will be illustrated with a toy language that we'll call
101"`Kaleidoscope <http://en.wikipedia.org/wiki/Kaleidoscope>`_" (derived
102from "meaning beautiful, form, and view"). Kaleidoscope is a procedural
103language that allows you to define functions, use conditionals, math,
104etc. Over the course of the tutorial, we'll extend Kaleidoscope to
105support the if/then/else construct, a for loop, user defined operators,
106JIT compilation with a simple command line interface, etc.
107
108Because we want to keep things simple, the only datatype in Kaleidoscope
109is a 64-bit floating point type (aka 'float' in OCaml parlance). As
110such, all values are implicitly double precision and the language
111doesn't require type declarations. This gives the language a very nice
112and 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
127We also allow Kaleidoscope to call into standard library functions (the
128LLVM 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
130useful 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
140A more interesting example is included in Chapter 6 where we write a
141little Kaleidoscope application that `displays a Mandelbrot
142Set <OCamlLangImpl6.html#kicking-the-tires>`_ at various levels of magnification.
143
144Lets dive into the implementation of this language!
145
146The Lexer
147=========
148
149When it comes to implementing a language, the first thing needed is the
150ability to process a text file and recognize what it says. The
151traditional 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
154the lexer includes a token code and potentially some metadata (e.g. the
155numeric value of a number). First, we define the possibilities:
156
157.. code-block:: ocaml
158
159    (* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
160     * these others for known things. *)
161    type token =
162      (* commands *)
163      | Def | Extern
164
165      (* primary *)
166      | Ident of string | Number of float
167
168      (* unknown *)
169      | Kwd of char
170
171Each token returned by our lexer will be one of the token variant
172values. An unknown character like '+' will be returned as
173``Token.Kwd '+'``. If the curr token is an identifier, the value will be
174``Token.Ident s``. If the current token is a numeric literal (like 1.0),
175the value will be ``Token.Number 1.0``.
176
177The actual implementation of the lexer is a collection of functions
178driven by a function named ``Lexer.lex``. The ``Lexer.lex`` function is
179called to return the next token from standard input. We will use
180`Camlp4 <http://caml.inria.fr/pub/docs/manual-camlp4/index.html>`_ to
181simplify the tokenization of the standard input. Its definition starts
182as:
183
184.. code-block:: ocaml
185
186    (*===----------------------------------------------------------------------===
187     * Lexer
188     *===----------------------------------------------------------------------===*)
189
190    let rec lex = parser
191      (* Skip any whitespace. *)
192      | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
193
194``Lexer.lex`` works by recursing over a ``char Stream.t`` to read
195characters one at a time from the standard input. It eats them as it
196recognizes them and stores them in in a ``Token.token`` variant. The
197first thing that it has to do is ignore whitespace between tokens. This
198is accomplished with the recursive call above.
199
200The next thing ``Lexer.lex`` needs to do is recognize identifiers and
201specific keywords like "def". Kaleidoscope does this with a pattern
202match and a helper function.
203
204.. code-block:: ocaml
205
206      (* identifier: [a-zA-Z][a-zA-Z0-9] *)
207      | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
208          let buffer = Buffer.create 1 in
209          Buffer.add_char buffer c;
210          lex_ident buffer stream
211
212    ...
213
214    and lex_ident buffer = parser
215      | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
216          Buffer.add_char buffer c;
217          lex_ident buffer stream
218      | [< stream=lex >] ->
219          match Buffer.contents buffer with
220          | "def" -> [< 'Token.Def; stream >]
221          | "extern" -> [< 'Token.Extern; stream >]
222          | id -> [< 'Token.Ident id; stream >]
223
224Numeric values are similar:
225
226.. code-block:: ocaml
227
228      (* number: [0-9.]+ *)
229      | [< ' ('0' .. '9' as c); stream >] ->
230          let buffer = Buffer.create 1 in
231          Buffer.add_char buffer c;
232          lex_number buffer stream
233
234    ...
235
236    and lex_number buffer = parser
237      | [< ' ('0' .. '9' | '.' as c); stream >] ->
238          Buffer.add_char buffer c;
239          lex_number buffer stream
240      | [< stream=lex >] ->
241          [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
242
243This is all pretty straight-forward code for processing input. When
244reading a numeric value from input, we use the ocaml ``float_of_string``
245function to convert it to a numeric value that we store in
246``Token.Number``. Note that this isn't doing sufficient error checking:
247it will raise ``Failure`` if the string "1.23.45.67". Feel free to
248extend it :). Next we handle comments:
249
250.. code-block:: ocaml
251
252      (* Comment until end of line. *)
253      | [< ' ('#'); stream >] ->
254          lex_comment stream
255
256    ...
257
258    and lex_comment = parser
259      | [< ' ('\n'); stream=lex >] -> stream
260      | [< 'c; e=lex_comment >] -> e
261      | [< >] -> [< >]
262
263We handle comments by skipping to the end of the line and then return
264the next token. Finally, if the input doesn't match one of the above
265cases, it is either an operator character like '+' or the end of the
266file. These are handled with this code:
267
268.. code-block:: ocaml
269
270      (* Otherwise, just return the character as its ascii value. *)
271      | [< 'c; stream >] ->
272          [< 'Token.Kwd c; lex stream >]
273
274      (* end of stream. *)
275      | [< >] -> [< >]
276
277With this, we have the complete lexer for the basic Kaleidoscope
278language (the `full code listing <OCamlLangImpl2.html#full-code-listing>`_ for the
279Lexer is available in the `next chapter <OCamlLangImpl2.html>`_ of the
280tutorial). Next we'll `build a simple parser that uses this to build an
281Abstract Syntax Tree <OCamlLangImpl2.html>`_. When we have that, we'll
282include a driver so that you can use the lexer and parser together.
283
284`Next: Implementing a Parser and AST <OCamlLangImpl2.html>`_
285
286