blob: 66843db5d3af0f0e6a45ba72d67fd4be53669549 [file] [log] [blame]
Chris Lattnerc38ef542007-10-22 04:32:37 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
3
4<html>
5<head>
Chris Lattner95ce0d62007-11-06 05:02:48 +00006 <title>Kaleidoscope: Tutorial Introduction and the Lexer</title>
Chris Lattnerc38ef542007-10-22 04:32:37 +00007 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
8 <meta name="author" content="Chris Lattner">
9 <link rel="stylesheet" href="../llvm.css" type="text/css">
10</head>
11
12<body>
13
Chris Lattner95ce0d62007-11-06 05:02:48 +000014<div class="doc_title">Kaleidoscope: Tutorial Introduction and the Lexer</div>
Chris Lattnerc38ef542007-10-22 04:32:37 +000015
Chris Lattner128eb862007-11-05 19:06:59 +000016<ul>
Chris Lattner0e555b12007-11-05 20:04:56 +000017<li><a href="index.html">Up to Tutorial Index</a></li>
Chris Lattner128eb862007-11-05 19:06:59 +000018<li>Chapter 1
19 <ol>
20 <li><a href="#intro">Tutorial Introduction</a></li>
21 <li><a href="#language">The Basic Language</a></li>
22 <li><a href="#lexer">The Lexer</a></li>
23 </ol>
24</li>
Chris Lattner0e555b12007-11-05 20:04:56 +000025<li><a href="LangImpl2.html">Chapter 2</a>: Implementing a Parser and AST</li>
Chris Lattner128eb862007-11-05 19:06:59 +000026</ul>
27
Chris Lattnerc38ef542007-10-22 04:32:37 +000028<div class="doc_author">
29 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
30</div>
31
32<!-- *********************************************************************** -->
33<div class="doc_section"><a name="intro">Tutorial Introduction</a></div>
34<!-- *********************************************************************** -->
35
36<div class="doc_text">
37
38<p>Welcome to the "Implementing a language with LLVM" tutorial. This tutorial
Chris Lattner95ce0d62007-11-06 05:02:48 +000039runs through the implementation of a simple language, showing how fun and
Erick Tryzelaar8a64d5e2008-03-26 00:38:56 +000040easy it can be. This tutorial will get you up and started as well as help to
Chris Lattner4134c282007-11-06 06:32:18 +000041build a framework you can extend to other languages. The code in this tutorial
42can also be used as a playground to hack on other LLVM specific things.
Chris Lattnerc38ef542007-10-22 04:32:37 +000043</p>
44
Chris Lattner95ce0d62007-11-06 05:02:48 +000045<p>
46The goal of this tutorial is to progressively unveil our language, describing
47how it is built up over time. This will let us cover a fairly broad range of
48language design and LLVM-specific usage issues, showing and explaining the code
49for it all along the way, without overwhelming you with tons of details up
50front.</p>
51
52<p>It is useful to point out ahead of time that this tutorial is really about
53teaching compiler techniques and LLVM specifically, <em>not</em> about teaching
54modern and sane software engineering principles. In practice, this means that
55we'll take a number of shortcuts to simplify the exposition. For example, the
56code leaks memory, uses global variables all over the place, doesn't use nice
Chris Lattner729eb142008-02-10 19:11:04 +000057design patterns like <a
58href="http://en.wikipedia.org/wiki/Visitor_pattern">visitors</a>, etc... but it
59is very simple. If you dig in and use the code as a basis for future projects,
60fixing these deficiencies shouldn't be hard.</p>
Chris Lattner95ce0d62007-11-06 05:02:48 +000061
62<p>I've tried to put this tutorial together in a way that makes chapters easy to
Chris Lattner4134c282007-11-06 06:32:18 +000063skip over if you are already familiar with or are uninterested in the various
64pieces. The structure of the tutorial is:
Chris Lattner95ce0d62007-11-06 05:02:48 +000065</p>
66
67<ul>
68<li><b><a href="#language">Chapter #1</a>: Introduction to the Kaleidoscope
69language, and the definition of its Lexer</b> - This shows where we are going
70and the basic functionality that we want it to do. In order to make this
71tutorial maximally understandable and hackable, we choose to implement
72everything in C++ instead of using lexer and parser generators. LLVM obviously
73works just fine with such tools, feel free to use one if you prefer.</li>
74<li><b><a href="LangImpl2.html">Chapter #2</a>: Implementing a Parser and
75AST</b> - With the lexer in place, we can talk about parsing techniques and
76basic AST construction. This tutorial describes recursive descent parsing and
77operator precedence parsing. Nothing in Chapters 1 or 2 is LLVM-specific,
78the code doesn't even link in LLVM at this point. :)</li>
79<li><b><a href="LangImpl3.html">Chapter #3</a>: Code generation to LLVM IR</b> -
80With the AST ready, we can show off how easy generation of LLVM IR really
81is.</li>
82<li><b><a href="LangImpl4.html">Chapter #4</a>: Adding JIT and Optimizer
83Support</b> - Because a lot of people are interested in using LLVM as a JIT,
84we'll dive right into it and show you the 3 lines it takes to add JIT support.
85LLVM is also useful in many other ways, but this is one simple and "sexy" way
Chris Lattner4134c282007-11-06 06:32:18 +000086to shows off its power. :)</li>
Chris Lattner95ce0d62007-11-06 05:02:48 +000087<li><b><a href="LangImpl5.html">Chapter #5</a>: Extending the Language: Control
88Flow</b> - With the language up and running, we show how to extend it with
Chris Lattner4134c282007-11-06 06:32:18 +000089control flow operations (if/then/else and a 'for' loop). This gives us a chance
Chris Lattner95ce0d62007-11-06 05:02:48 +000090to talk about simple SSA construction and control flow.</li>
91<li><b><a href="LangImpl6.html">Chapter #6</a>: Extending the Language:
92User-defined Operators</b> - This is a silly but fun chapter that talks about
93extending the language to let the user program define their own arbitrary
94unary and binary operators (with assignable precedence!). This lets us build a
95significant piece of the "language" as library routines.</li>
96<li><b><a href="LangImpl7.html">Chapter #7</a>: Extending the Language: Mutable
97Variables</b> - This chapter talks about adding user-defined local variables
Chris Lattner4134c282007-11-06 06:32:18 +000098along with an assignment operator. The interesting part about this is how
99easy and trivial it is to construct SSA form in LLVM: no, LLVM does <em>not</em>
100require your front-end to construct SSA form!</li>
Chris Lattner95ce0d62007-11-06 05:02:48 +0000101<li><b><a href="LangImpl8.html">Chapter #8</a>: Conclusion and other useful LLVM
102tidbits</b> - This chapter wraps up the series by talking about potential
103ways to extend the language, but also includes a bunch of pointers to info about
104"special topics" like adding garbage collection support, exceptions, debugging,
105support for "spaghetti stacks", and a bunch of other tips and tricks.</li>
106
107</ul>
108
Chris Lattner4134c282007-11-06 06:32:18 +0000109<p>By the end of the tutorial, we'll have written a bit less than 700 lines of
110non-comment, non-blank, lines of code. With this small amount of code, we'll
Chris Lattner95ce0d62007-11-06 05:02:48 +0000111have built up a very reasonable compiler for a non-trivial language including
112a hand-written lexer, parser, AST, as well as code generation support with a JIT
113compiler. While other systems may have interesting "hello world" tutorials,
114I think the breadth of this tutorial is a great testament to the strengths of
115LLVM and why you should consider it if you're interested in language or compiler
116design.</p>
117
118<p>A note about this tutorial: we expect you to extend the language and play
Chris Lattner4134c282007-11-06 06:32:18 +0000119with it on your own. Take the code and go crazy hacking away at it, compilers
120don't need to be scary creatures - it can be a lot of fun to play with
121languages!</p>
Chris Lattner95ce0d62007-11-06 05:02:48 +0000122
Chris Lattnerc38ef542007-10-22 04:32:37 +0000123</div>
124
125<!-- *********************************************************************** -->
Chris Lattner128eb862007-11-05 19:06:59 +0000126<div class="doc_section"><a name="language">The Basic Language</a></div>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000127<!-- *********************************************************************** -->
128
129<div class="doc_text">
130
131<p>This tutorial will be illustrated with a toy language that we'll call
Chris Lattner4134c282007-11-06 06:32:18 +0000132"<a href="http://en.wikipedia.org/wiki/Kaleidoscope">Kaleidoscope</a>" (derived
133from "meaning beautiful, form, and view").
Chris Lattnerc38ef542007-10-22 04:32:37 +0000134Kaleidoscope is a procedural language that allows you to define functions, use
135conditionals, math, etc. Over the course of the tutorial, we'll extend
Chris Lattner619bc0a2007-11-05 20:13:56 +0000136Kaleidoscope to support the if/then/else construct, a for loop, user defined
137operators, JIT compilation with a simple command line interface, etc.</p>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000138
Chris Lattner619bc0a2007-11-05 20:13:56 +0000139<p>Because we want to keep things simple, the only datatype in Kaleidoscope is a
Chris Lattnerc38ef542007-10-22 04:32:37 +000014064-bit floating point type (aka 'double' in C parlance). As such, all values
141are implicitly double precision and the language doesn't require type
142declarations. This gives the language a very nice and simple syntax. For
Chris Lattner619bc0a2007-11-05 20:13:56 +0000143example, the following simple example computes <a
144href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci numbers:</a></p>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000145
146<div class="doc_code">
147<pre>
148# Compute the x'th fibonacci number.
149def fib(x)
Chris Lattnere6c91042007-10-22 06:34:15 +0000150 if x &lt; 3 then
Chris Lattnerc38ef542007-10-22 04:32:37 +0000151 1
152 else
153 fib(x-1)+fib(x-2)
154
155# This expression will compute the 40th number.
156fib(40)
157</pre>
158</div>
159
Duncan Sands72261ff2007-11-05 16:04:58 +0000160<p>We also allow Kaleidoscope to call into standard library functions (the LLVM
Chris Lattnerc38ef542007-10-22 04:32:37 +0000161JIT makes this completely trivial). This means that you can use the 'extern'
162keyword to define a function before you use it (this is also useful for mutually
163recursive functions). For example:</p>
164
165<div class="doc_code">
166<pre>
167extern sin(arg);
168extern cos(arg);
169extern atan2(arg1 arg2);
170
171atan2(sin(.4), cos(42))
172</pre>
173</div>
174
Chris Lattner4134c282007-11-06 06:32:18 +0000175<p>A more interesting example is included in Chapter 6 where we write a little
176Kaleidoscope application that <a href="LangImpl6.html#example">displays
177a Mandelbrot Set</a> at various levels of magnification.</p>
178
179<p>Lets dive into the implementation of this language!</p>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000180
181</div>
182
183<!-- *********************************************************************** -->
Chris Lattner128eb862007-11-05 19:06:59 +0000184<div class="doc_section"><a name="lexer">The Lexer</a></div>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000185<!-- *********************************************************************** -->
186
187<div class="doc_text">
188
189<p>When it comes to implementing a language, the first thing needed is
190the ability to process a text file and recognize what it says. The traditional
191way to do this is to use a "<a
192href="http://en.wikipedia.org/wiki/Lexical_analysis">lexer</a>" (aka 'scanner')
193to break the input up into "tokens". Each token returned by the lexer includes
194a token code and potentially some metadata (e.g. the numeric value of a number).
195First, we define the possibilities:
196</p>
197
198<div class="doc_code">
199<pre>
200// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
201// of these for known things.
202enum Token {
203 tok_eof = -1,
204
205 // commands
206 tok_def = -2, tok_extern = -3,
207
208 // primary
209 tok_identifier = -4, tok_number = -5,
210};
211
212static std::string IdentifierStr; // Filled in if tok_identifier
213static double NumVal; // Filled in if tok_number
214</pre>
215</div>
216
217<p>Each token returned by our lexer will either be one of the Token enum values
Chris Lattner4134c282007-11-06 06:32:18 +0000218or it will be an 'unknown' character like '+', which is returned as its ASCII
Chris Lattnerc38ef542007-10-22 04:32:37 +0000219value. If the current token is an identifier, the <tt>IdentifierStr</tt>
220global variable holds the name of the identifier. If the current token is a
221numeric literal (like 1.0), <tt>NumVal</tt> holds its value. Note that we use
222global variables for simplicity, this is not the best choice for a real language
223implementation :).
224</p>
225
Chris Lattner619bc0a2007-11-05 20:13:56 +0000226<p>The actual implementation of the lexer is a single function named
227<tt>gettok</tt>. The <tt>gettok</tt> function is called to return the next token
228from standard input. Its definition starts as:</p>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000229
230<div class="doc_code">
231<pre>
232/// gettok - Return the next token from standard input.
233static int gettok() {
234 static int LastChar = ' ';
235
236 // Skip any whitespace.
237 while (isspace(LastChar))
238 LastChar = getchar();
239</pre>
240</div>
241
242<p>
243<tt>gettok</tt> works by calling the C <tt>getchar()</tt> function to read
244characters one at a time from standard input. It eats them as it recognizes
Chris Lattner619bc0a2007-11-05 20:13:56 +0000245them and stores the last character read, but not processed, in LastChar. The
Chris Lattnerc38ef542007-10-22 04:32:37 +0000246first thing that it has to do is ignore whitespace between tokens. This is
247accomplished with the loop above.</p>
248
Chris Lattner619bc0a2007-11-05 20:13:56 +0000249<p>The next thing <tt>gettok</tt> needs to do is recognize identifiers and
250specific keywords like "def". Kaleidoscope does this with this simple loop:</p>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000251
252<div class="doc_code">
253<pre>
254 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
255 IdentifierStr = LastChar;
256 while (isalnum((LastChar = getchar())))
257 IdentifierStr += LastChar;
258
259 if (IdentifierStr == "def") return tok_def;
260 if (IdentifierStr == "extern") return tok_extern;
261 return tok_identifier;
262 }
263</pre>
264</div>
265
Chris Lattner619bc0a2007-11-05 20:13:56 +0000266<p>Note that this code sets the '<tt>IdentifierStr</tt>' global whenever it
267lexes an identifier. Also, since language keywords are matched by the same
268loop, we handle them here inline. Numeric values are similar:</p>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000269
270<div class="doc_code">
271<pre>
272 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
273 std::string NumStr;
274 do {
275 NumStr += LastChar;
276 LastChar = getchar();
277 } while (isdigit(LastChar) || LastChar == '.');
278
279 NumVal = strtod(NumStr.c_str(), 0);
280 return tok_number;
281 }
282</pre>
283</div>
284
285<p>This is all pretty straight-forward code for processing input. When reading
286a numeric value from input, we use the C <tt>strtod</tt> function to convert it
287to a numeric value that we store in <tt>NumVal</tt>. Note that this isn't doing
Duncan Sands72261ff2007-11-05 16:04:58 +0000288sufficient error checking: it will incorrectly read "1.23.45.67" and handle it as
Chris Lattnerc38ef542007-10-22 04:32:37 +0000289if you typed in "1.23". Feel free to extend it :). Next we handle comments:
290</p>
291
292<div class="doc_code">
293<pre>
294 if (LastChar == '#') {
295 // Comment until end of line.
296 do LastChar = getchar();
Chris Lattnerc80c23f2007-12-02 22:46:01 +0000297 while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
Chris Lattnerc38ef542007-10-22 04:32:37 +0000298
299 if (LastChar != EOF)
300 return gettok();
301 }
302</pre>
303</div>
304
Chris Lattner71155212007-11-06 01:39:12 +0000305<p>We handle comments by skipping to the end of the line and then return the
Chris Lattner4134c282007-11-06 06:32:18 +0000306next token. Finally, if the input doesn't match one of the above cases, it is
307either an operator character like '+' or the end of the file. These are handled
308with this code:</p>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000309
310<div class="doc_code">
311<pre>
312 // Check for end of file. Don't eat the EOF.
313 if (LastChar == EOF)
314 return tok_eof;
315
316 // Otherwise, just return the character as its ascii value.
317 int ThisChar = LastChar;
318 LastChar = getchar();
319 return ThisChar;
320}
321</pre>
322</div>
323
Chris Lattner619bc0a2007-11-05 20:13:56 +0000324<p>With this, we have the complete lexer for the basic Kaleidoscope language
325(the <a href="LangImpl2.html#code">full code listing</a> for the Lexer is
326available in the <a href="LangImpl2.html">next chapter</a> of the tutorial).
Chris Lattnerc38ef542007-10-22 04:32:37 +0000327Next we'll <a href="LangImpl2.html">build a simple parser that uses this to
Chris Lattnere6c91042007-10-22 06:34:15 +0000328build an Abstract Syntax Tree</a>. When we have that, we'll include a driver
329so that you can use the lexer and parser together.
Chris Lattnerc38ef542007-10-22 04:32:37 +0000330</p>
331
Chris Lattner729eb142008-02-10 19:11:04 +0000332<a href="LangImpl2.html">Next: Implementing a Parser and AST</a>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000333</div>
334
335<!-- *********************************************************************** -->
336<hr>
337<address>
338 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
339 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
340 <a href="http://validator.w3.org/check/referer"><img
Chris Lattner8eef4b22007-10-23 06:30:50 +0000341 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
Chris Lattnerc38ef542007-10-22 04:32:37 +0000342
343 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
344 <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
Dan Gohman523e3922010-02-03 17:27:31 +0000345 Last modified: $Date$
Chris Lattnerc38ef542007-10-22 04:32:37 +0000346</address>
347</body>
348</html>