1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 2 "http://www.w3.org/TR/html4/strict.dtd"> 3 4<html> 5<head> 6 <title>Kaleidoscope: Tutorial Introduction and the Lexer</title> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 8 <meta name="author" content="Chris Lattner"> 9 <meta name="author" content="Erick Tryzelaar"> 10 <link rel="stylesheet" href="/_static/llvm.css" type="text/css"> 11</head> 12 13<body> 14 15<h1>Kaleidoscope: Tutorial Introduction and the Lexer</h1> 16 17<ul> 18<li><a href="index.html">Up to Tutorial Index</a></li> 19<li>Chapter 1 20 <ol> 21 <li><a href="#intro">Tutorial Introduction</a></li> 22 <li><a href="#language">The Basic Language</a></li> 23 <li><a href="#lexer">The Lexer</a></li> 24 </ol> 25</li> 26<li><a href="OCamlLangImpl2.html">Chapter 2</a>: Implementing a Parser and 27AST</li> 28</ul> 29 30<div class="doc_author"> 31 <p> 32 Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a> 33 and <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a> 34 </p> 35</div> 36 37<!-- *********************************************************************** --> 38<h2><a name="intro">Tutorial Introduction</a></h2> 39<!-- *********************************************************************** --> 40 41<div> 42 43<p>Welcome to the "Implementing a language with LLVM" tutorial. This tutorial 44runs through the implementation of a simple language, showing how fun and 45easy it can be. This tutorial will get you up and started as well as help to 46build a framework you can extend to other languages. The code in this tutorial 47can also be used as a playground to hack on other LLVM specific things. 48</p> 49 50<p> 51The goal of this tutorial is to progressively unveil our language, describing 52how it is built up over time. This will let us cover a fairly broad range of 53language design and LLVM-specific usage issues, showing and explaining the code 54for it all along the way, without overwhelming you with tons of details up 55front.</p> 56 57<p>It is useful to point out ahead of time that this tutorial is really about 58teaching compiler techniques and LLVM specifically, <em>not</em> about teaching 59modern and sane software engineering principles. In practice, this means that 60we'll take a number of shortcuts to simplify the exposition. For example, the 61code leaks memory, uses global variables all over the place, doesn't use nice 62design patterns like <a 63href="http://en.wikipedia.org/wiki/Visitor_pattern">visitors</a>, etc... but it 64is very simple. If you dig in and use the code as a basis for future projects, 65fixing these deficiencies shouldn't be hard.</p> 66 67<p>I've tried to put this tutorial together in a way that makes chapters easy to 68skip over if you are already familiar with or are uninterested in the various 69pieces. The structure of the tutorial is: 70</p> 71 72<ul> 73<li><b><a href="#language">Chapter #1</a>: Introduction to the Kaleidoscope 74language, and the definition of its Lexer</b> - This shows where we are going 75and the basic functionality that we want it to do. In order to make this 76tutorial maximally understandable and hackable, we choose to implement 77everything in Objective Caml instead of using lexer and parser generators. 78LLVM obviously works just fine with such tools, feel free to use one if you 79prefer.</li> 80<li><b><a href="OCamlLangImpl2.html">Chapter #2</a>: Implementing a Parser and 81AST</b> - With the lexer in place, we can talk about parsing techniques and 82basic AST construction. This tutorial describes recursive descent parsing and 83operator precedence parsing. Nothing in Chapters 1 or 2 is LLVM-specific, 84the code doesn't even link in LLVM at this point. :)</li> 85<li><b><a href="OCamlLangImpl3.html">Chapter #3</a>: Code generation to LLVM 86IR</b> - With the AST ready, we can show off how easy generation of LLVM IR 87really is.</li> 88<li><b><a href="OCamlLangImpl4.html">Chapter #4</a>: Adding JIT and Optimizer 89Support</b> - Because a lot of people are interested in using LLVM as a JIT, 90we'll dive right into it and show you the 3 lines it takes to add JIT support. 91LLVM is also useful in many other ways, but this is one simple and "sexy" way 92to shows off its power. :)</li> 93<li><b><a href="OCamlLangImpl5.html">Chapter #5</a>: Extending the Language: 94Control Flow</b> - With the language up and running, we show how to extend it 95with control flow operations (if/then/else and a 'for' loop). This gives us a 96chance to talk about simple SSA construction and control flow.</li> 97<li><b><a href="OCamlLangImpl6.html">Chapter #6</a>: Extending the Language: 98User-defined Operators</b> - This is a silly but fun chapter that talks about 99extending the language to let the user program define their own arbitrary 100unary and binary operators (with assignable precedence!). This lets us build a 101significant piece of the "language" as library routines.</li> 102<li><b><a href="OCamlLangImpl7.html">Chapter #7</a>: Extending the Language: 103Mutable Variables</b> - This chapter talks about adding user-defined local 104variables along with an assignment operator. The interesting part about this 105is how easy and trivial it is to construct SSA form in LLVM: no, LLVM does 106<em>not</em> require your front-end to construct SSA form!</li> 107<li><b><a href="OCamlLangImpl8.html">Chapter #8</a>: Conclusion and other 108useful LLVM tidbits</b> - This chapter wraps up the series by talking about 109potential ways to extend the language, but also includes a bunch of pointers to 110info about "special topics" like adding garbage collection support, exceptions, 111debugging, support for "spaghetti stacks", and a bunch of other tips and 112tricks.</li> 113 114</ul> 115 116<p>By the end of the tutorial, we'll have written a bit less than 700 lines of 117non-comment, non-blank, lines of code. With this small amount of code, we'll 118have built up a very reasonable compiler for a non-trivial language including 119a hand-written lexer, parser, AST, as well as code generation support with a JIT 120compiler. While other systems may have interesting "hello world" tutorials, 121I think the breadth of this tutorial is a great testament to the strengths of 122LLVM and why you should consider it if you're interested in language or compiler 123design.</p> 124 125<p>A note about this tutorial: we expect you to extend the language and play 126with it on your own. Take the code and go crazy hacking away at it, compilers 127don't need to be scary creatures - it can be a lot of fun to play with 128languages!</p> 129 130</div> 131 132<!-- *********************************************************************** --> 133<h2><a name="language">The Basic Language</a></h2> 134<!-- *********************************************************************** --> 135 136<div> 137 138<p>This tutorial will be illustrated with a toy language that we'll call 139"<a href="http://en.wikipedia.org/wiki/Kaleidoscope">Kaleidoscope</a>" (derived 140from "meaning beautiful, form, and view"). 141Kaleidoscope is a procedural language that allows you to define functions, use 142conditionals, math, etc. Over the course of the tutorial, we'll extend 143Kaleidoscope to support the if/then/else construct, a for loop, user defined 144operators, JIT compilation with a simple command line interface, etc.</p> 145 146<p>Because we want to keep things simple, the only datatype in Kaleidoscope is a 14764-bit floating point type (aka 'float' in O'Caml parlance). As such, all 148values are implicitly double precision and the language doesn't require type 149declarations. This gives the language a very nice and simple syntax. For 150example, the following simple example computes <a 151href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci numbers:</a></p> 152 153<div class="doc_code"> 154<pre> 155# Compute the x'th fibonacci number. 156def fib(x) 157 if x < 3 then 158 1 159 else 160 fib(x-1)+fib(x-2) 161 162# This expression will compute the 40th number. 163fib(40) 164</pre> 165</div> 166 167<p>We also allow Kaleidoscope to call into standard library functions (the LLVM 168JIT makes this completely trivial). This means that you can use the 'extern' 169keyword to define a function before you use it (this is also useful for mutually 170recursive functions). For example:</p> 171 172<div class="doc_code"> 173<pre> 174extern sin(arg); 175extern cos(arg); 176extern atan2(arg1 arg2); 177 178atan2(sin(.4), cos(42)) 179</pre> 180</div> 181 182<p>A more interesting example is included in Chapter 6 where we write a little 183Kaleidoscope application that <a href="OCamlLangImpl6.html#example">displays 184a Mandelbrot Set</a> at various levels of magnification.</p> 185 186<p>Lets dive into the implementation of this language!</p> 187 188</div> 189 190<!-- *********************************************************************** --> 191<h2><a name="lexer">The Lexer</a></h2> 192<!-- *********************************************************************** --> 193 194<div> 195 196<p>When it comes to implementing a language, the first thing needed is 197the ability to process a text file and recognize what it says. The traditional 198way to do this is to use a "<a 199href="http://en.wikipedia.org/wiki/Lexical_analysis">lexer</a>" (aka 'scanner') 200to break the input up into "tokens". Each token returned by the lexer includes 201a token code and potentially some metadata (e.g. the numeric value of a number). 202First, we define the possibilities: 203</p> 204 205<div class="doc_code"> 206<pre> 207(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of 208 * these others for known things. *) 209type token = 210 (* commands *) 211 | Def | Extern 212 213 (* primary *) 214 | Ident of string | Number of float 215 216 (* unknown *) 217 | Kwd of char 218</pre> 219</div> 220 221<p>Each token returned by our lexer will be one of the token variant values. 222An unknown character like '+' will be returned as <tt>Token.Kwd '+'</tt>. If 223the curr token is an identifier, the value will be <tt>Token.Ident s</tt>. If 224the current token is a numeric literal (like 1.0), the value will be 225<tt>Token.Number 1.0</tt>. 226</p> 227 228<p>The actual implementation of the lexer is a collection of functions driven 229by a function named <tt>Lexer.lex</tt>. The <tt>Lexer.lex</tt> function is 230called to return the next token from standard input. We will use 231<a href="http://caml.inria.fr/pub/docs/manual-camlp4/index.html">Camlp4</a> 232to simplify the tokenization of the standard input. Its definition starts 233as:</p> 234 235<div class="doc_code"> 236<pre> 237(*===----------------------------------------------------------------------=== 238 * Lexer 239 *===----------------------------------------------------------------------===*) 240 241let rec lex = parser 242 (* Skip any whitespace. *) 243 | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream 244</pre> 245</div> 246 247<p> 248<tt>Lexer.lex</tt> works by recursing over a <tt>char Stream.t</tt> to read 249characters one at a time from the standard input. It eats them as it recognizes 250them and stores them in in a <tt>Token.token</tt> variant. The first thing that 251it has to do is ignore whitespace between tokens. This is accomplished with the 252recursive call above.</p> 253 254<p>The next thing <tt>Lexer.lex</tt> needs to do is recognize identifiers and 255specific keywords like "def". Kaleidoscope does this with a pattern match 256and a helper function.<p> 257 258<div class="doc_code"> 259<pre> 260 (* identifier: [a-zA-Z][a-zA-Z0-9] *) 261 | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] -> 262 let buffer = Buffer.create 1 in 263 Buffer.add_char buffer c; 264 lex_ident buffer stream 265 266... 267 268and lex_ident buffer = parser 269 | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] -> 270 Buffer.add_char buffer c; 271 lex_ident buffer stream 272 | [< stream=lex >] -> 273 match Buffer.contents buffer with 274 | "def" -> [< 'Token.Def; stream >] 275 | "extern" -> [< 'Token.Extern; stream >] 276 | id -> [< 'Token.Ident id; stream >] 277</pre> 278</div> 279 280<p>Numeric values are similar:</p> 281 282<div class="doc_code"> 283<pre> 284 (* number: [0-9.]+ *) 285 | [< ' ('0' .. '9' as c); stream >] -> 286 let buffer = Buffer.create 1 in 287 Buffer.add_char buffer c; 288 lex_number buffer stream 289 290... 291 292and lex_number buffer = parser 293 | [< ' ('0' .. '9' | '.' as c); stream >] -> 294 Buffer.add_char buffer c; 295 lex_number buffer stream 296 | [< stream=lex >] -> 297 [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >] 298</pre> 299</div> 300 301<p>This is all pretty straight-forward code for processing input. When reading 302a numeric value from input, we use the ocaml <tt>float_of_string</tt> function 303to convert it to a numeric value that we store in <tt>Token.Number</tt>. Note 304that this isn't doing sufficient error checking: it will raise <tt>Failure</tt> 305if the string "1.23.45.67". Feel free to extend it :). Next we handle 306comments: 307</p> 308 309<div class="doc_code"> 310<pre> 311 (* Comment until end of line. *) 312 | [< ' ('#'); stream >] -> 313 lex_comment stream 314 315... 316 317and lex_comment = parser 318 | [< ' ('\n'); stream=lex >] -> stream 319 | [< 'c; e=lex_comment >] -> e 320 | [< >] -> [< >] 321</pre> 322</div> 323 324<p>We handle comments by skipping to the end of the line and then return the 325next token. Finally, if the input doesn't match one of the above cases, it is 326either an operator character like '+' or the end of the file. These are handled 327with this code:</p> 328 329<div class="doc_code"> 330<pre> 331 (* Otherwise, just return the character as its ascii value. *) 332 | [< 'c; stream >] -> 333 [< 'Token.Kwd c; lex stream >] 334 335 (* end of stream. *) 336 | [< >] -> [< >] 337</pre> 338</div> 339 340<p>With this, we have the complete lexer for the basic Kaleidoscope language 341(the <a href="OCamlLangImpl2.html#code">full code listing</a> for the Lexer is 342available in the <a href="OCamlLangImpl2.html">next chapter</a> of the 343tutorial). Next we'll <a href="OCamlLangImpl2.html">build a simple parser that 344uses this to build an Abstract Syntax Tree</a>. When we have that, we'll 345include a driver so that you can use the lexer and parser together. 346</p> 347 348<a href="OCamlLangImpl2.html">Next: Implementing a Parser and AST</a> 349</div> 350 351<!-- *********************************************************************** --> 352<hr> 353<address> 354 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img 355 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a> 356 <a href="http://validator.w3.org/check/referer"><img 357 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a> 358 359 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br> 360 <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a><br> 361 <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br> 362 Last modified: $Date$ 363</address> 364</body> 365</html> 366