LangImpl01.rst 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. :orphan:
  2. =====================================================
  3. Kaleidoscope: Kaleidoscope Introduction and the Lexer
  4. =====================================================
  5. .. contents::
  6. :local:
  7. The Kaleidoscope Language
  8. =========================
  9. This tutorial is illustrated with a toy language called
  10. "`Kaleidoscope <http://en.wikipedia.org/wiki/Kaleidoscope>`_" (derived
  11. from "meaning beautiful, form, and view"). Kaleidoscope is a procedural
  12. language that allows you to define functions, use conditionals, math,
  13. etc. Over the course of the tutorial, we'll extend Kaleidoscope to
  14. support the if/then/else construct, a for loop, user defined operators,
  15. JIT compilation with a simple command line interface, debug info, etc.
  16. We want to keep things simple, so the only datatype in Kaleidoscope
  17. is a 64-bit floating point type (aka 'double' in C parlance). As such,
  18. all values are implicitly double precision and the language doesn't
  19. require type declarations. This gives the language a very nice and
  20. simple syntax. For example, the following simple example computes
  21. `Fibonacci numbers: <http://en.wikipedia.org/wiki/Fibonacci_number>`_
  22. ::
  23. # Compute the x'th fibonacci number.
  24. def fib(x)
  25. if x < 3 then
  26. 1
  27. else
  28. fib(x-1)+fib(x-2)
  29. # This expression will compute the 40th number.
  30. fib(40)
  31. We also allow Kaleidoscope to call into standard library functions - the
  32. LLVM JIT makes this really easy. This means that you can use the
  33. 'extern' keyword to define a function before you use it (this is also
  34. useful for mutually recursive functions). For example:
  35. ::
  36. extern sin(arg);
  37. extern cos(arg);
  38. extern atan2(arg1 arg2);
  39. atan2(sin(.4), cos(42))
  40. A more interesting example is included in Chapter 6 where we write a
  41. little Kaleidoscope application that `displays a Mandelbrot
  42. Set <LangImpl06.html#kicking-the-tires>`_ at various levels of magnification.
  43. Let's dive into the implementation of this language!
  44. The Lexer
  45. =========
  46. When it comes to implementing a language, the first thing needed is the
  47. ability to process a text file and recognize what it says. The
  48. traditional way to do this is to use a
  49. "`lexer <http://en.wikipedia.org/wiki/Lexical_analysis>`_" (aka
  50. 'scanner') to break the input up into "tokens". Each token returned by
  51. the lexer includes a token code and potentially some metadata (e.g. the
  52. numeric value of a number). First, we define the possibilities:
  53. .. code-block:: c++
  54. // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
  55. // of these for known things.
  56. enum Token {
  57. tok_eof = -1,
  58. // commands
  59. tok_def = -2,
  60. tok_extern = -3,
  61. // primary
  62. tok_identifier = -4,
  63. tok_number = -5,
  64. };
  65. static std::string IdentifierStr; // Filled in if tok_identifier
  66. static double NumVal; // Filled in if tok_number
  67. Each token returned by our lexer will either be one of the Token enum
  68. values or it will be an 'unknown' character like '+', which is returned
  69. as its ASCII value. If the current token is an identifier, the
  70. ``IdentifierStr`` global variable holds the name of the identifier. If
  71. the current token is a numeric literal (like 1.0), ``NumVal`` holds its
  72. value. We use global variables for simplicity, but this is not the
  73. best choice for a real language implementation :).
  74. The actual implementation of the lexer is a single function named
  75. ``gettok``. The ``gettok`` function is called to return the next token
  76. from standard input. Its definition starts as:
  77. .. code-block:: c++
  78. /// gettok - Return the next token from standard input.
  79. static int gettok() {
  80. static int LastChar = ' ';
  81. // Skip any whitespace.
  82. while (isspace(LastChar))
  83. LastChar = getchar();
  84. ``gettok`` works by calling the C ``getchar()`` function to read
  85. characters one at a time from standard input. It eats them as it
  86. recognizes them and stores the last character read, but not processed,
  87. in LastChar. The first thing that it has to do is ignore whitespace
  88. between tokens. This is accomplished with the loop above.
  89. The next thing ``gettok`` needs to do is recognize identifiers and
  90. specific keywords like "def". Kaleidoscope does this with this simple
  91. loop:
  92. .. code-block:: c++
  93. if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
  94. IdentifierStr = LastChar;
  95. while (isalnum((LastChar = getchar())))
  96. IdentifierStr += LastChar;
  97. if (IdentifierStr == "def")
  98. return tok_def;
  99. if (IdentifierStr == "extern")
  100. return tok_extern;
  101. return tok_identifier;
  102. }
  103. Note that this code sets the '``IdentifierStr``' global whenever it
  104. lexes an identifier. Also, since language keywords are matched by the
  105. same loop, we handle them here inline. Numeric values are similar:
  106. .. code-block:: c++
  107. if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
  108. std::string NumStr;
  109. do {
  110. NumStr += LastChar;
  111. LastChar = getchar();
  112. } while (isdigit(LastChar) || LastChar == '.');
  113. NumVal = strtod(NumStr.c_str(), 0);
  114. return tok_number;
  115. }
  116. This is all pretty straightforward code for processing input. When
  117. reading a numeric value from input, we use the C ``strtod`` function to
  118. convert it to a numeric value that we store in ``NumVal``. Note that
  119. this isn't doing sufficient error checking: it will incorrectly read
  120. "1.23.45.67" and handle it as if you typed in "1.23". Feel free to
  121. extend it! Next we handle comments:
  122. .. code-block:: c++
  123. if (LastChar == '#') {
  124. // Comment until end of line.
  125. do
  126. LastChar = getchar();
  127. while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
  128. if (LastChar != EOF)
  129. return gettok();
  130. }
  131. We handle comments by skipping to the end of the line and then return
  132. the next token. Finally, if the input doesn't match one of the above
  133. cases, it is either an operator character like '+' or the end of the
  134. file. These are handled with this code:
  135. .. code-block:: c++
  136. // Check for end of file. Don't eat the EOF.
  137. if (LastChar == EOF)
  138. return tok_eof;
  139. // Otherwise, just return the character as its ascii value.
  140. int ThisChar = LastChar;
  141. LastChar = getchar();
  142. return ThisChar;
  143. }
  144. With this, we have the complete lexer for the basic Kaleidoscope
  145. language (the `full code listing <LangImpl02.html#full-code-listing>`_ for the Lexer
  146. is available in the `next chapter <LangImpl02.html>`_ of the tutorial).
  147. Next we'll `build a simple parser that uses this to build an Abstract
  148. Syntax Tree <LangImpl02.html>`_. When we have that, we'll include a
  149. driver so that you can use the lexer and parser together.
  150. `Next: Implementing a Parser and AST <LangImpl02.html>`_