blob: b04cde10274e05fa6a8fee964698e70716884112 [file] [log] [blame]
Sean Silvad7fb3962012-12-05 00:26:32 +00001=================================================
2Kaleidoscope: Tutorial Introduction and the Lexer
3=================================================
4
5.. contents::
6 :local:
7
Sean Silvad7fb3962012-12-05 00:26:32 +00008Tutorial 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
Lang Hames09bf4c12015-08-18 18:11:06 +000028exposition. For example, the code uses global variables
Sean Silvad7fb3962012-12-05 00:26:32 +000029all 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 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
Nikola Smiljanic39354b32013-05-01 13:05:43 +000058 simple and "sexy" way to show off its power. :)
Sean Silvad7fb3962012-12-05 00:26:32 +000059- `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!
Charlie Turnerd415cc82015-01-24 21:51:21 +000076- `Chapter #8 <LangImpl8.html>`_: Extending the Language: Debug
77 Information - Having built a decent little programming language with
78 control flow, functions and mutable variables, we consider what it
79 takes to add debug information to standalone executables. This debug
80 information will allow you to set breakpoints in Kaleidoscope
81 functions, print out argument variables, and call functions - all
82 from within the debugger!
83- `Chapter #9 <LangImpl8.html>`_: Conclusion and other useful LLVM
Sean Silvad7fb3962012-12-05 00:26:32 +000084 tidbits - This chapter wraps up the series by talking about
85 potential ways to extend the language, but also includes a bunch of
86 pointers to info about "special topics" like adding garbage
87 collection support, exceptions, debugging, support for "spaghetti
88 stacks", and a bunch of other tips and tricks.
89
Charlie Turner6cba0642015-01-24 21:51:17 +000090By the end of the tutorial, we'll have written a bit less than 1000 lines
Sean Silvad7fb3962012-12-05 00:26:32 +000091of non-comment, non-blank, lines of code. With this small amount of
92code, we'll have built up a very reasonable compiler for a non-trivial
93language including a hand-written lexer, parser, AST, as well as code
94generation support with a JIT compiler. While other systems may have
95interesting "hello world" tutorials, I think the breadth of this
96tutorial is a great testament to the strengths of LLVM and why you
97should consider it if you're interested in language or compiler design.
98
99A note about this tutorial: we expect you to extend the language and
100play with it on your own. Take the code and go crazy hacking away at it,
101compilers don't need to be scary creatures - it can be a lot of fun to
102play with languages!
103
104The Basic Language
105==================
106
107This tutorial will be illustrated with a toy language that we'll call
108"`Kaleidoscope <http://en.wikipedia.org/wiki/Kaleidoscope>`_" (derived
109from "meaning beautiful, form, and view"). Kaleidoscope is a procedural
110language that allows you to define functions, use conditionals, math,
111etc. Over the course of the tutorial, we'll extend Kaleidoscope to
112support the if/then/else construct, a for loop, user defined operators,
113JIT compilation with a simple command line interface, etc.
114
115Because we want to keep things simple, the only datatype in Kaleidoscope
116is a 64-bit floating point type (aka 'double' in C parlance). As such,
117all values are implicitly double precision and the language doesn't
118require type declarations. This gives the language a very nice and
119simple syntax. For example, the following simple example computes
120`Fibonacci numbers: <http://en.wikipedia.org/wiki/Fibonacci_number>`_
121
122::
123
124 # Compute the x'th fibonacci number.
125 def fib(x)
126 if x < 3 then
127 1
128 else
129 fib(x-1)+fib(x-2)
130
131 # This expression will compute the 40th number.
132 fib(40)
133
134We also allow Kaleidoscope to call into standard library functions (the
135LLVM JIT makes this completely trivial). This means that you can use the
136'extern' keyword to define a function before you use it (this is also
137useful for mutually recursive functions). For example:
138
139::
140
141 extern sin(arg);
142 extern cos(arg);
143 extern atan2(arg1 arg2);
144
145 atan2(sin(.4), cos(42))
146
147A more interesting example is included in Chapter 6 where we write a
148little Kaleidoscope application that `displays a Mandelbrot
Alex Denisov596e9792015-12-15 20:50:29 +0000149Set <LangImpl6.html#kicking-the-tires>`_ at various levels of magnification.
Sean Silvad7fb3962012-12-05 00:26:32 +0000150
151Lets dive into the implementation of this language!
152
153The Lexer
154=========
155
156When it comes to implementing a language, the first thing needed is the
157ability to process a text file and recognize what it says. The
158traditional way to do this is to use a
159"`lexer <http://en.wikipedia.org/wiki/Lexical_analysis>`_" (aka
160'scanner') to break the input up into "tokens". Each token returned by
161the lexer includes a token code and potentially some metadata (e.g. the
162numeric value of a number). First, we define the possibilities:
163
164.. code-block:: c++
165
166 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
167 // of these for known things.
168 enum Token {
169 tok_eof = -1,
170
171 // commands
Lang Hames59b0da82015-08-19 18:15:58 +0000172 tok_def = -2,
173 tok_extern = -3,
Sean Silvad7fb3962012-12-05 00:26:32 +0000174
175 // primary
Lang Hames59b0da82015-08-19 18:15:58 +0000176 tok_identifier = -4,
177 tok_number = -5,
Sean Silvad7fb3962012-12-05 00:26:32 +0000178 };
179
Lang Hames59b0da82015-08-19 18:15:58 +0000180 static std::string IdentifierStr; // Filled in if tok_identifier
181 static double NumVal; // Filled in if tok_number
Sean Silvad7fb3962012-12-05 00:26:32 +0000182
183Each token returned by our lexer will either be one of the Token enum
184values or it will be an 'unknown' character like '+', which is returned
185as its ASCII value. If the current token is an identifier, the
186``IdentifierStr`` global variable holds the name of the identifier. If
187the current token is a numeric literal (like 1.0), ``NumVal`` holds its
188value. Note that we use global variables for simplicity, this is not the
189best choice for a real language implementation :).
190
191The actual implementation of the lexer is a single function named
192``gettok``. The ``gettok`` function is called to return the next token
193from standard input. Its definition starts as:
194
195.. code-block:: c++
196
197 /// gettok - Return the next token from standard input.
198 static int gettok() {
199 static int LastChar = ' ';
200
201 // Skip any whitespace.
202 while (isspace(LastChar))
203 LastChar = getchar();
204
205``gettok`` works by calling the C ``getchar()`` function to read
206characters one at a time from standard input. It eats them as it
207recognizes them and stores the last character read, but not processed,
208in LastChar. The first thing that it has to do is ignore whitespace
209between tokens. This is accomplished with the loop above.
210
211The next thing ``gettok`` needs to do is recognize identifiers and
212specific keywords like "def". Kaleidoscope does this with this simple
213loop:
214
215.. code-block:: c++
216
217 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
218 IdentifierStr = LastChar;
219 while (isalnum((LastChar = getchar())))
220 IdentifierStr += LastChar;
221
Lang Hames59b0da82015-08-19 18:15:58 +0000222 if (IdentifierStr == "def")
223 return tok_def;
224 if (IdentifierStr == "extern")
225 return tok_extern;
Sean Silvad7fb3962012-12-05 00:26:32 +0000226 return tok_identifier;
227 }
228
229Note that this code sets the '``IdentifierStr``' global whenever it
230lexes an identifier. Also, since language keywords are matched by the
231same loop, we handle them here inline. Numeric values are similar:
232
233.. code-block:: c++
234
235 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
236 std::string NumStr;
237 do {
238 NumStr += LastChar;
239 LastChar = getchar();
240 } while (isdigit(LastChar) || LastChar == '.');
241
242 NumVal = strtod(NumStr.c_str(), 0);
243 return tok_number;
244 }
245
246This is all pretty straight-forward code for processing input. When
247reading a numeric value from input, we use the C ``strtod`` function to
248convert it to a numeric value that we store in ``NumVal``. Note that
249this isn't doing sufficient error checking: it will incorrectly read
250"1.23.45.67" and handle it as if you typed in "1.23". Feel free to
251extend it :). Next we handle comments:
252
253.. code-block:: c++
254
255 if (LastChar == '#') {
256 // Comment until end of line.
Lang Hames59b0da82015-08-19 18:15:58 +0000257 do
258 LastChar = getchar();
Sean Silvad7fb3962012-12-05 00:26:32 +0000259 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
260
261 if (LastChar != EOF)
262 return gettok();
263 }
264
265We handle comments by skipping to the end of the line and then return
266the next token. Finally, if the input doesn't match one of the above
267cases, it is either an operator character like '+' or the end of the
268file. These are handled with this code:
269
270.. code-block:: c++
271
272 // Check for end of file. Don't eat the EOF.
273 if (LastChar == EOF)
274 return tok_eof;
275
276 // Otherwise, just return the character as its ascii value.
277 int ThisChar = LastChar;
278 LastChar = getchar();
279 return ThisChar;
280 }
281
282With this, we have the complete lexer for the basic Kaleidoscope
Alex Denisov596e9792015-12-15 20:50:29 +0000283language (the `full code listing <LangImpl2.html#full-code-listing>`_ for the Lexer
Sean Silvad7fb3962012-12-05 00:26:32 +0000284is available in the `next chapter <LangImpl2.html>`_ of the tutorial).
285Next we'll `build a simple parser that uses this to build an Abstract
286Syntax Tree <LangImpl2.html>`_. When we have that, we'll include a
287driver so that you can use the lexer and parser together.
288
289`Next: Implementing a Parser and AST <LangImpl2.html>`_
290