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