OCamlLangImpl1.rst 12 KB

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