blob: eb84e4c923b44f6383e7ce3a0242bf9d7f39d2cd [file] [log] [blame]
Sean Silvaee47edf2012-12-05 00:26:32 +00001=================================================
2Kaleidoscope: Tutorial Introduction and the Lexer
3=================================================
4
5.. contents::
6 :local:
7
8Written by `Chris Lattner <mailto:sabre@nondot.org>`_
9
10Tutorial Introduction
11=====================
12
13Welcome to the "Implementing a language with LLVM" tutorial. This
14tutorial runs through the implementation of a simple language, showing
15how fun and easy it can be. This tutorial will get you up and started as
16well as help to build a framework you can extend to other languages. The
17code in this tutorial can also be used as a playground to hack on other
18LLVM specific things.
19
20The goal of this tutorial is to progressively unveil our language,
21describing how it is built up over time. This will let us cover a fairly
22broad range of language design and LLVM-specific usage issues, showing
23and explaining the code for it all along the way, without overwhelming
24you with tons of details up front.
25
26It is useful to point out ahead of time that this tutorial is really
27about teaching compiler techniques and LLVM specifically, *not* about
28teaching modern and sane software engineering principles. In practice,
29this means that we'll take a number of shortcuts to simplify the
30exposition. For example, the code leaks memory, uses global variables
31all over the place, doesn't use nice design patterns like
32`visitors <http://en.wikipedia.org/wiki/Visitor_pattern>`_, etc... but
33it is very simple. If you dig in and use the code as a basis for future
34projects, fixing these deficiencies shouldn't be hard.
35
36I've tried to put this tutorial together in a way that makes chapters
37easy to skip over if you are already familiar with or are uninterested
38in 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
85By the end of the tutorial, we'll have written a bit less than 700 lines
86of non-comment, non-blank, lines of code. With this small amount of
87code, we'll have built up a very reasonable compiler for a non-trivial
88language including a hand-written lexer, parser, AST, as well as code
89generation support with a JIT compiler. While other systems may have
90interesting "hello world" tutorials, I think the breadth of this
91tutorial is a great testament to the strengths of LLVM and why you
92should consider it if you're interested in language or compiler design.
93
94A note about this tutorial: we expect you to extend the language and
95play with it on your own. Take the code and go crazy hacking away at it,
96compilers don't need to be scary creatures - it can be a lot of fun to
97play with languages!
98
99The Basic Language
100==================
101
102This tutorial will be illustrated with a toy language that we'll call
103"`Kaleidoscope <http://en.wikipedia.org/wiki/Kaleidoscope>`_" (derived
104from "meaning beautiful, form, and view"). Kaleidoscope is a procedural
105language that allows you to define functions, use conditionals, math,
106etc. Over the course of the tutorial, we'll extend Kaleidoscope to
107support the if/then/else construct, a for loop, user defined operators,
108JIT compilation with a simple command line interface, etc.
109
110Because we want to keep things simple, the only datatype in Kaleidoscope
111is a 64-bit floating point type (aka 'double' in C parlance). As such,
112all values are implicitly double precision and the language doesn't
113require type declarations. This gives the language a very nice and
114simple 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
129We also allow Kaleidoscope to call into standard library functions (the
130LLVM 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
132useful 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
142A more interesting example is included in Chapter 6 where we write a
143little Kaleidoscope application that `displays a Mandelbrot
144Set <LangImpl6.html#example>`_ at various levels of magnification.
145
146Lets dive into the implementation of this language!
147
148The Lexer
149=========
150
151When it comes to implementing a language, the first thing needed is the
152ability to process a text file and recognize what it says. The
153traditional 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
156the lexer includes a token code and potentially some metadata (e.g. the
157numeric 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
176Each token returned by our lexer will either be one of the Token enum
177values or it will be an 'unknown' character like '+', which is returned
178as its ASCII value. If the current token is an identifier, the
179``IdentifierStr`` global variable holds the name of the identifier. If
180the current token is a numeric literal (like 1.0), ``NumVal`` holds its
181value. Note that we use global variables for simplicity, this is not the
182best choice for a real language implementation :).
183
184The actual implementation of the lexer is a single function named
185``gettok``. The ``gettok`` function is called to return the next token
186from 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
199characters one at a time from standard input. It eats them as it
200recognizes them and stores the last character read, but not processed,
201in LastChar. The first thing that it has to do is ignore whitespace
202between tokens. This is accomplished with the loop above.
203
204The next thing ``gettok`` needs to do is recognize identifiers and
205specific keywords like "def". Kaleidoscope does this with this simple
206loop:
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
220Note that this code sets the '``IdentifierStr``' global whenever it
221lexes an identifier. Also, since language keywords are matched by the
222same 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
237This is all pretty straight-forward code for processing input. When
238reading a numeric value from input, we use the C ``strtod`` function to
239convert it to a numeric value that we store in ``NumVal``. Note that
240this 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
242extend 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
255We handle comments by skipping to the end of the line and then return
256the next token. Finally, if the input doesn't match one of the above
257cases, it is either an operator character like '+' or the end of the
258file. 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
272With this, we have the complete lexer for the basic Kaleidoscope
273language (the `full code listing <LangImpl2.html#code>`_ for the Lexer
274is available in the `next chapter <LangImpl2.html>`_ of the tutorial).
275Next we'll `build a simple parser that uses this to build an Abstract
276Syntax Tree <LangImpl2.html>`_. When we have that, we'll include a
277driver so that you can use the lexer and parser together.
278
279`Next: Implementing a Parser and AST <LangImpl2.html>`_
280